0
# Authentication & Configuration
1
2
Client authentication, configuration options, and resource path management utilities for Google Cloud Trace. This covers credential handling, client configuration, and helper methods for constructing resource paths.
3
4
## Authentication Methods
5
6
### Default Credentials
7
8
Both v1 and v2 clients support automatic credential discovery using Google Cloud's default credential chain.
9
10
```python { .api }
11
class TraceServiceClient:
12
def __init__(
13
self,
14
*,
15
credentials: Optional[Credentials] = None,
16
transport: Optional[Union[str, TraceServiceTransport, Callable]] = None,
17
client_options: Optional[Union[ClientOptions, dict]] = None,
18
client_info: gapic_v1.client_info.ClientInfo = None
19
): ...
20
```
21
22
### Service Account Authentication
23
24
Create clients using service account credentials from file or dictionary.
25
26
```python { .api }
27
class TraceServiceClient:
28
@classmethod
29
def from_service_account_file(
30
cls,
31
filename: str,
32
*args,
33
**kwargs
34
) -> TraceServiceClient:
35
"""
36
Creates a client instance from a service account JSON file.
37
38
Args:
39
filename: Path to the service account JSON file
40
*args: Additional arguments to pass to the client constructor
41
**kwargs: Additional keyword arguments to pass to the client constructor
42
43
Returns:
44
Constructed TraceServiceClient instance
45
46
Raises:
47
google.auth.exceptions.DefaultCredentialsError: If the file is not found or invalid
48
"""
49
50
@classmethod
51
def from_service_account_info(
52
cls,
53
info: Dict[str, Any],
54
*args,
55
**kwargs
56
) -> TraceServiceClient:
57
"""
58
Creates a client instance from service account information.
59
60
Args:
61
info: Service account information as a dictionary
62
*args: Additional arguments to pass to the client constructor
63
**kwargs: Additional keyword arguments to pass to the client constructor
64
65
Returns:
66
Constructed TraceServiceClient instance
67
68
Raises:
69
google.auth.exceptions.DefaultCredentialsError: If the info is invalid
70
"""
71
72
# Alias for from_service_account_file
73
from_service_account_json = from_service_account_file
74
```
75
76
## Resource Path Helpers
77
78
### Common Resource Paths
79
80
Utility methods for constructing properly formatted resource names.
81
82
```python { .api }
83
class TraceServiceClient:
84
@staticmethod
85
def common_project_path(project: str) -> str:
86
"""
87
Returns a fully-qualified project string.
88
89
Args:
90
project: Project ID
91
92
Returns:
93
Formatted project resource name: "projects/{project}"
94
"""
95
96
@staticmethod
97
def parse_common_project_path(path: str) -> Dict[str, str]:
98
"""
99
Parses a project path into its component segments.
100
101
Args:
102
path: Project resource path
103
104
Returns:
105
Dictionary with parsed path components
106
"""
107
108
@staticmethod
109
def common_location_path(project: str, location: str) -> str:
110
"""
111
Returns a fully-qualified location string.
112
113
Args:
114
project: Project ID
115
location: Location ID
116
117
Returns:
118
Formatted location resource name: "projects/{project}/locations/{location}"
119
"""
120
121
@staticmethod
122
def parse_common_location_path(path: str) -> Dict[str, str]:
123
"""
124
Parses a location path into its component segments.
125
126
Args:
127
path: Location resource path
128
129
Returns:
130
Dictionary with keys: project, location
131
"""
132
133
@staticmethod
134
def common_billing_account_path(billing_account: str) -> str:
135
"""
136
Returns a fully-qualified billing account string.
137
138
Args:
139
billing_account: Billing account ID
140
141
Returns:
142
Formatted billing account resource name: "billingAccounts/{billing_account}"
143
"""
144
145
@staticmethod
146
def parse_common_billing_account_path(path: str) -> Dict[str, str]:
147
"""
148
Parses a billing account path into its component segments.
149
150
Args:
151
path: Billing account resource path
152
153
Returns:
154
Dictionary with keys: billing_account
155
"""
156
157
@staticmethod
158
def common_folder_path(folder: str) -> str:
159
"""
160
Returns a fully-qualified folder string.
161
162
Args:
163
folder: Folder ID
164
165
Returns:
166
Formatted folder resource name: "folders/{folder}"
167
"""
168
169
@staticmethod
170
def parse_common_folder_path(path: str) -> Dict[str, str]:
171
"""
172
Parses a folder path into its component segments.
173
174
Args:
175
path: Folder resource path
176
177
Returns:
178
Dictionary with keys: folder
179
"""
180
181
@staticmethod
182
def common_organization_path(organization: str) -> str:
183
"""
184
Returns a fully-qualified organization string.
185
186
Args:
187
organization: Organization ID
188
189
Returns:
190
Formatted organization resource name: "organizations/{organization}"
191
"""
192
193
@staticmethod
194
def parse_common_organization_path(path: str) -> Dict[str, str]:
195
"""
196
Parses an organization path into its component segments.
197
198
Args:
199
path: Organization resource path
200
201
Returns:
202
Dictionary with keys: organization
203
"""
204
```
205
206
### V2-Specific Resource Paths
207
208
Resource path helpers specific to the v2 API for span management.
209
210
```python { .api }
211
class TraceServiceClient:
212
@staticmethod
213
def span_path(project: str, trace: str, span: str) -> str:
214
"""
215
Returns a fully-qualified span string.
216
217
Args:
218
project: Project ID
219
trace: Trace ID
220
span: Span ID
221
222
Returns:
223
Formatted span resource name: "projects/{project}/traces/{trace}/spans/{span}"
224
"""
225
226
@staticmethod
227
def parse_span_path(path: str) -> Dict[str, str]:
228
"""
229
Parses a span path into its component segments.
230
231
Args:
232
path: Span resource path
233
234
Returns:
235
Dictionary with keys: project, trace, span
236
"""
237
```
238
239
## Client Configuration
240
241
### Transport Options
242
243
Configure transport mechanisms for client communication.
244
245
```python { .api }
246
# Transport types
247
TransportType = Union[str, TraceServiceTransport, Callable]
248
249
# Available transport strings:
250
# - "grpc" (default): gRPC transport
251
# - "grpc_asyncio": Async gRPC transport
252
# - "rest": REST transport
253
```
254
255
### Client Options
256
257
Configure client behavior through ClientOptions.
258
259
```python { .api }
260
class ClientOptions:
261
api_endpoint: Optional[str] # Override default API endpoint
262
client_cert_source: Optional[Callable] # Client certificate source
263
quota_project_id: Optional[str] # Project for quota and billing
264
credentials_file: Optional[str] # Path to credentials file
265
scopes: Optional[Sequence[str]] # OAuth 2.0 scopes
266
default_scopes: Optional[Sequence[str]] # Default OAuth 2.0 scopes
267
```
268
269
## Client Properties and Context Management
270
271
### Client Properties
272
273
Access client configuration and transport information.
274
275
```python { .api }
276
class TraceServiceClient:
277
@property
278
def transport(self) -> TraceServiceTransport:
279
"""Returns the transport used by the client instance."""
280
281
@property
282
def api_endpoint(self) -> str:
283
"""Returns the API endpoint used by the client instance."""
284
285
@property
286
def universe_domain(self) -> str:
287
"""Returns the universe domain used by the client instance."""
288
```
289
290
### Context Management
291
292
Both synchronous and asynchronous clients support context management for automatic resource cleanup.
293
294
```python { .api }
295
class TraceServiceClient:
296
def __enter__(self) -> "TraceServiceClient":
297
"""Enter the client context."""
298
299
def __exit__(self, type, value, traceback) -> None:
300
"""Exit the client context and clean up resources."""
301
302
class TraceServiceAsyncClient:
303
async def __aenter__(self) -> "TraceServiceAsyncClient":
304
"""Enter the async client context."""
305
306
async def __aexit__(self, type, value, traceback) -> None:
307
"""Exit the async client context and clean up resources."""
308
```
309
310
## Usage Examples
311
312
### Basic Authentication
313
314
```python
315
from google.cloud import trace_v2
316
317
# Using default credentials (recommended)
318
client = trace_v2.TraceServiceClient()
319
320
# Using specific credentials
321
from google.oauth2 import service_account
322
323
credentials = service_account.Credentials.from_service_account_file(
324
"path/to/service-account.json"
325
)
326
client = trace_v2.TraceServiceClient(credentials=credentials)
327
```
328
329
### Service Account Authentication
330
331
```python
332
from google.cloud import trace_v2
333
334
# From service account file
335
client = trace_v2.TraceServiceClient.from_service_account_file(
336
"path/to/credentials.json"
337
)
338
339
# From service account info dictionary
340
service_account_info = {
341
"type": "service_account",
342
"project_id": "my-project",
343
"private_key_id": "key-id",
344
"private_key": "-----BEGIN PRIVATE KEY-----\n...",
345
"client_email": "service@my-project.iam.gserviceaccount.com",
346
"client_id": "123456789",
347
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
348
"token_uri": "https://oauth2.googleapis.com/token"
349
}
350
351
client = trace_v2.TraceServiceClient.from_service_account_info(
352
service_account_info
353
)
354
```
355
356
### Client Configuration
357
358
```python
359
from google.cloud import trace_v2
360
from google.api_core import client_options
361
362
# Configure client options
363
options = client_options.ClientOptions(
364
api_endpoint="https://custom-trace-endpoint.com",
365
quota_project_id="billing-project"
366
)
367
368
client = trace_v2.TraceServiceClient(client_options=options)
369
370
# Configure transport
371
client = trace_v2.TraceServiceClient(transport="rest")
372
373
# Custom gRPC configuration
374
import grpc
375
from google.cloud.trace_v2.services.trace_service import transports
376
377
channel = grpc.secure_channel(
378
"cloudtrace.googleapis.com:443",
379
credentials=grpc.ssl_channel_credentials()
380
)
381
382
transport = transports.TraceServiceGrpcTransport(channel=channel)
383
client = trace_v2.TraceServiceClient(transport=transport)
384
```
385
386
### Resource Path Construction
387
388
```python
389
from google.cloud import trace_v2
390
391
# Create client
392
client = trace_v2.TraceServiceClient()
393
394
# Construct resource paths
395
project_path = client.common_project_path("my-project")
396
print(project_path) # "projects/my-project"
397
398
span_path = client.span_path("my-project", "trace-123", "span-456")
399
print(span_path) # "projects/my-project/traces/trace-123/spans/span-456"
400
401
# Parse resource paths
402
parsed = client.parse_span_path(span_path)
403
print(parsed) # {"project": "my-project", "trace": "trace-123", "span": "span-456"}
404
405
# Use in API calls
406
span = trace_v2.Span(
407
name=span_path,
408
span_id="span-456",
409
display_name=trace_v2.TruncatableString(value="my-operation"),
410
start_time={"seconds": 1609459200},
411
end_time={"seconds": 1609459201}
412
)
413
414
client.create_span(request=span)
415
```
416
417
### Environment Variables
418
419
```python
420
import os
421
from google.cloud import trace_v2
422
423
# Set credentials via environment variable
424
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/path/to/credentials.json"
425
426
# Set project ID via environment variable
427
os.environ["GOOGLE_CLOUD_PROJECT"] = "my-project"
428
429
# Client will automatically use these credentials
430
client = trace_v2.TraceServiceClient()
431
432
# Use project from environment
433
project_name = client.common_project_path(os.environ["GOOGLE_CLOUD_PROJECT"])
434
```
435
436
### Error Handling
437
438
```python
439
from google.cloud import trace_v2
440
from google.api_core import exceptions
441
442
try:
443
client = trace_v2.TraceServiceClient()
444
445
span = trace_v2.Span(
446
name="projects/my-project/traces/trace-123/spans/span-456",
447
span_id="span-456",
448
display_name=trace_v2.TruncatableString(value="test-span"),
449
start_time={"seconds": 1609459200},
450
end_time={"seconds": 1609459201}
451
)
452
453
client.create_span(request=span)
454
455
except exceptions.Unauthenticated:
456
print("Authentication failed - check credentials")
457
except exceptions.PermissionDenied:
458
print("Insufficient permissions for the operation")
459
except exceptions.InvalidArgument as e:
460
print(f"Invalid request parameters: {e}")
461
except exceptions.GoogleAPICallError as e:
462
print(f"API call failed: {e}")
463
```