forked from adhocteam/script_exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
script_exporter.go
232 lines (183 loc) · 5.56 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
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
package main
import (
"context"
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"regexp"
"syscall"
"time"
"gopkg.in/yaml.v2"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"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")
// A regex pattern that only matches valid ASCII domain name characters to
// prevent inadvertent or malicious injection of special shell characters
// into the scripts environment.
targetRegexp = regexp.MustCompile("^[a-zA-Z0-9-.]{4,253}$")
)
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
ExitCode int
Duration float64
}
func runScript(script *Script, target string) (err error, rc int) {
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(script.Timeout)*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, *shell)
cmd.Env = append(os.Environ(), fmt.Sprintf("TARGET=%s", target))
stdin, err := cmd.StdinPipe()
if err != nil {
return err, 1
}
if _, err = stdin.Write([]byte(script.Content)); err != nil {
return err, 1
}
stdin.Close()
if err = cmd.Run(); err != nil {
exitError, ok := err.(*exec.ExitError)
if ok {
rc = exitError.Sys().(syscall.WaitStatus).ExitStatus()
} else {
log.Printf("ERROR: cmd.Run() failed with error: %v\n", err)
rc = 1
}
} else {
rc = cmd.ProcessState.Sys().(syscall.WaitStatus).ExitStatus()
}
return err, rc
}
func runScripts(scripts []*Script, target string) []*Measurement {
measurements := make([]*Measurement, 0)
ch := make(chan *Measurement)
for _, script := range scripts {
go func(script *Script) {
start := time.Now()
success := 0
err, rc := runScript(script, target)
duration := time.Since(start).Seconds()
if err == nil {
log.Printf("OK: %s to %s (after %fs).\n", script.Name, target, duration)
success = 1
} else {
log.Printf("ERROR: %s to %s: %s (failed after %fs).\n", script.Name, target, err, duration)
}
ch <- &Measurement{
Script: script,
Duration: duration,
Success: success,
ExitCode: rc,
}
}(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")
target := params.Get("target")
scripts, err := scriptFilter(config.Scripts, name, pattern)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
// If the passed target does not validate return an error.
if target != "" && !targetRegexp.MatchString(target) {
log.Printf("ERROR: Target %s failed to match targetRegexp\n", target)
http.Error(w, "Invalid target parameter", 400)
return
}
measurements := runScripts(scripts, target)
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)
fmt.Fprintf(w, "script_exit_code{script=\"%s\"} %d\n", measurement.Script.Name, measurement.ExitCode)
}
}
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.Println("Starting script_exporter", version.Info())
yamlFile, err := ioutil.ReadFile(*configFile)
if err != nil {
log.Fatalf("Error reading config file: %s\n", err)
}
config := Config{}
err = yaml.Unmarshal(yamlFile, &config)
if err != nil {
log.Fatalf("Error parsing config file: %s\n", err)
}
log.Printf("Loaded %d script configurations\n", 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.Println("Listening on", *listenAddress)
if err := http.ListenAndServe(*listenAddress, nil); err != nil {
log.Fatalf("Error starting HTTP server: %s\n", err)
}
}