Debian Codegraph @

exporter/http.go

raw symbols SCIP
1 package exporter
2
3 import (
4 "crypto/subtle"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "net/http"
9 "net/url"
10 "strings"
11
12 "github.com/prometheus/client_golang/prometheus"
13 "github.com/prometheus/client_golang/prometheus/promhttp"
14 log "github.com/sirupsen/logrus"
15 "golang.org/x/crypto/bcrypt"
16 )
17
18 func (e *Exporter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
19 if err := e.verifyBasicAuth(r.BasicAuth()); err != nil {
20 w.Header().Set("WWW-Authenticate", `Basic realm="redis-exporter, charset=UTF-8"`)
21 http.Error(w, err.Error(), http.StatusUnauthorized)
22 return
23 }
24
25 e.mux.ServeHTTP(w, r)
26 }
27
28 func (e *Exporter) healthHandler(w http.ResponseWriter, r *http.Request) {
29 _, _ = w.Write([]byte(`ok`))
30 }
31
32 func (e *Exporter) indexHandler(w http.ResponseWriter, r *http.Request) {
33 if r.URL.Path != "/" {
34 http.NotFound(w, r)
35 return
36 }
37 _, _ = w.Write([]byte(`<html>
38 <head><title>Redis Exporter ` + e.buildInfo.Version + `</title></head>
39 <body>
40 <h1>Redis Exporter ` + e.buildInfo.Version + `</h1>
41 <p><a href='` + e.options.MetricsPath + `'>Metrics</a></p>
42 </body>
43 </html>
44 `))
45 }
46
47 func (e *Exporter) scrapeHandler(w http.ResponseWriter, r *http.Request) {
48 target := r.URL.Query().Get("target")
49 if target == "" {
50 http.Error(w, "'target' parameter must be specified", http.StatusBadRequest)
51 e.targetScrapeRequestErrors.Inc()
52 return
53 }
54
55 if !strings.Contains(target, "://") {
56 target = "redis://" + target
57 }
58
59 u, err := url.Parse(target)
60 if err != nil {
61 http.Error(w, fmt.Sprintf("Invalid 'target' parameter, parse err: %v ", err), http.StatusBadRequest)
62 e.targetScrapeRequestErrors.Inc()
63 return
64 }
65
66 opts := e.options
67
68 // get rid of username/password info in "target" so users don't send them in plain text via http
69 // and save "user" in options so we can use it later when connecting to the redis instance
70 // the password will be looked up from the password file
71 if u.User != nil {
72 opts.User = u.User.Username()
73 u.User = nil
74 }
75 target = u.String()
76
77 if ck := r.URL.Query().Get("check-keys"); ck != "" {
78 opts.CheckKeys = ck
79 }
80
81 if csk := r.URL.Query().Get("check-single-keys"); csk != "" {
82 opts.CheckSingleKeys = csk
83 }
84
85 if cs := r.URL.Query().Get("check-streams"); cs != "" {
86 opts.CheckStreams = cs
87 }
88
89 if css := r.URL.Query().Get("check-single-streams"); css != "" {
90 opts.CheckSingleStreams = css
91 }
92
93 if cntk := r.URL.Query().Get("count-keys"); cntk != "" {
94 opts.CountKeys = cntk
95 }
96
97 opts.Registry = prometheus.NewRegistry()
98
99 _, err = NewRedisExporter(target, opts)
100 if err != nil {
101 http.Error(w, fmt.Sprintf("NewRedisExporter() error: %v", err), http.StatusBadRequest)
102 e.targetScrapeRequestErrors.Inc()
103 return
104 }
105
106 promhttp.HandlerFor(
107 opts.Registry, promhttp.HandlerOpts{ErrorHandling: promhttp.ContinueOnError},
108 ).ServeHTTP(w, r)
109 }
110
111 func (e *Exporter) discoverClusterNodesHandler(w http.ResponseWriter, r *http.Request) {
112 if !e.options.IsCluster {
113 http.Error(w, "The discovery endpoint is only available on a redis cluster", http.StatusBadRequest)
114 return
115 }
116
117 c, err := e.connectToRedisCluster()
118 if err != nil {
119 http.Error(w, fmt.Sprintf("Couldn't connect to redis cluster: %s", err), http.StatusInternalServerError)
120 return
121 }
122 defer c.Close()
123
124 nodes, err := e.getClusterNodes(c)
125 if err != nil {
126 http.Error(w, fmt.Sprintf("Failed to fetch cluster nodes: %s", err), http.StatusInternalServerError)
127 return
128 }
129
130 discovery := []struct {
131 Targets []string `json:"targets"`
132 Labels map[string]string `json:"labels"`
133 }{
134 {
135 Targets: make([]string, len(nodes)),
136 Labels: make(map[string]string, 0),
137 },
138 }
139
140 isTls := strings.HasPrefix(e.redisAddr, "rediss://")
141 for i, node := range nodes {
142 if isTls {
143 discovery[0].Targets[i] = "rediss://" + node
144 } else {
145 discovery[0].Targets[i] = "redis://" + node
146 }
147 }
148
149 data, err := json.MarshalIndent(discovery, "", " ")
150 if err != nil {
151 http.Error(w, fmt.Sprintf("Failed to marshal discovery data: %s", err), http.StatusInternalServerError)
152 return
153 }
154
155 w.Header().Set("Content-Type", "application/json")
156 _, _ = w.Write(data)
157 }
158
159 func (e *Exporter) reloadPwdFile(w http.ResponseWriter, r *http.Request) {
160 if e.options.RedisPwdFile == "" {
161 http.Error(w, "There is no pwd file specified", http.StatusBadRequest)
162 return
163 }
164 log.Debugf("Reload redisPwdFile")
165 passwordMap, err := LoadPwdFile(e.options.RedisPwdFile)
166 if err != nil {
167 log.Errorf("Error reloading redis passwords from file %s, err: %s", e.options.RedisPwdFile, err)
168 http.Error(w, "failed to reload passwords file: "+err.Error(), http.StatusInternalServerError)
169 return
170 }
171 e.Lock()
172 e.options.PasswordMap = passwordMap
173 e.Unlock()
174 _, _ = w.Write([]byte(`ok`))
175 }
176
177 func (e *Exporter) isBasicAuthConfigured() bool {
178 return e.options.BasicAuthUsername != "" && (e.options.BasicAuthPassword != "" || e.options.BasicAuthHashPassword != "")
179 }
180
181 func (e *Exporter) verifyBasicAuth(user, password string, authHeaderSet bool) error {
182 if !e.isBasicAuthConfigured() {
183 return nil
184 }
185
186 if !authHeaderSet {
187 return errors.New("Unauthorized")
188 }
189
190 userCorrect := subtle.ConstantTimeCompare([]byte(user), []byte(e.options.BasicAuthUsername)) == 1
191 passCorrect := e.validateBasicAuthPassword(password)
192
193 if !userCorrect || !passCorrect {
194 return errors.New("Unauthorized")
195 }
196
197 return nil
198 }
199
200 func (e *Exporter) validateBasicAuthPassword(password string) bool {
201 if e.options.BasicAuthHashPassword != "" {
202 return bcrypt.CompareHashAndPassword([]byte(e.options.BasicAuthHashPassword), []byte(password)) == nil
203 } else {
204 return subtle.ConstantTimeCompare([]byte(password), []byte(e.options.BasicAuthPassword)) == 1
205 }
206 }