/
command.go
309 lines (270 loc) · 7.72 KB
/
command.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
package maprobe
import (
"bufio"
"bytes"
"context"
"crypto/sha256"
"encoding/json"
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
"syscall"
"time"
mackerel "github.com/mackerelio/mackerel-client-go"
"github.com/pkg/errors"
)
const CustomPrefix = "custom."
var DefaultCommandTimeout = 15 * time.Second
var graphDefsPosted = sync.Map{}
type CommandProbeConfig struct {
RawCommand interface{} `yaml:"command"`
command []string `yaml:"-"`
Timeout time.Duration `yaml:"timeout"`
GraphDefs bool `yaml:"graph_defs"`
Env map[string]string `yaml:"env"`
}
func (pc *CommandProbeConfig) initialize() error {
switch c := pc.RawCommand.(type) {
case []interface{}:
if len(c) == 0 {
return errors.Errorf("command is empty array")
}
for _, v := range c {
switch s := v.(type) {
case string:
pc.command = append(pc.command, s)
default:
return errors.Errorf("command must be array of string")
}
}
case string:
if len(c) == 0 {
return errors.Errorf("command is empty string")
}
pc.command = []string{c}
case nil:
return errors.Errorf("command is empty")
default:
return errors.Errorf("invalid command: %#v", pc.RawCommand)
}
return nil
}
func (pc *CommandProbeConfig) GenerateProbe(host *mackerel.Host, client *mackerel.Client) (Probe, error) {
p := &CommandProbe{
Timeout: pc.Timeout,
GraphDefs: pc.GraphDefs,
Command: make([]string, len(pc.command)),
}
var err error
for i, c := range pc.command {
p.Command[i], err = expandPlaceHolder(c, host, pc.Env)
if err != nil {
return nil, errors.Wrap(err, "invalid command")
}
}
if len(p.Command) == 1 && strings.Contains(p.Command[0], " ") {
p.Command = []string{"sh", "-c", p.Command[0]}
}
if p.Timeout == 0 {
p.Timeout = DefaultCommandTimeout
}
if p.GraphDefs && client != nil {
if err := p.PostGraphDefs(client, pc); err != nil {
log.Printf("[warn] failed to post graph defs for %#v: %s", p, err)
}
}
for name, value := range pc.Env {
p.env = append(p.env, name+"="+value)
}
return p, nil
}
type CommandProbe struct {
env []string
Command []string
Timeout time.Duration
GraphDefs bool
}
func (p *CommandProbe) MetricName(name string) string {
return name
}
func (p *CommandProbe) String() string {
b, _ := json.Marshal(p)
return string(b)
}
func (p *CommandProbe) TempDir() string {
s := sha256.Sum256([]byte(p.String()))
dir := filepath.Join(os.TempDir(), fmt.Sprintf("maprobe_command_%x", s))
err := os.Mkdir(dir, 0700)
if err != nil {
if os.IsExist(err) {
// ok
return dir
}
log.Printf("[warn] failed to create a new TempDir %s: %s using %s", dir, err, os.TempDir())
return os.TempDir()
}
log.Printf("[debug] TempDir %s created for %s", dir, strings.Join(p.Command, " "))
return dir
}
func (p *CommandProbe) Run(_ context.Context) (ms Metrics, err error) {
// Run() should not be canceled by parent context.
ctx, cancel := context.WithTimeout(context.Background(), p.Timeout)
defer cancel()
var cmd *exec.Cmd
switch len(p.Command) {
case 0:
return nil, errors.New("no command")
case 1:
cmd = exec.CommandContext(ctx, p.Command[0])
default:
cmd = exec.CommandContext(ctx, p.Command[0], p.Command[1:]...)
}
cmd.Env = append(cmd.Env, os.Environ()...)
cmd.Env = append(cmd.Env, p.env...)
cmd.Env = append(cmd.Env, "TMPDIR="+p.TempDir())
cmd.Stderr = os.Stderr
cmd.Cancel = func() error {
return cmd.Process.Signal(syscall.SIGTERM)
}
cmd.WaitDelay = 5 * time.Second // SIGKILL after 5 seconds
stdout, err := cmd.StdoutPipe()
if err != nil {
return ms, errors.Wrap(err, "stdout open failed")
}
scanner := bufio.NewScanner(stdout)
if err := cmd.Start(); err != nil {
return ms, errors.Wrap(err, fmt.Sprintf("command execute failed. %s", strings.Join(p.Command, " ")))
}
for scanner.Scan() {
log.Println("[trace]", scanner.Text())
m, err := parseMetricLine(scanner.Text())
if err != nil {
log.Printf("[warn] %s failed to parse metric line. %s", strings.Join(p.Command, " "), err)
continue
}
if p.GraphDefs {
m.Name = CustomPrefix + m.Name
}
ms = append(ms, m)
}
err = cmd.Wait()
if e, ok := err.(*exec.ExitError); ok {
return ms, errors.Wrap(e, "command execute failed")
}
return ms, nil
}
type GraphsOutput struct {
Graphs map[string]Graph `json:"graphs"`
}
type Graph struct {
Label string `json:"label"`
Unit string `json:"unit"`
Metrics []GraphDefsMetric `json:"metrics"`
}
type GraphDefsMetric struct {
Name string `json:"name"`
Label string `json:"label"`
Stacked bool `json:"stacked"`
}
var pluginMetaHeaderLine = []byte("# mackerel-agent-plugin\n")
func (p *CommandProbe) PostGraphDefs(client *mackerel.Client, pc *CommandProbeConfig) error {
if _, found := graphDefsPosted.Load(pc); found {
log.Printf("[trace] graphDefsPosted %v", pc)
return nil
}
out, err := p.GetGraphDefs()
if err != nil {
graphDefsPosted.Store(pc, struct{}{})
return err
}
log.Printf("[trace] Got graph defs %#v", out)
payloads := make([]*mackerel.GraphDefsParam, 0, len(out.Graphs))
for _name, g := range out.Graphs {
name := CustomPrefix + _name
metrics := make([]*mackerel.GraphDefsMetric, 0, len(g.Metrics))
for _, m := range g.Metrics {
metrics = append(metrics, &mackerel.GraphDefsMetric{
Name: name + "." + m.Name,
DisplayName: m.Label,
IsStacked: m.Stacked,
})
}
payloads = append(payloads, &mackerel.GraphDefsParam{
Name: name,
DisplayName: g.Label,
Unit: g.Unit,
Metrics: metrics,
})
}
b, _ := json.Marshal(payloads)
log.Println("[trace] create to graph defs", string(b))
if err := client.CreateGraphDefs(payloads); err != nil {
// When failed to post to Mackerel, graphDefsPosted shouldnot be stored.
return errors.Wrap(err, "could not create graph defs")
}
log.Printf("[info] success to create graph defs for %v", p.Command)
graphDefsPosted.Store(pc, struct{}{})
return nil
}
func (p *CommandProbe) GetGraphDefs() (*GraphsOutput, error) {
log.Printf("[trace] Get graph defs for %v", p.Command)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, p.Command[0], p.Command[1:]...)
cmd.Env = append(os.Environ(), "MACKEREL_AGENT_PLUGIN_META=1")
cmd.Cancel = func() error {
return cmd.Process.Signal(syscall.SIGTERM)
}
cmd.WaitDelay = 5 * time.Second // SIGKILL after 5 seconds
cmd.Stderr = os.Stderr
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, errors.Wrap(err, "stdout open failed")
}
r := bufio.NewReader(stdout)
if err := cmd.Start(); err != nil {
return nil, errors.Wrap(err, "command execute failed")
}
header, err := r.ReadBytes('\n')
if err != nil {
return nil, errors.Wrap(err, "could not fetch a first line")
}
if !bytes.Equal(header, pluginMetaHeaderLine) {
// invalid header
return nil, fmt.Errorf("%s didn't output graph defs", p.Command[0])
}
var out GraphsOutput
if err := json.NewDecoder(r).Decode(&out); err != nil {
return nil, errors.Wrap(err, "could not decode graph defs output")
}
return &out, nil
}
func parseMetricLine(b string) (Metric, error) {
cols := strings.SplitN(b, "\t", 3)
if len(cols) < 3 {
return Metric{}, errors.New("invalid metric format. insufficient columns")
}
name, value, timestamp := cols[0], cols[1], cols[2]
if name == "" {
return Metric{}, errors.New("invalid metric format. name is empty")
}
m := Metric{
Name: name,
}
if v, err := strconv.ParseFloat(value, 64); err != nil {
return m, fmt.Errorf("invalid metric value: %s", value)
} else {
m.Value = v
}
if ts, err := strconv.ParseInt(timestamp, 10, 64); err != nil {
return m, fmt.Errorf("invalid metric time: %s", timestamp)
} else {
m.Timestamp = time.Unix(ts, 0)
}
return m, nil
}