summaryrefslogtreecommitdiff
path: root/internal/json_report.go
blob: 411fd1b6b0b4b1f6e68cbcbe3aa21c77a3834802 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
package internal

import (
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"time"
)

type jsonReport struct {
	LastUpdated string       `json:"lastUpdated"`
	Subject     string       `json:"subject"`
	Summary     jsonSummary  `json:"summary"`
	Sections    jsonSections `json:"sections"`
}

type jsonSummary struct {
	Critical   int `json:"critical"`
	Warning    int `json:"warning"`
	Unknown    int `json:"unknown"`
	Stale      int `json:"stale"`
	Suppressed int `json:"suppressed"`
	Ok         int `json:"ok"`
}

type jsonSections struct {
	StatusChanged []jsonCheck `json:"statusChanged"`
	Unhandled     []jsonCheck `json:"unhandled"`
	Stale         []jsonCheck `json:"stale"`
	Suppressed    []jsonCheck `json:"suppressed"`
	Ok            []jsonCheck `json:"ok"`
}

type jsonCheck struct {
	Name                  string `json:"name"`
	Status                string `json:"status"`
	PrevStatus            string `json:"prevStatus,omitempty"`
	Output                string `json:"output"`
	FederatedFrom         string `json:"federatedFrom,omitempty"`
	Epoch                 int64  `json:"epoch"`
	LastCheckedAgeSeconds int64  `json:"lastCheckedAgeSeconds,omitempty"`
}

func persistJSONReport(state state, subject string, conf config) error {
	htmlFile := conf.HTMLStatusFile
	if htmlFile == "" {
		return nil
	}

	jsonFile := jsonReportPath(htmlFile)
	jsonDir := filepath.Dir(jsonFile)
	if err := os.MkdirAll(jsonDir, 0o755); err != nil {
		return fmt.Errorf("failed to create directory %s: %w", jsonDir, err)
	}

	tmpFile := jsonFile + ".tmp"
	f, err := os.Create(tmpFile)
	if err != nil {
		return fmt.Errorf("failed to create temp file: %w", err)
	}
	defer f.Close()

	report := state.jsonReport(subject, conf)
	encoder := json.NewEncoder(f)
	encoder.SetIndent("", "  ")
	if err := encoder.Encode(report); err != nil {
		return fmt.Errorf("failed to write JSON: %w", err)
	}

	return os.Rename(tmpFile, jsonFile)
}

func jsonReportPath(htmlPath string) string {
	ext := filepath.Ext(htmlPath)
	if ext == "" {
		return htmlPath + ".json"
	}
	return strings.TrimSuffix(htmlPath, ext) + ".json"
}

func (s state) jsonReport(subject string, conf config) jsonReport {
	now := time.Now()

	summary := jsonSummary{
		Critical:   s.countBy(conf, func(cs checkState) bool { return cs.Status == nagiosCritical }),
		Warning:    s.countBy(conf, func(cs checkState) bool { return cs.Status == nagiosWarning }),
		Unknown:    s.countBy(conf, func(cs checkState) bool { return cs.Status == nagiosUnknown }),
		Stale:      s.countStale(conf),
		Suppressed: s.countSuppressed(conf),
		Ok:         s.countBy(conf, func(cs checkState) bool { return cs.Status == nagiosOk }),
	}

	sections := jsonSections{
		StatusChanged: s.jsonReportChanged(now, conf),
		Unhandled:     s.jsonReportUnhandled(now, conf),
		Stale:         s.jsonReportStale(now, conf),
		Suppressed:    s.jsonReportSuppressed(conf),
		Ok: s.jsonReportBy(now, false, false, conf, func(cs checkState) bool {
			return cs.Status == nagiosOk
		}),
	}

	return jsonReport{
		LastUpdated: now.Format(time.RFC3339),
		Subject:     subject,
		Summary:     summary,
		Sections:    sections,
	}
}

func (s state) jsonReportChanged(now time.Time, conf config) []jsonCheck {
	var checks []jsonCheck
	checks = append(checks, s.jsonReportBy(now, true, false, conf, func(cs checkState) bool {
		return cs.Status == nagiosCritical && cs.changed()
	})...)
	checks = append(checks, s.jsonReportBy(now, true, false, conf, func(cs checkState) bool {
		return cs.Status == nagiosWarning && cs.changed()
	})...)
	checks = append(checks, s.jsonReportBy(now, true, false, conf, func(cs checkState) bool {
		return cs.Status == nagiosUnknown && cs.changed()
	})...)
	checks = append(checks, s.jsonReportBy(now, true, false, conf, func(cs checkState) bool {
		return cs.Status == nagiosOk && cs.changed()
	})...)
	return checks
}

func (s state) jsonReportUnhandled(now time.Time, conf config) []jsonCheck {
	var checks []jsonCheck
	checks = append(checks, s.jsonReportBy(now, false, false, conf, func(cs checkState) bool {
		return cs.Status == nagiosCritical
	})...)
	checks = append(checks, s.jsonReportBy(now, false, false, conf, func(cs checkState) bool {
		return cs.Status == nagiosWarning
	})...)
	checks = append(checks, s.jsonReportBy(now, false, false, conf, func(cs checkState) bool {
		return cs.Status == nagiosUnknown
	})...)
	return checks
}

func (s state) jsonReportStale(now time.Time, conf config) []jsonCheck {
	return s.jsonReportBy(now, false, true, conf, func(cs checkState) bool {
		return cs.Epoch < s.staleEpoch && cs.Status != nagiosOk
	})
}

func (s state) jsonReportSuppressed(conf config) []jsonCheck {
	var checks []jsonCheck
	for name, cs := range s.checks {
		if cs.Status == nagiosOk || !isCheckSuppressed(name, conf) {
			continue
		}
		checks = append(checks, jsonCheck{
			Name:          name,
			Status:        nagiosCode(cs.Status).Str(),
			Output:        cs.Output,
			FederatedFrom: cs.FederatedFrom,
			Epoch:         cs.Epoch,
		})
	}
	return checks
}

func (s state) jsonReportBy(now time.Time, showStatusChange, isStaleReport bool, conf config,
	filter func(cs checkState) bool,
) []jsonCheck {
	var checks []jsonCheck
	for name, cs := range s.checks {
		if !filter(cs) {
			continue
		}
		if !isStaleReport && cs.Epoch < s.staleEpoch {
			continue
		}
		if cs.Status != nagiosOk && isCheckSuppressed(name, conf) {
			continue
		}

		entry := jsonCheck{
			Name:          name,
			Status:        nagiosCode(cs.Status).Str(),
			Output:        cs.Output,
			FederatedFrom: cs.FederatedFrom,
			Epoch:         cs.Epoch,
		}
		if showStatusChange && cs.changed() {
			entry.PrevStatus = nagiosCode(cs.PrevStatus).Str()
		}
		if isStaleReport {
			entry.LastCheckedAgeSeconds = int64(now.Sub(time.Unix(cs.Epoch, 0)).Seconds())
		}
		checks = append(checks, entry)
	}
	return checks
}