Skip to content

Commit 1001e43

Browse files
committed
ran black
1 parent 6cef85e commit 1001e43

File tree

12 files changed

+344
-316
lines changed

12 files changed

+344
-316
lines changed

monitoring/api/v3/alerts-client/snippets.py

Lines changed: 122 additions & 106 deletions
Original file line numberDiff line numberDiff line change
@@ -27,19 +27,29 @@
2727
def list_alert_policies(project_name):
2828
client = monitoring_v3.AlertPolicyServiceClient()
2929
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+
3338
# [END monitoring_alert_list_policies]
3439

3540

3641
# [START monitoring_alert_list_channels]
3742
def list_notification_channels(project_name):
3843
client = monitoring_v3.NotificationChannelServiceClient()
3944
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+
4353
# [END monitoring_alert_list_channels]
4454

4555

@@ -60,76 +70,92 @@ def enable_alert_policies(project_name, enable, filter_=None):
6070

6171
for policy in policies:
6272
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+
)
6579
else:
6680
policy.enabled.value = bool(enable)
6781
mask = monitoring_v3.types.field_mask_pb2.FieldMask()
68-
mask.paths.append('enabled')
82+
mask.paths.append("enabled")
6983
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+
7187
# [END monitoring_alert_enable_policies]
7288

7389

7490
# [START monitoring_alert_replace_channels]
7591
def replace_notification_channels(project_name, alert_policy_id, channel_ids):
76-
_, project_id = project_name.split('/')
92+
_, project_id = project_name.split("/")
7793
alert_client = monitoring_v3.AlertPolicyServiceClient()
7894
channel_client = monitoring_v3.NotificationChannelServiceClient()
7995
policy = monitoring_v3.types.alert_pb2.AlertPolicy()
8096
policy.name = alert_client.alert_policy_path(project_id, alert_policy_id)
8197

8298
for channel_id in channel_ids:
8399
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+
)
85102

86103
mask = monitoring_v3.types.field_mask_pb2.FieldMask()
87-
mask.paths.append('notification_channels')
104+
mask.paths.append("notification_channels")
88105
updated_policy = alert_client.update_alert_policy(policy, mask)
89-
print('Updated', updated_policy.name)
106+
print("Updated", updated_policy.name)
107+
108+
90109
# [END monitoring_alert_replace_channels]
91110

92111

93112
# [START monitoring_alert_delete_channel]
94113
def delete_notification_channels(project_name, channel_ids, force=None):
95114
channel_client = monitoring_v3.NotificationChannelServiceClient()
96115
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)
99117
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))
103120
except ValueError:
104-
print('The parameters are invalid')
121+
print("The parameters are invalid")
105122
except Exception as e:
106-
print('API call failed: {}'.format(e))
123+
print("API call failed: {}".format(e))
124+
125+
107126
# [END monitoring_alert_delete_channel]
108127

109128

110129
# [START monitoring_alert_backup_policies]
111130
def backup(project_name, backup_filename):
112131
alert_client = monitoring_v3.AlertPolicyServiceClient()
113132
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+
)
121143
)
122144

123145

124146
class ProtoEncoder(json.JSONEncoder):
125147
"""Uses google.protobuf.json_format to encode protobufs as json."""
148+
126149
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+
):
130154
text = google.protobuf.json_format.MessageToJson(obj)
131155
return json.loads(text)
132156
return super(ProtoEncoder, self).default(obj)
157+
158+
133159
# [END monitoring_alert_backup_policies]
134160

135161

@@ -139,34 +165,43 @@ def default(self, obj):
139165
# [START monitoring_alert_update_channel]
140166
# [START monitoring_alert_enable_channel]
141167
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+
)
144172
)
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"]
147175
# 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+
]
152183
# 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+
]
157191

158192
# Restore the channels.
159193
channel_client = monitoring_v3.NotificationChannelServiceClient()
160194
channel_name_map = {}
161195

162196
for channel in channels:
163197
updated = False
164-
print('Updating channel', channel.display_name)
198+
print("Updating channel", channel.display_name)
165199
# This field is immutable and it is illegal to specify a
166200
# non-default value (UNVERIFIED or VERIFIED) in the
167201
# 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+
)
170205

171206
if is_same_project:
172207
try:
@@ -180,17 +215,18 @@ def restore(project_name, backup_filename):
180215
old_name = channel.name
181216
channel.ClearField("name")
182217
new_channel = channel_client.create_notification_channel(
183-
project_name, channel)
218+
project_name, channel
219+
)
184220
channel_name_map[old_name] = new_channel.name
185221

186222
# Restore the alerts
187223
alert_client = monitoring_v3.AlertPolicyServiceClient()
188224

189225
for policy in policies:
190-
print('Updating policy', policy.display_name)
226+
print("Updating policy", policy.display_name)
191227
# 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")
194230

195231
# Update old channel names with new channel names.
196232
for i, channel in enumerate(policy.notification_channels):
@@ -218,7 +254,9 @@ def restore(project_name, backup_filename):
218254
for condition in policy.conditions:
219255
condition.ClearField("name")
220256
policy = alert_client.create_alert_policy(project_name, policy)
221-
print('Updated', policy.name)
257+
print("Updated", policy.name)
258+
259+
222260
# [END monitoring_alert_enable_channel]
223261
# [END monitoring_alert_restore_policies]
224262
# [END monitoring_alert_create_policy]
@@ -239,105 +277,83 @@ def project_id():
239277
Returns:
240278
str -- the project name
241279
"""
242-
project_id = os.environ['GCLOUD_PROJECT']
280+
project_id = os.environ["GCLOUD_PROJECT"]
243281

244282
if not project_id:
245283
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+
)
248287
return project_id
249288

250289

251290
def project_name():
252-
return 'projects/' + project_id()
291+
return "projects/" + project_id()
253292

254293

255-
if __name__ == '__main__':
294+
if __name__ == "__main__":
256295

257296
parser = argparse.ArgumentParser(
258-
description='Demonstrates AlertPolicy API operations.')
297+
description="Demonstrates AlertPolicy API operations."
298+
)
259299

260-
subparsers = parser.add_subparsers(dest='command')
300+
subparsers = parser.add_subparsers(dest="command")
261301

262302
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__
265304
)
266305

267306
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__
270308
)
271309

272310
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__
278312
)
313+
enable_alert_policies_parser.add_argument("--filter",)
279314

280315
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__
286317
)
318+
disable_alert_policies_parser.add_argument("--filter",)
287319

288320
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__
291322
)
292323
replace_notification_channels_parser.add_argument(
293-
'-p', '--alert_policy_id',
294-
required=True
324+
"-p", "--alert_policy_id", required=True
295325
)
296326
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"
300328
)
301329

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)
310332

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)
319335

320336
args = parser.parse_args()
321337

322-
if args.command == 'list-alert-policies':
338+
if args.command == "list-alert-policies":
323339
list_alert_policies(project_name())
324340

325-
elif args.command == 'list-notification-channels':
341+
elif args.command == "list-notification-channels":
326342
list_notification_channels(project_name())
327343

328-
elif args.command == 'enable-alert-policies':
344+
elif args.command == "enable-alert-policies":
329345
enable_alert_policies(project_name(), enable=True, filter_=args.filter)
330346

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)
334349

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+
)
338354

339-
elif args.command == 'backup':
355+
elif args.command == "backup":
340356
backup(project_name(), args.backup_to_filename)
341357

342-
elif args.command == 'restore':
358+
elif args.command == "restore":
343359
restore(project_name(), args.restore_from_filename)

0 commit comments

Comments
 (0)