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