forked from gokuatkai/vault-exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
215 lines (180 loc) · 5.75 KB
/
main.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
package main
import (
"net/http"
_ "net/http/pprof"
"runtime"
"io/ioutil"
"fmt"
"time"
"os"
"strings"
vault_api "github.com/hashicorp/vault/api"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
kingpin "gopkg.in/alecthomas/kingpin.v2"
)
var (
listenAddress = kingpin.Flag("web.listen-address",
"Address to listen on for web interface and telemetry.").
Default(":9101").String()
metricsPath = kingpin.Flag("web.telemetry-path",
"Path under which to expose metrics.").
Default("/metrics").String()
vaultCACert = kingpin.Flag("vault-tls-cacert",
"The path to a PEM-encoded CA cert file to use to verify the Vault server SSL certificate.").String()
vaultClientCert = kingpin.Flag("vault-tls-client-cert",
"The path to the certificate for Vault communication.").String()
vaultClientKey = kingpin.Flag("vault-tls-client-key",
"The path to the private key for Vault communication.").String()
sslInsecure = kingpin.Flag("insecure-ssl",
"Set SSL to ignore certificate validation.").
Default("false").Bool()
)
var (
version string
branch string
revision string
buildDate string
goVersion = runtime.Version()
)
const (
namespace = "vault"
)
type VaultClient struct {
client *vault_api.Client
}
// NewExporter returns an initialized Exporter.
func NewVaultClient() (*VaultClient, error) {
vaultConfig := vault_api.DefaultConfig()
if *sslInsecure {
tlsconfig := &vault_api.TLSConfig{
Insecure: true,
}
err := vaultConfig.ConfigureTLS(tlsconfig)
if err != nil {
return nil, err
}
}
if *vaultCACert != "" || *vaultClientCert != "" || *vaultClientKey != "" {
tlsconfig := &vault_api.TLSConfig{
CACert: *vaultCACert,
ClientCert: *vaultClientCert,
ClientKey: *vaultClientKey,
Insecure: *sslInsecure,
}
err := vaultConfig.ConfigureTLS(tlsconfig)
if err != nil {
return nil, err
}
}
client, err := vault_api.NewClient(vaultConfig)
if err != nil {
return nil, err
}
return &VaultClient{
client: client,
}, nil
}
func bool2float(b bool) float64 {
if b {
return 1
}
return 0
}
// Collect fetches the stats from configured Vault and delivers them
// as Prometheus metrics. It implements prometheus.Collector.
func (e *VaultClient) getVaultHealth() (string) {
health, err := e.client.Sys().Health()
var b strings.Builder
if err != nil {
fmt.Fprintf(&b, "vault_up %v", 0)
}
fmt.Fprintf(&b, "vault_up %v", 1)
fmt.Fprintf(&b, "\nvault_initialized %v", bool2float(health.Initialized))
fmt.Fprintf(&b, "\nvault_sealed %v", bool2float(health.Sealed))
fmt.Fprintf(&b, "\nvault_standby %v", bool2float(health.Standby))
if health.ReplicationDRMode == "disabled" {
fmt.Fprintf(&b, "\nvault_replication_dr_primary %v", 0)
fmt.Fprintf(&b, "\nvault_replication_dr_secondary %v", 0)
} else if health.ReplicationDRMode == "primary" {
fmt.Fprintf(&b, "\nvault_replication_dr_primary %v", 1)
fmt.Fprintf(&b, "\nvault_replication_dr_secondary %v", 0)
} else if health.ReplicationDRMode == "secondary" {
fmt.Fprintf(&b, "\nvault_replication_dr_primary %v", 0)
fmt.Fprintf(&b, "\nvault_replication_dr_secondary %v", 1)
}
if health.ReplicationPerformanceMode == "disabled" {
fmt.Fprintf(&b, "\nvault_replication_performance_primary %v", 0)
fmt.Fprintf(&b, "\nvault_replication_performance_secondary %v", 0)
} else if health.ReplicationPerformanceMode == "primary" {
fmt.Fprintf(&b, "\nvault_replication_performance_primary %v", 1)
fmt.Fprintf(&b, "\nvault_replication_performance_secondary %v", 0)
} else if health.ReplicationPerformanceMode == "secondary" {
fmt.Fprintf(&b, "\nvault_replication_performance_primary %v", 0)
fmt.Fprintf(&b, "\nvault_replication_performance_secondary %v", 1)
}
fmt.Fprintf(&b, "\nvault_info{cluster_id=\"%v\",cluster_name=\"%v\",version=\"%v\"} %v",health.ClusterID, health.ClusterName,health.Version, 1)
return b.String()
}
func ServeVaultMetrics(w http.ResponseWriter, r *http.Request) {
vaultAddr := os.Getenv("VAULT_ADDR")
if vaultAddr == "" {
log.Fatal().Msg("VAULT_ADDR is required. Please set VAULT_ADDR environment variable to your Vault address.")
}
vaultToken := os.Getenv("VAULT_TOKEN")
if vaultToken == "" {
log.Fatal().Msg("VAULT_TOKEN is required. Please set VAULT_TOKEN environment variable to your Vault token.")
}
var httpClient = &http.Client{
Timeout: time.Second * 10,
}
url := fmt.Sprintf("%v/v1/sys/metrics", vaultAddr)
req, err := http.NewRequest("GET", url, nil)
if err != nil{
log.Fatal().Err(err)
}
var bearer = "Bearer " + vaultToken
req.Header.Add("Authorization", bearer)
q := req.URL.Query()
q.Add("format", "prometheus")
req.URL.RawQuery = q.Encode()
response, err := httpClient.Do(req)
defer response.Body.Close()
responseData, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Fatal().Err(err)
}
telemetryMetrics := string(responseData)
vaultClient, err := NewVaultClient()
if err != nil {
log.Fatal().Err(err)
}
health := vaultClient.getVaultHealth()
fmt.Fprint(w, telemetryMetrics, health)
}
func init() {
}
func main() {
kingpin.HelpFlag.Short('h')
kingpin.Parse()
// log as severity for stackdriver logging to recognize the level
zerolog.LevelFieldName = "severity"
// set some default fields added to all logs
log.Logger = zerolog.New(os.Stdout).With().
Timestamp().
Str("app", "vault-exporter").
Str("version", version).
Logger()
// log startup message
log.Info().
Str("branch", branch).
Str("revision", revision).
Str("buildDate", buildDate).
Str("goVersion", goVersion).
Msg("Starting vault exporter...")
log.Info().Msgf("Listening on", *listenAddress)
http.HandleFunc(*metricsPath, ServeVaultMetrics)
if err := http.ListenAndServe(*listenAddress, nil); err != nil {
log.Fatal().Err(err).Msg("Starting vault-exporter listener failed")
}
}