0
# Notification Channel Management
1
2
Comprehensive notification channel management for delivering alert notifications via email, SMS, Slack, PagerDuty, and other supported channels with verification and configuration management in Google Cloud Monitoring.
3
4
## Capabilities
5
6
### Notification Channel Operations
7
8
Manage the complete lifecycle of notification channels including creation, updates, retrieval, deletion, and verification.
9
10
```python { .api }
11
class NotificationChannelServiceClient:
12
def list_notification_channels(
13
self,
14
request=None,
15
*,
16
name: str = None,
17
retry=None,
18
timeout=None,
19
metadata=()
20
) -> pagers.ListNotificationChannelsPager:
21
"""
22
Lists the notification channels that have been created.
23
24
Args:
25
request: The request object or dict equivalent
26
name: Required. Project name in format 'projects/[PROJECT_ID]'
27
retry: Retry configuration
28
timeout: Request timeout in seconds
29
metadata: Additional metadata
30
31
Returns:
32
Pager for iterating over NotificationChannel objects
33
"""
34
35
def get_notification_channel(
36
self,
37
request=None,
38
*,
39
name: str = None,
40
retry=None,
41
timeout=None,
42
metadata=()
43
) -> notification_pb2.NotificationChannel:
44
"""
45
Gets a single notification channel.
46
47
Args:
48
request: The request object or dict equivalent
49
name: Required. Channel name in format 'projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID]'
50
retry: Retry configuration
51
timeout: Request timeout in seconds
52
metadata: Additional metadata
53
54
Returns:
55
NotificationChannel object
56
"""
57
58
def create_notification_channel(
59
self,
60
request=None,
61
*,
62
name: str = None,
63
notification_channel=None,
64
retry=None,
65
timeout=None,
66
metadata=()
67
) -> notification_pb2.NotificationChannel:
68
"""
69
Creates a new notification channel.
70
71
Args:
72
request: The request object or dict equivalent
73
name: Required. Project name
74
notification_channel: Required. The notification channel to create
75
retry: Retry configuration
76
timeout: Request timeout in seconds
77
metadata: Additional metadata
78
79
Returns:
80
Created NotificationChannel object
81
"""
82
83
def update_notification_channel(
84
self,
85
request=None,
86
*,
87
update_mask=None,
88
notification_channel=None,
89
retry=None,
90
timeout=None,
91
metadata=()
92
) -> notification_pb2.NotificationChannel:
93
"""
94
Updates a notification channel.
95
96
Args:
97
request: The request object or dict equivalent
98
update_mask: Field mask for selective updates
99
notification_channel: Required. Updated notification channel
100
retry: Retry configuration
101
timeout: Request timeout in seconds
102
metadata: Additional metadata
103
104
Returns:
105
Updated NotificationChannel object
106
"""
107
108
def delete_notification_channel(
109
self,
110
request=None,
111
*,
112
name: str = None,
113
force: bool = None,
114
retry=None,
115
timeout=None,
116
metadata=()
117
) -> None:
118
"""
119
Deletes a notification channel.
120
121
Args:
122
request: The request object or dict equivalent
123
name: Required. Channel name to delete
124
force: Force deletion even if channel is referenced
125
retry: Retry configuration
126
timeout: Request timeout in seconds
127
metadata: Additional metadata
128
"""
129
```
130
131
### Notification Channel Verification
132
133
Manage notification channel verification including sending and retrieving verification codes.
134
135
```python { .api }
136
class NotificationChannelServiceClient:
137
def send_notification_channel_verification_code(
138
self,
139
request=None,
140
*,
141
name: str = None,
142
retry=None,
143
timeout=None,
144
metadata=()
145
) -> None:
146
"""
147
Causes a verification code to be delivered to the channel.
148
149
Args:
150
request: The request object or dict equivalent
151
name: Required. Channel name
152
retry: Retry configuration
153
timeout: Request timeout in seconds
154
metadata: Additional metadata
155
"""
156
157
def get_notification_channel_verification_code(
158
self,
159
request=None,
160
*,
161
name: str = None,
162
retry=None,
163
timeout=None,
164
metadata=()
165
) -> notification_service.GetNotificationChannelVerificationCodeResponse:
166
"""
167
Requests a verification code for an already verified channel.
168
169
Args:
170
request: The request object or dict equivalent
171
name: Required. Channel name
172
retry: Retry configuration
173
timeout: Request timeout in seconds
174
metadata: Additional metadata
175
176
Returns:
177
GetNotificationChannelVerificationCodeResponse object
178
"""
179
180
def verify_notification_channel(
181
self,
182
request=None,
183
*,
184
name: str = None,
185
code: str = None,
186
retry=None,
187
timeout=None,
188
metadata=()
189
) -> notification_pb2.NotificationChannel:
190
"""
191
Verifies a NotificationChannel by proving receipt of the code.
192
193
Args:
194
request: The request object or dict equivalent
195
name: Required. Channel name
196
code: Required. Verification code
197
retry: Retry configuration
198
timeout: Request timeout in seconds
199
metadata: Additional metadata
200
201
Returns:
202
Verified NotificationChannel object
203
"""
204
```
205
206
### Notification Channel Descriptors
207
208
Retrieve information about supported notification channel types and their configurations.
209
210
```python { .api }
211
class NotificationChannelServiceClient:
212
def list_notification_channel_descriptors(
213
self,
214
request=None,
215
*,
216
name: str = None,
217
retry=None,
218
timeout=None,
219
metadata=()
220
) -> pagers.ListNotificationChannelDescriptorsPager:
221
"""
222
Lists the descriptors for supported notification channels.
223
224
Args:
225
request: The request object or dict equivalent
226
name: Required. Project name
227
retry: Retry configuration
228
timeout: Request timeout in seconds
229
metadata: Additional metadata
230
231
Returns:
232
Pager for iterating over NotificationChannelDescriptor objects
233
"""
234
235
def get_notification_channel_descriptor(
236
self,
237
request=None,
238
*,
239
name: str = None,
240
retry=None,
241
timeout=None,
242
metadata=()
243
) -> notification_pb2.NotificationChannelDescriptor:
244
"""
245
Gets a single notification channel descriptor.
246
247
Args:
248
request: The request object or dict equivalent
249
name: Required. Descriptor name
250
retry: Retry configuration
251
timeout: Request timeout in seconds
252
metadata: Additional metadata
253
254
Returns:
255
NotificationChannelDescriptor object
256
"""
257
```
258
259
## Data Types
260
261
### NotificationChannel
262
263
Represents a notification channel configuration.
264
265
```python { .api }
266
class NotificationChannel:
267
type: str # Channel type (email, sms, slack, etc.)
268
name: str # Resource name
269
display_name: str # Human-readable name
270
description: str # Channel description
271
labels: Dict[str, str] # Channel-specific configuration
272
user_labels: Dict[str, str] # User-defined labels
273
verification_status: NotificationChannel.VerificationStatus # Verification state
274
enabled: bool # Whether channel is enabled
275
creation_record: MutationRecord # Creation metadata
276
mutation_records: List[MutationRecord] # Modification history
277
278
class NotificationChannel.VerificationStatus(enum.Enum):
279
VERIFICATION_STATUS_UNSPECIFIED = 0
280
UNVERIFIED = 1
281
VERIFIED = 2
282
```
283
284
### NotificationChannelDescriptor
285
286
Describes a notification channel type and its required configuration.
287
288
```python { .api }
289
class NotificationChannelDescriptor:
290
name: str # Resource name
291
type: str # Channel type identifier
292
display_name: str # Human-readable type name
293
description: str # Type description
294
labels: List[LabelDescriptor] # Required and optional labels
295
supported_tiers: List[ServiceTier] # Supported service tiers
296
launch_stage: LaunchStage # Launch stage of the channel type
297
```
298
299
### Request and Response Types
300
301
```python { .api }
302
class CreateNotificationChannelRequest:
303
name: str # Required. Project name
304
notification_channel: NotificationChannel # Required. Channel to create
305
306
class DeleteNotificationChannelRequest:
307
name: str # Required. Channel name to delete
308
force: bool # Force deletion even if referenced
309
310
class GetNotificationChannelRequest:
311
name: str # Required. Channel name to retrieve
312
313
class ListNotificationChannelsRequest:
314
name: str # Required. Project name
315
filter: str # Filter expression
316
order_by: str # Ordering specification
317
page_size: int # Maximum results per page
318
page_token: str # Page token
319
320
class ListNotificationChannelsResponse:
321
notification_channels: List[NotificationChannel] # Channels
322
next_page_token: str # Next page token
323
324
class UpdateNotificationChannelRequest:
325
update_mask: FieldMask # Fields to update
326
notification_channel: NotificationChannel # Required. Updated channel
327
328
class SendNotificationChannelVerificationCodeRequest:
329
name: str # Required. Channel name
330
331
class GetNotificationChannelVerificationCodeRequest:
332
name: str # Required. Channel name
333
expire_time: Timestamp # Code expiration time
334
335
class GetNotificationChannelVerificationCodeResponse:
336
code: str # Verification code
337
expire_time: Timestamp # Code expiration time
338
339
class VerifyNotificationChannelRequest:
340
name: str # Required. Channel name
341
code: str # Required. Verification code
342
343
class GetNotificationChannelDescriptorRequest:
344
name: str # Required. Channel descriptor name
345
346
class ListNotificationChannelDescriptorsRequest:
347
name: str # Required. Project name
348
page_size: int # Maximum results per page
349
page_token: str # Page token
350
351
class ListNotificationChannelDescriptorsResponse:
352
channel_descriptors: List[NotificationChannelDescriptor] # Channel descriptors
353
next_page_token: str # Next page token
354
```
355
356
## Usage Examples
357
358
### Creating an Email Notification Channel
359
360
```python
361
from google.cloud.monitoring import NotificationChannelServiceClient
362
from google.api import notification_pb2
363
364
client = NotificationChannelServiceClient()
365
project_name = f"projects/{project_id}"
366
367
# Create email notification channel
368
channel = notification_pb2.NotificationChannel()
369
channel.type = "email"
370
channel.display_name = "Engineering Team Email"
371
channel.description = "Email notifications for engineering team"
372
373
# Set email address in labels
374
channel.labels["email_address"] = "engineering@example.com"
375
376
# Add user labels for organization
377
channel.user_labels["team"] = "engineering"
378
channel.user_labels["priority"] = "high"
379
380
# Create the channel
381
created_channel = client.create_notification_channel(
382
name=project_name,
383
notification_channel=channel
384
)
385
print(f"Created notification channel: {created_channel.name}")
386
print(f"Verification status: {created_channel.verification_status}")
387
```
388
389
### Creating a Slack Notification Channel
390
391
```python
392
# Create Slack notification channel
393
slack_channel = notification_pb2.NotificationChannel()
394
slack_channel.type = "slack"
395
slack_channel.display_name = "Engineering Slack Channel"
396
slack_channel.description = "Slack notifications for critical alerts"
397
398
# Set Slack webhook URL
399
slack_channel.labels["url"] = "https://hooks.slack.com/services/YOUR/SLACK/WEBHOOK"
400
401
created_slack = client.create_notification_channel(
402
name=project_name,
403
notification_channel=slack_channel
404
)
405
print(f"Created Slack channel: {created_slack.name}")
406
```
407
408
### Verifying a Notification Channel
409
410
```python
411
channel_name = f"projects/{project_id}/notificationChannels/{channel_id}"
412
413
# Send verification code
414
client.send_notification_channel_verification_code(name=channel_name)
415
print("Verification code sent")
416
417
# After receiving the code, verify the channel
418
verification_code = "123456" # Code received via email/SMS
419
verified_channel = client.verify_notification_channel(
420
name=channel_name,
421
code=verification_code
422
)
423
print(f"Channel verified: {verified_channel.verification_status}")
424
```
425
426
### Listing Notification Channels
427
428
```python
429
client = NotificationChannelServiceClient()
430
project_name = f"projects/{project_id}"
431
432
# List all notification channels
433
print("All notification channels:")
434
for channel in client.list_notification_channels(name=project_name):
435
print(f"- {channel.display_name} ({channel.type})")
436
print(f" Status: {channel.verification_status}")
437
print(f" Enabled: {channel.enabled}")
438
439
# List only email channels
440
email_filter = 'type="email"'
441
print("\nEmail channels only:")
442
for channel in client.list_notification_channels(name=project_name, filter=email_filter):
443
print(f"- {channel.display_name}: {channel.labels.get('email_address')}")
444
```
445
446
### Updating a Notification Channel
447
448
```python
449
from google.protobuf import field_mask_pb2
450
451
# Get existing channel
452
channel_name = f"projects/{project_id}/notificationChannels/{channel_id}"
453
channel = client.get_notification_channel(name=channel_name)
454
455
# Update channel properties
456
channel.display_name = "Updated Engineering Team Email"
457
channel.enabled = True
458
channel.user_labels["environment"] = "production"
459
460
# Create field mask for selective update
461
update_mask = field_mask_pb2.FieldMask()
462
update_mask.paths.extend(["display_name", "enabled", "user_labels"])
463
464
# Update the channel
465
updated_channel = client.update_notification_channel(
466
notification_channel=channel,
467
update_mask=update_mask
468
)
469
print(f"Updated channel: {updated_channel.display_name}")
470
```
471
472
### Working with Channel Descriptors
473
474
```python
475
# List all supported notification channel types
476
print("Supported notification channel types:")
477
for descriptor in client.list_notification_channel_descriptors(name=project_name):
478
print(f"- {descriptor.type}: {descriptor.display_name}")
479
print(f" Description: {descriptor.description}")
480
print(f" Launch stage: {descriptor.launch_stage}")
481
482
# Show required labels
483
print(" Required labels:")
484
for label in descriptor.labels:
485
print(f" - {label.key}: {label.description}")
486
487
# Get specific channel type descriptor
488
email_descriptor_name = f"projects/{project_id}/notificationChannelDescriptors/email"
489
email_descriptor = client.get_notification_channel_descriptor(name=email_descriptor_name)
490
print(f"\nEmail channel descriptor: {email_descriptor.display_name}")
491
for label in email_descriptor.labels:
492
print(f" {label.key}: {label.description} (required: {label.value_type})")
493
```
494
495
### Creating SMS Notification Channel
496
497
```python
498
# Create SMS notification channel
499
sms_channel = notification_pb2.NotificationChannel()
500
sms_channel.type = "sms"
501
sms_channel.display_name = "On-call SMS Alerts"
502
sms_channel.description = "SMS notifications for critical incidents"
503
504
# Set phone number
505
sms_channel.labels["number"] = "+1234567890"
506
507
created_sms = client.create_notification_channel(
508
name=project_name,
509
notification_channel=sms_channel
510
)
511
print(f"Created SMS channel: {created_sms.name}")
512
513
# SMS channels typically require verification
514
client.send_notification_channel_verification_code(name=created_sms.name)
515
print("SMS verification code sent")
516
```
517
518
### Deleting Notification Channels
519
520
```python
521
channel_name = f"projects/{project_id}/notificationChannels/{channel_id}"
522
523
try:
524
# Regular deletion
525
client.delete_notification_channel(name=channel_name)
526
print("Channel deleted successfully")
527
except Exception as e:
528
print(f"Could not delete channel: {e}")
529
530
# Force deletion even if referenced by alert policies
531
client.delete_notification_channel(name=channel_name, force=True)
532
print("Channel force deleted")
533
```
534
535
### Async Notification Operations
536
537
```python
538
import asyncio
539
from google.cloud.monitoring import NotificationChannelServiceAsyncClient
540
541
async def manage_notifications():
542
client = NotificationChannelServiceAsyncClient()
543
project_name = f"projects/{project_id}"
544
545
# List channels asynchronously
546
async for channel in await client.list_notification_channels(name=project_name):
547
print(f"Async channel: {channel.display_name}")
548
549
# Create channel asynchronously
550
new_channel = notification_pb2.NotificationChannel()
551
new_channel.type = "email"
552
new_channel.display_name = "Async Created Email"
553
new_channel.labels["email_address"] = "async@example.com"
554
555
created = await client.create_notification_channel(
556
name=project_name,
557
notification_channel=new_channel
558
)
559
print(f"Async created channel: {created.name}")
560
561
asyncio.run(manage_notifications())
562
```
563
564
## Resource Path Helpers
565
566
```python { .api }
567
class NotificationChannelServiceClient:
568
@staticmethod
569
def notification_channel_path(project: str, notification_channel: str) -> str:
570
"""Returns a fully-qualified notification_channel string."""
571
572
@staticmethod
573
def notification_channel_descriptor_path(project: str, channel_descriptor: str) -> str:
574
"""Returns a fully-qualified notification_channel_descriptor string."""
575
576
@staticmethod
577
def parse_notification_channel_path(path: str) -> Dict[str, str]:
578
"""Parses a notification_channel path into its component segments."""
579
```
580
581
## Error Handling
582
583
Notification channel operations can raise specific exceptions:
584
585
```python
586
from google.api_core import exceptions
587
from google.cloud.monitoring import NotificationChannelServiceClient
588
589
client = NotificationChannelServiceClient()
590
591
try:
592
channel = client.get_notification_channel(name="invalid/path")
593
except exceptions.NotFound:
594
print("Notification channel not found")
595
except exceptions.InvalidArgument as e:
596
print(f"Invalid channel configuration: {e}")
597
except exceptions.PermissionDenied:
598
print("Insufficient permissions")
599
except exceptions.FailedPrecondition as e:
600
print(f"Channel verification required: {e}")
601
```