-
Notifications
You must be signed in to change notification settings - Fork 52
/
script_exporter.go
207 lines (159 loc) · 4.53 KB
/
script_exporter.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
package main
import (
"context"
"errors"
"flag"
"fmt"
"gopkg.in/yaml.v2"
"io/ioutil"
"net/http"
"os"
"os/exec"
"regexp"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/common/log"
"github.com/prometheus/common/version"
)
var (
showVersion = flag.Bool("version", false, "Print version information.")
configFile = flag.String("config.file", "script-exporter.yml", "Script exporter configuration file.")
listenAddress = flag.String("web.listen-address", ":9172", "The address to listen on for HTTP requests.")
metricsPath = flag.String("web.telemetry-path", "/metrics", "Path under which to expose metrics.")
shell = flag.String("config.shell", "/bin/sh", "Shell to execute script")
)
type Config struct {
Scripts []*Script `yaml:"scripts"`
}
type Script struct {
Name string `yaml:"name"`
Content string `yaml:"script"`
Timeout int64 `yaml:"timeout"`
}
type Measurement struct {
Script *Script
Success int
Duration float64
}
func runScript(script *Script) error {
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(script.Timeout)*time.Second)
defer cancel()
bashCmd := exec.CommandContext(ctx, *shell)
bashIn, err := bashCmd.StdinPipe()
if err != nil {
return err
}
if err = bashCmd.Start(); err != nil {
return err
}
if _, err = bashIn.Write([]byte(script.Content)); err != nil {
return err
}
bashIn.Close()
return bashCmd.Wait()
}
func runScripts(scripts []*Script) []*Measurement {
measurements := make([]*Measurement, 0)
ch := make(chan *Measurement)
for _, script := range scripts {
go func(script *Script) {
start := time.Now()
success := 0
err := runScript(script)
duration := time.Since(start).Seconds()
if err == nil {
log.Debugf("OK: %s (after %fs).", script.Name, duration)
success = 1
} else {
log.Infof("ERROR: %s: %s (failed after %fs).", script.Name, err, duration)
}
ch <- &Measurement{
Script: script,
Duration: duration,
Success: success,
}
}(script)
}
for i := 0; i < len(scripts); i++ {
measurements = append(measurements, <-ch)
}
return measurements
}
func scriptFilter(scripts []*Script, name, pattern string) (filteredScripts []*Script, err error) {
if name == "" && pattern == "" {
err = errors.New("`name` or `pattern` required")
return
}
var patternRegexp *regexp.Regexp
if pattern != "" {
patternRegexp, err = regexp.Compile(pattern)
if err != nil {
return
}
}
for _, script := range scripts {
if script.Name == name || (pattern != "" && patternRegexp.MatchString(script.Name)) {
filteredScripts = append(filteredScripts, script)
}
}
return
}
func scriptRunHandler(w http.ResponseWriter, r *http.Request, config *Config) {
params := r.URL.Query()
name := params.Get("name")
pattern := params.Get("pattern")
scripts, err := scriptFilter(config.Scripts, name, pattern)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
measurements := runScripts(scripts)
for _, measurement := range measurements {
fmt.Fprintf(w, "script_duration_seconds{script=\"%s\"} %f\n", measurement.Script.Name, measurement.Duration)
fmt.Fprintf(w, "script_success{script=\"%s\"} %d\n", measurement.Script.Name, measurement.Success)
}
}
func init() {
prometheus.MustRegister(version.NewCollector("script_exporter"))
}
func main() {
flag.Parse()
if *showVersion {
fmt.Fprintln(os.Stdout, version.Print("script_exporter"))
os.Exit(0)
}
log.Infoln("Starting script_exporter", version.Info())
yamlFile, err := ioutil.ReadFile(*configFile)
if err != nil {
log.Fatalf("Error reading config file: %s", err)
}
config := Config{}
err = yaml.Unmarshal(yamlFile, &config)
if err != nil {
log.Fatalf("Error parsing config file: %s", err)
}
log.Infof("Loaded %d script configurations", len(config.Scripts))
for _, script := range config.Scripts {
if script.Timeout == 0 {
script.Timeout = 15
}
}
http.Handle("/metrics", promhttp.Handler())
http.HandleFunc("/probe", func(w http.ResponseWriter, r *http.Request) {
scriptRunHandler(w, r, &config)
})
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`<html>
<head><title>Script Exporter</title></head>
<body>
<h1>Script Exporter</h1>
<p><a href="` + *metricsPath + `">Metrics</a></p>
</body>
</html>`))
})
log.Infoln("Listening on", *listenAddress)
if err := http.ListenAndServe(*listenAddress, nil); err != nil {
log.Fatalf("Error starting HTTP server: %s", err)
}
}