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