-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathmackerel-plugin.go
361 lines (320 loc) · 8.79 KB
/
mackerel-plugin.go
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
package mackerelplugin
import (
"crypto/sha1"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"math"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"golang.org/x/text/cases"
"golang.org/x/text/language"
"github.com/mackerelio/golib/pluginutil"
)
// Metric units
const (
UnitFloat = "float"
UnitInteger = "integer"
UnitPercentage = "percentage"
UnitSeconds = "seconds"
UnitMilliseconds = "milliseconds"
UnitBytes = "bytes"
UnitBytesPerSecond = "bytes/sec"
UnitBitsPerSecond = "bits/sec"
UnitIOPS = "iops"
)
// Metrics represents definition of a metric
type Metrics struct {
Name string `json:"name"`
Label string `json:"label"`
Diff bool `json:"-"`
Stacked bool `json:"stacked"`
Scale float64 `json:"-"`
}
// Graphs represents definition of a graph
type Graphs struct {
Label string `json:"label"`
Unit string `json:"unit"`
Metrics []Metrics `json:"metrics"`
}
// Plugin is old interface of mackerel-plugin
type Plugin interface {
FetchMetrics() (map[string]float64, error)
GraphDefinition() map[string]Graphs
}
// PluginWithPrefix is recommended interface
type PluginWithPrefix interface {
Plugin
MetricKeyPrefix() string
}
// MackerelPlugin is for mackerel-agent-plugins
type MackerelPlugin struct {
Plugin
Tempfile string
diff *bool
writer io.Writer
}
// NewMackerelPlugin returns new MackrelPlugin
func NewMackerelPlugin(plugin Plugin) *MackerelPlugin {
return &MackerelPlugin{Plugin: plugin}
}
func (mp *MackerelPlugin) getWriter() io.Writer {
if mp.writer == nil {
mp.writer = os.Stdout
}
return mp.writer
}
func (mp *MackerelPlugin) hasDiff() bool {
if mp.diff == nil {
diff := false
mp.diff = &diff
DiffCheck:
for _, graph := range mp.GraphDefinition() {
for _, metric := range graph.Metrics {
if metric.Diff {
*mp.diff = true
break DiffCheck
}
}
}
}
return *mp.diff
}
func (mp *MackerelPlugin) printValue(w io.Writer, key string, value float64, now time.Time) {
if math.IsNaN(value) || math.IsInf(value, 0) {
log.Printf("Invalid value: key = %s, value = %f\n", key, value)
return
}
if value == float64(int(value)) {
fmt.Fprintf(w, "%s\t%d\t%d\n", key, int(value), now.Unix())
} else {
fmt.Fprintf(w, "%s\t%f\t%d\n", key, value, now.Unix())
}
}
var errStateRecentlyUpdated = errors.New("state was recently updated")
const oldEnoughDuration = time.Second
func (mp *MackerelPlugin) fetchLastValues(now time.Time) (map[string]float64, time.Time, error) {
if !mp.hasDiff() {
return nil, time.Time{}, nil
}
f, err := os.Open(mp.tempfilename())
if err != nil {
if os.IsNotExist(err) {
return nil, time.Time{}, nil
}
return nil, time.Time{}, err
}
defer f.Close()
stat := make(map[string]float64)
decoder := json.NewDecoder(f)
err = decoder.Decode(&stat)
if err != nil {
return stat, time.Time{}, err
}
lastTime := time.Unix(int64(stat["_lastTime"]), 0)
if now.Sub(lastTime) < oldEnoughDuration {
return stat, time.Time{}, errStateRecentlyUpdated
}
return stat, lastTime, nil
}
func (mp *MackerelPlugin) saveValues(values map[string]float64, now time.Time) error {
if !mp.hasDiff() {
return nil
}
f, err := os.Create(mp.tempfilename())
if err != nil {
return err
}
defer f.Close()
// Since Go 1.15 strconv.ParseFloat returns +Inf if it couldn't parse a string.
// But JSON does not accept invalid numbers, such as +Inf, -Inf or NaN.
// We perhaps have some plugins that is affected above change,
// so saveState should clear invalid numbers in the values before saving it.
for k, v := range values {
if math.IsInf(v, 0) || math.IsNaN(v) {
delete(values, k)
}
}
values["_lastTime"] = float64(now.Unix())
encoder := json.NewEncoder(f)
err = encoder.Encode(values)
if err != nil {
return err
}
return nil
}
func (mp *MackerelPlugin) calcDiff(value float64, now time.Time, lastValue float64, lastTime time.Time) (float64, error) {
diffTime := now.Unix() - lastTime.Unix()
if diffTime > 600 {
return 0, errors.New("too long duration")
}
diff := (value - lastValue) * 60 / float64(diffTime)
if diff < 0 {
return 0, errors.New("counter seems to be reset")
}
return diff, nil
}
func (mp *MackerelPlugin) tempfilename() string {
if mp.Tempfile == "" {
mp.Tempfile = mp.generateTempfilePath(os.Args)
}
return mp.Tempfile
}
var tempfileSanitizeReg = regexp.MustCompile(`[^-_.A-Za-z0-9]`)
// SetTempfileByBasename sets Tempfile under proper directory with specified basename.
func (mp *MackerelPlugin) SetTempfileByBasename(base string) {
mp.Tempfile = filepath.Join(pluginutil.PluginWorkDir(), base)
}
func (mp *MackerelPlugin) generateTempfilePath(args []string) string {
commandPath := args[0]
var prefix string
if p, ok := mp.Plugin.(PluginWithPrefix); ok {
prefix = p.MetricKeyPrefix()
} else {
name := filepath.Base(commandPath)
prefix = strings.TrimPrefix(tempfileSanitizeReg.ReplaceAllString(name, "_"), "mackerel-plugin-")
}
filename := fmt.Sprintf(
"mackerel-plugin-%s-%x",
prefix,
// When command-line options are different, mostly different metrics.
// e.g. `-host` and `-port` options for mackerel-plugin-mysql
sha1.Sum([]byte(strings.Join(args[1:], " "))),
)
return filepath.Join(pluginutil.PluginWorkDir(), filename)
}
// OutputValues output the metrics
func (mp *MackerelPlugin) OutputValues() {
now := time.Now()
stat, err := mp.FetchMetrics()
if err != nil {
log.Fatalln("OutputValues: ", err)
}
lastStat, lastTime, err := mp.fetchLastValues(now)
if err != nil {
if err == errStateRecentlyUpdated {
log.Println("OutputValues:", err)
return
}
log.Println("fetchLastValues (ignore):", err)
}
for key, graph := range mp.GraphDefinition() {
for _, metric := range graph.Metrics {
if strings.ContainsAny(key+metric.Name, "*#") {
mp.formatValuesWithWildcard(key, metric, stat, lastStat, now, lastTime)
} else {
mp.formatValues(key, metric, stat, lastStat, now, lastTime)
}
}
}
err = mp.saveValues(stat, now)
if err != nil {
log.Fatalf("saveValues: %s", err)
}
}
func (mp *MackerelPlugin) formatValuesWithWildcard(prefix string, metric Metrics, stat map[string]float64, lastStat map[string]float64, now time.Time, lastTime time.Time) {
regexpStr := `\A` + prefix + "." + metric.Name
regexpStr = strings.Replace(regexpStr, ".", `\.`, -1)
regexpStr = strings.Replace(regexpStr, "*", `[-a-zA-Z0-9_]+`, -1)
regexpStr = strings.Replace(regexpStr, "#", `[-a-zA-Z0-9_]+`, -1)
re, err := regexp.Compile(regexpStr)
if err != nil {
log.Fatalln("Failed to compile regexp: ", err)
}
for k := range stat {
if re.MatchString(k) {
metricEach := metric
metricEach.Name = k
mp.formatValues("", metricEach, stat, lastStat, now, lastTime)
}
}
}
func (mp *MackerelPlugin) formatValues(prefix string, metric Metrics, stat map[string]float64, lastStat map[string]float64, now time.Time, lastTime time.Time) {
name := metric.Name
value, ok := stat[name]
if !ok {
return
}
if metric.Diff {
lastValue, ok := lastStat[name]
if ok {
var err error
value, err = mp.calcDiff(value, now, lastValue, lastTime)
if err != nil {
log.Println("OutputValues: ", err)
}
} else {
log.Printf("%s does not exist at last fetch\n", metric.Name)
return
}
}
if metric.Scale != 0 {
value *= metric.Scale
}
metricNames := []string{}
if p, ok := mp.Plugin.(PluginWithPrefix); ok {
metricNames = append(metricNames, p.MetricKeyPrefix())
}
if prefix != "" {
metricNames = append(metricNames, prefix)
}
metricNames = append(metricNames, metric.Name)
mp.printValue(mp.getWriter(), strings.Join(metricNames, "."), value, now)
}
// GraphDef is graph definitions
type GraphDef struct {
Graphs map[string]Graphs `json:"graphs"`
}
func title(s string) string {
r := strings.NewReplacer(".", " ", "_", " ", "*", "", "#", "")
return strings.TrimSpace(cases.Title(language.Und, cases.NoLower).String(r.Replace(s)))
}
// OutputDefinitions outputs graph definitions
func (mp *MackerelPlugin) OutputDefinitions() {
fmt.Fprintln(mp.getWriter(), "# mackerel-agent-plugin")
graphs := make(map[string]Graphs)
for key, graph := range mp.GraphDefinition() {
g := graph
k := key
if p, ok := mp.Plugin.(PluginWithPrefix); ok {
prefix := p.MetricKeyPrefix()
if k == "" {
k = prefix
} else {
k = prefix + "." + k
}
}
if g.Label == "" {
g.Label = title(k)
}
metrics := []Metrics{}
for _, v := range g.Metrics {
if v.Label == "" {
v.Label = title(v.Name)
}
metrics = append(metrics, v)
}
g.Metrics = metrics
graphs[k] = g
}
var graphdef GraphDef
graphdef.Graphs = graphs
b, err := json.Marshal(graphdef)
if err != nil {
log.Fatalln("OutputDefinitions: ", err)
}
fmt.Fprintln(mp.getWriter(), string(b))
}
// Run the plugin
func (mp *MackerelPlugin) Run() {
if os.Getenv("MACKEREL_AGENT_PLUGIN_META") != "" {
mp.OutputDefinitions()
} else {
mp.OutputValues()
}
}