// backupPolicies writes a JSON representation of the project's alert
// policies and notification channels.
func backupPolicies(w io.Writer, projectID string) error {
b := backup{ProjectID: projectID}
ctx := context.Background()
alertClient, err := monitoring.NewAlertPolicyClient(ctx)
if err != nil {
return err
}
defer alertClient.Close()
alertReq := &monitoringpb.ListAlertPoliciesRequest{
Name: "projects/" + projectID,
// Filter: "", // See https://cloud.google.com/monitoring/api/v3/sorting-and-filtering.
// OrderBy: "", // See https://cloud.google.com/monitoring/api/v3/sorting-and-filtering.
}
alertIt := alertClient.ListAlertPolicies(ctx, alertReq)
for {
resp, err := alertIt.Next()
if err == iterator.Done {
break
}
if err != nil {
return err
}
b.AlertPolicies = append(b.AlertPolicies, &alertPolicy{resp})
}
channelClient, err := monitoring.NewNotificationChannelClient(ctx)
if err != nil {
return err
}
defer channelClient.Close()
channelReq := &monitoringpb.ListNotificationChannelsRequest{
Name: "projects/" + projectID,
// Filter: "", // See https://cloud.google.com/monitoring/api/v3/sorting-and-filtering.
// OrderBy: "", // See https://cloud.google.com/monitoring/api/v3/sorting-and-filtering.
}
channelIt := channelClient.ListNotificationChannels(ctx, channelReq)
for {
resp, err := channelIt.Next()
if err == iterator.Done {
break
}
if err != nil {
return err
}
b.Channels = append(b.Channels, &channel{resp})
}
bs, err := json.MarshalIndent(b, "", " ")
if err != nil {
return err
}
if _, err := w.Write(bs); err != nil {
return err
}
return nil
}
// alertPolicy is a wrapper around the AlertPolicy proto to
// ensure JSON marshaling/unmarshaling works correctly.
type alertPolicy struct {
*monitoringpb.AlertPolicy
}
// channel is a wrapper around the NotificationChannel proto to
// ensure JSON marshaling/unmarshaling works correctly.
type channel struct {
*monitoringpb.NotificationChannel
}
// backup is used to backup and restore a project's policies.
type backup struct {
ProjectID string
AlertPolicies []*alertPolicy
Channels []*channel
}
func (a *alertPolicy) MarshalJSON() ([]byte, error) {
m := &jsonpb.Marshaler{EmitDefaults: true}
b := new(bytes.Buffer)
m.Marshal(b, a.AlertPolicy)
return b.Bytes(), nil
}
func (a *alertPolicy) UnmarshalJSON(b []byte) error {
u := &jsonpb.Unmarshaler{}
a.AlertPolicy = new(monitoringpb.AlertPolicy)
return u.Unmarshal(bytes.NewReader(b), a.AlertPolicy)
}
func (c *channel) MarshalJSON() ([]byte, error) {
m := &jsonpb.Marshaler{}
b := new(bytes.Buffer)
m.Marshal(b, c.NotificationChannel)
return b.Bytes(), nil
}
func (c *channel) UnmarshalJSON(b []byte) error {
u := &jsonpb.Unmarshaler{}
c.NotificationChannel = new(monitoringpb.NotificationChannel)
return u.Unmarshal(bytes.NewReader(b), c.NotificationChannel)
}