CWL spec -> CWL standards
[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.arvados.org/arvados.git/lib/config"
24         "git.arvados.org/arvados.git/sdk/go/arvados"
25         "git.arvados.org/arvados.git/sdk/go/arvadosclient"
26         "git.arvados.org/arvados.git/sdk/go/health"
27         "git.arvados.org/arvados.git/sdk/go/httpserver"
28         "git.arvados.org/arvados.git/sdk/go/keepclient"
29         "github.com/coreos/go-systemd/daemon"
30         "github.com/ghodss/yaml"
31         "github.com/gorilla/mux"
32         log "github.com/sirupsen/logrus"
33 )
34
35 var version = "dev"
36
37 var (
38         listener net.Listener
39         router   http.Handler
40 )
41
42 const rfc3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00"
43
44 func configure(logger log.FieldLogger, args []string) (*arvados.Cluster, error) {
45         flags := flag.NewFlagSet(args[0], flag.ExitOnError)
46
47         dumpConfig := flags.Bool("dump-config", false, "write current configuration to stdout and exit")
48         getVersion := flags.Bool("version", false, "Print version information and exit.")
49
50         loader := config.NewLoader(os.Stdin, logger)
51         loader.SetupFlags(flags)
52
53         args = loader.MungeLegacyConfigArgs(logger, args[1:], "-legacy-keepproxy-config")
54         flags.Parse(args)
55
56         // Print version information if requested
57         if *getVersion {
58                 fmt.Printf("keepproxy %s\n", version)
59                 return nil, nil
60         }
61
62         cfg, err := loader.Load()
63         if err != nil {
64                 return nil, err
65         }
66         cluster, err := cfg.GetCluster("")
67         if err != nil {
68                 return nil, err
69         }
70
71         if *dumpConfig {
72                 out, err := yaml.Marshal(cfg)
73                 if err != nil {
74                         return nil, err
75                 }
76                 if _, err := os.Stdout.Write(out); err != nil {
77                         return nil, err
78                 }
79                 return nil, nil
80         }
81         return cluster, nil
82 }
83
84 func main() {
85         logger := log.New()
86         logger.Formatter = &log.JSONFormatter{
87                 TimestampFormat: rfc3339NanoFixed,
88         }
89
90         cluster, err := configure(logger, os.Args)
91         if err != nil {
92                 log.Fatal(err)
93         }
94         if cluster == nil {
95                 return
96         }
97
98         log.Printf("keepproxy %s started", version)
99
100         if err := run(logger, cluster); err != nil {
101                 log.Fatal(err)
102         }
103
104         log.Println("shutting down")
105 }
106
107 func run(logger log.FieldLogger, cluster *arvados.Cluster) error {
108         client, err := arvados.NewClientFromConfig(cluster)
109         if err != nil {
110                 return err
111         }
112         client.AuthToken = cluster.SystemRootToken
113
114         arv, err := arvadosclient.New(client)
115         if err != nil {
116                 return fmt.Errorf("Error setting up arvados client %v", err)
117         }
118
119         if cluster.SystemLogs.LogLevel == "debug" {
120                 keepclient.DebugPrintf = log.Printf
121         }
122         kc, err := keepclient.MakeKeepClient(arv)
123         if err != nil {
124                 return fmt.Errorf("Error setting up keep client %v", err)
125         }
126         keepclient.RefreshServiceDiscoveryOnSIGHUP()
127
128         if cluster.Collections.DefaultReplication > 0 {
129                 kc.Want_replicas = cluster.Collections.DefaultReplication
130         }
131
132         var listen arvados.URL
133         for listen = range cluster.Services.Keepproxy.InternalURLs {
134                 break
135         }
136
137         var lErr error
138         listener, lErr = net.Listen("tcp", listen.Host)
139         if lErr != nil {
140                 return fmt.Errorf("listen(%s): %v", listen.Host, lErr)
141         }
142
143         if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
144                 log.Printf("Error notifying init daemon: %v", err)
145         }
146         log.Println("listening at", listener.Addr())
147
148         // Shut down the server gracefully (by closing the listener)
149         // if SIGTERM is received.
150         term := make(chan os.Signal, 1)
151         go func(sig <-chan os.Signal) {
152                 s := <-sig
153                 log.Println("caught signal:", s)
154                 listener.Close()
155         }(term)
156         signal.Notify(term, syscall.SIGTERM)
157         signal.Notify(term, syscall.SIGINT)
158
159         // Start serving requests.
160         router = MakeRESTRouter(kc, time.Duration(cluster.API.KeepServiceRequestTimeout), cluster.ManagementToken)
161         return http.Serve(listener, httpserver.AddRequestIDs(httpserver.LogRequests(router)))
162 }
163
164 type ApiTokenCache struct {
165         tokens     map[string]int64
166         lock       sync.Mutex
167         expireTime int64
168 }
169
170 // Cache the token and set an expire time.  If we already have an expire time
171 // on the token, it is not updated.
172 func (this *ApiTokenCache) RememberToken(token string) {
173         this.lock.Lock()
174         defer this.lock.Unlock()
175
176         now := time.Now().Unix()
177         if this.tokens[token] == 0 {
178                 this.tokens[token] = now + this.expireTime
179         }
180 }
181
182 // Check if the cached token is known and still believed to be valid.
183 func (this *ApiTokenCache) RecallToken(token string) bool {
184         this.lock.Lock()
185         defer this.lock.Unlock()
186
187         now := time.Now().Unix()
188         if this.tokens[token] == 0 {
189                 // Unknown token
190                 return false
191         } else if now < this.tokens[token] {
192                 // Token is known and still valid
193                 return true
194         } else {
195                 // Token is expired
196                 this.tokens[token] = 0
197                 return false
198         }
199 }
200
201 func GetRemoteAddress(req *http.Request) string {
202         if xff := req.Header.Get("X-Forwarded-For"); xff != "" {
203                 return xff + "," + req.RemoteAddr
204         }
205         return req.RemoteAddr
206 }
207
208 func CheckAuthorizationHeader(kc *keepclient.KeepClient, cache *ApiTokenCache, req *http.Request) (pass bool, tok string) {
209         parts := strings.SplitN(req.Header.Get("Authorization"), " ", 2)
210         if len(parts) < 2 || !(parts[0] == "OAuth2" || parts[0] == "Bearer") || len(parts[1]) == 0 {
211                 return false, ""
212         }
213         tok = parts[1]
214
215         // Tokens are validated differently depending on what kind of
216         // operation is being performed. For example, tokens in
217         // collection-sharing links permit GET requests, but not
218         // PUT requests.
219         var op string
220         if req.Method == "GET" || req.Method == "HEAD" {
221                 op = "read"
222         } else {
223                 op = "write"
224         }
225
226         if cache.RecallToken(op + ":" + tok) {
227                 // Valid in the cache, short circuit
228                 return true, tok
229         }
230
231         var err error
232         arv := *kc.Arvados
233         arv.ApiToken = tok
234         arv.RequestID = req.Header.Get("X-Request-Id")
235         if op == "read" {
236                 err = arv.Call("HEAD", "keep_services", "", "accessible", nil, nil)
237         } else {
238                 err = arv.Call("HEAD", "users", "", "current", nil, nil)
239         }
240         if err != nil {
241                 log.Printf("%s: CheckAuthorizationHeader error: %v", GetRemoteAddress(req), err)
242                 return false, ""
243         }
244
245         // Success!  Update cache
246         cache.RememberToken(op + ":" + tok)
247
248         return true, tok
249 }
250
251 // We need to make a private copy of the default http transport early
252 // in initialization, then make copies of our private copy later. It
253 // won't be safe to copy http.DefaultTransport itself later, because
254 // its private mutexes might have already been used. (Without this,
255 // the test suite sometimes panics "concurrent map writes" in
256 // net/http.(*Transport).removeIdleConnLocked().)
257 var defaultTransport = *(http.DefaultTransport.(*http.Transport))
258
259 type proxyHandler struct {
260         http.Handler
261         *keepclient.KeepClient
262         *ApiTokenCache
263         timeout   time.Duration
264         transport *http.Transport
265 }
266
267 // MakeRESTRouter returns an http.Handler that passes GET and PUT
268 // requests to the appropriate handlers.
269 func MakeRESTRouter(kc *keepclient.KeepClient, timeout time.Duration, mgmtToken string) http.Handler {
270         rest := mux.NewRouter()
271
272         transport := defaultTransport
273         transport.DialContext = (&net.Dialer{
274                 Timeout:   keepclient.DefaultConnectTimeout,
275                 KeepAlive: keepclient.DefaultKeepAlive,
276                 DualStack: true,
277         }).DialContext
278         transport.TLSClientConfig = arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure)
279         transport.TLSHandshakeTimeout = keepclient.DefaultTLSHandshakeTimeout
280
281         h := &proxyHandler{
282                 Handler:    rest,
283                 KeepClient: kc,
284                 timeout:    timeout,
285                 transport:  &transport,
286                 ApiTokenCache: &ApiTokenCache{
287                         tokens:     make(map[string]int64),
288                         expireTime: 300,
289                 },
290         }
291
292         rest.HandleFunc(`/{locator:[0-9a-f]{32}\+.*}`, h.Get).Methods("GET", "HEAD")
293         rest.HandleFunc(`/{locator:[0-9a-f]{32}}`, h.Get).Methods("GET", "HEAD")
294
295         // List all blocks
296         rest.HandleFunc(`/index`, h.Index).Methods("GET")
297
298         // List blocks whose hash has the given prefix
299         rest.HandleFunc(`/index/{prefix:[0-9a-f]{0,32}}`, h.Index).Methods("GET")
300
301         rest.HandleFunc(`/{locator:[0-9a-f]{32}\+.*}`, h.Put).Methods("PUT")
302         rest.HandleFunc(`/{locator:[0-9a-f]{32}}`, h.Put).Methods("PUT")
303         rest.HandleFunc(`/`, h.Put).Methods("POST")
304         rest.HandleFunc(`/{any}`, h.Options).Methods("OPTIONS")
305         rest.HandleFunc(`/`, h.Options).Methods("OPTIONS")
306
307         rest.Handle("/_health/{check}", &health.Handler{
308                 Token:  mgmtToken,
309                 Prefix: "/_health/",
310         }).Methods("GET")
311
312         rest.NotFoundHandler = InvalidPathHandler{}
313         return h
314 }
315
316 var errLoopDetected = errors.New("loop detected")
317
318 func (*proxyHandler) checkLoop(resp http.ResponseWriter, req *http.Request) error {
319         if via := req.Header.Get("Via"); strings.Index(via, " "+viaAlias) >= 0 {
320                 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)
321                 http.Error(resp, errLoopDetected.Error(), http.StatusInternalServerError)
322                 return errLoopDetected
323         }
324         return nil
325 }
326
327 func SetCorsHeaders(resp http.ResponseWriter) {
328         resp.Header().Set("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, OPTIONS")
329         resp.Header().Set("Access-Control-Allow-Origin", "*")
330         resp.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Length, Content-Type, X-Keep-Desired-Replicas")
331         resp.Header().Set("Access-Control-Max-Age", "86486400")
332 }
333
334 type InvalidPathHandler struct{}
335
336 func (InvalidPathHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
337         log.Printf("%s: %s %s unroutable", GetRemoteAddress(req), req.Method, req.URL.Path)
338         http.Error(resp, "Bad request", http.StatusBadRequest)
339 }
340
341 func (h *proxyHandler) Options(resp http.ResponseWriter, req *http.Request) {
342         log.Printf("%s: %s %s", GetRemoteAddress(req), req.Method, req.URL.Path)
343         SetCorsHeaders(resp)
344 }
345
346 var BadAuthorizationHeader = errors.New("Missing or invalid Authorization header")
347 var ContentLengthMismatch = errors.New("Actual length != expected content length")
348 var MethodNotSupported = errors.New("Method not supported")
349
350 var removeHint, _ = regexp.Compile("\\+K@[a-z0-9]{5}(\\+|$)")
351
352 func (h *proxyHandler) Get(resp http.ResponseWriter, req *http.Request) {
353         if err := h.checkLoop(resp, req); err != nil {
354                 return
355         }
356         SetCorsHeaders(resp)
357         resp.Header().Set("Via", req.Proto+" "+viaAlias)
358
359         locator := mux.Vars(req)["locator"]
360         var err error
361         var status int
362         var expectLength, responseLength int64
363         var proxiedURI = "-"
364
365         defer func() {
366                 log.Println(GetRemoteAddress(req), req.Method, req.URL.Path, status, expectLength, responseLength, proxiedURI, err)
367                 if status != http.StatusOK {
368                         http.Error(resp, err.Error(), status)
369                 }
370         }()
371
372         kc := h.makeKeepClient(req)
373
374         var pass bool
375         var tok string
376         if pass, tok = CheckAuthorizationHeader(kc, h.ApiTokenCache, req); !pass {
377                 status, err = http.StatusForbidden, BadAuthorizationHeader
378                 return
379         }
380
381         // Copy ArvadosClient struct and use the client's API token
382         arvclient := *kc.Arvados
383         arvclient.ApiToken = tok
384         kc.Arvados = &arvclient
385
386         var reader io.ReadCloser
387
388         locator = removeHint.ReplaceAllString(locator, "$1")
389
390         switch req.Method {
391         case "HEAD":
392                 expectLength, proxiedURI, err = kc.Ask(locator)
393         case "GET":
394                 reader, expectLength, proxiedURI, err = kc.Get(locator)
395                 if reader != nil {
396                         defer reader.Close()
397                 }
398         default:
399                 status, err = http.StatusNotImplemented, MethodNotSupported
400                 return
401         }
402
403         if expectLength == -1 {
404                 log.Println("Warning:", GetRemoteAddress(req), req.Method, proxiedURI, "Content-Length not provided")
405         }
406
407         switch respErr := err.(type) {
408         case nil:
409                 status = http.StatusOK
410                 resp.Header().Set("Content-Length", fmt.Sprint(expectLength))
411                 switch req.Method {
412                 case "HEAD":
413                         responseLength = 0
414                 case "GET":
415                         responseLength, err = io.Copy(resp, reader)
416                         if err == nil && expectLength > -1 && responseLength != expectLength {
417                                 err = ContentLengthMismatch
418                         }
419                 }
420         case keepclient.Error:
421                 if respErr == keepclient.BlockNotFound {
422                         status = http.StatusNotFound
423                 } else if respErr.Temporary() {
424                         status = http.StatusBadGateway
425                 } else {
426                         status = 422
427                 }
428         default:
429                 status = http.StatusInternalServerError
430         }
431 }
432
433 var LengthRequiredError = errors.New(http.StatusText(http.StatusLengthRequired))
434 var LengthMismatchError = errors.New("Locator size hint does not match Content-Length header")
435
436 func (h *proxyHandler) Put(resp http.ResponseWriter, req *http.Request) {
437         if err := h.checkLoop(resp, req); err != nil {
438                 return
439         }
440         SetCorsHeaders(resp)
441         resp.Header().Set("Via", "HTTP/1.1 "+viaAlias)
442
443         kc := h.makeKeepClient(req)
444
445         var err error
446         var expectLength int64
447         var status = http.StatusInternalServerError
448         var wroteReplicas int
449         var locatorOut string = "-"
450
451         defer func() {
452                 log.Println(GetRemoteAddress(req), req.Method, req.URL.Path, status, expectLength, kc.Want_replicas, wroteReplicas, locatorOut, err)
453                 if status != http.StatusOK {
454                         http.Error(resp, err.Error(), status)
455                 }
456         }()
457
458         locatorIn := mux.Vars(req)["locator"]
459
460         // Check if the client specified storage classes
461         if req.Header.Get("X-Keep-Storage-Classes") != "" {
462                 var scl []string
463                 for _, sc := range strings.Split(req.Header.Get("X-Keep-Storage-Classes"), ",") {
464                         scl = append(scl, strings.Trim(sc, " "))
465                 }
466                 kc.StorageClasses = scl
467         }
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                 bytes, err2 := ioutil.ReadAll(req.Body)
513                 if err2 != nil {
514                         err = fmt.Errorf("Error reading request body: %s", err2)
515                         status = http.StatusInternalServerError
516                         return
517                 }
518                 locatorOut, wroteReplicas, err = kc.PutB(bytes)
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.RequestID = req.Header.Get("X-Request-Id")
613         kc.HTTPClient = &proxyClient{
614                 client: &http.Client{
615                         Timeout:   h.timeout,
616                         Transport: h.transport,
617                 },
618                 proto: req.Proto,
619         }
620         return &kc
621 }