in monitoring/alert/alert.go [186:269]
func restorePolicies(w io.Writer, projectID string, r io.Reader) error {
b := backup{}
if err := json.NewDecoder(r).Decode(&b); err != nil {
return err
}
sameProject := projectID == b.ProjectID
ctx := context.Background()
alertClient, err := monitoring.NewAlertPolicyClient(ctx)
if err != nil {
return err
}
defer alertClient.Close()
channelClient, err := monitoring.NewNotificationChannelClient(ctx)
if err != nil {
return err
}
defer channelClient.Close()
// When a channel is recreated, rather than updated, it will get
// a new name. We have to update the AlertPolicy with the new
// name. channelNames keeps track of the new names.
channelNames := make(map[string]string)
for _, c := range b.Channels {
fmt.Fprintf(w, "Updating channel %q\n", c.GetDisplayName())
c.VerificationStatus = monitoringpb.NotificationChannel_VERIFICATION_STATUS_UNSPECIFIED
updated := false
if sameProject {
req := &monitoringpb.UpdateNotificationChannelRequest{
NotificationChannel: c.NotificationChannel,
}
_, err := channelClient.UpdateNotificationChannel(ctx, req)
if err == nil {
updated = true
}
}
if !updated {
req := &monitoringpb.CreateNotificationChannelRequest{
Name: "projects/" + projectID,
NotificationChannel: c.NotificationChannel,
}
oldName := c.GetName()
c.Name = ""
newC, err := channelClient.CreateNotificationChannel(ctx, req)
if err != nil {
return err
}
channelNames[oldName] = newC.GetName()
}
}
for _, policy := range b.AlertPolicies {
fmt.Fprintf(w, "Updating alert %q\n", policy.GetDisplayName())
policy.CreationRecord = nil
policy.MutationRecord = nil
for i, aChannel := range policy.GetNotificationChannels() {
if c, ok := channelNames[aChannel]; ok {
policy.NotificationChannels[i] = c
}
}
updated := false
if sameProject {
req := &monitoringpb.UpdateAlertPolicyRequest{
AlertPolicy: policy.AlertPolicy,
}
_, err := alertClient.UpdateAlertPolicy(ctx, req)
if err == nil {
updated = true
}
}
if !updated {
req := &monitoringpb.CreateAlertPolicyRequest{
Name: "projects/" + projectID,
AlertPolicy: policy.AlertPolicy,
}
if _, err = alertClient.CreateAlertPolicy(ctx, req); err != nil {
log.Fatal(err)
}
}
}
fmt.Fprintf(w, "Successfully restored alerts.")
return nil
}