watchtower/pkg/notifications/json.go

72 lines
1.7 KiB
Go
Raw Normal View History

2023-01-25 18:24:01 +01:00
package notifications
import (
"encoding/json"
t "github.com/containrrr/watchtower/pkg/types"
)
2023-01-29 16:51:37 +01:00
type jsonMap = map[string]interface{}
2023-01-25 18:24:01 +01:00
// MarshalJSON implements json.Marshaler
func (d Data) MarshalJSON() ([]byte, error) {
2023-01-29 16:51:37 +01:00
var entries = make([]jsonMap, len(d.Entries))
2023-01-25 18:24:01 +01:00
for i, entry := range d.Entries {
2023-01-29 16:51:37 +01:00
entries[i] = jsonMap{
2023-01-25 18:24:01 +01:00
`level`: entry.Level,
`message`: entry.Message,
`data`: entry.Data,
`time`: entry.Time,
}
}
2023-01-29 16:51:37 +01:00
var report jsonMap
2023-01-25 18:24:01 +01:00
if d.Report != nil {
2023-01-29 16:51:37 +01:00
report = jsonMap{
2023-01-25 18:24:01 +01:00
`scanned`: marshalReports(d.Report.Scanned()),
`updated`: marshalReports(d.Report.Updated()),
`failed`: marshalReports(d.Report.Failed()),
`skipped`: marshalReports(d.Report.Skipped()),
`stale`: marshalReports(d.Report.Stale()),
`fresh`: marshalReports(d.Report.Fresh()),
}
}
2023-01-29 16:51:37 +01:00
return json.Marshal(jsonMap{
2023-01-25 18:24:01 +01:00
`report`: report,
`title`: d.Title,
`host`: d.Host,
`entries`: entries,
})
}
2023-01-29 16:51:37 +01:00
func marshalReports(reports []t.ContainerReport) []jsonMap {
jsonReports := make([]jsonMap, len(reports))
2023-01-25 18:24:01 +01:00
for i, report := range reports {
2023-01-29 16:51:37 +01:00
jsonReports[i] = jsonMap{
2023-01-29 16:16:10 +01:00
`id`: report.ID().ShortID(),
2023-01-25 18:24:01 +01:00
`name`: report.Name(),
2023-01-29 16:16:10 +01:00
`currentImageId`: report.CurrentImageID().ShortID(),
`latestImageId`: report.LatestImageID().ShortID(),
2023-01-25 18:24:01 +01:00
`imageName`: report.ImageName(),
`state`: report.State(),
}
if errorMessage := report.Error(); errorMessage != "" {
jsonReports[i][`error`] = errorMessage
}
}
return jsonReports
}
var _ json.Marshaler = &Data{}
func toJSON(v interface{}) string {
2023-01-29 16:51:37 +01:00
var bytes []byte
var err error
if bytes, err = json.MarshalIndent(v, "", " "); err != nil {
2023-01-25 18:24:01 +01:00
LocalLog.Errorf("failed to marshal JSON in notification template: %v", err)
return ""
}
2023-01-29 16:51:37 +01:00
return string(bytes)
2023-01-25 18:24:01 +01:00
}