1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
22 "git.arvados.org/arvados.git/lib/config"
23 "git.arvados.org/arvados.git/sdk/go/arvados"
24 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
25 "git.arvados.org/arvados.git/sdk/go/health"
26 "git.arvados.org/arvados.git/sdk/go/httpserver"
27 "git.arvados.org/arvados.git/sdk/go/keepclient"
28 "github.com/coreos/go-systemd/daemon"
29 "github.com/ghodss/yaml"
30 "github.com/gorilla/mux"
31 lru "github.com/hashicorp/golang-lru"
32 log "github.com/sirupsen/logrus"
42 const rfc3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00"
44 func configure(logger log.FieldLogger, args []string) (*arvados.Cluster, error) {
45 flags := flag.NewFlagSet(args[0], flag.ExitOnError)
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.")
50 loader := config.NewLoader(os.Stdin, logger)
51 loader.SetupFlags(flags)
53 args = loader.MungeLegacyConfigArgs(logger, args[1:], "-legacy-keepproxy-config")
56 // Print version information if requested
58 fmt.Printf("keepproxy %s\n", version)
62 cfg, err := loader.Load()
66 cluster, err := cfg.GetCluster("")
72 out, err := yaml.Marshal(cfg)
76 if _, err := os.Stdout.Write(out); err != nil {
86 logger.Formatter = &log.JSONFormatter{
87 TimestampFormat: rfc3339NanoFixed,
90 cluster, err := configure(logger, os.Args)
98 log.Printf("keepproxy %s started", version)
100 if err := run(logger, cluster); err != nil {
104 log.Println("shutting down")
107 func run(logger log.FieldLogger, cluster *arvados.Cluster) error {
108 client, err := arvados.NewClientFromConfig(cluster)
112 client.AuthToken = cluster.SystemRootToken
114 arv, err := arvadosclient.New(client)
116 return fmt.Errorf("Error setting up arvados client %v", err)
119 // If a config file is available, use the keepstores defined there
120 // instead of the legacy autodiscover mechanism via the API server
121 for k := range cluster.Services.Keepstore.InternalURLs {
122 arv.KeepServiceURIs = append(arv.KeepServiceURIs, strings.TrimRight(k.String(), "/"))
125 if cluster.SystemLogs.LogLevel == "debug" {
126 keepclient.DebugPrintf = log.Printf
128 kc, err := keepclient.MakeKeepClient(arv)
130 return fmt.Errorf("Error setting up keep client %v", err)
132 keepclient.RefreshServiceDiscoveryOnSIGHUP()
134 if cluster.Collections.DefaultReplication > 0 {
135 kc.Want_replicas = cluster.Collections.DefaultReplication
138 var listen arvados.URL
139 for listen = range cluster.Services.Keepproxy.InternalURLs {
144 listener, lErr = net.Listen("tcp", listen.Host)
146 return fmt.Errorf("listen(%s): %v", listen.Host, lErr)
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(kc, time.Duration(keepclient.DefaultProxyRequestTimeout), cluster, logger)
167 return http.Serve(listener, httpserver.AddRequestIDs(httpserver.LogRequests(router)))
170 type TokenCacheEntry struct {
175 type APITokenCache struct {
176 tokens *lru.TwoQueueCache
180 // RememberToken caches the token and set an expire time. If the
181 // token is already in the cache, it is not updated.
182 func (cache *APITokenCache) RememberToken(token string, user *arvados.User) {
183 now := time.Now().Unix()
184 _, ok := cache.tokens.Get(token)
186 cache.tokens.Add(token, TokenCacheEntry{
187 expire: now + cache.expireTime,
193 // RecallToken checks if the cached token is known and still believed to be
195 func (cache *APITokenCache) RecallToken(token string) (bool, *arvados.User) {
196 val, ok := cache.tokens.Get(token)
201 cacheEntry := val.(TokenCacheEntry)
202 now := time.Now().Unix()
203 if now < cacheEntry.expire {
204 // Token is known and still valid
205 return true, cacheEntry.user
208 cache.tokens.Remove(token)
213 // GetRemoteAddress returns a string with the remote address for the request.
214 // If the X-Forwarded-For header is set and has a non-zero length, it returns a
215 // string made from a comma separated list of all the remote addresses,
216 // starting with the one(s) from the X-Forwarded-For header.
217 func GetRemoteAddress(req *http.Request) string {
218 if xff := req.Header.Get("X-Forwarded-For"); xff != "" {
219 return xff + "," + req.RemoteAddr
221 return req.RemoteAddr
224 func (h *proxyHandler) CheckAuthorizationHeader(req *http.Request) (pass bool, tok string, user *arvados.User) {
225 parts := strings.SplitN(req.Header.Get("Authorization"), " ", 2)
226 if len(parts) < 2 || !(parts[0] == "OAuth2" || parts[0] == "Bearer") || len(parts[1]) == 0 {
227 return false, "", nil
231 // Tokens are validated differently depending on what kind of
232 // operation is being performed. For example, tokens in
233 // collection-sharing links permit GET requests, but not
236 if req.Method == "GET" || req.Method == "HEAD" {
242 if ok, user := h.APITokenCache.RecallToken(op + ":" + tok); ok {
243 // Valid in the cache, short circuit
244 return true, tok, user
248 arv := *h.KeepClient.Arvados
250 arv.RequestID = req.Header.Get("X-Request-Id")
251 user = &arvados.User{}
252 userCurrentError := arv.Call("GET", "users", "", "current", nil, user)
253 err = userCurrentError
254 if err != nil && op == "read" {
255 apiError, ok := err.(arvadosclient.APIServerError)
256 if ok && apiError.HttpStatusCode == http.StatusForbidden {
257 // If it was a scoped "sharing" token it will
258 // return 403 instead of 401 for the current
259 // user check. If it is a download operation
260 // and they have permission to read the
261 // keep_services table, we can allow it.
262 err = arv.Call("HEAD", "keep_services", "", "accessible", nil, nil)
266 log.Printf("%s: CheckAuthorizationHeader error: %v", GetRemoteAddress(req), err)
267 return false, "", nil
270 if userCurrentError == nil && user.IsAdmin {
271 // checking userCurrentError is probably redundant,
272 // IsAdmin would be false anyway. But can't hurt.
273 if op == "read" && !h.cluster.Collections.KeepproxyPermission.Admin.Download {
274 return false, "", nil
276 if op == "write" && !h.cluster.Collections.KeepproxyPermission.Admin.Upload {
277 return false, "", nil
280 if op == "read" && !h.cluster.Collections.KeepproxyPermission.User.Download {
281 return false, "", nil
283 if op == "write" && !h.cluster.Collections.KeepproxyPermission.User.Upload {
284 return false, "", nil
288 // Success! Update cache
289 h.APITokenCache.RememberToken(op+":"+tok, user)
291 return true, tok, user
294 // We need to make a private copy of the default http transport early
295 // in initialization, then make copies of our private copy later. It
296 // won't be safe to copy http.DefaultTransport itself later, because
297 // its private mutexes might have already been used. (Without this,
298 // the test suite sometimes panics "concurrent map writes" in
299 // net/http.(*Transport).removeIdleConnLocked().)
300 var defaultTransport = *(http.DefaultTransport.(*http.Transport))
302 type proxyHandler struct {
304 *keepclient.KeepClient
306 timeout time.Duration
307 transport *http.Transport
308 logger log.FieldLogger
309 cluster *arvados.Cluster
312 // MakeRESTRouter returns an http.Handler that passes GET and PUT
313 // requests to the appropriate handlers.
314 func MakeRESTRouter(kc *keepclient.KeepClient, timeout time.Duration, cluster *arvados.Cluster, logger log.FieldLogger) http.Handler {
315 rest := mux.NewRouter()
317 transport := defaultTransport
318 transport.DialContext = (&net.Dialer{
319 Timeout: keepclient.DefaultConnectTimeout,
320 KeepAlive: keepclient.DefaultKeepAlive,
323 transport.TLSClientConfig = arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure)
324 transport.TLSHandshakeTimeout = keepclient.DefaultTLSHandshakeTimeout
326 cacheQ, err := lru.New2Q(500)
328 panic("Could not create 2Q")
335 transport: &transport,
336 APITokenCache: &APITokenCache{
344 rest.HandleFunc(`/{locator:[0-9a-f]{32}\+.*}`, h.Get).Methods("GET", "HEAD")
345 rest.HandleFunc(`/{locator:[0-9a-f]{32}}`, h.Get).Methods("GET", "HEAD")
348 rest.HandleFunc(`/index`, h.Index).Methods("GET")
350 // List blocks whose hash has the given prefix
351 rest.HandleFunc(`/index/{prefix:[0-9a-f]{0,32}}`, h.Index).Methods("GET")
353 rest.HandleFunc(`/{locator:[0-9a-f]{32}\+.*}`, h.Put).Methods("PUT")
354 rest.HandleFunc(`/{locator:[0-9a-f]{32}}`, h.Put).Methods("PUT")
355 rest.HandleFunc(`/`, h.Put).Methods("POST")
356 rest.HandleFunc(`/{any}`, h.Options).Methods("OPTIONS")
357 rest.HandleFunc(`/`, h.Options).Methods("OPTIONS")
359 rest.Handle("/_health/{check}", &health.Handler{
360 Token: cluster.ManagementToken,
364 rest.NotFoundHandler = InvalidPathHandler{}
368 var errLoopDetected = errors.New("loop detected")
370 func (h *proxyHandler) checkLoop(resp http.ResponseWriter, req *http.Request) error {
371 if via := req.Header.Get("Via"); strings.Index(via, " "+viaAlias) >= 0 {
372 h.logger.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)
373 http.Error(resp, errLoopDetected.Error(), http.StatusInternalServerError)
374 return errLoopDetected
379 func SetCorsHeaders(resp http.ResponseWriter) {
380 resp.Header().Set("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, OPTIONS")
381 resp.Header().Set("Access-Control-Allow-Origin", "*")
382 resp.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Length, Content-Type, X-Keep-Desired-Replicas")
383 resp.Header().Set("Access-Control-Max-Age", "86486400")
386 type InvalidPathHandler struct{}
388 func (InvalidPathHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
389 log.Printf("%s: %s %s unroutable", GetRemoteAddress(req), req.Method, req.URL.Path)
390 http.Error(resp, "Bad request", http.StatusBadRequest)
393 func (h *proxyHandler) Options(resp http.ResponseWriter, req *http.Request) {
394 log.Printf("%s: %s %s", GetRemoteAddress(req), req.Method, req.URL.Path)
398 var errBadAuthorizationHeader = errors.New("Missing or invalid Authorization header, or method not allowed")
399 var errContentLengthMismatch = errors.New("Actual length != expected content length")
400 var errMethodNotSupported = errors.New("Method not supported")
402 var removeHint, _ = regexp.Compile("\\+K@[a-z0-9]{5}(\\+|$)")
404 func (h *proxyHandler) Get(resp http.ResponseWriter, req *http.Request) {
405 if err := h.checkLoop(resp, req); err != nil {
409 resp.Header().Set("Via", req.Proto+" "+viaAlias)
411 locator := mux.Vars(req)["locator"]
414 var expectLength, responseLength int64
418 log.Println(GetRemoteAddress(req), req.Method, req.URL.Path, status, expectLength, responseLength, proxiedURI, err)
419 if status != http.StatusOK {
420 http.Error(resp, err.Error(), status)
424 kc := h.makeKeepClient(req)
428 var user *arvados.User
429 if pass, tok, user = h.CheckAuthorizationHeader(req); !pass {
430 status, err = http.StatusForbidden, errBadAuthorizationHeader
434 // Copy ArvadosClient struct and use the client's API token
435 arvclient := *kc.Arvados
436 arvclient.ApiToken = tok
437 kc.Arvados = &arvclient
439 var reader io.ReadCloser
441 locator = removeHint.ReplaceAllString(locator, "$1")
444 parts := strings.SplitN(locator, "+", 3)
448 logger = logger.WithField("user_uuid", user.UUID).
449 WithField("user_full_name", user.FullName)
451 logger.WithField("locator", fmt.Sprintf("%s+%s", parts[0], parts[1])).Infof("Block download")
457 expectLength, proxiedURI, err = kc.Ask(locator)
459 reader, expectLength, proxiedURI, err = kc.Get(locator)
464 status, err = http.StatusNotImplemented, errMethodNotSupported
468 if expectLength == -1 {
469 log.Println("Warning:", GetRemoteAddress(req), req.Method, proxiedURI, "Content-Length not provided")
472 switch respErr := err.(type) {
474 status = http.StatusOK
475 resp.Header().Set("Content-Length", fmt.Sprint(expectLength))
480 responseLength, err = io.Copy(resp, reader)
481 if err == nil && expectLength > -1 && responseLength != expectLength {
482 err = errContentLengthMismatch
485 case keepclient.Error:
486 if respErr == keepclient.BlockNotFound {
487 status = http.StatusNotFound
488 } else if respErr.Temporary() {
489 status = http.StatusBadGateway
494 status = http.StatusInternalServerError
498 var errLengthRequired = errors.New(http.StatusText(http.StatusLengthRequired))
499 var errLengthMismatch = errors.New("Locator size hint does not match Content-Length header")
501 func (h *proxyHandler) Put(resp http.ResponseWriter, req *http.Request) {
502 if err := h.checkLoop(resp, req); err != nil {
506 resp.Header().Set("Via", "HTTP/1.1 "+viaAlias)
508 kc := h.makeKeepClient(req)
511 var expectLength int64
512 var status = http.StatusInternalServerError
513 var wroteReplicas int
514 var locatorOut string = "-"
517 log.Println(GetRemoteAddress(req), req.Method, req.URL.Path, status, expectLength, kc.Want_replicas, wroteReplicas, locatorOut, err)
518 if status != http.StatusOK {
519 http.Error(resp, err.Error(), status)
523 locatorIn := mux.Vars(req)["locator"]
525 // Check if the client specified storage classes
526 if req.Header.Get("X-Keep-Storage-Classes") != "" {
528 for _, sc := range strings.Split(req.Header.Get("X-Keep-Storage-Classes"), ",") {
529 scl = append(scl, strings.Trim(sc, " "))
531 kc.StorageClasses = scl
534 _, err = fmt.Sscanf(req.Header.Get("Content-Length"), "%d", &expectLength)
535 if err != nil || expectLength < 0 {
536 err = errLengthRequired
537 status = http.StatusLengthRequired
542 var loc *keepclient.Locator
543 if loc, err = keepclient.MakeLocator(locatorIn); err != nil {
544 status = http.StatusBadRequest
546 } else if loc.Size > 0 && int64(loc.Size) != expectLength {
547 err = errLengthMismatch
548 status = http.StatusBadRequest
555 var user *arvados.User
556 if pass, tok, user = h.CheckAuthorizationHeader(req); !pass {
557 err = errBadAuthorizationHeader
558 status = http.StatusForbidden
562 // Copy ArvadosClient struct and use the client's API token
563 arvclient := *kc.Arvados
564 arvclient.ApiToken = tok
565 kc.Arvados = &arvclient
567 // Check if the client specified the number of replicas
568 if req.Header.Get("X-Keep-Desired-Replicas") != "" {
570 _, err := fmt.Sscanf(req.Header.Get(keepclient.XKeepDesiredReplicas), "%d", &r)
576 // Now try to put the block through
578 bytes, err2 := ioutil.ReadAll(req.Body)
580 err = fmt.Errorf("Error reading request body: %s", err2)
581 status = http.StatusInternalServerError
584 locatorOut, wroteReplicas, err = kc.PutB(bytes)
586 locatorOut, wroteReplicas, err = kc.PutHR(locatorIn, req.Body, expectLength)
589 if locatorOut != "" {
590 parts := strings.SplitN(locatorOut, "+", 3)
594 logger = logger.WithField("user_uuid", user.UUID).
595 WithField("user_full_name", user.FullName)
597 logger.WithField("locator", fmt.Sprintf("%s+%s", parts[0], parts[1])).Infof("Block upload")
601 // Tell the client how many successful PUTs we accomplished
602 resp.Header().Set(keepclient.XKeepReplicasStored, fmt.Sprintf("%d", wroteReplicas))
606 status = http.StatusOK
607 _, err = io.WriteString(resp, locatorOut)
609 case keepclient.OversizeBlockError:
611 status = http.StatusRequestEntityTooLarge
613 case keepclient.InsufficientReplicasError:
614 if wroteReplicas > 0 {
615 // At least one write is considered success. The
616 // client can decide if getting less than the number of
617 // replications it asked for is a fatal error.
618 status = http.StatusOK
619 _, err = io.WriteString(resp, locatorOut)
621 status = http.StatusServiceUnavailable
625 status = http.StatusBadGateway
629 // ServeHTTP implementation for IndexHandler
630 // Supports only GET requests for /index/{prefix:[0-9a-f]{0,32}}
631 // For each keep server found in LocalRoots:
632 // Invokes GetIndex using keepclient
633 // Expects "complete" response (terminating with blank new line)
634 // Aborts on any errors
635 // Concatenates responses from all those keep servers and returns
636 func (h *proxyHandler) Index(resp http.ResponseWriter, req *http.Request) {
639 prefix := mux.Vars(req)["prefix"]
644 if status != http.StatusOK {
645 http.Error(resp, err.Error(), status)
649 kc := h.makeKeepClient(req)
650 ok, token, _ := h.CheckAuthorizationHeader(req)
652 status, err = http.StatusForbidden, errBadAuthorizationHeader
656 // Copy ArvadosClient struct and use the client's API token
657 arvclient := *kc.Arvados
658 arvclient.ApiToken = token
659 kc.Arvados = &arvclient
661 // Only GET method is supported
662 if req.Method != "GET" {
663 status, err = http.StatusNotImplemented, errMethodNotSupported
667 // Get index from all LocalRoots and write to resp
669 for uuid := range kc.LocalRoots() {
670 reader, err = kc.GetIndex(uuid, prefix)
672 status = http.StatusBadGateway
676 _, err = io.Copy(resp, reader)
678 status = http.StatusBadGateway
683 // Got index from all the keep servers and wrote to resp
684 status = http.StatusOK
685 resp.Write([]byte("\n"))
688 func (h *proxyHandler) makeKeepClient(req *http.Request) *keepclient.KeepClient {
690 kc.RequestID = req.Header.Get("X-Request-Id")
691 kc.HTTPClient = &proxyClient{
692 client: &http.Client{
694 Transport: h.transport,