-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
376 lines (333 loc) · 9.6 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
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
package main
import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"flag"
"fmt"
"log/slog"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"syscall"
"github.com/oklog/run"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/promhttp"
"tailscale.com/client/tailscale"
"tailscale.com/client/tailscale/apitype"
"tailscale.com/tsnet"
tslogger "tailscale.com/types/logger"
)
var (
requestsInFlight = promauto.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: "tsproxy",
Name: "requests_in_flight",
Help: "Number of requests currently being served by the server.",
},
[]string{"upstream"},
)
requests = promauto.NewCounterVec(
prometheus.CounterOpts{
Namespace: "tsproxy",
Name: "requests_total",
Help: "Number of requests received by the server.",
},
[]string{"upstream", "code", "method"},
)
duration = promauto.NewHistogramVec(
prometheus.HistogramOpts{
Namespace: "tsproxy",
Name: "request_duration_seconds",
Help: "A histogram of latencies for requests handled by the server.",
NativeHistogramBucketFactor: 1.1,
},
[]string{"upstream", "code", "method"},
)
)
type upstreamFlag []upstream
func (f *upstreamFlag) String() string {
return fmt.Sprintf("%+v", *f)
}
func (f *upstreamFlag) Set(val string) error {
up, err := parseUpstreamFlag(val)
if err != nil {
return err
}
*f = append(*f, up)
return nil
}
type upstream struct {
name string
backend *url.URL
prometheus bool
funnel bool
}
type target struct {
name string
magicDNS string
prometheus bool
}
func parseUpstreamFlag(fval string) (upstream, error) {
k, v, ok := strings.Cut(fval, "=")
if !ok {
return upstream{}, errors.New("format: name=http://backend")
}
val := strings.Split(v, ";")
be, err := url.Parse(val[0])
if err != nil {
return upstream{}, err
}
up := upstream{name: k, backend: be}
if len(val) > 1 {
for _, opt := range val[1:] {
switch opt {
case "prometheus":
up.prometheus = true
case "funnel":
up.funnel = true
default:
return upstream{}, fmt.Errorf("unsupported option: %v", opt)
}
}
}
return up, nil
}
func main() {
if err := tsproxy(context.Background()); err != nil {
fmt.Fprintf(os.Stderr, "tsproxy: %v\n", err)
os.Exit(1)
}
}
func tsproxy(ctx context.Context) error {
var (
state = flag.String("state", "", "Optional directory for storing Tailscale state.")
tslog = flag.Bool("tslog", false, "If true, log Tailscale output.")
port = flag.Int("port", 32019, "HTTP port for metrics and service discovery.")
)
var upstreams upstreamFlag
flag.Var(&upstreams, "upstream", "Repeated for each upstream. Format: name=http://backend:8000")
flag.Parse()
if len(upstreams) == 0 {
return fmt.Errorf("required flag missing: upstream")
}
if *state == "" {
v, err := os.UserCacheDir()
if err != nil {
return err
}
dir := filepath.Join(v, "tsproxy")
if err := os.MkdirAll(dir, 0o700); err != nil {
return err
}
state = &dir
}
logger := slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{}))
slog.SetDefault(logger)
// If tailscaled isn't ready yet, just crash.
st, err := (&tailscale.LocalClient{}).Status(ctx)
if err != nil {
return fmt.Errorf("tailscale: get node status: %w", err)
}
if v := len(st.Self.TailscaleIPs); v != 2 {
return fmt.Errorf("want 2 tailscale IPs, got %d", v)
}
// service discovery targets (self + all upstreams)
targets := make([]target, len(upstreams)+1)
var g run.Group
ctx, cancel := context.WithCancel(ctx)
defer cancel()
g.Add(run.SignalHandler(ctx, os.Interrupt, syscall.SIGTERM))
{
p := strconv.Itoa(*port)
var listeners []net.Listener
for _, ip := range st.Self.TailscaleIPs {
ln, err := net.Listen("tcp", net.JoinHostPort(ip.String(), p))
if err != nil {
return fmt.Errorf("listen on %s:%d: %w", ip, *port, err)
}
listeners = append(listeners, ln)
}
http.Handle("/metrics", promhttp.Handler())
http.Handle("/sd", serveDiscovery(net.JoinHostPort(st.Self.DNSName, p), targets))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(`<html>
<head><title>tsproxy</title></head>
<body>
<h1>tsproxy</h1>
<p><a href="/metrics">Metrics</a></p>
<p><a href="/sd">Discovery</a></p>
</body>
</html>`))
})
srv := &http.Server{}
for _, ln := range listeners {
ln := ln
g.Add(func() error {
logger.Info("server ready", slog.String("addr", ln.Addr().String()))
return srv.Serve(ln)
}, func(err error) {
if err := srv.Close(); err != nil {
logger.Error("shutdown server", lerr(err))
}
cancel()
})
}
}
for i, upstream := range upstreams {
// https://go.dev/doc/faq#closures_and_goroutines
i := i
upstream := upstream
log := logger.With(slog.String("upstream", upstream.name))
ts := &tsnet.Server{
Hostname: upstream.name,
Dir: filepath.Join(*state, "tailscale-"+upstream.name),
}
defer ts.Close()
if *tslog {
ts.Logf = func(format string, args ...any) {
log.Info(fmt.Sprintf(format, args...), slog.String("logger", "tailscale"))
}
} else {
ts.Logf = tslogger.Discard
}
if err := os.MkdirAll(ts.Dir, 0o700); err != nil {
return err
}
lc, err := ts.LocalClient()
if err != nil {
return fmt.Errorf("tailscale: get local client for %s: %w", upstream.name, err)
}
srv := &http.Server{
TLSConfig: &tls.Config{GetCertificate: lc.GetCertificate},
Handler: promhttp.InstrumentHandlerInFlight(requestsInFlight.With(prometheus.Labels{"upstream": upstream.name}),
promhttp.InstrumentHandlerDuration(duration.MustCurryWith(prometheus.Labels{"upstream": upstream.name}),
promhttp.InstrumentHandlerCounter(requests.MustCurryWith(prometheus.Labels{"upstream": upstream.name}),
newReverseProxy(log, lc, upstream.backend)))),
}
g.Add(func() error {
st, err := ts.Up(ctx)
if err != nil {
return fmt.Errorf("tailscale: wait for node %s to be ready: %w", upstream.name, err)
}
// register in service discovery when we're ready.
targets[i] = target{name: upstream.name, prometheus: upstream.prometheus, magicDNS: st.Self.DNSName}
ln, err := ts.Listen("tcp", ":80")
if err != nil {
return fmt.Errorf("tailscale: listen for %s on port 80: %w", upstream.name, err)
}
return srv.Serve(ln)
}, func(err error) {
if err := srv.Close(); err != nil {
log.Error("server shutdown", lerr(err))
}
cancel()
})
g.Add(func() error {
_, err := ts.Up(ctx)
if err != nil {
return fmt.Errorf("tailscale: wait for node %s to be ready: %w", upstream.name, err)
}
if upstream.funnel {
ln, err := ts.ListenFunnel("tcp", ":443")
if err != nil {
return fmt.Errorf("tailscale: funnel for %s on port 443: %w", upstream.name, err)
}
return srv.Serve(ln)
}
ln, err := ts.Listen("tcp", ":443")
if err != nil {
return fmt.Errorf("tailscale: listen for %s on port 443: %w", upstream.name, err)
}
return srv.ServeTLS(ln, "", "")
}, func(err error) {
if err := srv.Close(); err != nil {
log.Error("TLS server shutdown", lerr(err))
}
cancel()
})
}
return g.Run()
}
type tailscaleLocalClient interface {
WhoIs(context.Context, string) (*apitype.WhoIsResponse, error)
}
func newReverseProxy(logger *slog.Logger, lc tailscaleLocalClient, url *url.URL) http.HandlerFunc {
// TODO(sr) Instrument proxy.Transport
rproxy := &httputil.ReverseProxy{
Rewrite: func(req *httputil.ProxyRequest) {
req.SetURL(url)
req.SetXForwarded()
req.Out.Host = req.In.Host
},
}
rproxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
http.Error(w, http.StatusText(http.StatusBadGateway), http.StatusBadGateway)
logger.Error("upstream error", lerr(err))
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
whois, err := lc.WhoIs(r.Context(), r.RemoteAddr)
if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
logger.Error("tailscale whois", lerr(err))
return
}
if whois.Node == nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
logger.Error("tailscale whois", slog.String("err", "node missing"))
return
}
if whois.UserProfile == nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
logger.Error("tailscale whois", slog.String("err", "user profile missing"))
return
}
// Proxy requests from tagged nodes as is.
if whois.Node.IsTagged() {
rproxy.ServeHTTP(w, r)
return
}
req := r.Clone(r.Context())
req.Header.Set("X-Webauth-User", whois.UserProfile.LoginName)
req.Header.Set("X-Webauth-Name", whois.UserProfile.DisplayName)
rproxy.ServeHTTP(w, req)
})
}
func serveDiscovery(self string, targets []target) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var tgs []string
tgs = append(tgs, self)
for _, t := range targets {
if t.magicDNS == "" {
continue
}
if !t.prometheus {
continue
}
tgs = append(tgs, t.magicDNS)
}
sort.Strings(tgs)
buf, err := json.Marshal([]struct {
Targets []string `json:"targets"`
}{
{Targets: tgs},
})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
_, _ = w.Write(buf)
})
}
func lerr(err error) slog.Attr {
return slog.String("err", err.Error())
}