27
27
def list_alert_policies (project_name ):
28
28
client = monitoring_v3 .AlertPolicyServiceClient ()
29
29
policies = client .list_alert_policies (project_name )
30
- print (tabulate .tabulate (
31
- [(policy .name , policy .display_name ) for policy in policies ],
32
- ('name' , 'display_name' )))
30
+ print (
31
+ tabulate .tabulate (
32
+ [(policy .name , policy .display_name ) for policy in policies ],
33
+ ("name" , "display_name" ),
34
+ )
35
+ )
36
+
37
+
33
38
# [END monitoring_alert_list_policies]
34
39
35
40
36
41
# [START monitoring_alert_list_channels]
37
42
def list_notification_channels (project_name ):
38
43
client = monitoring_v3 .NotificationChannelServiceClient ()
39
44
channels = client .list_notification_channels (project_name )
40
- print (tabulate .tabulate (
41
- [(channel .name , channel .display_name ) for channel in channels ],
42
- ('name' , 'display_name' )))
45
+ print (
46
+ tabulate .tabulate (
47
+ [(channel .name , channel .display_name ) for channel in channels ],
48
+ ("name" , "display_name" ),
49
+ )
50
+ )
51
+
52
+
43
53
# [END monitoring_alert_list_channels]
44
54
45
55
@@ -60,76 +70,92 @@ def enable_alert_policies(project_name, enable, filter_=None):
60
70
61
71
for policy in policies :
62
72
if bool (enable ) == policy .enabled .value :
63
- print ('Policy' , policy .name , 'is already' ,
64
- 'enabled' if policy .enabled .value else 'disabled' )
73
+ print (
74
+ "Policy" ,
75
+ policy .name ,
76
+ "is already" ,
77
+ "enabled" if policy .enabled .value else "disabled" ,
78
+ )
65
79
else :
66
80
policy .enabled .value = bool (enable )
67
81
mask = monitoring_v3 .types .field_mask_pb2 .FieldMask ()
68
- mask .paths .append (' enabled' )
82
+ mask .paths .append (" enabled" )
69
83
client .update_alert_policy (policy , mask )
70
- print ('Enabled' if enable else 'Disabled' , policy .name )
84
+ print ("Enabled" if enable else "Disabled" , policy .name )
85
+
86
+
71
87
# [END monitoring_alert_enable_policies]
72
88
73
89
74
90
# [START monitoring_alert_replace_channels]
75
91
def replace_notification_channels (project_name , alert_policy_id , channel_ids ):
76
- _ , project_id = project_name .split ('/' )
92
+ _ , project_id = project_name .split ("/" )
77
93
alert_client = monitoring_v3 .AlertPolicyServiceClient ()
78
94
channel_client = monitoring_v3 .NotificationChannelServiceClient ()
79
95
policy = monitoring_v3 .types .alert_pb2 .AlertPolicy ()
80
96
policy .name = alert_client .alert_policy_path (project_id , alert_policy_id )
81
97
82
98
for channel_id in channel_ids :
83
99
policy .notification_channels .append (
84
- channel_client .notification_channel_path (project_id , channel_id ))
100
+ channel_client .notification_channel_path (project_id , channel_id )
101
+ )
85
102
86
103
mask = monitoring_v3 .types .field_mask_pb2 .FieldMask ()
87
- mask .paths .append (' notification_channels' )
104
+ mask .paths .append (" notification_channels" )
88
105
updated_policy = alert_client .update_alert_policy (policy , mask )
89
- print ('Updated' , updated_policy .name )
106
+ print ("Updated" , updated_policy .name )
107
+
108
+
90
109
# [END monitoring_alert_replace_channels]
91
110
92
111
93
112
# [START monitoring_alert_delete_channel]
94
113
def delete_notification_channels (project_name , channel_ids , force = None ):
95
114
channel_client = monitoring_v3 .NotificationChannelServiceClient ()
96
115
for channel_id in channel_ids :
97
- channel_name = '{}/notificationChannels/{}' .format (
98
- project_name , channel_id )
116
+ channel_name = "{}/notificationChannels/{}" .format (project_name , channel_id )
99
117
try :
100
- channel_client .delete_notification_channel (
101
- channel_name , force = force )
102
- print ('Channel {} deleted' .format (channel_name ))
118
+ channel_client .delete_notification_channel (channel_name , force = force )
119
+ print ("Channel {} deleted" .format (channel_name ))
103
120
except ValueError :
104
- print (' The parameters are invalid' )
121
+ print (" The parameters are invalid" )
105
122
except Exception as e :
106
- print ('API call failed: {}' .format (e ))
123
+ print ("API call failed: {}" .format (e ))
124
+
125
+
107
126
# [END monitoring_alert_delete_channel]
108
127
109
128
110
129
# [START monitoring_alert_backup_policies]
111
130
def backup (project_name , backup_filename ):
112
131
alert_client = monitoring_v3 .AlertPolicyServiceClient ()
113
132
channel_client = monitoring_v3 .NotificationChannelServiceClient ()
114
- record = {'project_name' : project_name ,
115
- 'policies' : list (alert_client .list_alert_policies (project_name )),
116
- 'channels' : list (channel_client .list_notification_channels (
117
- project_name ))}
118
- json .dump (record , open (backup_filename , 'wt' ), cls = ProtoEncoder , indent = 2 )
119
- print ('Backed up alert policies and notification channels to {}.' .format (
120
- backup_filename )
133
+ record = {
134
+ "project_name" : project_name ,
135
+ "policies" : list (alert_client .list_alert_policies (project_name )),
136
+ "channels" : list (channel_client .list_notification_channels (project_name )),
137
+ }
138
+ json .dump (record , open (backup_filename , "wt" ), cls = ProtoEncoder , indent = 2 )
139
+ print (
140
+ "Backed up alert policies and notification channels to {}." .format (
141
+ backup_filename
142
+ )
121
143
)
122
144
123
145
124
146
class ProtoEncoder (json .JSONEncoder ):
125
147
"""Uses google.protobuf.json_format to encode protobufs as json."""
148
+
126
149
def default (self , obj ):
127
- if type (obj ) in (monitoring_v3 .types .alert_pb2 .AlertPolicy ,
128
- monitoring_v3 .types .notification_pb2 .
129
- NotificationChannel ):
150
+ if type (obj ) in (
151
+ monitoring_v3 .types .alert_pb2 .AlertPolicy ,
152
+ monitoring_v3 .types .notification_pb2 .NotificationChannel ,
153
+ ):
130
154
text = google .protobuf .json_format .MessageToJson (obj )
131
155
return json .loads (text )
132
156
return super (ProtoEncoder , self ).default (obj )
157
+
158
+
133
159
# [END monitoring_alert_backup_policies]
134
160
135
161
@@ -139,34 +165,43 @@ def default(self, obj):
139
165
# [START monitoring_alert_update_channel]
140
166
# [START monitoring_alert_enable_channel]
141
167
def restore (project_name , backup_filename ):
142
- print ('Loading alert policies and notification channels from {}.' .format (
143
- backup_filename )
168
+ print (
169
+ "Loading alert policies and notification channels from {}." .format (
170
+ backup_filename
171
+ )
144
172
)
145
- record = json .load (open (backup_filename , 'rt' ))
146
- is_same_project = project_name == record [' project_name' ]
173
+ record = json .load (open (backup_filename , "rt" ))
174
+ is_same_project = project_name == record [" project_name" ]
147
175
# Convert dicts to AlertPolicies.
148
- policies_json = [json .dumps (policy ) for policy in record ['policies' ]]
149
- policies = [google .protobuf .json_format .Parse (
150
- policy_json , monitoring_v3 .types .alert_pb2 .AlertPolicy ())
151
- for policy_json in policies_json ]
176
+ policies_json = [json .dumps (policy ) for policy in record ["policies" ]]
177
+ policies = [
178
+ google .protobuf .json_format .Parse (
179
+ policy_json , monitoring_v3 .types .alert_pb2 .AlertPolicy ()
180
+ )
181
+ for policy_json in policies_json
182
+ ]
152
183
# Convert dicts to NotificationChannels
153
- channels_json = [json .dumps (channel ) for channel in record ['channels' ]]
154
- channels = [google .protobuf .json_format .Parse (
155
- channel_json , monitoring_v3 .types .notification_pb2 .
156
- NotificationChannel ()) for channel_json in channels_json ]
184
+ channels_json = [json .dumps (channel ) for channel in record ["channels" ]]
185
+ channels = [
186
+ google .protobuf .json_format .Parse (
187
+ channel_json , monitoring_v3 .types .notification_pb2 .NotificationChannel ()
188
+ )
189
+ for channel_json in channels_json
190
+ ]
157
191
158
192
# Restore the channels.
159
193
channel_client = monitoring_v3 .NotificationChannelServiceClient ()
160
194
channel_name_map = {}
161
195
162
196
for channel in channels :
163
197
updated = False
164
- print (' Updating channel' , channel .display_name )
198
+ print (" Updating channel" , channel .display_name )
165
199
# This field is immutable and it is illegal to specify a
166
200
# non-default value (UNVERIFIED or VERIFIED) in the
167
201
# Create() or Update() operations.
168
- channel .verification_status = monitoring_v3 .enums .NotificationChannel .\
169
- VerificationStatus .VERIFICATION_STATUS_UNSPECIFIED
202
+ channel .verification_status = (
203
+ monitoring_v3 .enums .NotificationChannel .VerificationStatus .VERIFICATION_STATUS_UNSPECIFIED
204
+ )
170
205
171
206
if is_same_project :
172
207
try :
@@ -180,17 +215,18 @@ def restore(project_name, backup_filename):
180
215
old_name = channel .name
181
216
channel .ClearField ("name" )
182
217
new_channel = channel_client .create_notification_channel (
183
- project_name , channel )
218
+ project_name , channel
219
+ )
184
220
channel_name_map [old_name ] = new_channel .name
185
221
186
222
# Restore the alerts
187
223
alert_client = monitoring_v3 .AlertPolicyServiceClient ()
188
224
189
225
for policy in policies :
190
- print (' Updating policy' , policy .display_name )
226
+ print (" Updating policy" , policy .display_name )
191
227
# These two fields cannot be set directly, so clear them.
192
- policy .ClearField (' creation_record' )
193
- policy .ClearField (' mutation_record' )
228
+ policy .ClearField (" creation_record" )
229
+ policy .ClearField (" mutation_record" )
194
230
195
231
# Update old channel names with new channel names.
196
232
for i , channel in enumerate (policy .notification_channels ):
@@ -218,7 +254,9 @@ def restore(project_name, backup_filename):
218
254
for condition in policy .conditions :
219
255
condition .ClearField ("name" )
220
256
policy = alert_client .create_alert_policy (project_name , policy )
221
- print ('Updated' , policy .name )
257
+ print ("Updated" , policy .name )
258
+
259
+
222
260
# [END monitoring_alert_enable_channel]
223
261
# [END monitoring_alert_restore_policies]
224
262
# [END monitoring_alert_create_policy]
@@ -239,105 +277,83 @@ def project_id():
239
277
Returns:
240
278
str -- the project name
241
279
"""
242
- project_id = os .environ [' GCLOUD_PROJECT' ]
280
+ project_id = os .environ [" GCLOUD_PROJECT" ]
243
281
244
282
if not project_id :
245
283
raise MissingProjectIdError (
246
- 'Set the environment variable ' +
247
- 'GCLOUD_PROJECT to your Google Cloud Project Id.' )
284
+ "Set the environment variable "
285
+ + "GCLOUD_PROJECT to your Google Cloud Project Id."
286
+ )
248
287
return project_id
249
288
250
289
251
290
def project_name ():
252
- return ' projects/' + project_id ()
291
+ return " projects/" + project_id ()
253
292
254
293
255
- if __name__ == ' __main__' :
294
+ if __name__ == " __main__" :
256
295
257
296
parser = argparse .ArgumentParser (
258
- description = 'Demonstrates AlertPolicy API operations.' )
297
+ description = "Demonstrates AlertPolicy API operations."
298
+ )
259
299
260
- subparsers = parser .add_subparsers (dest = ' command' )
300
+ subparsers = parser .add_subparsers (dest = " command" )
261
301
262
302
list_alert_policies_parser = subparsers .add_parser (
263
- 'list-alert-policies' ,
264
- help = list_alert_policies .__doc__
303
+ "list-alert-policies" , help = list_alert_policies .__doc__
265
304
)
266
305
267
306
list_notification_channels_parser = subparsers .add_parser (
268
- 'list-notification-channels' ,
269
- help = list_alert_policies .__doc__
307
+ "list-notification-channels" , help = list_alert_policies .__doc__
270
308
)
271
309
272
310
enable_alert_policies_parser = subparsers .add_parser (
273
- 'enable-alert-policies' ,
274
- help = enable_alert_policies .__doc__
275
- )
276
- enable_alert_policies_parser .add_argument (
277
- '--filter' ,
311
+ "enable-alert-policies" , help = enable_alert_policies .__doc__
278
312
)
313
+ enable_alert_policies_parser .add_argument ("--filter" ,)
279
314
280
315
disable_alert_policies_parser = subparsers .add_parser (
281
- 'disable-alert-policies' ,
282
- help = enable_alert_policies .__doc__
283
- )
284
- disable_alert_policies_parser .add_argument (
285
- '--filter' ,
316
+ "disable-alert-policies" , help = enable_alert_policies .__doc__
286
317
)
318
+ disable_alert_policies_parser .add_argument ("--filter" ,)
287
319
288
320
replace_notification_channels_parser = subparsers .add_parser (
289
- 'replace-notification-channels' ,
290
- help = replace_notification_channels .__doc__
321
+ "replace-notification-channels" , help = replace_notification_channels .__doc__
291
322
)
292
323
replace_notification_channels_parser .add_argument (
293
- '-p' , '--alert_policy_id' ,
294
- required = True
324
+ "-p" , "--alert_policy_id" , required = True
295
325
)
296
326
replace_notification_channels_parser .add_argument (
297
- '-c' , '--notification_channel_id' ,
298
- required = True ,
299
- action = 'append'
327
+ "-c" , "--notification_channel_id" , required = True , action = "append"
300
328
)
301
329
302
- backup_parser = subparsers .add_parser (
303
- 'backup' ,
304
- help = backup .__doc__
305
- )
306
- backup_parser .add_argument (
307
- '--backup_to_filename' ,
308
- required = True
309
- )
330
+ backup_parser = subparsers .add_parser ("backup" , help = backup .__doc__ )
331
+ backup_parser .add_argument ("--backup_to_filename" , required = True )
310
332
311
- restore_parser = subparsers .add_parser (
312
- 'restore' ,
313
- help = restore .__doc__
314
- )
315
- restore_parser .add_argument (
316
- '--restore_from_filename' ,
317
- required = True
318
- )
333
+ restore_parser = subparsers .add_parser ("restore" , help = restore .__doc__ )
334
+ restore_parser .add_argument ("--restore_from_filename" , required = True )
319
335
320
336
args = parser .parse_args ()
321
337
322
- if args .command == ' list-alert-policies' :
338
+ if args .command == " list-alert-policies" :
323
339
list_alert_policies (project_name ())
324
340
325
- elif args .command == ' list-notification-channels' :
341
+ elif args .command == " list-notification-channels" :
326
342
list_notification_channels (project_name ())
327
343
328
- elif args .command == ' enable-alert-policies' :
344
+ elif args .command == " enable-alert-policies" :
329
345
enable_alert_policies (project_name (), enable = True , filter_ = args .filter )
330
346
331
- elif args .command == 'disable-alert-policies' :
332
- enable_alert_policies (project_name (), enable = False ,
333
- filter_ = args .filter )
347
+ elif args .command == "disable-alert-policies" :
348
+ enable_alert_policies (project_name (), enable = False , filter_ = args .filter )
334
349
335
- elif args .command == 'replace-notification-channels' :
336
- replace_notification_channels (project_name (), args .alert_policy_id ,
337
- args .notification_channel_id )
350
+ elif args .command == "replace-notification-channels" :
351
+ replace_notification_channels (
352
+ project_name (), args .alert_policy_id , args .notification_channel_id
353
+ )
338
354
339
- elif args .command == ' backup' :
355
+ elif args .command == " backup" :
340
356
backup (project_name (), args .backup_to_filename )
341
357
342
- elif args .command == ' restore' :
358
+ elif args .command == " restore" :
343
359
restore (project_name (), args .restore_from_filename )
0 commit comments