This repository was archived by the owner on Feb 7, 2022. It is now read-only.
forked from Luzifer/grafana-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
188 lines (160 loc) · 4.87 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
package main
import (
"context"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/cookiejar"
"net/url"
"os"
"time"
"github.com/Luzifer/rconfig"
"github.com/cenkalti/backoff"
"github.com/satori/go.uuid"
log "github.com/sirupsen/logrus"
)
const RequestIDKey = "request_id"
var (
cfg = struct {
User string `flag:"user,u" default:"" env:"USER" description:"Username for Grafana login"`
Pass string `flag:"pass,p" default:"" env:"PASS" description:"Password for Grafana login"`
BaseURL string `flag:"baseurl" default:"" env:"BASEURL" description:"BaseURL (excluding last /) of Grafana"`
Listen string `flag:"listen" default:"127.0.0.1:8081" description:"IP/Port to listen on"`
Token string `flag:"token" default:"" env:"TOKEN" description:"(optional) require a ?token=xyz parameter to show the dashboard"`
LogFormat string `flag:"log-format" default:"text" env:"LOG_FORMAT" description:"Output format for logs (text/json)"`
}{}
cookieJar *cookiejar.Jar
client *http.Client
base *url.URL
)
func init() {
if err := rconfig.Parse(&cfg); err != nil {
log.Fatalf("Unable to parse commandline options: %s", err)
}
switch cfg.LogFormat {
case "text":
log.SetFormatter(&log.TextFormatter{})
case "json":
log.SetFormatter(&log.JSONFormatter{})
default:
log.Fatalf("Unknown log format: %s", cfg.LogFormat)
}
log.SetLevel(log.InfoLevel)
if cfg.User == "" || cfg.Pass == "" || cfg.BaseURL == "" {
rconfig.Usage()
os.Exit(1)
}
cookieJar, _ = cookiejar.New(nil)
client = &http.Client{
Jar: cookieJar,
}
}
func loadLogin(ctx context.Context) {
backoff.Retry(func() error {
resp, err := client.PostForm(fmt.Sprintf("%s/login", cfg.BaseURL), url.Values{
"user": {cfg.User},
"password": {cfg.Pass},
})
if err != nil {
log.WithError(err).WithFields(log.Fields{
"user": cfg.User,
"request_id": requestIDFromContext(ctx),
}).Error("Login failed")
return err
}
defer resp.Body.Close()
return nil
}, backoff.NewExponentialBackOff())
}
type proxy struct{}
func (p proxy) ServeHTTP(res http.ResponseWriter, r *http.Request) {
requestID := uuid.NewV4().String()
bgCtx := context.Background()
ctx := context.WithValue(bgCtx, RequestIDKey, requestID)
requestLog := log.WithFields(log.Fields{
"http_user_agent": r.Header.Get("User-Agent"),
"host": r.Host,
"remote_addr": r.Header.Get("X-Forwarded-For"),
"request": r.URL.Path,
"request_full": r.URL.String(),
"request_method": r.Method,
"request_id": requestIDFromContext(ctx),
})
bo := backoff.NewExponentialBackOff()
bo.MaxElapsedTime = 5 * time.Second
if err := backoff.Retry(func() error {
r.URL.Host = base.Host
r.URL.Scheme = base.Scheme
r.RequestURI = ""
r.Host = base.Host
suppliedToken := r.URL.Query().Get("token")
if authCookie, err := r.Cookie("grafana-proxy-auth"); err == nil {
suppliedToken = authCookie.Value
}
if cfg.Token != "" && suppliedToken != cfg.Token {
requestLog.Error("Token parameter is wrong")
http.Error(res, "Please add the `?token=xyz` parameter with correct token", http.StatusForbidden)
return nil
}
// Do not forward cookies set by the client, use our own cookie jar
r.Header.Del("Cookie")
resp, err := client.Do(r)
if err != nil {
requestLog.WithError(err).Error("Request failed")
return err
}
defer resp.Body.Close()
res.Header().Del("Content-Type")
res.Header().Del("Set-Cookie") // Client does not need to handle cookies but Grafana passes them
for k, v := range resp.Header {
for _, v1 := range v {
res.Header().Set(k, v1)
}
}
if r.URL.Query().Get("token") != "" {
http.SetCookie(res, &http.Cookie{
Name: "grafana-proxy-auth",
Value: r.URL.Query().Get("token"),
MaxAge: 31536000, // 1 Year
Path: "/",
})
}
if resp.StatusCode == 401 {
errmsg, _ := ioutil.ReadAll(resp.Body)
requestLog.WithFields(log.Fields{
"error": string(errmsg),
"header": r.Header,
}).Info("Unauthorized, trying to login")
loadLogin(ctx)
return fmt.Errorf("Need to relogin")
}
res.WriteHeader(resp.StatusCode)
written, _ := io.Copy(res, resp.Body)
requestLog.WithFields(log.Fields{
"status": resp.StatusCode,
"bytes_sent": written,
}).Info("Request completed")
return nil
}, bo); err != nil {
requestLog.WithError(err).WithFields(log.Fields{
"status": http.StatusInternalServerError,
}).Error("Backend request failed")
http.Error(res, fmt.Sprintf("Woot?\n%s", err), http.StatusInternalServerError)
}
}
func requestIDFromContext(ctx context.Context) string {
if id, ok := ctx.Value(RequestIDKey).(string); ok {
return id
}
return ""
}
func main() {
loadLogin(context.Background())
var err error
base, err = url.Parse(cfg.BaseURL)
if err != nil {
log.WithError(err).WithField("base_url", base).Fatalf("BaseURL is not parsesable")
}
log.Fatal(http.ListenAndServe(cfg.Listen, proxy{}))
}