1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
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/keepclient"
28 "github.com/coreos/go-systemd/daemon"
29 "github.com/ghodss/yaml"
30 "github.com/gorilla/mux"
39 Timeout arvados.Duration
44 func DefaultConfig() *Config {
47 Timeout: arvados.Duration(15 * time.Second),
57 cfg := DefaultConfig()
59 flagset := flag.NewFlagSet("keepproxy", flag.ExitOnError)
62 const deprecated = " (DEPRECATED -- use config file instead)"
63 flagset.StringVar(&cfg.Listen, "listen", cfg.Listen, "Local port to listen on."+deprecated)
64 flagset.BoolVar(&cfg.DisableGet, "no-get", cfg.DisableGet, "Disable GET operations."+deprecated)
65 flagset.BoolVar(&cfg.DisablePut, "no-put", cfg.DisablePut, "Disable PUT operations."+deprecated)
66 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)
67 flagset.StringVar(&cfg.PIDFile, "pid", cfg.PIDFile, "Path to write pid file."+deprecated)
68 timeoutSeconds := flagset.Int("timeout", int(time.Duration(cfg.Timeout)/time.Second), "Timeout (in seconds) on requests to internal Keep services."+deprecated)
71 const defaultCfgPath = "/etc/arvados/keepproxy/keepproxy.yml"
72 flagset.StringVar(&cfgPath, "config", defaultCfgPath, "Configuration file `path`")
73 dumpConfig := flagset.Bool("dump-config", false, "write current configuration to stdout and exit")
74 flagset.Parse(os.Args[1:])
76 err := config.LoadFile(cfg, cfgPath)
78 h := os.Getenv("ARVADOS_API_HOST")
79 t := os.Getenv("ARVADOS_API_TOKEN")
80 if h == "" || t == "" || !os.IsNotExist(err) || cfgPath != defaultCfgPath {
83 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.")
84 cfg.Client.APIHost = h
85 cfg.Client.AuthToken = t
86 if regexp.MustCompile("^(?i:1|yes|true)$").MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE")) {
87 cfg.Client.Insecure = true
89 if y, err := yaml.Marshal(cfg); err == nil && !*dumpConfig {
90 log.Print("Current configuration:\n", string(y))
92 cfg.Timeout = arvados.Duration(time.Duration(*timeoutSeconds) * time.Second)
96 log.Fatal(config.DumpAndExit(cfg))
99 arv, err := arvadosclient.New(&cfg.Client)
101 log.Fatalf("Error setting up arvados client %s", err.Error())
105 keepclient.DebugPrintf = log.Printf
107 kc, err := keepclient.MakeKeepClient(arv)
109 log.Fatalf("Error setting up keep client %s", err.Error())
111 keepclient.RefreshServiceDiscoveryOnSIGHUP()
113 if cfg.PIDFile != "" {
114 f, err := os.Create(cfg.PIDFile)
119 err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
121 log.Fatalf("flock(%s): %s", cfg.PIDFile, err)
123 defer os.Remove(cfg.PIDFile)
126 log.Fatalf("truncate(%s): %s", cfg.PIDFile, err)
128 _, err = fmt.Fprint(f, os.Getpid())
130 log.Fatalf("write(%s): %s", cfg.PIDFile, err)
134 log.Fatal("sync(%s): %s", cfg.PIDFile, err)
138 if cfg.DefaultReplicas > 0 {
139 kc.Want_replicas = cfg.DefaultReplicas
142 listener, err = net.Listen("tcp", cfg.Listen)
144 log.Fatalf("listen(%s): %s", cfg.Listen, err)
146 if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
147 log.Printf("Error notifying init daemon: %v", err)
149 log.Println("Listening at", listener.Addr())
151 // Shut down the server gracefully (by closing the listener)
152 // if SIGTERM is received.
153 term := make(chan os.Signal, 1)
154 go func(sig <-chan os.Signal) {
156 log.Println("caught signal:", s)
159 signal.Notify(term, syscall.SIGTERM)
160 signal.Notify(term, syscall.SIGINT)
162 // Start serving requests.
163 router = MakeRESTRouter(!cfg.DisableGet, !cfg.DisablePut, kc, time.Duration(cfg.Timeout))
164 http.Serve(listener, router)
166 log.Println("shutting down")
169 type ApiTokenCache struct {
170 tokens map[string]int64
175 // Cache the token and set an expire time. If we already have an expire time
176 // on the token, it is not updated.
177 func (this *ApiTokenCache) RememberToken(token string) {
179 defer this.lock.Unlock()
181 now := time.Now().Unix()
182 if this.tokens[token] == 0 {
183 this.tokens[token] = now + this.expireTime
187 // Check if the cached token is known and still believed to be valid.
188 func (this *ApiTokenCache) RecallToken(token string) bool {
190 defer this.lock.Unlock()
192 now := time.Now().Unix()
193 if this.tokens[token] == 0 {
196 } else if now < this.tokens[token] {
197 // Token is known and still valid
201 this.tokens[token] = 0
206 func GetRemoteAddress(req *http.Request) string {
207 if xff := req.Header.Get("X-Forwarded-For"); xff != "" {
208 return xff + "," + req.RemoteAddr
210 return req.RemoteAddr
213 func CheckAuthorizationHeader(kc *keepclient.KeepClient, cache *ApiTokenCache, req *http.Request) (pass bool, tok string) {
215 if auth = req.Header.Get("Authorization"); auth == "" {
219 _, err := fmt.Sscanf(auth, "OAuth2 %s", &tok)
225 if cache.RecallToken(tok) {
226 // Valid in the cache, short circuit
232 if err := arv.Call("HEAD", "users", "", "current", nil, nil); err != nil {
233 log.Printf("%s: CheckAuthorizationHeader error: %v", GetRemoteAddress(req), err)
237 // Success! Update cache
238 cache.RememberToken(tok)
243 type proxyHandler struct {
245 *keepclient.KeepClient
247 timeout time.Duration
248 transport *http.Transport
251 // MakeRESTRouter returns an http.Handler that passes GET and PUT
252 // requests to the appropriate handlers.
253 func MakeRESTRouter(enable_get bool, enable_put bool, kc *keepclient.KeepClient, timeout time.Duration) http.Handler {
254 rest := mux.NewRouter()
256 transport := *(http.DefaultTransport.(*http.Transport))
257 transport.DialContext = (&net.Dialer{
258 Timeout: keepclient.DefaultConnectTimeout,
259 KeepAlive: keepclient.DefaultKeepAlive,
262 transport.TLSClientConfig = arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure)
263 transport.TLSHandshakeTimeout = keepclient.DefaultTLSHandshakeTimeout
269 transport: &transport,
270 ApiTokenCache: &ApiTokenCache{
271 tokens: make(map[string]int64),
277 rest.HandleFunc(`/{locator:[0-9a-f]{32}\+.*}`, h.Get).Methods("GET", "HEAD")
278 rest.HandleFunc(`/{locator:[0-9a-f]{32}}`, h.Get).Methods("GET", "HEAD")
281 rest.HandleFunc(`/index`, h.Index).Methods("GET")
283 // List blocks whose hash has the given prefix
284 rest.HandleFunc(`/index/{prefix:[0-9a-f]{0,32}}`, h.Index).Methods("GET")
288 rest.HandleFunc(`/{locator:[0-9a-f]{32}\+.*}`, h.Put).Methods("PUT")
289 rest.HandleFunc(`/{locator:[0-9a-f]{32}}`, h.Put).Methods("PUT")
290 rest.HandleFunc(`/`, h.Put).Methods("POST")
291 rest.HandleFunc(`/{any}`, h.Options).Methods("OPTIONS")
292 rest.HandleFunc(`/`, h.Options).Methods("OPTIONS")
295 rest.NotFoundHandler = InvalidPathHandler{}
299 var errLoopDetected = errors.New("loop detected")
301 func (*proxyHandler) checkLoop(resp http.ResponseWriter, req *http.Request) error {
302 if via := req.Header.Get("Via"); strings.Index(via, " "+viaAlias) >= 0 {
303 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)
304 http.Error(resp, errLoopDetected.Error(), http.StatusInternalServerError)
305 return errLoopDetected
310 func SetCorsHeaders(resp http.ResponseWriter) {
311 resp.Header().Set("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, OPTIONS")
312 resp.Header().Set("Access-Control-Allow-Origin", "*")
313 resp.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Length, Content-Type, X-Keep-Desired-Replicas")
314 resp.Header().Set("Access-Control-Max-Age", "86486400")
317 type InvalidPathHandler struct{}
319 func (InvalidPathHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
320 log.Printf("%s: %s %s unroutable", GetRemoteAddress(req), req.Method, req.URL.Path)
321 http.Error(resp, "Bad request", http.StatusBadRequest)
324 func (h *proxyHandler) Options(resp http.ResponseWriter, req *http.Request) {
325 log.Printf("%s: %s %s", GetRemoteAddress(req), req.Method, req.URL.Path)
329 var BadAuthorizationHeader = errors.New("Missing or invalid Authorization header")
330 var ContentLengthMismatch = errors.New("Actual length != expected content length")
331 var MethodNotSupported = errors.New("Method not supported")
333 var removeHint, _ = regexp.Compile("\\+K@[a-z0-9]{5}(\\+|$)")
335 func (h *proxyHandler) Get(resp http.ResponseWriter, req *http.Request) {
336 if err := h.checkLoop(resp, req); err != nil {
340 resp.Header().Set("Via", req.Proto+" "+viaAlias)
342 locator := mux.Vars(req)["locator"]
345 var expectLength, responseLength int64
349 log.Println(GetRemoteAddress(req), req.Method, req.URL.Path, status, expectLength, responseLength, proxiedURI, err)
350 if status != http.StatusOK {
351 http.Error(resp, err.Error(), status)
355 kc := h.makeKeepClient(req)
359 if pass, tok = CheckAuthorizationHeader(kc, h.ApiTokenCache, req); !pass {
360 status, err = http.StatusForbidden, BadAuthorizationHeader
364 // Copy ArvadosClient struct and use the client's API token
365 arvclient := *kc.Arvados
366 arvclient.ApiToken = tok
367 kc.Arvados = &arvclient
369 var reader io.ReadCloser
371 locator = removeHint.ReplaceAllString(locator, "$1")
375 expectLength, proxiedURI, err = kc.Ask(locator)
377 reader, expectLength, proxiedURI, err = kc.Get(locator)
382 status, err = http.StatusNotImplemented, MethodNotSupported
386 if expectLength == -1 {
387 log.Println("Warning:", GetRemoteAddress(req), req.Method, proxiedURI, "Content-Length not provided")
390 switch respErr := err.(type) {
392 status = http.StatusOK
393 resp.Header().Set("Content-Length", fmt.Sprint(expectLength))
398 responseLength, err = io.Copy(resp, reader)
399 if err == nil && expectLength > -1 && responseLength != expectLength {
400 err = ContentLengthMismatch
403 case keepclient.Error:
404 if respErr == keepclient.BlockNotFound {
405 status = http.StatusNotFound
406 } else if respErr.Temporary() {
407 status = http.StatusBadGateway
412 status = http.StatusInternalServerError
416 var LengthRequiredError = errors.New(http.StatusText(http.StatusLengthRequired))
417 var LengthMismatchError = errors.New("Locator size hint does not match Content-Length header")
419 func (h *proxyHandler) Put(resp http.ResponseWriter, req *http.Request) {
420 if err := h.checkLoop(resp, req); err != nil {
424 resp.Header().Set("Via", "HTTP/1.1 "+viaAlias)
426 kc := h.makeKeepClient(req)
429 var expectLength int64
430 var status = http.StatusInternalServerError
431 var wroteReplicas int
432 var locatorOut string = "-"
435 log.Println(GetRemoteAddress(req), req.Method, req.URL.Path, status, expectLength, kc.Want_replicas, wroteReplicas, locatorOut, err)
436 if status != http.StatusOK {
437 http.Error(resp, err.Error(), status)
441 locatorIn := mux.Vars(req)["locator"]
443 _, err = fmt.Sscanf(req.Header.Get("Content-Length"), "%d", &expectLength)
444 if err != nil || expectLength < 0 {
445 err = LengthRequiredError
446 status = http.StatusLengthRequired
451 var loc *keepclient.Locator
452 if loc, err = keepclient.MakeLocator(locatorIn); err != nil {
453 status = http.StatusBadRequest
455 } else if loc.Size > 0 && int64(loc.Size) != expectLength {
456 err = LengthMismatchError
457 status = http.StatusBadRequest
464 if pass, tok = CheckAuthorizationHeader(kc, h.ApiTokenCache, req); !pass {
465 err = BadAuthorizationHeader
466 status = http.StatusForbidden
470 // Copy ArvadosClient struct and use the client's API token
471 arvclient := *kc.Arvados
472 arvclient.ApiToken = tok
473 kc.Arvados = &arvclient
475 // Check if the client specified the number of replicas
476 if req.Header.Get("X-Keep-Desired-Replicas") != "" {
478 _, err := fmt.Sscanf(req.Header.Get(keepclient.X_Keep_Desired_Replicas), "%d", &r)
484 // Now try to put the block through
486 if bytes, err := ioutil.ReadAll(req.Body); err != nil {
487 err = errors.New(fmt.Sprintf("Error reading request body: %s", err))
488 status = http.StatusInternalServerError
491 locatorOut, wroteReplicas, err = kc.PutB(bytes)
494 locatorOut, wroteReplicas, err = kc.PutHR(locatorIn, req.Body, expectLength)
497 // Tell the client how many successful PUTs we accomplished
498 resp.Header().Set(keepclient.X_Keep_Replicas_Stored, fmt.Sprintf("%d", wroteReplicas))
502 status = http.StatusOK
503 _, err = io.WriteString(resp, locatorOut)
505 case keepclient.OversizeBlockError:
507 status = http.StatusRequestEntityTooLarge
509 case keepclient.InsufficientReplicasError:
510 if wroteReplicas > 0 {
511 // At least one write is considered success. The
512 // client can decide if getting less than the number of
513 // replications it asked for is a fatal error.
514 status = http.StatusOK
515 _, err = io.WriteString(resp, locatorOut)
517 status = http.StatusServiceUnavailable
521 status = http.StatusBadGateway
525 // ServeHTTP implementation for IndexHandler
526 // Supports only GET requests for /index/{prefix:[0-9a-f]{0,32}}
527 // For each keep server found in LocalRoots:
528 // Invokes GetIndex using keepclient
529 // Expects "complete" response (terminating with blank new line)
530 // Aborts on any errors
531 // Concatenates responses from all those keep servers and returns
532 func (h *proxyHandler) Index(resp http.ResponseWriter, req *http.Request) {
535 prefix := mux.Vars(req)["prefix"]
540 if status != http.StatusOK {
541 http.Error(resp, err.Error(), status)
545 kc := h.makeKeepClient(req)
546 ok, token := CheckAuthorizationHeader(kc, h.ApiTokenCache, req)
548 status, err = http.StatusForbidden, BadAuthorizationHeader
552 // Copy ArvadosClient struct and use the client's API token
553 arvclient := *kc.Arvados
554 arvclient.ApiToken = token
555 kc.Arvados = &arvclient
557 // Only GET method is supported
558 if req.Method != "GET" {
559 status, err = http.StatusNotImplemented, MethodNotSupported
563 // Get index from all LocalRoots and write to resp
565 for uuid := range kc.LocalRoots() {
566 reader, err = kc.GetIndex(uuid, prefix)
568 status = http.StatusBadGateway
572 _, err = io.Copy(resp, reader)
574 status = http.StatusBadGateway
579 // Got index from all the keep servers and wrote to resp
580 status = http.StatusOK
581 resp.Write([]byte("\n"))
584 func (h *proxyHandler) makeKeepClient(req *http.Request) *keepclient.KeepClient {
586 kc.HTTPClient = &proxyClient{
587 client: &http.Client{
589 Transport: h.transport,