1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
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"
41 Timeout arvados.Duration
44 ManagementToken string
47 func DefaultConfig() *Config {
50 Timeout: arvados.Duration(15 * time.Second),
59 const rfc3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00"
62 log.SetFormatter(&log.JSONFormatter{
63 TimestampFormat: rfc3339NanoFixed,
66 cfg := DefaultConfig()
68 flagset := flag.NewFlagSet("keepproxy", flag.ExitOnError)
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.")
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:])
86 err := config.LoadFile(cfg, cfgPath)
88 h := os.Getenv("ARVADOS_API_HOST")
89 t := os.Getenv("ARVADOS_API_TOKEN")
90 if h == "" || t == "" || !os.IsNotExist(err) || cfgPath != defaultCfgPath {
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
99 if y, err := yaml.Marshal(cfg); err == nil && !*dumpConfig {
100 log.Print("Current configuration:\n", string(y))
102 cfg.Timeout = arvados.Duration(time.Duration(*timeoutSeconds) * time.Second)
106 log.Fatal(config.DumpAndExit(cfg))
109 arv, err := arvadosclient.New(&cfg.Client)
111 log.Fatalf("Error setting up arvados client %s", err.Error())
115 keepclient.DebugPrintf = log.Printf
117 kc, err := keepclient.MakeKeepClient(arv)
119 log.Fatalf("Error setting up keep client %s", err.Error())
121 keepclient.RefreshServiceDiscoveryOnSIGHUP()
123 if cfg.PIDFile != "" {
124 f, err := os.Create(cfg.PIDFile)
129 err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
131 log.Fatalf("flock(%s): %s", cfg.PIDFile, err)
133 defer os.Remove(cfg.PIDFile)
136 log.Fatalf("truncate(%s): %s", cfg.PIDFile, err)
138 _, err = fmt.Fprint(f, os.Getpid())
140 log.Fatalf("write(%s): %s", cfg.PIDFile, err)
144 log.Fatal("sync(%s): %s", cfg.PIDFile, err)
148 if cfg.DefaultReplicas > 0 {
149 kc.Want_replicas = cfg.DefaultReplicas
152 listener, err = net.Listen("tcp", cfg.Listen)
154 log.Fatalf("listen(%s): %s", cfg.Listen, err)
156 if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
157 log.Printf("Error notifying init daemon: %v", err)
159 log.Println("Listening at", listener.Addr())
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) {
166 log.Println("caught signal:", s)
169 signal.Notify(term, syscall.SIGTERM)
170 signal.Notify(term, syscall.SIGINT)
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)))
176 log.Println("shutting down")
179 type ApiTokenCache struct {
180 tokens map[string]int64
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) {
189 defer this.lock.Unlock()
191 now := time.Now().Unix()
192 if this.tokens[token] == 0 {
193 this.tokens[token] = now + this.expireTime
197 // Check if the cached token is known and still believed to be valid.
198 func (this *ApiTokenCache) RecallToken(token string) bool {
200 defer this.lock.Unlock()
202 now := time.Now().Unix()
203 if this.tokens[token] == 0 {
206 } else if now < this.tokens[token] {
207 // Token is known and still valid
211 this.tokens[token] = 0
216 func GetRemoteAddress(req *http.Request) string {
217 if xff := req.Header.Get("X-Forwarded-For"); xff != "" {
218 return xff + "," + req.RemoteAddr
220 return req.RemoteAddr
223 func CheckAuthorizationHeader(kc *keepclient.KeepClient, cache *ApiTokenCache, req *http.Request) (pass bool, tok string) {
225 if auth = req.Header.Get("Authorization"); auth == "" {
229 _, err := fmt.Sscanf(auth, "OAuth2 %s", &tok)
235 if cache.RecallToken(tok) {
236 // Valid in the cache, short circuit
242 if err := arv.Call("HEAD", "users", "", "current", nil, nil); err != nil {
243 log.Printf("%s: CheckAuthorizationHeader error: %v", GetRemoteAddress(req), err)
247 // Success! Update cache
248 cache.RememberToken(tok)
253 type proxyHandler struct {
255 *keepclient.KeepClient
257 timeout time.Duration
258 transport *http.Transport
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()
266 transport := *(http.DefaultTransport.(*http.Transport))
267 transport.DialContext = (&net.Dialer{
268 Timeout: keepclient.DefaultConnectTimeout,
269 KeepAlive: keepclient.DefaultKeepAlive,
272 transport.TLSClientConfig = arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure)
273 transport.TLSHandshakeTimeout = keepclient.DefaultTLSHandshakeTimeout
279 transport: &transport,
280 ApiTokenCache: &ApiTokenCache{
281 tokens: make(map[string]int64),
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")
291 rest.HandleFunc(`/index`, h.Index).Methods("GET")
293 // List blocks whose hash has the given prefix
294 rest.HandleFunc(`/index/{prefix:[0-9a-f]{0,32}}`, h.Index).Methods("GET")
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")
305 rest.Handle("/_health/{check}", &health.Handler{
310 rest.NotFoundHandler = InvalidPathHandler{}
314 var errLoopDetected = errors.New("loop detected")
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
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")
332 type InvalidPathHandler struct{}
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)
339 func (h *proxyHandler) Options(resp http.ResponseWriter, req *http.Request) {
340 log.Printf("%s: %s %s", GetRemoteAddress(req), req.Method, req.URL.Path)
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")
348 var removeHint, _ = regexp.Compile("\\+K@[a-z0-9]{5}(\\+|$)")
350 func (h *proxyHandler) Get(resp http.ResponseWriter, req *http.Request) {
351 if err := h.checkLoop(resp, req); err != nil {
355 resp.Header().Set("Via", req.Proto+" "+viaAlias)
357 locator := mux.Vars(req)["locator"]
360 var expectLength, responseLength int64
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)
370 kc := h.makeKeepClient(req)
374 if pass, tok = CheckAuthorizationHeader(kc, h.ApiTokenCache, req); !pass {
375 status, err = http.StatusForbidden, BadAuthorizationHeader
379 // Copy ArvadosClient struct and use the client's API token
380 arvclient := *kc.Arvados
381 arvclient.ApiToken = tok
382 kc.Arvados = &arvclient
384 var reader io.ReadCloser
386 locator = removeHint.ReplaceAllString(locator, "$1")
390 expectLength, proxiedURI, err = kc.Ask(locator)
392 reader, expectLength, proxiedURI, err = kc.Get(locator)
397 status, err = http.StatusNotImplemented, MethodNotSupported
401 if expectLength == -1 {
402 log.Println("Warning:", GetRemoteAddress(req), req.Method, proxiedURI, "Content-Length not provided")
405 switch respErr := err.(type) {
407 status = http.StatusOK
408 resp.Header().Set("Content-Length", fmt.Sprint(expectLength))
413 responseLength, err = io.Copy(resp, reader)
414 if err == nil && expectLength > -1 && responseLength != expectLength {
415 err = ContentLengthMismatch
418 case keepclient.Error:
419 if respErr == keepclient.BlockNotFound {
420 status = http.StatusNotFound
421 } else if respErr.Temporary() {
422 status = http.StatusBadGateway
427 status = http.StatusInternalServerError
431 var LengthRequiredError = errors.New(http.StatusText(http.StatusLengthRequired))
432 var LengthMismatchError = errors.New("Locator size hint does not match Content-Length header")
434 func (h *proxyHandler) Put(resp http.ResponseWriter, req *http.Request) {
435 if err := h.checkLoop(resp, req); err != nil {
439 resp.Header().Set("Via", "HTTP/1.1 "+viaAlias)
441 kc := h.makeKeepClient(req)
444 var expectLength int64
445 var status = http.StatusInternalServerError
446 var wroteReplicas int
447 var locatorOut string = "-"
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)
456 locatorIn := mux.Vars(req)["locator"]
458 _, err = fmt.Sscanf(req.Header.Get("Content-Length"), "%d", &expectLength)
459 if err != nil || expectLength < 0 {
460 err = LengthRequiredError
461 status = http.StatusLengthRequired
466 var loc *keepclient.Locator
467 if loc, err = keepclient.MakeLocator(locatorIn); err != nil {
468 status = http.StatusBadRequest
470 } else if loc.Size > 0 && int64(loc.Size) != expectLength {
471 err = LengthMismatchError
472 status = http.StatusBadRequest
479 if pass, tok = CheckAuthorizationHeader(kc, h.ApiTokenCache, req); !pass {
480 err = BadAuthorizationHeader
481 status = http.StatusForbidden
485 // Copy ArvadosClient struct and use the client's API token
486 arvclient := *kc.Arvados
487 arvclient.ApiToken = tok
488 kc.Arvados = &arvclient
490 // Check if the client specified the number of replicas
491 if req.Header.Get("X-Keep-Desired-Replicas") != "" {
493 _, err := fmt.Sscanf(req.Header.Get(keepclient.X_Keep_Desired_Replicas), "%d", &r)
499 // Now try to put the block through
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
506 locatorOut, wroteReplicas, err = kc.PutB(bytes)
509 locatorOut, wroteReplicas, err = kc.PutHR(locatorIn, req.Body, expectLength)
512 // Tell the client how many successful PUTs we accomplished
513 resp.Header().Set(keepclient.X_Keep_Replicas_Stored, fmt.Sprintf("%d", wroteReplicas))
517 status = http.StatusOK
518 _, err = io.WriteString(resp, locatorOut)
520 case keepclient.OversizeBlockError:
522 status = http.StatusRequestEntityTooLarge
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)
532 status = http.StatusServiceUnavailable
536 status = http.StatusBadGateway
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) {
550 prefix := mux.Vars(req)["prefix"]
555 if status != http.StatusOK {
556 http.Error(resp, err.Error(), status)
560 kc := h.makeKeepClient(req)
561 ok, token := CheckAuthorizationHeader(kc, h.ApiTokenCache, req)
563 status, err = http.StatusForbidden, BadAuthorizationHeader
567 // Copy ArvadosClient struct and use the client's API token
568 arvclient := *kc.Arvados
569 arvclient.ApiToken = token
570 kc.Arvados = &arvclient
572 // Only GET method is supported
573 if req.Method != "GET" {
574 status, err = http.StatusNotImplemented, MethodNotSupported
578 // Get index from all LocalRoots and write to resp
580 for uuid := range kc.LocalRoots() {
581 reader, err = kc.GetIndex(uuid, prefix)
583 status = http.StatusBadGateway
587 _, err = io.Copy(resp, reader)
589 status = http.StatusBadGateway
594 // Got index from all the keep servers and wrote to resp
595 status = http.StatusOK
596 resp.Write([]byte("\n"))
599 func (h *proxyHandler) makeKeepClient(req *http.Request) *keepclient.KeepClient {
601 kc.HTTPClient = &proxyClient{
602 client: &http.Client{
604 Transport: h.transport,
607 requestID: req.Header.Get("X-Request-Id"),