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/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"
40 Timeout arvados.Duration
43 ManagementToken string
46 func DefaultConfig() *Config {
49 Timeout: arvados.Duration(15 * time.Second),
59 cfg := DefaultConfig()
61 flagset := flag.NewFlagSet("keepproxy", flag.ExitOnError)
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.")
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:])
79 err := config.LoadFile(cfg, cfgPath)
81 h := os.Getenv("ARVADOS_API_HOST")
82 t := os.Getenv("ARVADOS_API_TOKEN")
83 if h == "" || t == "" || !os.IsNotExist(err) || cfgPath != defaultCfgPath {
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
92 if y, err := yaml.Marshal(cfg); err == nil && !*dumpConfig {
93 log.Print("Current configuration:\n", string(y))
95 cfg.Timeout = arvados.Duration(time.Duration(*timeoutSeconds) * time.Second)
99 log.Fatal(config.DumpAndExit(cfg))
102 arv, err := arvadosclient.New(&cfg.Client)
104 log.Fatalf("Error setting up arvados client %s", err.Error())
108 keepclient.DebugPrintf = log.Printf
110 kc, err := keepclient.MakeKeepClient(arv)
112 log.Fatalf("Error setting up keep client %s", err.Error())
114 keepclient.RefreshServiceDiscoveryOnSIGHUP()
116 if cfg.PIDFile != "" {
117 f, err := os.Create(cfg.PIDFile)
122 err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
124 log.Fatalf("flock(%s): %s", cfg.PIDFile, err)
126 defer os.Remove(cfg.PIDFile)
129 log.Fatalf("truncate(%s): %s", cfg.PIDFile, err)
131 _, err = fmt.Fprint(f, os.Getpid())
133 log.Fatalf("write(%s): %s", cfg.PIDFile, err)
137 log.Fatal("sync(%s): %s", cfg.PIDFile, err)
141 if cfg.DefaultReplicas > 0 {
142 kc.Want_replicas = cfg.DefaultReplicas
145 listener, err = net.Listen("tcp", cfg.Listen)
147 log.Fatalf("listen(%s): %s", cfg.Listen, err)
149 if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
150 log.Printf("Error notifying init daemon: %v", err)
152 log.Println("Listening at", listener.Addr())
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) {
159 log.Println("caught signal:", s)
162 signal.Notify(term, syscall.SIGTERM)
163 signal.Notify(term, syscall.SIGINT)
165 // Start serving requests.
166 router = MakeRESTRouter(!cfg.DisableGet, !cfg.DisablePut, kc, time.Duration(cfg.Timeout), cfg.ManagementToken)
167 http.Serve(listener, router)
169 log.Println("shutting down")
172 type ApiTokenCache struct {
173 tokens map[string]int64
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) {
182 defer this.lock.Unlock()
184 now := time.Now().Unix()
185 if this.tokens[token] == 0 {
186 this.tokens[token] = now + this.expireTime
190 // Check if the cached token is known and still believed to be valid.
191 func (this *ApiTokenCache) RecallToken(token string) bool {
193 defer this.lock.Unlock()
195 now := time.Now().Unix()
196 if this.tokens[token] == 0 {
199 } else if now < this.tokens[token] {
200 // Token is known and still valid
204 this.tokens[token] = 0
209 func GetRemoteAddress(req *http.Request) string {
210 if xff := req.Header.Get("X-Forwarded-For"); xff != "" {
211 return xff + "," + req.RemoteAddr
213 return req.RemoteAddr
216 func CheckAuthorizationHeader(kc *keepclient.KeepClient, cache *ApiTokenCache, req *http.Request) (pass bool, tok string) {
218 if auth = req.Header.Get("Authorization"); auth == "" {
222 _, err := fmt.Sscanf(auth, "OAuth2 %s", &tok)
228 if cache.RecallToken(tok) {
229 // Valid in the cache, short circuit
235 if err := arv.Call("HEAD", "users", "", "current", nil, nil); err != nil {
236 log.Printf("%s: CheckAuthorizationHeader error: %v", GetRemoteAddress(req), err)
240 // Success! Update cache
241 cache.RememberToken(tok)
246 type proxyHandler struct {
248 *keepclient.KeepClient
250 timeout time.Duration
251 transport *http.Transport
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()
259 transport := *(http.DefaultTransport.(*http.Transport))
260 transport.DialContext = (&net.Dialer{
261 Timeout: keepclient.DefaultConnectTimeout,
262 KeepAlive: keepclient.DefaultKeepAlive,
265 transport.TLSClientConfig = arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure)
266 transport.TLSHandshakeTimeout = keepclient.DefaultTLSHandshakeTimeout
272 transport: &transport,
273 ApiTokenCache: &ApiTokenCache{
274 tokens: make(map[string]int64),
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")
284 rest.HandleFunc(`/index`, h.Index).Methods("GET")
286 // List blocks whose hash has the given prefix
287 rest.HandleFunc(`/index/{prefix:[0-9a-f]{0,32}}`, h.Index).Methods("GET")
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")
298 rest.Handle("/_health/{check}", &health.Handler{
303 rest.NotFoundHandler = InvalidPathHandler{}
307 var errLoopDetected = errors.New("loop detected")
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
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")
325 type InvalidPathHandler struct{}
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)
332 func (h *proxyHandler) Options(resp http.ResponseWriter, req *http.Request) {
333 log.Printf("%s: %s %s", GetRemoteAddress(req), req.Method, req.URL.Path)
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")
341 var removeHint, _ = regexp.Compile("\\+K@[a-z0-9]{5}(\\+|$)")
343 func (h *proxyHandler) Get(resp http.ResponseWriter, req *http.Request) {
344 if err := h.checkLoop(resp, req); err != nil {
348 resp.Header().Set("Via", req.Proto+" "+viaAlias)
350 locator := mux.Vars(req)["locator"]
353 var expectLength, responseLength int64
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)
363 kc := h.makeKeepClient(req)
367 if pass, tok = CheckAuthorizationHeader(kc, h.ApiTokenCache, req); !pass {
368 status, err = http.StatusForbidden, BadAuthorizationHeader
372 // Copy ArvadosClient struct and use the client's API token
373 arvclient := *kc.Arvados
374 arvclient.ApiToken = tok
375 kc.Arvados = &arvclient
377 var reader io.ReadCloser
379 locator = removeHint.ReplaceAllString(locator, "$1")
383 expectLength, proxiedURI, err = kc.Ask(locator)
385 reader, expectLength, proxiedURI, err = kc.Get(locator)
390 status, err = http.StatusNotImplemented, MethodNotSupported
394 if expectLength == -1 {
395 log.Println("Warning:", GetRemoteAddress(req), req.Method, proxiedURI, "Content-Length not provided")
398 switch respErr := err.(type) {
400 status = http.StatusOK
401 resp.Header().Set("Content-Length", fmt.Sprint(expectLength))
406 responseLength, err = io.Copy(resp, reader)
407 if err == nil && expectLength > -1 && responseLength != expectLength {
408 err = ContentLengthMismatch
411 case keepclient.Error:
412 if respErr == keepclient.BlockNotFound {
413 status = http.StatusNotFound
414 } else if respErr.Temporary() {
415 status = http.StatusBadGateway
420 status = http.StatusInternalServerError
424 var LengthRequiredError = errors.New(http.StatusText(http.StatusLengthRequired))
425 var LengthMismatchError = errors.New("Locator size hint does not match Content-Length header")
427 func (h *proxyHandler) Put(resp http.ResponseWriter, req *http.Request) {
428 if err := h.checkLoop(resp, req); err != nil {
432 resp.Header().Set("Via", "HTTP/1.1 "+viaAlias)
434 kc := h.makeKeepClient(req)
437 var expectLength int64
438 var status = http.StatusInternalServerError
439 var wroteReplicas int
440 var locatorOut string = "-"
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)
449 locatorIn := mux.Vars(req)["locator"]
451 _, err = fmt.Sscanf(req.Header.Get("Content-Length"), "%d", &expectLength)
452 if err != nil || expectLength < 0 {
453 err = LengthRequiredError
454 status = http.StatusLengthRequired
459 var loc *keepclient.Locator
460 if loc, err = keepclient.MakeLocator(locatorIn); err != nil {
461 status = http.StatusBadRequest
463 } else if loc.Size > 0 && int64(loc.Size) != expectLength {
464 err = LengthMismatchError
465 status = http.StatusBadRequest
472 if pass, tok = CheckAuthorizationHeader(kc, h.ApiTokenCache, req); !pass {
473 err = BadAuthorizationHeader
474 status = http.StatusForbidden
478 // Copy ArvadosClient struct and use the client's API token
479 arvclient := *kc.Arvados
480 arvclient.ApiToken = tok
481 kc.Arvados = &arvclient
483 // Check if the client specified the number of replicas
484 if req.Header.Get("X-Keep-Desired-Replicas") != "" {
486 _, err := fmt.Sscanf(req.Header.Get(keepclient.X_Keep_Desired_Replicas), "%d", &r)
492 // Now try to put the block through
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
499 locatorOut, wroteReplicas, err = kc.PutB(bytes)
502 locatorOut, wroteReplicas, err = kc.PutHR(locatorIn, req.Body, expectLength)
505 // Tell the client how many successful PUTs we accomplished
506 resp.Header().Set(keepclient.X_Keep_Replicas_Stored, fmt.Sprintf("%d", wroteReplicas))
510 status = http.StatusOK
511 _, err = io.WriteString(resp, locatorOut)
513 case keepclient.OversizeBlockError:
515 status = http.StatusRequestEntityTooLarge
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)
525 status = http.StatusServiceUnavailable
529 status = http.StatusBadGateway
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) {
543 prefix := mux.Vars(req)["prefix"]
548 if status != http.StatusOK {
549 http.Error(resp, err.Error(), status)
553 kc := h.makeKeepClient(req)
554 ok, token := CheckAuthorizationHeader(kc, h.ApiTokenCache, req)
556 status, err = http.StatusForbidden, BadAuthorizationHeader
560 // Copy ArvadosClient struct and use the client's API token
561 arvclient := *kc.Arvados
562 arvclient.ApiToken = token
563 kc.Arvados = &arvclient
565 // Only GET method is supported
566 if req.Method != "GET" {
567 status, err = http.StatusNotImplemented, MethodNotSupported
571 // Get index from all LocalRoots and write to resp
573 for uuid := range kc.LocalRoots() {
574 reader, err = kc.GetIndex(uuid, prefix)
576 status = http.StatusBadGateway
580 _, err = io.Copy(resp, reader)
582 status = http.StatusBadGateway
587 // Got index from all the keep servers and wrote to resp
588 status = http.StatusOK
589 resp.Write([]byte("\n"))
592 func (h *proxyHandler) makeKeepClient(req *http.Request) *keepclient.KeepClient {
594 kc.HTTPClient = &proxyClient{
595 client: &http.Client{
597 Transport: h.transport,