forked from tynany/junos_exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopenroadm_exporter.go
246 lines (218 loc) · 7.41 KB
/
openroadm_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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
package main
import (
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/common/log"
"github.com/prometheus/common/version"
"github.com/utdal/openroadm_exporter/collector"
"github.com/utdal/openroadm_exporter/config"
"golang.org/x/crypto/ssh"
kingpin "gopkg.in/alecthomas/kingpin.v2"
)
var (
listenAddress = kingpin.Flag("web.listen-address", "Address on which to expose metrics and web interface.").Default(":9930").String()
telemetryPath = kingpin.Flag("web.telemetry-path", "Path under which to expose metrics.").Default("/metrics").String()
configPath = kingpin.Flag("config.path", "Path of the YAML configuration file.").Required().String()
// Slice of all configs.
collectors = []collector.Collector{}
// Map of client SSH configuration (value) per config as specified in the config file (key).
exporterSSHConfig = map[string]*ssh.ClientConfig{}
// Globally accessible configuration loaded from the config file.
collectorConfig *config.Configuration
interfaceDescriptionKeys = map[string][]string{}
interfaceMetricKeys = map[string][]string{}
bgpTypeKeys = map[string][]string{}
)
func initCollectors() {
collectors = append(collectors, collector.NewInterfaceCollector())
collectors = append(collectors, collector.NewEnvCollector())
collectors = append(collectors, collector.NewPowerCollector())
collectors = append(collectors, collector.NewRECollector())
collectors = append(collectors, collector.NewIpsecCollector())
collectors = append(collectors, collector.NewOpticsCollector())
}
func validateRequest(configParam string, targetParam string) error {
if configParam == "" {
return fmt.Errorf("'config' parameter must be specified")
}
for configName := range collectorConfig.Config {
if configParam == configName {
goto ConfigFound
}
}
return fmt.Errorf("could not find %q config in configuration file", configParam)
ConfigFound:
if targetParam == "" {
return fmt.Errorf("'target' parameter must be specified")
}
if len(collectorConfig.Config[configParam].AllowedTargets) > 0 {
for _, target := range collectorConfig.Config[configParam].AllowedTargets {
if targetParam == target {
goto TargetFound
}
}
return fmt.Errorf("allowed_targets is defined under %q configuration but %q is not listed", configParam, targetParam)
}
if len(collectorConfig.Global.AllowedTargets) > 0 {
for _, target := range collectorConfig.Global.AllowedTargets {
if targetParam == target {
goto TargetFound
}
}
return fmt.Errorf("allowed_targets is defined under global configuration but %q is not listed", targetParam)
}
TargetFound:
return nil
}
func handler(w http.ResponseWriter, r *http.Request) {
configParam := r.URL.Query().Get("config")
targetParam := r.URL.Query().Get("target")
if err := validateRequest(configParam, targetParam); err != nil {
http.Error(w, err.Error(), 400)
return
}
registry := prometheus.NewRegistry()
enabledCollectors := []collector.Collector{}
for _, collector := range collectors {
for _, col := range collectorConfig.Config[configParam].Collectors {
if collector.Name() == col {
enabledCollectors = append(enabledCollectors, collector)
}
}
}
config := collector.Config{
SSHClientConfig: exporterSSHConfig[configParam],
SSHTarget: targetParam,
IfaceDescrKeys: interfaceDescriptionKeys[configParam],
IfaceMetricKeys: interfaceMetricKeys[configParam],
BGPTypeKeys: bgpTypeKeys[configParam],
}
ne, err := collector.NewExporter(enabledCollectors, config)
if err != nil {
println("could not start exporter: %s", err)
return
}
registry.Register(ne)
gatherers := prometheus.Gatherers{
prometheus.DefaultGatherer,
registry,
}
handlerOpts := promhttp.HandlerOpts{
#ErrorLog: log.NewErrorLogger(),
ErrorHandling: promhttp.ContinueOnError,
}
promhttp.HandlerFor(gatherers, handlerOpts).ServeHTTP(w, r)
}
func parseCLI() {
println(kingpin.CommandLine)
kingpin.Version(version.Print("openroadm_exporter"))
kingpin.HelpFlag.Short('h')
kingpin.Parse()
}
func generateSSHConfig() error {
for name, configData := range collectorConfig.Config {
sshClientConfig := &ssh.ClientConfig{
User: configData.Username,
}
if configData.SSHKey != "" {
buf, err := ioutil.ReadFile(configData.SSHKey)
if err != nil {
return fmt.Errorf("could not open ssh key %q: %s", configData.SSHKey, err)
}
parsedKey, err := ssh.ParsePrivateKey(buf)
if err != nil {
return err
}
sshClientConfig.Auth = []ssh.AuthMethod{ssh.PublicKeys(parsedKey)}
} else {
sshClientConfig.Auth = []ssh.AuthMethod{ssh.Password(configData.Password)}
}
if configData.Timeout != 0 {
sshClientConfig.Timeout = time.Second * time.Duration(configData.Timeout)
} else if collectorConfig.Global.Timeout != 0 {
sshClientConfig.Timeout = time.Second * time.Duration(collectorConfig.Global.Timeout)
} else {
sshClientConfig.Timeout = time.Second * 20
}
sshClientConfig.HostKeyCallback = ssh.InsecureIgnoreHostKey()
exporterSSHConfig[name] = sshClientConfig
}
return nil
}
func getInterfaceDescriptionKeys() {
var globalIfaceDesc []string
if len(interfaceDescriptionKeys) == 0 {
if len(collectorConfig.Global.InterfaceDescKeys) > 0 {
for _, descrKey := range collectorConfig.Global.InterfaceDescKeys {
globalIfaceDesc = append(globalIfaceDesc, descrKey)
}
}
}
for name, configData := range collectorConfig.Config {
if len(configData.InterfaceDescKeys) > 0 {
for _, descrKey := range configData.InterfaceDescKeys {
interfaceDescriptionKeys[name] = append(interfaceDescriptionKeys[name], descrKey)
}
} else {
interfaceDescriptionKeys[name] = globalIfaceDesc
}
}
}
func getInterfaceMetricKeys() {
var globalIfaceMetrics []string
if len(interfaceMetricKeys) == 0 {
if len(collectorConfig.Global.InterfaceMetricKeys) > 0 {
for _, descrKey := range collectorConfig.Global.InterfaceMetricKeys {
globalIfaceMetrics = append(globalIfaceMetrics, descrKey)
}
}
}
for name, configData := range collectorConfig.Config {
if len(configData.InterfaceMetricKeys) > 0 {
for _, metricKey := range configData.InterfaceMetricKeys {
interfaceMetricKeys[name] = append(interfaceMetricKeys[name], metricKey)
}
} else {
interfaceMetricKeys[name] = globalIfaceMetrics
}
}
}
func main() {
prometheus.MustRegister(version.NewCollector("openroadm_exporter"))
initCollectors()
parseCLI()
println("Starting openroadm_exporter %s on %s", version.Info(), *listenAddress)
// Get a list of collector names to validate collectors specified in the config file exist.
var collectorNames []string
for _, collector := range collectors {
collectorNames = append(collectorNames, collector.Name())
}
var err error
collectorConfig, err = config.LoadConfigFile(*configPath, collectorNames)
if err != nil {
println(err)
}
if err = generateSSHConfig(); err != nil {
println("could not generate SSH configuration: %s", err)
}
getInterfaceDescriptionKeys()
getInterfaceMetricKeys()
getBGPTypeKeys()
http.HandleFunc(*telemetryPath, handler)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`<html>
<head><title>OpenROADM Exporter</title></head>
<body>
<h1>OpenROADM Exporter</h1>
<p><a href="` + *telemetryPath + `">Metrics</a></p>
</body>
</html>`))
})
if err := http.ListenAndServe(*listenAddress, nil); err != nil {
println(err)
}
}