forked from influxdata/telegraf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
execd.go
211 lines (169 loc) · 4.55 KB
/
execd.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
package execd
import (
"bufio"
"context"
"fmt"
"io"
"log"
"os/exec"
"sync"
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/plugins/inputs"
"github.com/influxdata/telegraf/plugins/parsers"
)
const sampleConfig = `
## Program to run as daemon
command = ["telegraf-smartctl", "-d", "/dev/sda"]
## Define how the process is signaled on each collection interval.
## Valid values are:
## "none" : Do not signal anything.
## The process must output metrics by itself.
## "STDIN" : Send a newline on STDIN.
## "SIGHUP" : Send a HUP signal. Not available on Windows.
## "SIGUSR1" : Send a USR1 signal. Not available on Windows.
## "SIGUSR2" : Send a USR2 signal. Not available on Windows.
signal = "none"
## Delay before the process is restarted after an unexpected termination
restart_delay = "10s"
## Data format to consume.
## Each data format has its own unique set of configuration options, read
## more about them here:
## https://github.com/influxdata/telegraf/blob/master/docs/DATA_FORMATS_INPUT.md
data_format = "influx"
`
type Execd struct {
Command []string
Signal string
RestartDelay internal.Duration
acc telegraf.Accumulator
cmd *exec.Cmd
parser parsers.Parser
stdin io.WriteCloser
cancel context.CancelFunc
wg sync.WaitGroup
}
func (e *Execd) SampleConfig() string {
return sampleConfig
}
func (e *Execd) Description() string {
return "Run executable as long-running input plugin"
}
func (e *Execd) SetParser(parser parsers.Parser) {
e.parser = parser
}
func (e *Execd) Start(acc telegraf.Accumulator) error {
e.acc = acc
if len(e.Command) == 0 {
return fmt.Errorf("E! [inputs.execd] FATAL no command specified")
}
e.wg.Add(1)
var ctx context.Context
ctx, e.cancel = context.WithCancel(context.Background())
go func() {
e.cmdLoop(ctx)
e.wg.Done()
}()
return nil
}
func (e *Execd) Stop() {
e.cancel()
e.wg.Wait()
}
func (e *Execd) cmdLoop(ctx context.Context) {
for {
// Use a buffered channel to ensure goroutine below can exit
// if `ctx.Done` is selected and nothing reads on `done` anymore
done := make(chan error, 1)
go func() {
done <- e.cmdRun()
}()
select {
case <-ctx.Done():
e.stdin.Close()
// Immediately exit process but with a graceful shutdown
// period before killing
internal.WaitTimeout(e.cmd, 200*time.Millisecond)
return
case err := <-done:
log.Printf("E! [inputs.execd] Process %s terminated: %s", e.Command, err)
}
log.Printf("E! [inputs.execd] Restarting in %s...", e.RestartDelay.Duration)
select {
case <-ctx.Done():
return
case <-time.After(e.RestartDelay.Duration):
// Continue the loop and restart the process
}
}
}
func (e *Execd) cmdRun() error {
var wg sync.WaitGroup
if len(e.Command) > 1 {
e.cmd = exec.Command(e.Command[0], e.Command[1:]...)
} else {
e.cmd = exec.Command(e.Command[0])
}
stdin, err := e.cmd.StdinPipe()
if err != nil {
return fmt.Errorf("E! [inputs.execd] Error opening stdin pipe: %s", err)
}
e.stdin = stdin
stdout, err := e.cmd.StdoutPipe()
if err != nil {
return fmt.Errorf("E! [inputs.execd] Error opening stdout pipe: %s", err)
}
stderr, err := e.cmd.StderrPipe()
if err != nil {
return fmt.Errorf("E! [inputs.execd] Error opening stderr pipe: %s", err)
}
log.Printf("D! [inputs.execd] Starting process: %s", e.Command)
err = e.cmd.Start()
if err != nil {
return fmt.Errorf("E! [inputs.execd] Error starting process: %s", err)
}
wg.Add(2)
go func() {
e.cmdReadOut(stdout)
wg.Done()
}()
go func() {
e.cmdReadErr(stderr)
wg.Done()
}()
wg.Wait()
return e.cmd.Wait()
}
func (e *Execd) cmdReadOut(out io.Reader) {
scanner := bufio.NewScanner(out)
for scanner.Scan() {
metrics, err := e.parser.Parse(scanner.Bytes())
if err != nil {
e.acc.AddError(fmt.Errorf("E! [inputs.execd] Parse error: %s", err))
}
for _, metric := range metrics {
e.acc.AddMetric(metric)
}
}
if err := scanner.Err(); err != nil {
e.acc.AddError(fmt.Errorf("E! [inputs.execd] Error reading stdout: %s", err))
}
}
func (e *Execd) cmdReadErr(out io.Reader) {
scanner := bufio.NewScanner(out)
for scanner.Scan() {
log.Printf("E! [inputs.execd] stderr: %q", scanner.Text())
}
if err := scanner.Err(); err != nil {
e.acc.AddError(fmt.Errorf("E! [inputs.execd] Error reading stderr: %s", err))
}
}
func init() {
inputs.Add("execd", func() telegraf.Input {
return &Execd{
Signal: "none",
RestartDelay: internal.Duration{Duration: 10 * time.Second},
}
})
}