59eec0bb04a3e67842334cbd429a006ba178f80d
[arvados.git] / services / keepproxy / keepproxy.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package main
6
7 import (
8         "errors"
9         "flag"
10         "fmt"
11         "io"
12         "io/ioutil"
13         "log"
14         "net"
15         "net/http"
16         "os"
17         "os/signal"
18         "regexp"
19         "strings"
20         "sync"
21         "syscall"
22         "time"
23
24         "git.curoverse.com/arvados.git/sdk/go/arvados"
25         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
26         "git.curoverse.com/arvados.git/sdk/go/config"
27         "git.curoverse.com/arvados.git/sdk/go/health"
28         "git.curoverse.com/arvados.git/sdk/go/keepclient"
29         "github.com/coreos/go-systemd/daemon"
30         "github.com/ghodss/yaml"
31         "github.com/gorilla/mux"
32 )
33
34 var version = "dev"
35
36 type Config struct {
37         Client          arvados.Client
38         Listen          string
39         DisableGet      bool
40         DisablePut      bool
41         DefaultReplicas int
42         Timeout         arvados.Duration
43         PIDFile         string
44         Debug           bool
45         ManagementToken string
46 }
47
48 func DefaultConfig() *Config {
49         return &Config{
50                 Listen:  ":25107",
51                 Timeout: arvados.Duration(15 * time.Second),
52         }
53 }
54
55 var (
56         listener net.Listener
57         router   http.Handler
58 )
59
60 func main() {
61         cfg := DefaultConfig()
62
63         flagset := flag.NewFlagSet("keepproxy", flag.ExitOnError)
64         flagset.Usage = usage
65
66         const deprecated = " (DEPRECATED -- use config file instead)"
67         flagset.StringVar(&cfg.Listen, "listen", cfg.Listen, "Local port to listen on."+deprecated)
68         flagset.BoolVar(&cfg.DisableGet, "no-get", cfg.DisableGet, "Disable GET operations."+deprecated)
69         flagset.BoolVar(&cfg.DisablePut, "no-put", cfg.DisablePut, "Disable PUT operations."+deprecated)
70         flagset.IntVar(&cfg.DefaultReplicas, "default-replicas", cfg.DefaultReplicas, "Default number of replicas to write if not specified by the client. If 0, use site default."+deprecated)
71         flagset.StringVar(&cfg.PIDFile, "pid", cfg.PIDFile, "Path to write pid file."+deprecated)
72         timeoutSeconds := flagset.Int("timeout", int(time.Duration(cfg.Timeout)/time.Second), "Timeout (in seconds) on requests to internal Keep services."+deprecated)
73         flagset.StringVar(&cfg.ManagementToken, "management-token", cfg.ManagementToken, "Authorization token to be included in all health check requests.")
74
75         var cfgPath string
76         const defaultCfgPath = "/etc/arvados/keepproxy/keepproxy.yml"
77         flagset.StringVar(&cfgPath, "config", defaultCfgPath, "Configuration file `path`")
78         dumpConfig := flagset.Bool("dump-config", false, "write current configuration to stdout and exit")
79         getVersion := flagset.Bool("version", false, "Print version information and exit.")
80         flagset.Parse(os.Args[1:])
81
82         // Print version information if requested
83         if *getVersion {
84                 fmt.Printf("Version: %s\n", version)
85                 os.Exit(0)
86         }
87
88         err := config.LoadFile(cfg, cfgPath)
89         if err != nil {
90                 h := os.Getenv("ARVADOS_API_HOST")
91                 t := os.Getenv("ARVADOS_API_TOKEN")
92                 if h == "" || t == "" || !os.IsNotExist(err) || cfgPath != defaultCfgPath {
93                         log.Fatal(err)
94                 }
95                 log.Print("DEPRECATED: No config file found, but ARVADOS_API_HOST and ARVADOS_API_TOKEN environment variables are set. Please use a config file instead.")
96                 cfg.Client.APIHost = h
97                 cfg.Client.AuthToken = t
98                 if regexp.MustCompile("^(?i:1|yes|true)$").MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE")) {
99                         cfg.Client.Insecure = true
100                 }
101                 if y, err := yaml.Marshal(cfg); err == nil && !*dumpConfig {
102                         log.Print("Current configuration:\n", string(y))
103                 }
104                 cfg.Timeout = arvados.Duration(time.Duration(*timeoutSeconds) * time.Second)
105         }
106
107         if *dumpConfig {
108                 log.Fatal(config.DumpAndExit(cfg))
109         }
110
111         log.Printf("keepproxy %q started", version)
112
113         arv, err := arvadosclient.New(&cfg.Client)
114         if err != nil {
115                 log.Fatalf("Error setting up arvados client %s", err.Error())
116         }
117
118         if cfg.Debug {
119                 keepclient.DebugPrintf = log.Printf
120         }
121         kc, err := keepclient.MakeKeepClient(arv)
122         if err != nil {
123                 log.Fatalf("Error setting up keep client %s", err.Error())
124         }
125         keepclient.RefreshServiceDiscoveryOnSIGHUP()
126
127         if cfg.PIDFile != "" {
128                 f, err := os.Create(cfg.PIDFile)
129                 if err != nil {
130                         log.Fatal(err)
131                 }
132                 defer f.Close()
133                 err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
134                 if err != nil {
135                         log.Fatalf("flock(%s): %s", cfg.PIDFile, err)
136                 }
137                 defer os.Remove(cfg.PIDFile)
138                 err = f.Truncate(0)
139                 if err != nil {
140                         log.Fatalf("truncate(%s): %s", cfg.PIDFile, err)
141                 }
142                 _, err = fmt.Fprint(f, os.Getpid())
143                 if err != nil {
144                         log.Fatalf("write(%s): %s", cfg.PIDFile, err)
145                 }
146                 err = f.Sync()
147                 if err != nil {
148                         log.Fatal("sync(%s): %s", cfg.PIDFile, err)
149                 }
150         }
151
152         if cfg.DefaultReplicas > 0 {
153                 kc.Want_replicas = cfg.DefaultReplicas
154         }
155
156         listener, err = net.Listen("tcp", cfg.Listen)
157         if err != nil {
158                 log.Fatalf("listen(%s): %s", cfg.Listen, err)
159         }
160         if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
161                 log.Printf("Error notifying init daemon: %v", err)
162         }
163         log.Println("Listening at", listener.Addr())
164
165         // Shut down the server gracefully (by closing the listener)
166         // if SIGTERM is received.
167         term := make(chan os.Signal, 1)
168         go func(sig <-chan os.Signal) {
169                 s := <-sig
170                 log.Println("caught signal:", s)
171                 listener.Close()
172         }(term)
173         signal.Notify(term, syscall.SIGTERM)
174         signal.Notify(term, syscall.SIGINT)
175
176         // Start serving requests.
177         router = MakeRESTRouter(!cfg.DisableGet, !cfg.DisablePut, kc, time.Duration(cfg.Timeout), cfg.ManagementToken)
178         http.Serve(listener, router)
179
180         log.Println("shutting down")
181 }
182
183 type ApiTokenCache struct {
184         tokens     map[string]int64
185         lock       sync.Mutex
186         expireTime int64
187 }
188
189 // Cache the token and set an expire time.  If we already have an expire time
190 // on the token, it is not updated.
191 func (this *ApiTokenCache) RememberToken(token string) {
192         this.lock.Lock()
193         defer this.lock.Unlock()
194
195         now := time.Now().Unix()
196         if this.tokens[token] == 0 {
197                 this.tokens[token] = now + this.expireTime
198         }
199 }
200
201 // Check if the cached token is known and still believed to be valid.
202 func (this *ApiTokenCache) RecallToken(token string) bool {
203         this.lock.Lock()
204         defer this.lock.Unlock()
205
206         now := time.Now().Unix()
207         if this.tokens[token] == 0 {
208                 // Unknown token
209                 return false
210         } else if now < this.tokens[token] {
211                 // Token is known and still valid
212                 return true
213         } else {
214                 // Token is expired
215                 this.tokens[token] = 0
216                 return false
217         }
218 }
219
220 func GetRemoteAddress(req *http.Request) string {
221         if xff := req.Header.Get("X-Forwarded-For"); xff != "" {
222                 return xff + "," + req.RemoteAddr
223         }
224         return req.RemoteAddr
225 }
226
227 func CheckAuthorizationHeader(kc *keepclient.KeepClient, cache *ApiTokenCache, req *http.Request) (pass bool, tok string) {
228         var auth string
229         if auth = req.Header.Get("Authorization"); auth == "" {
230                 return false, ""
231         }
232
233         _, err := fmt.Sscanf(auth, "OAuth2 %s", &tok)
234         if err != nil {
235                 // Scanning error
236                 return false, ""
237         }
238
239         if cache.RecallToken(tok) {
240                 // Valid in the cache, short circuit
241                 return true, tok
242         }
243
244         arv := *kc.Arvados
245         arv.ApiToken = tok
246         if err := arv.Call("HEAD", "users", "", "current", nil, nil); err != nil {
247                 log.Printf("%s: CheckAuthorizationHeader error: %v", GetRemoteAddress(req), err)
248                 return false, ""
249         }
250
251         // Success!  Update cache
252         cache.RememberToken(tok)
253
254         return true, tok
255 }
256
257 type proxyHandler struct {
258         http.Handler
259         *keepclient.KeepClient
260         *ApiTokenCache
261         timeout   time.Duration
262         transport *http.Transport
263 }
264
265 // MakeRESTRouter returns an http.Handler that passes GET and PUT
266 // requests to the appropriate handlers.
267 func MakeRESTRouter(enable_get bool, enable_put bool, kc *keepclient.KeepClient, timeout time.Duration, mgmtToken string) http.Handler {
268         rest := mux.NewRouter()
269
270         transport := *(http.DefaultTransport.(*http.Transport))
271         transport.DialContext = (&net.Dialer{
272                 Timeout:   keepclient.DefaultConnectTimeout,
273                 KeepAlive: keepclient.DefaultKeepAlive,
274                 DualStack: true,
275         }).DialContext
276         transport.TLSClientConfig = arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure)
277         transport.TLSHandshakeTimeout = keepclient.DefaultTLSHandshakeTimeout
278
279         h := &proxyHandler{
280                 Handler:    rest,
281                 KeepClient: kc,
282                 timeout:    timeout,
283                 transport:  &transport,
284                 ApiTokenCache: &ApiTokenCache{
285                         tokens:     make(map[string]int64),
286                         expireTime: 300,
287                 },
288         }
289
290         if enable_get {
291                 rest.HandleFunc(`/{locator:[0-9a-f]{32}\+.*}`, h.Get).Methods("GET", "HEAD")
292                 rest.HandleFunc(`/{locator:[0-9a-f]{32}}`, h.Get).Methods("GET", "HEAD")
293
294                 // List all blocks
295                 rest.HandleFunc(`/index`, h.Index).Methods("GET")
296
297                 // List blocks whose hash has the given prefix
298                 rest.HandleFunc(`/index/{prefix:[0-9a-f]{0,32}}`, h.Index).Methods("GET")
299         }
300
301         if enable_put {
302                 rest.HandleFunc(`/{locator:[0-9a-f]{32}\+.*}`, h.Put).Methods("PUT")
303                 rest.HandleFunc(`/{locator:[0-9a-f]{32}}`, h.Put).Methods("PUT")
304                 rest.HandleFunc(`/`, h.Put).Methods("POST")
305                 rest.HandleFunc(`/{any}`, h.Options).Methods("OPTIONS")
306                 rest.HandleFunc(`/`, h.Options).Methods("OPTIONS")
307         }
308
309         rest.Handle("/_health/{check}", &health.Handler{
310                 Token:  mgmtToken,
311                 Prefix: "/_health/",
312         }).Methods("GET")
313
314         rest.NotFoundHandler = InvalidPathHandler{}
315         return h
316 }
317
318 var errLoopDetected = errors.New("loop detected")
319
320 func (*proxyHandler) checkLoop(resp http.ResponseWriter, req *http.Request) error {
321         if via := req.Header.Get("Via"); strings.Index(via, " "+viaAlias) >= 0 {
322                 log.Printf("proxy loop detected (request has Via: %q): perhaps keepproxy is misidentified by gateway config as an external client, or its keep_services record does not have service_type=proxy?", via)
323                 http.Error(resp, errLoopDetected.Error(), http.StatusInternalServerError)
324                 return errLoopDetected
325         }
326         return nil
327 }
328
329 func SetCorsHeaders(resp http.ResponseWriter) {
330         resp.Header().Set("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, OPTIONS")
331         resp.Header().Set("Access-Control-Allow-Origin", "*")
332         resp.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Length, Content-Type, X-Keep-Desired-Replicas")
333         resp.Header().Set("Access-Control-Max-Age", "86486400")
334 }
335
336 type InvalidPathHandler struct{}
337
338 func (InvalidPathHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
339         log.Printf("%s: %s %s unroutable", GetRemoteAddress(req), req.Method, req.URL.Path)
340         http.Error(resp, "Bad request", http.StatusBadRequest)
341 }
342
343 func (h *proxyHandler) Options(resp http.ResponseWriter, req *http.Request) {
344         log.Printf("%s: %s %s", GetRemoteAddress(req), req.Method, req.URL.Path)
345         SetCorsHeaders(resp)
346 }
347
348 var BadAuthorizationHeader = errors.New("Missing or invalid Authorization header")
349 var ContentLengthMismatch = errors.New("Actual length != expected content length")
350 var MethodNotSupported = errors.New("Method not supported")
351
352 var removeHint, _ = regexp.Compile("\\+K@[a-z0-9]{5}(\\+|$)")
353
354 func (h *proxyHandler) Get(resp http.ResponseWriter, req *http.Request) {
355         if err := h.checkLoop(resp, req); err != nil {
356                 return
357         }
358         SetCorsHeaders(resp)
359         resp.Header().Set("Via", req.Proto+" "+viaAlias)
360
361         locator := mux.Vars(req)["locator"]
362         var err error
363         var status int
364         var expectLength, responseLength int64
365         var proxiedURI = "-"
366
367         defer func() {
368                 log.Println(GetRemoteAddress(req), req.Method, req.URL.Path, status, expectLength, responseLength, proxiedURI, err)
369                 if status != http.StatusOK {
370                         http.Error(resp, err.Error(), status)
371                 }
372         }()
373
374         kc := h.makeKeepClient(req)
375
376         var pass bool
377         var tok string
378         if pass, tok = CheckAuthorizationHeader(kc, h.ApiTokenCache, req); !pass {
379                 status, err = http.StatusForbidden, BadAuthorizationHeader
380                 return
381         }
382
383         // Copy ArvadosClient struct and use the client's API token
384         arvclient := *kc.Arvados
385         arvclient.ApiToken = tok
386         kc.Arvados = &arvclient
387
388         var reader io.ReadCloser
389
390         locator = removeHint.ReplaceAllString(locator, "$1")
391
392         switch req.Method {
393         case "HEAD":
394                 expectLength, proxiedURI, err = kc.Ask(locator)
395         case "GET":
396                 reader, expectLength, proxiedURI, err = kc.Get(locator)
397                 if reader != nil {
398                         defer reader.Close()
399                 }
400         default:
401                 status, err = http.StatusNotImplemented, MethodNotSupported
402                 return
403         }
404
405         if expectLength == -1 {
406                 log.Println("Warning:", GetRemoteAddress(req), req.Method, proxiedURI, "Content-Length not provided")
407         }
408
409         switch respErr := err.(type) {
410         case nil:
411                 status = http.StatusOK
412                 resp.Header().Set("Content-Length", fmt.Sprint(expectLength))
413                 switch req.Method {
414                 case "HEAD":
415                         responseLength = 0
416                 case "GET":
417                         responseLength, err = io.Copy(resp, reader)
418                         if err == nil && expectLength > -1 && responseLength != expectLength {
419                                 err = ContentLengthMismatch
420                         }
421                 }
422         case keepclient.Error:
423                 if respErr == keepclient.BlockNotFound {
424                         status = http.StatusNotFound
425                 } else if respErr.Temporary() {
426                         status = http.StatusBadGateway
427                 } else {
428                         status = 422
429                 }
430         default:
431                 status = http.StatusInternalServerError
432         }
433 }
434
435 var LengthRequiredError = errors.New(http.StatusText(http.StatusLengthRequired))
436 var LengthMismatchError = errors.New("Locator size hint does not match Content-Length header")
437
438 func (h *proxyHandler) Put(resp http.ResponseWriter, req *http.Request) {
439         if err := h.checkLoop(resp, req); err != nil {
440                 return
441         }
442         SetCorsHeaders(resp)
443         resp.Header().Set("Via", "HTTP/1.1 "+viaAlias)
444
445         kc := h.makeKeepClient(req)
446
447         var err error
448         var expectLength int64
449         var status = http.StatusInternalServerError
450         var wroteReplicas int
451         var locatorOut string = "-"
452
453         defer func() {
454                 log.Println(GetRemoteAddress(req), req.Method, req.URL.Path, status, expectLength, kc.Want_replicas, wroteReplicas, locatorOut, err)
455                 if status != http.StatusOK {
456                         http.Error(resp, err.Error(), status)
457                 }
458         }()
459
460         locatorIn := mux.Vars(req)["locator"]
461
462         _, err = fmt.Sscanf(req.Header.Get("Content-Length"), "%d", &expectLength)
463         if err != nil || expectLength < 0 {
464                 err = LengthRequiredError
465                 status = http.StatusLengthRequired
466                 return
467         }
468
469         if locatorIn != "" {
470                 var loc *keepclient.Locator
471                 if loc, err = keepclient.MakeLocator(locatorIn); err != nil {
472                         status = http.StatusBadRequest
473                         return
474                 } else if loc.Size > 0 && int64(loc.Size) != expectLength {
475                         err = LengthMismatchError
476                         status = http.StatusBadRequest
477                         return
478                 }
479         }
480
481         var pass bool
482         var tok string
483         if pass, tok = CheckAuthorizationHeader(kc, h.ApiTokenCache, req); !pass {
484                 err = BadAuthorizationHeader
485                 status = http.StatusForbidden
486                 return
487         }
488
489         // Copy ArvadosClient struct and use the client's API token
490         arvclient := *kc.Arvados
491         arvclient.ApiToken = tok
492         kc.Arvados = &arvclient
493
494         // Check if the client specified the number of replicas
495         if req.Header.Get("X-Keep-Desired-Replicas") != "" {
496                 var r int
497                 _, err := fmt.Sscanf(req.Header.Get(keepclient.X_Keep_Desired_Replicas), "%d", &r)
498                 if err == nil {
499                         kc.Want_replicas = r
500                 }
501         }
502
503         // Now try to put the block through
504         if locatorIn == "" {
505                 if bytes, err := ioutil.ReadAll(req.Body); err != nil {
506                         err = errors.New(fmt.Sprintf("Error reading request body: %s", err))
507                         status = http.StatusInternalServerError
508                         return
509                 } else {
510                         locatorOut, wroteReplicas, err = kc.PutB(bytes)
511                 }
512         } else {
513                 locatorOut, wroteReplicas, err = kc.PutHR(locatorIn, req.Body, expectLength)
514         }
515
516         // Tell the client how many successful PUTs we accomplished
517         resp.Header().Set(keepclient.X_Keep_Replicas_Stored, fmt.Sprintf("%d", wroteReplicas))
518
519         switch err.(type) {
520         case nil:
521                 status = http.StatusOK
522                 _, err = io.WriteString(resp, locatorOut)
523
524         case keepclient.OversizeBlockError:
525                 // Too much data
526                 status = http.StatusRequestEntityTooLarge
527
528         case keepclient.InsufficientReplicasError:
529                 if wroteReplicas > 0 {
530                         // At least one write is considered success.  The
531                         // client can decide if getting less than the number of
532                         // replications it asked for is a fatal error.
533                         status = http.StatusOK
534                         _, err = io.WriteString(resp, locatorOut)
535                 } else {
536                         status = http.StatusServiceUnavailable
537                 }
538
539         default:
540                 status = http.StatusBadGateway
541         }
542 }
543
544 // ServeHTTP implementation for IndexHandler
545 // Supports only GET requests for /index/{prefix:[0-9a-f]{0,32}}
546 // For each keep server found in LocalRoots:
547 //   Invokes GetIndex using keepclient
548 //   Expects "complete" response (terminating with blank new line)
549 //   Aborts on any errors
550 // Concatenates responses from all those keep servers and returns
551 func (h *proxyHandler) Index(resp http.ResponseWriter, req *http.Request) {
552         SetCorsHeaders(resp)
553
554         prefix := mux.Vars(req)["prefix"]
555         var err error
556         var status int
557
558         defer func() {
559                 if status != http.StatusOK {
560                         http.Error(resp, err.Error(), status)
561                 }
562         }()
563
564         kc := h.makeKeepClient(req)
565         ok, token := CheckAuthorizationHeader(kc, h.ApiTokenCache, req)
566         if !ok {
567                 status, err = http.StatusForbidden, BadAuthorizationHeader
568                 return
569         }
570
571         // Copy ArvadosClient struct and use the client's API token
572         arvclient := *kc.Arvados
573         arvclient.ApiToken = token
574         kc.Arvados = &arvclient
575
576         // Only GET method is supported
577         if req.Method != "GET" {
578                 status, err = http.StatusNotImplemented, MethodNotSupported
579                 return
580         }
581
582         // Get index from all LocalRoots and write to resp
583         var reader io.Reader
584         for uuid := range kc.LocalRoots() {
585                 reader, err = kc.GetIndex(uuid, prefix)
586                 if err != nil {
587                         status = http.StatusBadGateway
588                         return
589                 }
590
591                 _, err = io.Copy(resp, reader)
592                 if err != nil {
593                         status = http.StatusBadGateway
594                         return
595                 }
596         }
597
598         // Got index from all the keep servers and wrote to resp
599         status = http.StatusOK
600         resp.Write([]byte("\n"))
601 }
602
603 func (h *proxyHandler) makeKeepClient(req *http.Request) *keepclient.KeepClient {
604         kc := *h.KeepClient
605         kc.HTTPClient = &proxyClient{
606                 client: &http.Client{
607                         Timeout:   h.timeout,
608                         Transport: h.transport,
609                 },
610                 proto: req.Proto,
611         }
612         return &kc
613 }