0
# Alert Suppression (Snooze)
1
2
Comprehensive alert suppression functionality for temporarily preventing alert policies from generating notifications in Google Cloud Monitoring. Snooze functionality allows planned maintenance windows and temporary alert silencing with configurable duration and criteria.
3
4
## Capabilities
5
6
### Snooze Operations
7
8
Manage the complete lifecycle of snooze configurations including creation, updates, retrieval, and listing.
9
10
```python { .api }
11
class SnoozeServiceClient:
12
def create_snooze(
13
self,
14
request=None,
15
*,
16
parent: str = None,
17
snooze=None,
18
retry=None,
19
timeout=None,
20
metadata=()
21
) -> snooze.Snooze:
22
"""
23
Creates a Snooze that will prevent alerts.
24
25
Args:
26
request: The request object or dict equivalent
27
parent: Required. Project name in format 'projects/[PROJECT_ID]'
28
snooze: Required. The Snooze to create
29
retry: Retry configuration
30
timeout: Request timeout in seconds
31
metadata: Additional metadata
32
33
Returns:
34
Created Snooze object
35
"""
36
37
def list_snoozes(
38
self,
39
request=None,
40
*,
41
parent: str = None,
42
retry=None,
43
timeout=None,
44
metadata=()
45
) -> pagers.ListSnoozesPager:
46
"""
47
Lists the existing valid Snooze records.
48
49
Args:
50
request: The request object or dict equivalent
51
parent: Required. Project name
52
retry: Retry configuration
53
timeout: Request timeout in seconds
54
metadata: Additional metadata
55
56
Returns:
57
Pager for iterating over Snooze objects
58
"""
59
60
def get_snooze(
61
self,
62
request=None,
63
*,
64
name: str = None,
65
retry=None,
66
timeout=None,
67
metadata=()
68
) -> snooze.Snooze:
69
"""
70
Retrieves a Snooze by name.
71
72
Args:
73
request: The request object or dict equivalent
74
name: Required. Snooze name in format 'projects/[PROJECT_ID]/snoozes/[SNOOZE_ID]'
75
retry: Retry configuration
76
timeout: Request timeout in seconds
77
metadata: Additional metadata
78
79
Returns:
80
Snooze object
81
"""
82
83
def update_snooze(
84
self,
85
request=None,
86
*,
87
snooze=None,
88
update_mask=None,
89
retry=None,
90
timeout=None,
91
metadata=()
92
) -> snooze.Snooze:
93
"""
94
Updates a Snooze, identified by its name.
95
96
Args:
97
request: The request object or dict equivalent
98
snooze: Required. Updated Snooze
99
update_mask: Field mask for selective updates
100
retry: Retry configuration
101
timeout: Request timeout in seconds
102
metadata: Additional metadata
103
104
Returns:
105
Updated Snooze object
106
"""
107
```
108
109
## Data Types
110
111
### Snooze
112
113
Represents a snooze configuration for suppressing alerts.
114
115
```python { .api }
116
class Snooze:
117
name: str # Resource name
118
criteria: Snooze.Criteria # Criteria for when snooze applies
119
interval: TimeInterval # Time interval when snooze is active
120
display_name: str # Human-readable name
121
```
122
123
### Snooze.Criteria
124
125
Defines the criteria for when a snooze should suppress alerts.
126
127
```python { .api }
128
class Snooze.Criteria:
129
policies: List[str] # Alert policy names to snooze
130
```
131
132
### Request and Response Types
133
134
```python { .api }
135
class CreateSnoozeRequest:
136
parent: str # Required. Project name
137
snooze: Snooze # Required. Snooze to create
138
139
class GetSnoozeRequest:
140
name: str # Required. Snooze name to retrieve
141
142
class ListSnoozesRequest:
143
parent: str # Required. Project name
144
filter: str # Filter expression
145
page_size: int # Maximum results per page
146
page_token: str # Page token
147
148
class ListSnoozesResponse:
149
snoozes: List[Snooze] # Snoozes
150
next_page_token: str # Next page token
151
152
class UpdateSnoozeRequest:
153
snooze: Snooze # Required. Updated snooze
154
update_mask: FieldMask # Fields to update
155
```
156
157
## Usage Examples
158
159
### Creating a Basic Snooze for Maintenance Window
160
161
```python
162
from google.cloud.monitoring import SnoozeServiceClient
163
from google.cloud.monitoring_v3.types import Snooze, TimeInterval
164
from google.protobuf.timestamp_pb2 import Timestamp
165
import time
166
167
client = SnoozeServiceClient()
168
project_name = f"projects/{project_id}"
169
170
# Create snooze for maintenance window
171
snooze_obj = Snooze()
172
snooze_obj.display_name = "Weekly Maintenance Window"
173
174
# Define snooze criteria
175
criteria = Snooze.Criteria()
176
criteria.policies = [
177
f"projects/{project_id}/alertPolicies/{alert_policy_id_1}",
178
f"projects/{project_id}/alertPolicies/{alert_policy_id_2}"
179
]
180
snooze_obj.criteria = criteria
181
182
# Define time interval (next Sunday 2-4 AM)
183
now = time.time()
184
start_time = now + (6 * 24 * 60 * 60) # Next Sunday
185
end_time = start_time + (2 * 60 * 60) # 2 hours later
186
187
interval = TimeInterval()
188
interval.start_time.seconds = int(start_time)
189
interval.end_time.seconds = int(end_time)
190
snooze_obj.interval = interval
191
192
created_snooze = client.create_snooze(
193
parent=project_name,
194
snooze=snooze_obj
195
)
196
print(f"Created snooze: {created_snooze.name}")
197
print(f"Display name: {created_snooze.display_name}")
198
print(f"Start time: {created_snooze.interval.start_time}")
199
print(f"End time: {created_snooze.interval.end_time}")
200
```
201
202
### Creating an Emergency Snooze
203
204
```python
205
from datetime import datetime, timedelta
206
207
# Create emergency snooze to suppress all alerts temporarily
208
emergency_snooze = Snooze()
209
emergency_snooze.display_name = "Emergency Alert Suppression"
210
211
# Snooze all alert policies in the project
212
criteria = Snooze.Criteria()
213
# You would populate this with actual alert policy names
214
criteria.policies = [
215
f"projects/{project_id}/alertPolicies/{policy_id}"
216
for policy_id in alert_policy_ids # List of policy IDs
217
]
218
emergency_snooze.criteria = criteria
219
220
# Set interval for next 4 hours
221
now = time.time()
222
interval = TimeInterval()
223
interval.start_time.seconds = int(now)
224
interval.end_time.seconds = int(now + 4 * 60 * 60) # 4 hours
225
emergency_snooze.interval = interval
226
227
created_emergency = client.create_snooze(
228
parent=project_name,
229
snooze=emergency_snooze
230
)
231
print(f"Created emergency snooze: {created_emergency.name}")
232
print(f"Suppressing alerts for 4 hours")
233
```
234
235
### Creating a Scheduled Recurring Snooze
236
237
```python
238
# Create snooze for regular maintenance (happening every week)
239
weekly_snooze = Snooze()
240
weekly_snooze.display_name = "Database Maintenance - Weekly"
241
242
# Define which alert policies to snooze
243
criteria = Snooze.Criteria()
244
criteria.policies = [
245
f"projects/{project_id}/alertPolicies/{database_alert_policy_id}"
246
]
247
weekly_snooze.criteria = criteria
248
249
# Schedule for this Sunday 3-5 AM UTC
250
import datetime
251
now = datetime.datetime.utcnow()
252
days_until_sunday = (6 - now.weekday()) % 7
253
next_sunday = now + datetime.timedelta(days=days_until_sunday)
254
maintenance_start = next_sunday.replace(hour=3, minute=0, second=0, microsecond=0)
255
maintenance_end = maintenance_start + datetime.timedelta(hours=2)
256
257
interval = TimeInterval()
258
interval.start_time.seconds = int(maintenance_start.timestamp())
259
interval.end_time.seconds = int(maintenance_end.timestamp())
260
weekly_snooze.interval = interval
261
262
created_weekly = client.create_snooze(
263
parent=project_name,
264
snooze=weekly_snooze
265
)
266
print(f"Created weekly maintenance snooze: {created_weekly.name}")
267
print(f"Scheduled for: {maintenance_start} - {maintenance_end} UTC")
268
```
269
270
### Listing Active and Upcoming Snoozes
271
272
```python
273
# List all snoozes
274
print("All snoozes:")
275
for snooze_item in client.list_snoozes(parent=project_name):
276
print(f"- {snooze_item.display_name}: {snooze_item.name}")
277
278
start_time = datetime.datetime.fromtimestamp(snooze_item.interval.start_time.seconds)
279
end_time = datetime.datetime.fromtimestamp(snooze_item.interval.end_time.seconds)
280
281
print(f" Start: {start_time}")
282
print(f" End: {end_time}")
283
print(f" Policies: {len(snooze_item.criteria.policies)}")
284
285
# Check if snooze is currently active
286
current_time = time.time()
287
if (snooze_item.interval.start_time.seconds <= current_time <=
288
snooze_item.interval.end_time.seconds):
289
print(" Status: ACTIVE")
290
elif snooze_item.interval.start_time.seconds > current_time:
291
print(" Status: SCHEDULED")
292
else:
293
print(" Status: EXPIRED")
294
295
# Filter for active snoozes only
296
current_timestamp = int(time.time())
297
filter_expr = f'interval.start_time.seconds <= {current_timestamp} AND interval.end_time.seconds >= {current_timestamp}'
298
299
print(f"\nCurrently active snoozes:")
300
for active_snooze in client.list_snoozes(parent=project_name, filter=filter_expr):
301
print(f"- {active_snooze.display_name}")
302
```
303
304
### Updating a Snooze
305
306
```python
307
from google.protobuf import field_mask_pb2
308
309
# Get existing snooze
310
snooze_name = f"projects/{project_id}/snoozes/{snooze_id}"
311
snooze_obj = client.get_snooze(name=snooze_name)
312
313
# Update snooze display name
314
snooze_obj.display_name = "Updated Weekly Maintenance Window"
315
316
# Extend the snooze duration by 1 hour
317
snooze_obj.interval.end_time.seconds += 3600 # Add 1 hour
318
319
# Create field mask for selective update
320
update_mask = field_mask_pb2.FieldMask()
321
update_mask.paths.extend(["display_name", "interval.end_time"])
322
323
updated_snooze = client.update_snooze(
324
snooze=snooze_obj,
325
update_mask=update_mask
326
)
327
print(f"Updated snooze: {updated_snooze.display_name}")
328
print(f"New end time: {datetime.datetime.fromtimestamp(updated_snooze.interval.end_time.seconds)}")
329
```
330
331
### Creating a Snooze for Specific Alert Conditions
332
333
```python
334
# Create snooze that targets specific alert policies based on their display names
335
from google.cloud.monitoring import AlertPolicyServiceClient
336
337
# First, get alert policies to snooze
338
alert_client = AlertPolicyServiceClient()
339
policies_to_snooze = []
340
341
for policy in alert_client.list_alert_policies(name=project_name):
342
# Snooze only high CPU alerts during maintenance
343
if "High CPU" in policy.display_name:
344
policies_to_snooze.append(policy.name)
345
346
if policies_to_snooze:
347
# Create targeted snooze
348
targeted_snooze = Snooze()
349
targeted_snooze.display_name = "CPU Alert Maintenance Snooze"
350
351
criteria = Snooze.Criteria()
352
criteria.policies = policies_to_snooze
353
targeted_snooze.criteria = criteria
354
355
# Set for next planned maintenance
356
now = time.time()
357
maintenance_window = 2 * 60 * 60 # 2 hours
358
359
interval = TimeInterval()
360
interval.start_time.seconds = int(now + 3600) # Start in 1 hour
361
interval.end_time.seconds = int(now + 3600 + maintenance_window)
362
targeted_snooze.interval = interval
363
364
created_targeted = client.create_snooze(
365
parent=project_name,
366
snooze=targeted_snooze
367
)
368
print(f"Created targeted snooze for {len(policies_to_snooze)} CPU alert policies")
369
print(f"Snooze name: {created_targeted.name}")
370
```
371
372
### Working with Snooze Time Zones
373
374
```python
375
import pytz
376
from datetime import datetime
377
378
# Create snooze with specific timezone considerations
379
timezone_snooze = Snooze()
380
timezone_snooze.display_name = "East Coast Maintenance Window"
381
382
criteria = Snooze.Criteria()
383
criteria.policies = [f"projects/{project_id}/alertPolicies/{policy_id}"]
384
timezone_snooze.criteria = criteria
385
386
# Schedule for 2 AM EST (7 AM UTC during standard time)
387
est = pytz.timezone('US/Eastern')
388
utc = pytz.UTC
389
390
# Define maintenance window in EST
391
local_start = est.localize(datetime(2024, 1, 15, 2, 0, 0)) # 2 AM EST
392
local_end = est.localize(datetime(2024, 1, 15, 4, 0, 0)) # 4 AM EST
393
394
# Convert to UTC for API
395
utc_start = local_start.astimezone(utc)
396
utc_end = local_end.astimezone(utc)
397
398
interval = TimeInterval()
399
interval.start_time.seconds = int(utc_start.timestamp())
400
interval.end_time.seconds = int(utc_end.timestamp())
401
timezone_snooze.interval = interval
402
403
created_timezone = client.create_snooze(
404
parent=project_name,
405
snooze=timezone_snooze
406
)
407
print(f"Created timezone-aware snooze: {created_timezone.name}")
408
print(f"Local time: {local_start} - {local_end} EST")
409
print(f"UTC time: {utc_start} - {utc_end} UTC")
410
```
411
412
### Snooze Management Utilities
413
414
```python
415
def get_active_snoozes(client, project_name):
416
"""Get all currently active snoozes."""
417
current_time = int(time.time())
418
active_snoozes = []
419
420
for snooze_item in client.list_snoozes(parent=project_name):
421
if (snooze_item.interval.start_time.seconds <= current_time <=
422
snooze_item.interval.end_time.seconds):
423
active_snoozes.append(snooze_item)
424
425
return active_snoozes
426
427
def get_upcoming_snoozes(client, project_name, hours_ahead=24):
428
"""Get snoozes starting within the next N hours."""
429
current_time = int(time.time())
430
future_time = current_time + (hours_ahead * 3600)
431
upcoming_snoozes = []
432
433
for snooze_item in client.list_snoozes(parent=project_name):
434
if (current_time < snooze_item.interval.start_time.seconds <= future_time):
435
upcoming_snoozes.append(snooze_item)
436
437
return upcoming_snoozes
438
439
# Usage
440
active = get_active_snoozes(client, project_name)
441
print(f"Currently active snoozes: {len(active)}")
442
443
upcoming = get_upcoming_snoozes(client, project_name, 48) # Next 48 hours
444
print(f"Upcoming snoozes (next 48h): {len(upcoming)}")
445
446
for snooze_item in upcoming:
447
start_dt = datetime.datetime.fromtimestamp(snooze_item.interval.start_time.seconds)
448
print(f"- {snooze_item.display_name} starts at {start_dt}")
449
```
450
451
### Async Snooze Operations
452
453
```python
454
import asyncio
455
from google.cloud.monitoring import SnoozeServiceAsyncClient
456
457
async def manage_snoozes():
458
client = SnoozeServiceAsyncClient()
459
project_name = f"projects/{project_id}"
460
461
# List snoozes asynchronously
462
async for snooze_item in await client.list_snoozes(parent=project_name):
463
print(f"Async snooze: {snooze_item.display_name}")
464
465
# Get snooze asynchronously
466
snooze_obj = await client.get_snooze(name=snooze_name)
467
print(f"Retrieved async snooze: {snooze_obj.display_name}")
468
469
# Update snooze asynchronously
470
snooze_obj.display_name = "Async Updated Snooze"
471
updated = await client.update_snooze(snooze=snooze_obj)
472
print(f"Async updated snooze: {updated.display_name}")
473
474
asyncio.run(manage_snoozes())
475
```
476
477
## Resource Path Helpers
478
479
```python { .api }
480
class SnoozeServiceClient:
481
@staticmethod
482
def alert_policy_path(project: str, alert_policy: str) -> str:
483
"""Returns a fully-qualified alert_policy string."""
484
485
@staticmethod
486
def snooze_path(project: str, snooze: str) -> str:
487
"""Returns a fully-qualified snooze string."""
488
489
@staticmethod
490
def parse_snooze_path(path: str) -> Dict[str, str]:
491
"""Parses a snooze path into its component segments."""
492
```
493
494
## Error Handling
495
496
Snooze operations can raise specific exceptions:
497
498
```python
499
from google.api_core import exceptions
500
from google.cloud.monitoring import SnoozeServiceClient
501
502
client = SnoozeServiceClient()
503
504
try:
505
snooze_obj = client.get_snooze(name="invalid/path")
506
except exceptions.NotFound:
507
print("Snooze not found")
508
except exceptions.InvalidArgument as e:
509
print(f"Invalid snooze configuration: {e}")
510
# Common issues: invalid time intervals, non-existent alert policies
511
except exceptions.PermissionDenied:
512
print("Insufficient permissions")
513
except exceptions.FailedPrecondition as e:
514
print(f"Snooze conflict or invalid state: {e}")
515
```
516
517
## Best Practices
518
519
### Snooze Planning and Management
520
521
```python
522
def create_maintenance_snooze_with_validation(
523
client,
524
project_name,
525
alert_policy_ids,
526
start_time,
527
duration_hours,
528
display_name
529
):
530
"""Create a maintenance snooze with proper validation."""
531
532
# Validate alert policies exist
533
alert_client = AlertPolicyServiceClient()
534
valid_policies = []
535
536
for policy_id in alert_policy_ids:
537
policy_name = f"projects/{project_id}/alertPolicies/{policy_id}"
538
try:
539
alert_client.get_alert_policy(name=policy_name)
540
valid_policies.append(policy_name)
541
except exceptions.NotFound:
542
print(f"Warning: Alert policy {policy_id} not found, skipping")
543
544
if not valid_policies:
545
raise ValueError("No valid alert policies provided")
546
547
# Create snooze
548
snooze_obj = Snooze()
549
snooze_obj.display_name = display_name
550
551
criteria = Snooze.Criteria()
552
criteria.policies = valid_policies
553
snooze_obj.criteria = criteria
554
555
# Set time interval
556
end_time = start_time + (duration_hours * 3600)
557
interval = TimeInterval()
558
interval.start_time.seconds = int(start_time)
559
interval.end_time.seconds = int(end_time)
560
snooze_obj.interval = interval
561
562
return client.create_snooze(parent=project_name, snooze=snooze_obj)
563
564
# Usage
565
maintenance_snooze = create_maintenance_snooze_with_validation(
566
client=client,
567
project_name=project_name,
568
alert_policy_ids=["policy1", "policy2", "policy3"],
569
start_time=time.time() + 3600, # Start in 1 hour
570
duration_hours=2,
571
display_name="Validated Maintenance Window"
572
)
573
print(f"Created validated snooze: {maintenance_snooze.name}")
574
```