1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
23 "git.arvados.org/arvados.git/lib/config"
24 "git.arvados.org/arvados.git/sdk/go/arvados"
25 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
26 "git.arvados.org/arvados.git/sdk/go/health"
27 "git.arvados.org/arvados.git/sdk/go/httpserver"
28 "git.arvados.org/arvados.git/sdk/go/keepclient"
29 "github.com/coreos/go-systemd/daemon"
30 "github.com/ghodss/yaml"
31 "github.com/gorilla/mux"
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.ManagementToken)
167 return http.Serve(listener, httpserver.AddRequestIDs(httpserver.LogRequests(router)))
170 type APITokenCache struct {
171 tokens map[string]int64
176 // RememberToken caches the token and set an expire time. If we already have
177 // an expire time on the token, it is not updated.
178 func (cache *APITokenCache) RememberToken(token string) {
180 defer cache.lock.Unlock()
182 now := time.Now().Unix()
183 if cache.tokens[token] == 0 {
184 cache.tokens[token] = now + cache.expireTime
188 // RecallToken checks if the cached token is known and still believed to be
190 func (cache *APITokenCache) RecallToken(token string) bool {
192 defer cache.lock.Unlock()
194 now := time.Now().Unix()
195 if cache.tokens[token] == 0 {
198 } else if now < cache.tokens[token] {
199 // Token is known and still valid
203 cache.tokens[token] = 0
208 // GetRemoteAddress returns a string with the remote address for the request.
209 // If the X-Forwarded-For header is set and has a non-zero length, it returns a
210 // string made from a comma separated list of all the remote addresses,
211 // starting with the one(s) from the X-Forwarded-For header.
212 func GetRemoteAddress(req *http.Request) string {
213 if xff := req.Header.Get("X-Forwarded-For"); xff != "" {
214 return xff + "," + req.RemoteAddr
216 return req.RemoteAddr
219 func CheckAuthorizationHeader(kc *keepclient.KeepClient, cache *APITokenCache, req *http.Request) (pass bool, tok string) {
220 parts := strings.SplitN(req.Header.Get("Authorization"), " ", 2)
221 if len(parts) < 2 || !(parts[0] == "OAuth2" || parts[0] == "Bearer") || len(parts[1]) == 0 {
226 // Tokens are validated differently depending on what kind of
227 // operation is being performed. For example, tokens in
228 // collection-sharing links permit GET requests, but not
231 if req.Method == "GET" || req.Method == "HEAD" {
237 if cache.RecallToken(op + ":" + tok) {
238 // Valid in the cache, short circuit
245 arv.RequestID = req.Header.Get("X-Request-Id")
247 err = arv.Call("HEAD", "keep_services", "", "accessible", nil, nil)
249 err = arv.Call("HEAD", "users", "", "current", nil, nil)
252 log.Printf("%s: CheckAuthorizationHeader error: %v", GetRemoteAddress(req), err)
256 // Success! Update cache
257 cache.RememberToken(op + ":" + tok)
262 // We need to make a private copy of the default http transport early
263 // in initialization, then make copies of our private copy later. It
264 // won't be safe to copy http.DefaultTransport itself later, because
265 // its private mutexes might have already been used. (Without this,
266 // the test suite sometimes panics "concurrent map writes" in
267 // net/http.(*Transport).removeIdleConnLocked().)
268 var defaultTransport = *(http.DefaultTransport.(*http.Transport))
270 type proxyHandler struct {
272 *keepclient.KeepClient
274 timeout time.Duration
275 transport *http.Transport
278 // MakeRESTRouter returns an http.Handler that passes GET and PUT
279 // requests to the appropriate handlers.
280 func MakeRESTRouter(kc *keepclient.KeepClient, timeout time.Duration, mgmtToken string) http.Handler {
281 rest := mux.NewRouter()
283 transport := defaultTransport
284 transport.DialContext = (&net.Dialer{
285 Timeout: keepclient.DefaultConnectTimeout,
286 KeepAlive: keepclient.DefaultKeepAlive,
289 transport.TLSClientConfig = arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure)
290 transport.TLSHandshakeTimeout = keepclient.DefaultTLSHandshakeTimeout
296 transport: &transport,
297 APITokenCache: &APITokenCache{
298 tokens: make(map[string]int64),
303 rest.HandleFunc(`/{locator:[0-9a-f]{32}\+.*}`, h.Get).Methods("GET", "HEAD")
304 rest.HandleFunc(`/{locator:[0-9a-f]{32}}`, h.Get).Methods("GET", "HEAD")
307 rest.HandleFunc(`/index`, h.Index).Methods("GET")
309 // List blocks whose hash has the given prefix
310 rest.HandleFunc(`/index/{prefix:[0-9a-f]{0,32}}`, h.Index).Methods("GET")
312 rest.HandleFunc(`/{locator:[0-9a-f]{32}\+.*}`, h.Put).Methods("PUT")
313 rest.HandleFunc(`/{locator:[0-9a-f]{32}}`, h.Put).Methods("PUT")
314 rest.HandleFunc(`/`, h.Put).Methods("POST")
315 rest.HandleFunc(`/{any}`, h.Options).Methods("OPTIONS")
316 rest.HandleFunc(`/`, h.Options).Methods("OPTIONS")
318 rest.Handle("/_health/{check}", &health.Handler{
323 rest.NotFoundHandler = InvalidPathHandler{}
327 var errLoopDetected = errors.New("loop detected")
329 func (*proxyHandler) checkLoop(resp http.ResponseWriter, req *http.Request) error {
330 if via := req.Header.Get("Via"); strings.Index(via, " "+viaAlias) >= 0 {
331 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)
332 http.Error(resp, errLoopDetected.Error(), http.StatusInternalServerError)
333 return errLoopDetected
338 func SetCorsHeaders(resp http.ResponseWriter) {
339 resp.Header().Set("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, OPTIONS")
340 resp.Header().Set("Access-Control-Allow-Origin", "*")
341 resp.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Length, Content-Type, X-Keep-Desired-Replicas")
342 resp.Header().Set("Access-Control-Max-Age", "86486400")
345 type InvalidPathHandler struct{}
347 func (InvalidPathHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
348 log.Printf("%s: %s %s unroutable", GetRemoteAddress(req), req.Method, req.URL.Path)
349 http.Error(resp, "Bad request", http.StatusBadRequest)
352 func (h *proxyHandler) Options(resp http.ResponseWriter, req *http.Request) {
353 log.Printf("%s: %s %s", GetRemoteAddress(req), req.Method, req.URL.Path)
357 var errBadAuthorizationHeader = errors.New("Missing or invalid Authorization header")
358 var errContentLengthMismatch = errors.New("Actual length != expected content length")
359 var errMethodNotSupported = errors.New("Method not supported")
361 var removeHint, _ = regexp.Compile("\\+K@[a-z0-9]{5}(\\+|$)")
363 func (h *proxyHandler) Get(resp http.ResponseWriter, req *http.Request) {
364 if err := h.checkLoop(resp, req); err != nil {
368 resp.Header().Set("Via", req.Proto+" "+viaAlias)
370 locator := mux.Vars(req)["locator"]
373 var expectLength, responseLength int64
377 log.Println(GetRemoteAddress(req), req.Method, req.URL.Path, status, expectLength, responseLength, proxiedURI, err)
378 if status != http.StatusOK {
379 http.Error(resp, err.Error(), status)
383 kc := h.makeKeepClient(req)
387 if pass, tok = CheckAuthorizationHeader(kc, h.APITokenCache, req); !pass {
388 status, err = http.StatusForbidden, errBadAuthorizationHeader
392 // Copy ArvadosClient struct and use the client's API token
393 arvclient := *kc.Arvados
394 arvclient.ApiToken = tok
395 kc.Arvados = &arvclient
397 var reader io.ReadCloser
399 locator = removeHint.ReplaceAllString(locator, "$1")
403 expectLength, proxiedURI, err = kc.Ask(locator)
405 reader, expectLength, proxiedURI, err = kc.Get(locator)
410 status, err = http.StatusNotImplemented, errMethodNotSupported
414 if expectLength == -1 {
415 log.Println("Warning:", GetRemoteAddress(req), req.Method, proxiedURI, "Content-Length not provided")
418 switch respErr := err.(type) {
420 status = http.StatusOK
421 resp.Header().Set("Content-Length", fmt.Sprint(expectLength))
426 responseLength, err = io.Copy(resp, reader)
427 if err == nil && expectLength > -1 && responseLength != expectLength {
428 err = errContentLengthMismatch
431 case keepclient.Error:
432 if respErr == keepclient.BlockNotFound {
433 status = http.StatusNotFound
434 } else if respErr.Temporary() {
435 status = http.StatusBadGateway
440 status = http.StatusInternalServerError
444 var errLengthRequired = errors.New(http.StatusText(http.StatusLengthRequired))
445 var errLengthMismatch = errors.New("Locator size hint does not match Content-Length header")
447 func (h *proxyHandler) Put(resp http.ResponseWriter, req *http.Request) {
448 if err := h.checkLoop(resp, req); err != nil {
452 resp.Header().Set("Via", "HTTP/1.1 "+viaAlias)
454 kc := h.makeKeepClient(req)
457 var expectLength int64
458 var status = http.StatusInternalServerError
459 var wroteReplicas int
460 var locatorOut string = "-"
463 log.Println(GetRemoteAddress(req), req.Method, req.URL.Path, status, expectLength, kc.Want_replicas, wroteReplicas, locatorOut, err)
464 if status != http.StatusOK {
465 http.Error(resp, err.Error(), status)
469 locatorIn := mux.Vars(req)["locator"]
471 // Check if the client specified storage classes
472 if req.Header.Get("X-Keep-Storage-Classes") != "" {
474 for _, sc := range strings.Split(req.Header.Get("X-Keep-Storage-Classes"), ",") {
475 scl = append(scl, strings.Trim(sc, " "))
477 kc.StorageClasses = scl
480 _, err = fmt.Sscanf(req.Header.Get("Content-Length"), "%d", &expectLength)
481 if err != nil || expectLength < 0 {
482 err = errLengthRequired
483 status = http.StatusLengthRequired
488 var loc *keepclient.Locator
489 if loc, err = keepclient.MakeLocator(locatorIn); err != nil {
490 status = http.StatusBadRequest
492 } else if loc.Size > 0 && int64(loc.Size) != expectLength {
493 err = errLengthMismatch
494 status = http.StatusBadRequest
501 if pass, tok = CheckAuthorizationHeader(kc, h.APITokenCache, req); !pass {
502 err = errBadAuthorizationHeader
503 status = http.StatusForbidden
507 // Copy ArvadosClient struct and use the client's API token
508 arvclient := *kc.Arvados
509 arvclient.ApiToken = tok
510 kc.Arvados = &arvclient
512 // Check if the client specified the number of replicas
513 if req.Header.Get("X-Keep-Desired-Replicas") != "" {
515 _, err := fmt.Sscanf(req.Header.Get(keepclient.XKeepDesiredReplicas), "%d", &r)
521 // Now try to put the block through
523 bytes, err2 := ioutil.ReadAll(req.Body)
525 err = fmt.Errorf("Error reading request body: %s", err2)
526 status = http.StatusInternalServerError
529 locatorOut, wroteReplicas, err = kc.PutB(bytes)
531 locatorOut, wroteReplicas, err = kc.PutHR(locatorIn, req.Body, expectLength)
534 // Tell the client how many successful PUTs we accomplished
535 resp.Header().Set(keepclient.XKeepReplicasStored, fmt.Sprintf("%d", wroteReplicas))
539 status = http.StatusOK
540 _, err = io.WriteString(resp, locatorOut)
542 case keepclient.OversizeBlockError:
544 status = http.StatusRequestEntityTooLarge
546 case keepclient.InsufficientReplicasError:
547 if wroteReplicas > 0 {
548 // At least one write is considered success. The
549 // client can decide if getting less than the number of
550 // replications it asked for is a fatal error.
551 status = http.StatusOK
552 _, err = io.WriteString(resp, locatorOut)
554 status = http.StatusServiceUnavailable
558 status = http.StatusBadGateway
562 // ServeHTTP implementation for IndexHandler
563 // Supports only GET requests for /index/{prefix:[0-9a-f]{0,32}}
564 // For each keep server found in LocalRoots:
565 // Invokes GetIndex using keepclient
566 // Expects "complete" response (terminating with blank new line)
567 // Aborts on any errors
568 // Concatenates responses from all those keep servers and returns
569 func (h *proxyHandler) Index(resp http.ResponseWriter, req *http.Request) {
572 prefix := mux.Vars(req)["prefix"]
577 if status != http.StatusOK {
578 http.Error(resp, err.Error(), status)
582 kc := h.makeKeepClient(req)
583 ok, token := CheckAuthorizationHeader(kc, h.APITokenCache, req)
585 status, err = http.StatusForbidden, errBadAuthorizationHeader
589 // Copy ArvadosClient struct and use the client's API token
590 arvclient := *kc.Arvados
591 arvclient.ApiToken = token
592 kc.Arvados = &arvclient
594 // Only GET method is supported
595 if req.Method != "GET" {
596 status, err = http.StatusNotImplemented, errMethodNotSupported
600 // Get index from all LocalRoots and write to resp
602 for uuid := range kc.LocalRoots() {
603 reader, err = kc.GetIndex(uuid, prefix)
605 status = http.StatusBadGateway
609 _, err = io.Copy(resp, reader)
611 status = http.StatusBadGateway
616 // Got index from all the keep servers and wrote to resp
617 status = http.StatusOK
618 resp.Write([]byte("\n"))
621 func (h *proxyHandler) makeKeepClient(req *http.Request) *keepclient.KeepClient {
623 kc.RequestID = req.Header.Get("X-Request-Id")
624 kc.HTTPClient = &proxyClient{
625 client: &http.Client{
627 Transport: h.transport,