def backup(project_name, backup_filename):
"""Backup alert policies from a project to a local file.
Arguments:
project_name (str): The Google Cloud Project to use. The project name
must be in the format - 'projects/<PROJECT_NAME>'
backup_filename (str): Name of the file (along with its path) to which
the alert policies will be written as backup.
"""
alert_client = monitoring_v3.AlertPolicyServiceClient()
channel_client = monitoring_v3.NotificationChannelServiceClient()
record = {
"project_name": project_name,
"policies": list(alert_client.list_alert_policies(name=project_name)),
"channels": list(channel_client.list_notification_channels(name=project_name)),
}
json.dump(record, open(backup_filename, "wt"), cls=ProtoEncoder, indent=2)
print(
"Backed up alert policies and notification channels to {}.".format(
backup_filename
)
)
class ProtoEncoder(json.JSONEncoder):
"""Encode protobufs as json."""
def default(self, obj):
if type(obj) in (monitoring_v3.AlertPolicy, monitoring_v3.NotificationChannel):
text = proto.Message.to_json(obj)
return json.loads(text)
return super(ProtoEncoder, self).default(obj)