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