-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathplugin.go
More file actions
249 lines (208 loc) · 5.98 KB
/
plugin.go
File metadata and controls
249 lines (208 loc) · 5.98 KB
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
package metrics
import (
"bufio"
"encoding/json"
"fmt"
"os"
"regexp"
"strconv"
"strings"
"github.com/mackerelio/mackerel-agent/config"
"github.com/mackerelio/mackerel-agent/logging"
"github.com/mackerelio/mackerel-agent/mackerel"
"github.com/mackerelio/mackerel-agent/util"
)
// pluginGenerator collects user-defined metrics.
// mackerel-agent runs specified command and parses the result for the metric names and values.
type pluginGenerator struct {
Config config.PluginConfig
Meta *pluginMeta
}
// pluginMeta is generated from plugin command. (not the configuration file)
type pluginMeta struct {
Graphs map[string]customGraphDef
}
type customGraphDef struct {
Label string
Unit string
Metrics []customGraphMetricDef
}
type customGraphMetricDef struct {
Name string
Label string
Stacked bool
}
var pluginLogger = logging.GetLogger("metrics.plugin")
const pluginPrefix = "custom."
var pluginConfigurationEnvName = "MACKEREL_AGENT_PLUGIN_META"
// NewPluginGenerator XXX
func NewPluginGenerator(conf config.PluginConfig) PluginGenerator {
return &pluginGenerator{Config: conf}
}
func (g *pluginGenerator) Generate() (Values, error) {
results, err := g.collectValues()
if err != nil {
return nil, err
}
return results, nil
}
func (g *pluginGenerator) PrepareGraphDefs() ([]mackerel.CreateGraphDefsPayload, error) {
err := g.loadPluginMeta()
if err != nil {
return nil, err
}
payload := g.makeCreateGraphDefsPayload()
return payload, nil
}
// loadPluginMeta obtains plugin information (e.g. graph visuals, metric
// namespaces, etc) from the command specified.
// mackerel-agent runs the command with MACKEREL_AGENT_PLUGIN_META
// environment variable set. The command is supposed to output like below:
//
// # mackerel-agent-plugin
// {
// "graphs": {
// GRAPH_NAME: {
// "label": GRAPH_LABEL,
// "unit": UNIT_TYPE
// "metrics": [
// {
// "name": METRIC_NAME,
// "label": METRIC_LABEL
// },
// ...
// ]
// },
// GRAPH_NAME: ...
// }
// }
//
// Valid UNIT_TYPEs are: "float", "integer", "percentage", "bytes", "bytes/sec", "iops"
//
// The output should start with a line beginning with '#', which contains
// meta-info of the configuration. (eg. plugin schema version)
//
// Below is a working example where the plugin emits metrics named "dice.d6" and "dice.d20":
//
// {
// "graphs": {
// "dice": {
// "metrics": [
// {
// "name": "d6",
// "label": "Die (d6)"
// },
// {
// "name": "d20",
// "label": "Die (d20)"
// }
// ],
// "unit": "integer",
// "label": "My Dice"
// }
// }
// }
func (g *pluginGenerator) loadPluginMeta() error {
command := g.Config.Command
pluginLogger.Debugf("Obtaining plugin configuration: %q", command)
// Set environment variable to make the plugin command generate its configuration
os.Setenv(pluginConfigurationEnvName, "1")
defer os.Setenv(pluginConfigurationEnvName, "")
stdout, stderr, exitCode, err := util.RunCommand(command)
if err != nil {
return fmt.Errorf("running %q failed: %s, exit=%d stderr=%q", command, err, exitCode, stderr)
}
outBuffer := bufio.NewReader(strings.NewReader(stdout))
// Read the plugin configuration meta (version etc)
headerLine, err := outBuffer.ReadString('\n')
if err != nil {
return fmt.Errorf("while reading the first line of command %q: %s", command, err)
}
// Parse the header line of format:
// # mackerel-agent-plugin [key=value]...
pluginMetaHeader := map[string]string{}
re := regexp.MustCompile(`^#\s*mackerel-agent-plugin\b(.*)`)
m := re.FindStringSubmatch(headerLine)
if m == nil {
return fmt.Errorf("bad format of first line: %q", headerLine)
}
for _, field := range strings.Fields(m[1]) {
keyValue := strings.Split(field, "=")
var value string
if len(keyValue) > 1 {
value = keyValue[1]
} else {
value = ""
}
pluginMetaHeader[keyValue[0]] = value
}
// Check schema version
version, ok := pluginMetaHeader["version"]
if !ok {
version = "1"
}
if version != "1" {
return fmt.Errorf("unsupported plugin meta version: %q", version)
}
conf := &pluginMeta{}
err = json.NewDecoder(outBuffer).Decode(conf)
if err != nil {
return fmt.Errorf("while reading plugin configuration: %s", err)
}
g.Meta = conf
return nil
}
func (g *pluginGenerator) makeCreateGraphDefsPayload() []mackerel.CreateGraphDefsPayload {
if g.Meta == nil {
return nil
}
payloads := []mackerel.CreateGraphDefsPayload{}
for key, graph := range g.Meta.Graphs {
payload := mackerel.CreateGraphDefsPayload{
Name: pluginPrefix + key,
DisplayName: graph.Label,
Unit: graph.Unit,
}
if payload.Unit == "" {
payload.Unit = "float"
}
for _, metric := range graph.Metrics {
metricPayload := mackerel.CreateGraphDefsPayloadMetric{
Name: pluginPrefix + key + "." + metric.Name,
DisplayName: metric.Label,
IsStacked: metric.Stacked,
}
payload.Metrics = append(payload.Metrics, metricPayload)
}
payloads = append(payloads, payload)
}
return payloads
}
var delimReg = regexp.MustCompile(`[\s\t]+`)
func (g *pluginGenerator) collectValues() (Values, error) {
command := g.Config.Command
pluginLogger.Debugf("Executing plugin: command = \"%s\"", command)
os.Setenv(pluginConfigurationEnvName, "")
stdout, stderr, _, err := util.RunCommand(command)
if err != nil {
pluginLogger.Errorf("Failed to execute command \"%s\" (skip these metrics):\n%s", command, stderr)
return nil, err
}
results := make(map[string]float64, 0)
for _, line := range strings.Split(stdout, "\n") {
// Key, value, timestamp
// ex.) tcp.CLOSING 0 1397031808
items := delimReg.Split(line, 3)
if len(items) != 3 {
continue
}
value, err := strconv.ParseFloat(items[1], 64)
if err != nil {
pluginLogger.Warningf("Failed to parse values: %s", err)
continue
}
key := items[0]
results[pluginPrefix+key] = value
}
return results, nil
}