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, err = MakeRESTRouter(kc, time.Duration(keepclient.DefaultProxyRequestTimeout), cluster, logger)
170 return http.Serve(listener, httpserver.AddRequestIDs(httpserver.LogRequests(router)))
173 type TokenCacheEntry struct {
178 type APITokenCache struct {
179 tokens *lru.TwoQueueCache
183 // RememberToken caches the token and set an expire time. If the
184 // token is already in the cache, it is not updated.
185 func (cache *APITokenCache) RememberToken(token string, user *arvados.User) {
186 now := time.Now().Unix()
187 _, ok := cache.tokens.Get(token)
189 cache.tokens.Add(token, TokenCacheEntry{
190 expire: now + cache.expireTime,
196 // RecallToken checks if the cached token is known and still believed to be
198 func (cache *APITokenCache) RecallToken(token string) (bool, *arvados.User) {
199 val, ok := cache.tokens.Get(token)
204 cacheEntry := val.(TokenCacheEntry)
205 now := time.Now().Unix()
206 if now < cacheEntry.expire {
207 // Token is known and still valid
208 return true, cacheEntry.user
211 cache.tokens.Remove(token)
216 // GetRemoteAddress returns a string with the remote address for the request.
217 // If the X-Forwarded-For header is set and has a non-zero length, it returns a
218 // string made from a comma separated list of all the remote addresses,
219 // starting with the one(s) from the X-Forwarded-For header.
220 func GetRemoteAddress(req *http.Request) string {
221 if xff := req.Header.Get("X-Forwarded-For"); xff != "" {
222 return xff + "," + req.RemoteAddr
224 return req.RemoteAddr
227 func (h *proxyHandler) CheckAuthorizationHeader(req *http.Request) (pass bool, tok string, user *arvados.User) {
228 parts := strings.SplitN(req.Header.Get("Authorization"), " ", 2)
229 if len(parts) < 2 || !(parts[0] == "OAuth2" || parts[0] == "Bearer") || len(parts[1]) == 0 {
230 return false, "", nil
234 // Tokens are validated differently depending on what kind of
235 // operation is being performed. For example, tokens in
236 // collection-sharing links permit GET requests, but not
239 if req.Method == "GET" || req.Method == "HEAD" {
245 if ok, user := h.APITokenCache.RecallToken(op + ":" + tok); ok {
246 // Valid in the cache, short circuit
247 return true, tok, user
251 arv := *h.KeepClient.Arvados
253 arv.RequestID = req.Header.Get("X-Request-Id")
254 user = &arvados.User{}
255 userCurrentError := arv.Call("GET", "users", "", "current", nil, user)
256 err = userCurrentError
257 if err != nil && op == "read" {
258 apiError, ok := err.(arvadosclient.APIServerError)
259 if ok && apiError.HttpStatusCode == http.StatusForbidden {
260 // If it was a scoped "sharing" token it will
261 // return 403 instead of 401 for the current
262 // user check. If it is a download operation
263 // and they have permission to read the
264 // keep_services table, we can allow it.
265 err = arv.Call("HEAD", "keep_services", "", "accessible", nil, nil)
269 log.Printf("%s: CheckAuthorizationHeader error: %v", GetRemoteAddress(req), err)
270 return false, "", nil
273 if userCurrentError == nil && user.IsAdmin {
274 // checking userCurrentError is probably redundant,
275 // IsAdmin would be false anyway. But can't hurt.
276 if op == "read" && !h.cluster.Collections.KeepproxyPermission.Admin.Download {
277 return false, "", nil
279 if op == "write" && !h.cluster.Collections.KeepproxyPermission.Admin.Upload {
280 return false, "", nil
283 if op == "read" && !h.cluster.Collections.KeepproxyPermission.User.Download {
284 return false, "", nil
286 if op == "write" && !h.cluster.Collections.KeepproxyPermission.User.Upload {
287 return false, "", nil
291 // Success! Update cache
292 h.APITokenCache.RememberToken(op+":"+tok, user)
294 return true, tok, user
297 // We need to make a private copy of the default http transport early
298 // in initialization, then make copies of our private copy later. It
299 // won't be safe to copy http.DefaultTransport itself later, because
300 // its private mutexes might have already been used. (Without this,
301 // the test suite sometimes panics "concurrent map writes" in
302 // net/http.(*Transport).removeIdleConnLocked().)
303 var defaultTransport = *(http.DefaultTransport.(*http.Transport))
305 type proxyHandler struct {
307 *keepclient.KeepClient
309 timeout time.Duration
310 transport *http.Transport
311 logger log.FieldLogger
312 cluster *arvados.Cluster
315 // MakeRESTRouter returns an http.Handler that passes GET and PUT
316 // requests to the appropriate handlers.
317 func MakeRESTRouter(kc *keepclient.KeepClient, timeout time.Duration, cluster *arvados.Cluster, logger log.FieldLogger) (http.Handler, error) {
318 rest := mux.NewRouter()
320 transport := defaultTransport
321 transport.DialContext = (&net.Dialer{
322 Timeout: keepclient.DefaultConnectTimeout,
323 KeepAlive: keepclient.DefaultKeepAlive,
326 transport.TLSClientConfig = arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure)
327 transport.TLSHandshakeTimeout = keepclient.DefaultTLSHandshakeTimeout
329 cacheQ, err := lru.New2Q(500)
331 return nil, fmt.Errorf("Error from lru.New2Q: %v", err)
338 transport: &transport,
339 APITokenCache: &APITokenCache{
347 rest.HandleFunc(`/{locator:[0-9a-f]{32}\+.*}`, h.Get).Methods("GET", "HEAD")
348 rest.HandleFunc(`/{locator:[0-9a-f]{32}}`, h.Get).Methods("GET", "HEAD")
351 rest.HandleFunc(`/index`, h.Index).Methods("GET")
353 // List blocks whose hash has the given prefix
354 rest.HandleFunc(`/index/{prefix:[0-9a-f]{0,32}}`, h.Index).Methods("GET")
356 rest.HandleFunc(`/{locator:[0-9a-f]{32}\+.*}`, h.Put).Methods("PUT")
357 rest.HandleFunc(`/{locator:[0-9a-f]{32}}`, h.Put).Methods("PUT")
358 rest.HandleFunc(`/`, h.Put).Methods("POST")
359 rest.HandleFunc(`/{any}`, h.Options).Methods("OPTIONS")
360 rest.HandleFunc(`/`, h.Options).Methods("OPTIONS")
362 rest.Handle("/_health/{check}", &health.Handler{
363 Token: cluster.ManagementToken,
367 rest.NotFoundHandler = InvalidPathHandler{}
371 var errLoopDetected = errors.New("loop detected")
373 func (h *proxyHandler) checkLoop(resp http.ResponseWriter, req *http.Request) error {
374 if via := req.Header.Get("Via"); strings.Index(via, " "+viaAlias) >= 0 {
375 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)
376 http.Error(resp, errLoopDetected.Error(), http.StatusInternalServerError)
377 return errLoopDetected
382 func SetCorsHeaders(resp http.ResponseWriter) {
383 resp.Header().Set("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, OPTIONS")
384 resp.Header().Set("Access-Control-Allow-Origin", "*")
385 resp.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Length, Content-Type, X-Keep-Desired-Replicas")
386 resp.Header().Set("Access-Control-Max-Age", "86486400")
389 type InvalidPathHandler struct{}
391 func (InvalidPathHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
392 log.Printf("%s: %s %s unroutable", GetRemoteAddress(req), req.Method, req.URL.Path)
393 http.Error(resp, "Bad request", http.StatusBadRequest)
396 func (h *proxyHandler) Options(resp http.ResponseWriter, req *http.Request) {
397 log.Printf("%s: %s %s", GetRemoteAddress(req), req.Method, req.URL.Path)
401 var errBadAuthorizationHeader = errors.New("Missing or invalid Authorization header, or method not allowed")
402 var errContentLengthMismatch = errors.New("Actual length != expected content length")
403 var errMethodNotSupported = errors.New("Method not supported")
405 var removeHint, _ = regexp.Compile("\\+K@[a-z0-9]{5}(\\+|$)")
407 func (h *proxyHandler) Get(resp http.ResponseWriter, req *http.Request) {
408 if err := h.checkLoop(resp, req); err != nil {
412 resp.Header().Set("Via", req.Proto+" "+viaAlias)
414 locator := mux.Vars(req)["locator"]
417 var expectLength, responseLength int64
421 log.Println(GetRemoteAddress(req), req.Method, req.URL.Path, status, expectLength, responseLength, proxiedURI, err)
422 if status != http.StatusOK {
423 http.Error(resp, err.Error(), status)
427 kc := h.makeKeepClient(req)
431 var user *arvados.User
432 if pass, tok, user = h.CheckAuthorizationHeader(req); !pass {
433 status, err = http.StatusForbidden, errBadAuthorizationHeader
437 // Copy ArvadosClient struct and use the client's API token
438 arvclient := *kc.Arvados
439 arvclient.ApiToken = tok
440 kc.Arvados = &arvclient
442 var reader io.ReadCloser
444 locator = removeHint.ReplaceAllString(locator, "$1")
447 parts := strings.SplitN(locator, "+", 3)
451 logger = logger.WithField("user_uuid", user.UUID).
452 WithField("user_full_name", user.FullName)
454 logger.WithField("locator", fmt.Sprintf("%s+%s", parts[0], parts[1])).Infof("Block download")
460 expectLength, proxiedURI, err = kc.Ask(locator)
462 reader, expectLength, proxiedURI, err = kc.Get(locator)
467 status, err = http.StatusNotImplemented, errMethodNotSupported
471 if expectLength == -1 {
472 log.Println("Warning:", GetRemoteAddress(req), req.Method, proxiedURI, "Content-Length not provided")
475 switch respErr := err.(type) {
477 status = http.StatusOK
478 resp.Header().Set("Content-Length", fmt.Sprint(expectLength))
483 responseLength, err = io.Copy(resp, reader)
484 if err == nil && expectLength > -1 && responseLength != expectLength {
485 err = errContentLengthMismatch
488 case keepclient.Error:
489 if respErr == keepclient.BlockNotFound {
490 status = http.StatusNotFound
491 } else if respErr.Temporary() {
492 status = http.StatusBadGateway
497 status = http.StatusInternalServerError
501 var errLengthRequired = errors.New(http.StatusText(http.StatusLengthRequired))
502 var errLengthMismatch = errors.New("Locator size hint does not match Content-Length header")
504 func (h *proxyHandler) Put(resp http.ResponseWriter, req *http.Request) {
505 if err := h.checkLoop(resp, req); err != nil {
509 resp.Header().Set("Via", "HTTP/1.1 "+viaAlias)
511 kc := h.makeKeepClient(req)
514 var expectLength int64
515 var status = http.StatusInternalServerError
516 var wroteReplicas int
517 var locatorOut string = "-"
520 log.Println(GetRemoteAddress(req), req.Method, req.URL.Path, status, expectLength, kc.Want_replicas, wroteReplicas, locatorOut, err)
521 if status != http.StatusOK {
522 http.Error(resp, err.Error(), status)
526 locatorIn := mux.Vars(req)["locator"]
528 // Check if the client specified storage classes
529 if req.Header.Get("X-Keep-Storage-Classes") != "" {
531 for _, sc := range strings.Split(req.Header.Get("X-Keep-Storage-Classes"), ",") {
532 scl = append(scl, strings.Trim(sc, " "))
534 kc.SetStorageClasses(scl)
537 _, err = fmt.Sscanf(req.Header.Get("Content-Length"), "%d", &expectLength)
538 if err != nil || expectLength < 0 {
539 err = errLengthRequired
540 status = http.StatusLengthRequired
545 var loc *keepclient.Locator
546 if loc, err = keepclient.MakeLocator(locatorIn); err != nil {
547 status = http.StatusBadRequest
549 } else if loc.Size > 0 && int64(loc.Size) != expectLength {
550 err = errLengthMismatch
551 status = http.StatusBadRequest
558 var user *arvados.User
559 if pass, tok, user = h.CheckAuthorizationHeader(req); !pass {
560 err = errBadAuthorizationHeader
561 status = http.StatusForbidden
565 // Copy ArvadosClient struct and use the client's API token
566 arvclient := *kc.Arvados
567 arvclient.ApiToken = tok
568 kc.Arvados = &arvclient
570 // Check if the client specified the number of replicas
571 if desiredReplicas := req.Header.Get(keepclient.XKeepDesiredReplicas); desiredReplicas != "" {
573 _, err := fmt.Sscanf(desiredReplicas, "%d", &r)
579 // Now try to put the block through
581 bytes, err2 := ioutil.ReadAll(req.Body)
583 err = fmt.Errorf("Error reading request body: %s", err2)
584 status = http.StatusInternalServerError
587 locatorOut, wroteReplicas, err = kc.PutB(bytes)
589 locatorOut, wroteReplicas, err = kc.PutHR(locatorIn, req.Body, expectLength)
592 if locatorOut != "" {
593 parts := strings.SplitN(locatorOut, "+", 3)
597 logger = logger.WithField("user_uuid", user.UUID).
598 WithField("user_full_name", user.FullName)
600 logger.WithField("locator", fmt.Sprintf("%s+%s", parts[0], parts[1])).Infof("Block upload")
604 // Tell the client how many successful PUTs we accomplished
605 resp.Header().Set(keepclient.XKeepReplicasStored, fmt.Sprintf("%d", wroteReplicas))
609 status = http.StatusOK
610 if len(kc.StorageClasses) > 0 {
611 // A successful PUT request with storage classes means that all
612 // storage classes were fulfilled, so the client will get a
613 // confirmation via the X-Storage-Classes-Confirmed header.
616 for _, sc := range kc.StorageClasses {
618 hdr = fmt.Sprintf("%s=%d", sc, wroteReplicas)
621 hdr += fmt.Sprintf(", %s=%d", sc, wroteReplicas)
624 resp.Header().Set(keepclient.XKeepStorageClassesConfirmed, hdr)
626 _, err = io.WriteString(resp, locatorOut)
627 case keepclient.OversizeBlockError:
629 status = http.StatusRequestEntityTooLarge
630 case keepclient.InsufficientReplicasError:
631 status = http.StatusServiceUnavailable
633 status = http.StatusBadGateway
637 // ServeHTTP implementation for IndexHandler
638 // Supports only GET requests for /index/{prefix:[0-9a-f]{0,32}}
639 // For each keep server found in LocalRoots:
640 // Invokes GetIndex using keepclient
641 // Expects "complete" response (terminating with blank new line)
642 // Aborts on any errors
643 // Concatenates responses from all those keep servers and returns
644 func (h *proxyHandler) Index(resp http.ResponseWriter, req *http.Request) {
647 prefix := mux.Vars(req)["prefix"]
652 if status != http.StatusOK {
653 http.Error(resp, err.Error(), status)
657 kc := h.makeKeepClient(req)
658 ok, token, _ := h.CheckAuthorizationHeader(req)
660 status, err = http.StatusForbidden, errBadAuthorizationHeader
664 // Copy ArvadosClient struct and use the client's API token
665 arvclient := *kc.Arvados
666 arvclient.ApiToken = token
667 kc.Arvados = &arvclient
669 // Only GET method is supported
670 if req.Method != "GET" {
671 status, err = http.StatusNotImplemented, errMethodNotSupported
675 // Get index from all LocalRoots and write to resp
677 for uuid := range kc.LocalRoots() {
678 reader, err = kc.GetIndex(uuid, prefix)
680 status = http.StatusBadGateway
684 _, err = io.Copy(resp, reader)
686 status = http.StatusBadGateway
691 // Got index from all the keep servers and wrote to resp
692 status = http.StatusOK
693 resp.Write([]byte("\n"))
696 func (h *proxyHandler) makeKeepClient(req *http.Request) *keepclient.KeepClient {
698 kc.RequestID = req.Header.Get("X-Request-Id")
699 kc.HTTPClient = &proxyClient{
700 client: &http.Client{
702 Transport: h.transport,