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 // Cache the token and set an expire time. If we already have an expire time
177 // on the token, it is not updated.
178 func (this *ApiTokenCache) RememberToken(token string) {
180 defer this.lock.Unlock()
182 now := time.Now().Unix()
183 if this.tokens[token] == 0 {
184 this.tokens[token] = now + this.expireTime
188 // Check if the cached token is known and still believed to be valid.
189 func (this *ApiTokenCache) RecallToken(token string) bool {
191 defer this.lock.Unlock()
193 now := time.Now().Unix()
194 if this.tokens[token] == 0 {
197 } else if now < this.tokens[token] {
198 // Token is known and still valid
202 this.tokens[token] = 0
207 func GetRemoteAddress(req *http.Request) string {
208 if xff := req.Header.Get("X-Forwarded-For"); xff != "" {
209 return xff + "," + req.RemoteAddr
211 return req.RemoteAddr
214 func CheckAuthorizationHeader(kc *keepclient.KeepClient, cache *ApiTokenCache, req *http.Request) (pass bool, tok string) {
215 parts := strings.SplitN(req.Header.Get("Authorization"), " ", 2)
216 if len(parts) < 2 || !(parts[0] == "OAuth2" || parts[0] == "Bearer") || len(parts[1]) == 0 {
221 // Tokens are validated differently depending on what kind of
222 // operation is being performed. For example, tokens in
223 // collection-sharing links permit GET requests, but not
226 if req.Method == "GET" || req.Method == "HEAD" {
232 if cache.RecallToken(op + ":" + tok) {
233 // Valid in the cache, short circuit
240 arv.RequestID = req.Header.Get("X-Request-Id")
242 err = arv.Call("HEAD", "keep_services", "", "accessible", nil, nil)
244 err = arv.Call("HEAD", "users", "", "current", nil, nil)
247 log.Printf("%s: CheckAuthorizationHeader error: %v", GetRemoteAddress(req), err)
251 // Success! Update cache
252 cache.RememberToken(op + ":" + tok)
257 // We need to make a private copy of the default http transport early
258 // in initialization, then make copies of our private copy later. It
259 // won't be safe to copy http.DefaultTransport itself later, because
260 // its private mutexes might have already been used. (Without this,
261 // the test suite sometimes panics "concurrent map writes" in
262 // net/http.(*Transport).removeIdleConnLocked().)
263 var defaultTransport = *(http.DefaultTransport.(*http.Transport))
265 type proxyHandler struct {
267 *keepclient.KeepClient
269 timeout time.Duration
270 transport *http.Transport
273 // MakeRESTRouter returns an http.Handler that passes GET and PUT
274 // requests to the appropriate handlers.
275 func MakeRESTRouter(kc *keepclient.KeepClient, timeout time.Duration, mgmtToken string) http.Handler {
276 rest := mux.NewRouter()
278 transport := defaultTransport
279 transport.DialContext = (&net.Dialer{
280 Timeout: keepclient.DefaultConnectTimeout,
281 KeepAlive: keepclient.DefaultKeepAlive,
284 transport.TLSClientConfig = arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure)
285 transport.TLSHandshakeTimeout = keepclient.DefaultTLSHandshakeTimeout
291 transport: &transport,
292 ApiTokenCache: &ApiTokenCache{
293 tokens: make(map[string]int64),
298 rest.HandleFunc(`/{locator:[0-9a-f]{32}\+.*}`, h.Get).Methods("GET", "HEAD")
299 rest.HandleFunc(`/{locator:[0-9a-f]{32}}`, h.Get).Methods("GET", "HEAD")
302 rest.HandleFunc(`/index`, h.Index).Methods("GET")
304 // List blocks whose hash has the given prefix
305 rest.HandleFunc(`/index/{prefix:[0-9a-f]{0,32}}`, h.Index).Methods("GET")
307 rest.HandleFunc(`/{locator:[0-9a-f]{32}\+.*}`, h.Put).Methods("PUT")
308 rest.HandleFunc(`/{locator:[0-9a-f]{32}}`, h.Put).Methods("PUT")
309 rest.HandleFunc(`/`, h.Put).Methods("POST")
310 rest.HandleFunc(`/{any}`, h.Options).Methods("OPTIONS")
311 rest.HandleFunc(`/`, h.Options).Methods("OPTIONS")
313 rest.Handle("/_health/{check}", &health.Handler{
318 rest.NotFoundHandler = InvalidPathHandler{}
322 var errLoopDetected = errors.New("loop detected")
324 func (*proxyHandler) checkLoop(resp http.ResponseWriter, req *http.Request) error {
325 if via := req.Header.Get("Via"); strings.Index(via, " "+viaAlias) >= 0 {
326 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)
327 http.Error(resp, errLoopDetected.Error(), http.StatusInternalServerError)
328 return errLoopDetected
333 func SetCorsHeaders(resp http.ResponseWriter) {
334 resp.Header().Set("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, OPTIONS")
335 resp.Header().Set("Access-Control-Allow-Origin", "*")
336 resp.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Length, Content-Type, X-Keep-Desired-Replicas")
337 resp.Header().Set("Access-Control-Max-Age", "86486400")
340 type InvalidPathHandler struct{}
342 func (InvalidPathHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
343 log.Printf("%s: %s %s unroutable", GetRemoteAddress(req), req.Method, req.URL.Path)
344 http.Error(resp, "Bad request", http.StatusBadRequest)
347 func (h *proxyHandler) Options(resp http.ResponseWriter, req *http.Request) {
348 log.Printf("%s: %s %s", GetRemoteAddress(req), req.Method, req.URL.Path)
352 var BadAuthorizationHeader = errors.New("Missing or invalid Authorization header")
353 var ContentLengthMismatch = errors.New("Actual length != expected content length")
354 var MethodNotSupported = errors.New("Method not supported")
356 var removeHint, _ = regexp.Compile("\\+K@[a-z0-9]{5}(\\+|$)")
358 func (h *proxyHandler) Get(resp http.ResponseWriter, req *http.Request) {
359 if err := h.checkLoop(resp, req); err != nil {
363 resp.Header().Set("Via", req.Proto+" "+viaAlias)
365 locator := mux.Vars(req)["locator"]
368 var expectLength, responseLength int64
372 log.Println(GetRemoteAddress(req), req.Method, req.URL.Path, status, expectLength, responseLength, proxiedURI, err)
373 if status != http.StatusOK {
374 http.Error(resp, err.Error(), status)
378 kc := h.makeKeepClient(req)
382 if pass, tok = CheckAuthorizationHeader(kc, h.ApiTokenCache, req); !pass {
383 status, err = http.StatusForbidden, BadAuthorizationHeader
387 // Copy ArvadosClient struct and use the client's API token
388 arvclient := *kc.Arvados
389 arvclient.ApiToken = tok
390 kc.Arvados = &arvclient
392 var reader io.ReadCloser
394 locator = removeHint.ReplaceAllString(locator, "$1")
398 expectLength, proxiedURI, err = kc.Ask(locator)
400 reader, expectLength, proxiedURI, err = kc.Get(locator)
405 status, err = http.StatusNotImplemented, MethodNotSupported
409 if expectLength == -1 {
410 log.Println("Warning:", GetRemoteAddress(req), req.Method, proxiedURI, "Content-Length not provided")
413 switch respErr := err.(type) {
415 status = http.StatusOK
416 resp.Header().Set("Content-Length", fmt.Sprint(expectLength))
421 responseLength, err = io.Copy(resp, reader)
422 if err == nil && expectLength > -1 && responseLength != expectLength {
423 err = ContentLengthMismatch
426 case keepclient.Error:
427 if respErr == keepclient.BlockNotFound {
428 status = http.StatusNotFound
429 } else if respErr.Temporary() {
430 status = http.StatusBadGateway
435 status = http.StatusInternalServerError
439 var LengthRequiredError = errors.New(http.StatusText(http.StatusLengthRequired))
440 var LengthMismatchError = errors.New("Locator size hint does not match Content-Length header")
442 func (h *proxyHandler) Put(resp http.ResponseWriter, req *http.Request) {
443 if err := h.checkLoop(resp, req); err != nil {
447 resp.Header().Set("Via", "HTTP/1.1 "+viaAlias)
449 kc := h.makeKeepClient(req)
452 var expectLength int64
453 var status = http.StatusInternalServerError
454 var wroteReplicas int
455 var locatorOut string = "-"
458 log.Println(GetRemoteAddress(req), req.Method, req.URL.Path, status, expectLength, kc.Want_replicas, wroteReplicas, locatorOut, err)
459 if status != http.StatusOK {
460 http.Error(resp, err.Error(), status)
464 locatorIn := mux.Vars(req)["locator"]
466 // Check if the client specified storage classes
467 if req.Header.Get("X-Keep-Storage-Classes") != "" {
469 for _, sc := range strings.Split(req.Header.Get("X-Keep-Storage-Classes"), ",") {
470 scl = append(scl, strings.Trim(sc, " "))
472 kc.StorageClasses = scl
475 _, err = fmt.Sscanf(req.Header.Get("Content-Length"), "%d", &expectLength)
476 if err != nil || expectLength < 0 {
477 err = LengthRequiredError
478 status = http.StatusLengthRequired
483 var loc *keepclient.Locator
484 if loc, err = keepclient.MakeLocator(locatorIn); err != nil {
485 status = http.StatusBadRequest
487 } else if loc.Size > 0 && int64(loc.Size) != expectLength {
488 err = LengthMismatchError
489 status = http.StatusBadRequest
496 if pass, tok = CheckAuthorizationHeader(kc, h.ApiTokenCache, req); !pass {
497 err = BadAuthorizationHeader
498 status = http.StatusForbidden
502 // Copy ArvadosClient struct and use the client's API token
503 arvclient := *kc.Arvados
504 arvclient.ApiToken = tok
505 kc.Arvados = &arvclient
507 // Check if the client specified the number of replicas
508 if req.Header.Get("X-Keep-Desired-Replicas") != "" {
510 _, err := fmt.Sscanf(req.Header.Get(keepclient.X_Keep_Desired_Replicas), "%d", &r)
516 // Now try to put the block through
518 bytes, err2 := ioutil.ReadAll(req.Body)
520 err = fmt.Errorf("Error reading request body: %s", err2)
521 status = http.StatusInternalServerError
524 locatorOut, wroteReplicas, err = kc.PutB(bytes)
526 locatorOut, wroteReplicas, err = kc.PutHR(locatorIn, req.Body, expectLength)
529 // Tell the client how many successful PUTs we accomplished
530 resp.Header().Set(keepclient.X_Keep_Replicas_Stored, fmt.Sprintf("%d", wroteReplicas))
534 status = http.StatusOK
535 _, err = io.WriteString(resp, locatorOut)
537 case keepclient.OversizeBlockError:
539 status = http.StatusRequestEntityTooLarge
541 case keepclient.InsufficientReplicasError:
542 if wroteReplicas > 0 {
543 // At least one write is considered success. The
544 // client can decide if getting less than the number of
545 // replications it asked for is a fatal error.
546 status = http.StatusOK
547 _, err = io.WriteString(resp, locatorOut)
549 status = http.StatusServiceUnavailable
553 status = http.StatusBadGateway
557 // ServeHTTP implementation for IndexHandler
558 // Supports only GET requests for /index/{prefix:[0-9a-f]{0,32}}
559 // For each keep server found in LocalRoots:
560 // Invokes GetIndex using keepclient
561 // Expects "complete" response (terminating with blank new line)
562 // Aborts on any errors
563 // Concatenates responses from all those keep servers and returns
564 func (h *proxyHandler) Index(resp http.ResponseWriter, req *http.Request) {
567 prefix := mux.Vars(req)["prefix"]
572 if status != http.StatusOK {
573 http.Error(resp, err.Error(), status)
577 kc := h.makeKeepClient(req)
578 ok, token := CheckAuthorizationHeader(kc, h.ApiTokenCache, req)
580 status, err = http.StatusForbidden, BadAuthorizationHeader
584 // Copy ArvadosClient struct and use the client's API token
585 arvclient := *kc.Arvados
586 arvclient.ApiToken = token
587 kc.Arvados = &arvclient
589 // Only GET method is supported
590 if req.Method != "GET" {
591 status, err = http.StatusNotImplemented, MethodNotSupported
595 // Get index from all LocalRoots and write to resp
597 for uuid := range kc.LocalRoots() {
598 reader, err = kc.GetIndex(uuid, prefix)
600 status = http.StatusBadGateway
604 _, err = io.Copy(resp, reader)
606 status = http.StatusBadGateway
611 // Got index from all the keep servers and wrote to resp
612 status = http.StatusOK
613 resp.Write([]byte("\n"))
616 func (h *proxyHandler) makeKeepClient(req *http.Request) *keepclient.KeepClient {
618 kc.RequestID = req.Header.Get("X-Request-Id")
619 kc.HTTPClient = &proxyClient{
620 client: &http.Client{
622 Transport: h.transport,