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