10666: Merge branch 'master' into 10666-report-version
[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         var auth string
236         if auth = req.Header.Get("Authorization"); auth == "" {
237                 return false, ""
238         }
239
240         _, err := fmt.Sscanf(auth, "OAuth2 %s", &tok)
241         if err != nil {
242                 // Scanning error
243                 return false, ""
244         }
245
246         if cache.RecallToken(tok) {
247                 // Valid in the cache, short circuit
248                 return true, tok
249         }
250
251         arv := *kc.Arvados
252         arv.ApiToken = tok
253         if err := arv.Call("HEAD", "users", "", "current", nil, nil); err != nil {
254                 log.Printf("%s: CheckAuthorizationHeader error: %v", GetRemoteAddress(req), err)
255                 return false, ""
256         }
257
258         // Success!  Update cache
259         cache.RememberToken(tok)
260
261         return true, tok
262 }
263
264 type proxyHandler struct {
265         http.Handler
266         *keepclient.KeepClient
267         *ApiTokenCache
268         timeout   time.Duration
269         transport *http.Transport
270 }
271
272 // MakeRESTRouter returns an http.Handler that passes GET and PUT
273 // requests to the appropriate handlers.
274 func MakeRESTRouter(enable_get bool, enable_put bool, kc *keepclient.KeepClient, timeout time.Duration, mgmtToken string) http.Handler {
275         rest := mux.NewRouter()
276
277         transport := *(http.DefaultTransport.(*http.Transport))
278         transport.DialContext = (&net.Dialer{
279                 Timeout:   keepclient.DefaultConnectTimeout,
280                 KeepAlive: keepclient.DefaultKeepAlive,
281                 DualStack: true,
282         }).DialContext
283         transport.TLSClientConfig = arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure)
284         transport.TLSHandshakeTimeout = keepclient.DefaultTLSHandshakeTimeout
285
286         h := &proxyHandler{
287                 Handler:    rest,
288                 KeepClient: kc,
289                 timeout:    timeout,
290                 transport:  &transport,
291                 ApiTokenCache: &ApiTokenCache{
292                         tokens:     make(map[string]int64),
293                         expireTime: 300,
294                 },
295         }
296
297         if enable_get {
298                 rest.HandleFunc(`/{locator:[0-9a-f]{32}\+.*}`, h.Get).Methods("GET", "HEAD")
299                 rest.HandleFunc(`/{locator:[0-9a-f]{32}}`, h.Get).Methods("GET", "HEAD")
300
301                 // List all blocks
302                 rest.HandleFunc(`/index`, h.Index).Methods("GET")
303
304                 // List blocks whose hash has the given prefix
305                 rest.HandleFunc(`/index/{prefix:[0-9a-f]{0,32}}`, h.Index).Methods("GET")
306         }
307
308         if enable_put {
309                 rest.HandleFunc(`/{locator:[0-9a-f]{32}\+.*}`, h.Put).Methods("PUT")
310                 rest.HandleFunc(`/{locator:[0-9a-f]{32}}`, h.Put).Methods("PUT")
311                 rest.HandleFunc(`/`, h.Put).Methods("POST")
312                 rest.HandleFunc(`/{any}`, h.Options).Methods("OPTIONS")
313                 rest.HandleFunc(`/`, h.Options).Methods("OPTIONS")
314         }
315
316         rest.Handle("/_health/{check}", &health.Handler{
317                 Token:  mgmtToken,
318                 Prefix: "/_health/",
319         }).Methods("GET")
320
321         rest.NotFoundHandler = InvalidPathHandler{}
322         return h
323 }
324
325 var errLoopDetected = errors.New("loop detected")
326
327 func (*proxyHandler) checkLoop(resp http.ResponseWriter, req *http.Request) error {
328         if via := req.Header.Get("Via"); strings.Index(via, " "+viaAlias) >= 0 {
329                 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)
330                 http.Error(resp, errLoopDetected.Error(), http.StatusInternalServerError)
331                 return errLoopDetected
332         }
333         return nil
334 }
335
336 func SetCorsHeaders(resp http.ResponseWriter) {
337         resp.Header().Set("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, OPTIONS")
338         resp.Header().Set("Access-Control-Allow-Origin", "*")
339         resp.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Length, Content-Type, X-Keep-Desired-Replicas")
340         resp.Header().Set("Access-Control-Max-Age", "86486400")
341 }
342
343 type InvalidPathHandler struct{}
344
345 func (InvalidPathHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
346         log.Printf("%s: %s %s unroutable", GetRemoteAddress(req), req.Method, req.URL.Path)
347         http.Error(resp, "Bad request", http.StatusBadRequest)
348 }
349
350 func (h *proxyHandler) Options(resp http.ResponseWriter, req *http.Request) {
351         log.Printf("%s: %s %s", GetRemoteAddress(req), req.Method, req.URL.Path)
352         SetCorsHeaders(resp)
353 }
354
355 var BadAuthorizationHeader = errors.New("Missing or invalid Authorization header")
356 var ContentLengthMismatch = errors.New("Actual length != expected content length")
357 var MethodNotSupported = errors.New("Method not supported")
358
359 var removeHint, _ = regexp.Compile("\\+K@[a-z0-9]{5}(\\+|$)")
360
361 func (h *proxyHandler) Get(resp http.ResponseWriter, req *http.Request) {
362         if err := h.checkLoop(resp, req); err != nil {
363                 return
364         }
365         SetCorsHeaders(resp)
366         resp.Header().Set("Via", req.Proto+" "+viaAlias)
367
368         locator := mux.Vars(req)["locator"]
369         var err error
370         var status int
371         var expectLength, responseLength int64
372         var proxiedURI = "-"
373
374         defer func() {
375                 log.Println(GetRemoteAddress(req), req.Method, req.URL.Path, status, expectLength, responseLength, proxiedURI, err)
376                 if status != http.StatusOK {
377                         http.Error(resp, err.Error(), status)
378                 }
379         }()
380
381         kc := h.makeKeepClient(req)
382
383         var pass bool
384         var tok string
385         if pass, tok = CheckAuthorizationHeader(kc, h.ApiTokenCache, req); !pass {
386                 status, err = http.StatusForbidden, BadAuthorizationHeader
387                 return
388         }
389
390         // Copy ArvadosClient struct and use the client's API token
391         arvclient := *kc.Arvados
392         arvclient.ApiToken = tok
393         kc.Arvados = &arvclient
394
395         var reader io.ReadCloser
396
397         locator = removeHint.ReplaceAllString(locator, "$1")
398
399         switch req.Method {
400         case "HEAD":
401                 expectLength, proxiedURI, err = kc.Ask(locator)
402         case "GET":
403                 reader, expectLength, proxiedURI, err = kc.Get(locator)
404                 if reader != nil {
405                         defer reader.Close()
406                 }
407         default:
408                 status, err = http.StatusNotImplemented, MethodNotSupported
409                 return
410         }
411
412         if expectLength == -1 {
413                 log.Println("Warning:", GetRemoteAddress(req), req.Method, proxiedURI, "Content-Length not provided")
414         }
415
416         switch respErr := err.(type) {
417         case nil:
418                 status = http.StatusOK
419                 resp.Header().Set("Content-Length", fmt.Sprint(expectLength))
420                 switch req.Method {
421                 case "HEAD":
422                         responseLength = 0
423                 case "GET":
424                         responseLength, err = io.Copy(resp, reader)
425                         if err == nil && expectLength > -1 && responseLength != expectLength {
426                                 err = ContentLengthMismatch
427                         }
428                 }
429         case keepclient.Error:
430                 if respErr == keepclient.BlockNotFound {
431                         status = http.StatusNotFound
432                 } else if respErr.Temporary() {
433                         status = http.StatusBadGateway
434                 } else {
435                         status = 422
436                 }
437         default:
438                 status = http.StatusInternalServerError
439         }
440 }
441
442 var LengthRequiredError = errors.New(http.StatusText(http.StatusLengthRequired))
443 var LengthMismatchError = errors.New("Locator size hint does not match Content-Length header")
444
445 func (h *proxyHandler) Put(resp http.ResponseWriter, req *http.Request) {
446         if err := h.checkLoop(resp, req); err != nil {
447                 return
448         }
449         SetCorsHeaders(resp)
450         resp.Header().Set("Via", "HTTP/1.1 "+viaAlias)
451
452         kc := h.makeKeepClient(req)
453
454         var err error
455         var expectLength int64
456         var status = http.StatusInternalServerError
457         var wroteReplicas int
458         var locatorOut string = "-"
459
460         defer func() {
461                 log.Println(GetRemoteAddress(req), req.Method, req.URL.Path, status, expectLength, kc.Want_replicas, wroteReplicas, locatorOut, err)
462                 if status != http.StatusOK {
463                         http.Error(resp, err.Error(), status)
464                 }
465         }()
466
467         locatorIn := mux.Vars(req)["locator"]
468
469         _, err = fmt.Sscanf(req.Header.Get("Content-Length"), "%d", &expectLength)
470         if err != nil || expectLength < 0 {
471                 err = LengthRequiredError
472                 status = http.StatusLengthRequired
473                 return
474         }
475
476         if locatorIn != "" {
477                 var loc *keepclient.Locator
478                 if loc, err = keepclient.MakeLocator(locatorIn); err != nil {
479                         status = http.StatusBadRequest
480                         return
481                 } else if loc.Size > 0 && int64(loc.Size) != expectLength {
482                         err = LengthMismatchError
483                         status = http.StatusBadRequest
484                         return
485                 }
486         }
487
488         var pass bool
489         var tok string
490         if pass, tok = CheckAuthorizationHeader(kc, h.ApiTokenCache, req); !pass {
491                 err = BadAuthorizationHeader
492                 status = http.StatusForbidden
493                 return
494         }
495
496         // Copy ArvadosClient struct and use the client's API token
497         arvclient := *kc.Arvados
498         arvclient.ApiToken = tok
499         kc.Arvados = &arvclient
500
501         // Check if the client specified the number of replicas
502         if req.Header.Get("X-Keep-Desired-Replicas") != "" {
503                 var r int
504                 _, err := fmt.Sscanf(req.Header.Get(keepclient.X_Keep_Desired_Replicas), "%d", &r)
505                 if err == nil {
506                         kc.Want_replicas = r
507                 }
508         }
509
510         // Now try to put the block through
511         if locatorIn == "" {
512                 if bytes, err := ioutil.ReadAll(req.Body); err != nil {
513                         err = errors.New(fmt.Sprintf("Error reading request body: %s", err))
514                         status = http.StatusInternalServerError
515                         return
516                 } else {
517                         locatorOut, wroteReplicas, err = kc.PutB(bytes)
518                 }
519         } else {
520                 locatorOut, wroteReplicas, err = kc.PutHR(locatorIn, req.Body, expectLength)
521         }
522
523         // Tell the client how many successful PUTs we accomplished
524         resp.Header().Set(keepclient.X_Keep_Replicas_Stored, fmt.Sprintf("%d", wroteReplicas))
525
526         switch err.(type) {
527         case nil:
528                 status = http.StatusOK
529                 _, err = io.WriteString(resp, locatorOut)
530
531         case keepclient.OversizeBlockError:
532                 // Too much data
533                 status = http.StatusRequestEntityTooLarge
534
535         case keepclient.InsufficientReplicasError:
536                 if wroteReplicas > 0 {
537                         // At least one write is considered success.  The
538                         // client can decide if getting less than the number of
539                         // replications it asked for is a fatal error.
540                         status = http.StatusOK
541                         _, err = io.WriteString(resp, locatorOut)
542                 } else {
543                         status = http.StatusServiceUnavailable
544                 }
545
546         default:
547                 status = http.StatusBadGateway
548         }
549 }
550
551 // ServeHTTP implementation for IndexHandler
552 // Supports only GET requests for /index/{prefix:[0-9a-f]{0,32}}
553 // For each keep server found in LocalRoots:
554 //   Invokes GetIndex using keepclient
555 //   Expects "complete" response (terminating with blank new line)
556 //   Aborts on any errors
557 // Concatenates responses from all those keep servers and returns
558 func (h *proxyHandler) Index(resp http.ResponseWriter, req *http.Request) {
559         SetCorsHeaders(resp)
560
561         prefix := mux.Vars(req)["prefix"]
562         var err error
563         var status int
564
565         defer func() {
566                 if status != http.StatusOK {
567                         http.Error(resp, err.Error(), status)
568                 }
569         }()
570
571         kc := h.makeKeepClient(req)
572         ok, token := CheckAuthorizationHeader(kc, h.ApiTokenCache, req)
573         if !ok {
574                 status, err = http.StatusForbidden, BadAuthorizationHeader
575                 return
576         }
577
578         // Copy ArvadosClient struct and use the client's API token
579         arvclient := *kc.Arvados
580         arvclient.ApiToken = token
581         kc.Arvados = &arvclient
582
583         // Only GET method is supported
584         if req.Method != "GET" {
585                 status, err = http.StatusNotImplemented, MethodNotSupported
586                 return
587         }
588
589         // Get index from all LocalRoots and write to resp
590         var reader io.Reader
591         for uuid := range kc.LocalRoots() {
592                 reader, err = kc.GetIndex(uuid, prefix)
593                 if err != nil {
594                         status = http.StatusBadGateway
595                         return
596                 }
597
598                 _, err = io.Copy(resp, reader)
599                 if err != nil {
600                         status = http.StatusBadGateway
601                         return
602                 }
603         }
604
605         // Got index from all the keep servers and wrote to resp
606         status = http.StatusOK
607         resp.Write([]byte("\n"))
608 }
609
610 func (h *proxyHandler) makeKeepClient(req *http.Request) *keepclient.KeepClient {
611         kc := *h.KeepClient
612         kc.HTTPClient = &proxyClient{
613                 client: &http.Client{
614                         Timeout:   h.timeout,
615                         Transport: h.transport,
616                 },
617                 proto:     req.Proto,
618                 requestID: req.Header.Get("X-Request-Id"),
619         }
620         return &kc
621 }