1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
23 "git.curoverse.com/arvados.git/lib/config"
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/health"
27 "git.curoverse.com/arvados.git/sdk/go/httpserver"
28 "git.curoverse.com/arvados.git/sdk/go/keepclient"
29 "github.com/coreos/go-systemd/daemon"
30 "github.com/gorilla/mux"
31 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 {
45 flags := flag.NewFlagSet(args[0], flag.ExitOnError)
48 dumpConfig := flags.Bool("dump-config", false, "write current configuration to stdout and exit")
49 getVersion := flags.Bool("version", false, "Print version information and exit.")
51 loader := config.NewLoader(os.Stdin, logger)
52 loader.SetupFlags(flags)
54 args = loader.MungeLegacyConfigArgs(logger, args[1:], "-legacy-keepproxy-config")
57 // Print version information if requested
59 fmt.Printf("keepproxy %s\n", version)
63 cfg, err := loader.Load()
68 cluster, err := cfg.GetCluster("")
74 out, err := yaml.Marshal(cfg)
78 _, err = os.Stdout.Write(out)
89 logger.Formatter = &log.JSONFormatter{
90 TimestampFormat: rfc3339NanoFixed,
93 cluster := configure(logger, os.Args)
98 log.Printf("keepproxy %s started", version)
100 client, err := arvados.NewClientFromConfig(cluster)
104 client.AuthToken = cluster.SystemRootToken
106 arv, err := arvadosclient.New(client)
108 log.Fatalf("Error setting up arvados client %s", err.Error())
111 if cluster.SystemLogs.LogLevel == "debug" {
112 keepclient.DebugPrintf = log.Printf
114 kc, err := keepclient.MakeKeepClient(arv)
116 log.Fatalf("Error setting up keep client %s", err.Error())
118 keepclient.RefreshServiceDiscoveryOnSIGHUP()
120 pidFile := "keepproxy"
121 f, err := os.Create(pidFile)
126 err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
128 log.Fatalf("flock(%s): %s", pidFile, err)
130 defer os.Remove(pidFile)
133 log.Fatalf("truncate(%s): %s", pidFile, err)
135 _, err = fmt.Fprint(f, os.Getpid())
137 log.Fatalf("write(%s): %s", pidFile, err)
141 log.Fatalf("sync(%s): %s", pidFile, err)
144 if cluster.Collections.DefaultReplication > 0 {
145 kc.Want_replicas = cluster.Collections.DefaultReplication
148 var listen arvados.URL
149 for listen = range cluster.Services.Keepproxy.InternalURLs {
152 listener, err := net.Listen("tcp", listen.Host)
154 log.Fatalf("listen(%s): %s", listen, err)
157 if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
158 log.Printf("Error notifying init daemon: %v", err)
160 log.Println("Listening at", listener.Addr())
162 // Shut down the server gracefully (by closing the listener)
163 // if SIGTERM is received.
164 term := make(chan os.Signal, 1)
165 go func(sig <-chan os.Signal) {
167 log.Println("caught signal:", s)
170 signal.Notify(term, syscall.SIGTERM)
171 signal.Notify(term, syscall.SIGINT)
173 // Start serving requests.
174 router = MakeRESTRouter(kc, time.Duration(cluster.API.KeepServiceRequestTimeout), cluster.SystemRootToken)
175 http.Serve(listener, httpserver.AddRequestIDs(httpserver.LogRequests(router)))
177 log.Println("shutting down")
180 type ApiTokenCache struct {
181 tokens map[string]int64
186 // Cache the token and set an expire time. If we already have an expire time
187 // on the token, it is not updated.
188 func (this *ApiTokenCache) RememberToken(token string) {
190 defer this.lock.Unlock()
192 now := time.Now().Unix()
193 if this.tokens[token] == 0 {
194 this.tokens[token] = now + this.expireTime
198 // Check if the cached token is known and still believed to be valid.
199 func (this *ApiTokenCache) RecallToken(token string) bool {
201 defer this.lock.Unlock()
203 now := time.Now().Unix()
204 if this.tokens[token] == 0 {
207 } else if now < this.tokens[token] {
208 // Token is known and still valid
212 this.tokens[token] = 0
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 CheckAuthorizationHeader(kc *keepclient.KeepClient, cache *ApiTokenCache, req *http.Request) (pass bool, tok string) {
225 parts := strings.SplitN(req.Header.Get("Authorization"), " ", 2)
226 if len(parts) < 2 || !(parts[0] == "OAuth2" || parts[0] == "Bearer") || len(parts[1]) == 0 {
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 cache.RecallToken(op + ":" + tok) {
243 // Valid in the cache, short circuit
250 arv.RequestID = req.Header.Get("X-Request-Id")
252 err = arv.Call("HEAD", "keep_services", "", "accessible", nil, nil)
254 err = arv.Call("HEAD", "users", "", "current", nil, nil)
257 log.Printf("%s: CheckAuthorizationHeader error: %v", GetRemoteAddress(req), err)
261 // Success! Update cache
262 cache.RememberToken(op + ":" + tok)
267 // We need to make a private copy of the default http transport early
268 // in initialization, then make copies of our private copy later. It
269 // won't be safe to copy http.DefaultTransport itself later, because
270 // its private mutexes might have already been used. (Without this,
271 // the test suite sometimes panics "concurrent map writes" in
272 // net/http.(*Transport).removeIdleConnLocked().)
273 var defaultTransport = *(http.DefaultTransport.(*http.Transport))
275 type proxyHandler struct {
277 *keepclient.KeepClient
279 timeout time.Duration
280 transport *http.Transport
283 // MakeRESTRouter returns an http.Handler that passes GET and PUT
284 // requests to the appropriate handlers.
285 func MakeRESTRouter(kc *keepclient.KeepClient, timeout time.Duration, mgmtToken string) http.Handler {
286 rest := mux.NewRouter()
288 transport := defaultTransport
289 transport.DialContext = (&net.Dialer{
290 Timeout: keepclient.DefaultConnectTimeout,
291 KeepAlive: keepclient.DefaultKeepAlive,
294 transport.TLSClientConfig = arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure)
295 transport.TLSHandshakeTimeout = keepclient.DefaultTLSHandshakeTimeout
301 transport: &transport,
302 ApiTokenCache: &ApiTokenCache{
303 tokens: make(map[string]int64),
308 rest.HandleFunc(`/{locator:[0-9a-f]{32}\+.*}`, h.Get).Methods("GET", "HEAD")
309 rest.HandleFunc(`/{locator:[0-9a-f]{32}}`, h.Get).Methods("GET", "HEAD")
312 rest.HandleFunc(`/index`, h.Index).Methods("GET")
314 // List blocks whose hash has the given prefix
315 rest.HandleFunc(`/index/{prefix:[0-9a-f]{0,32}}`, h.Index).Methods("GET")
317 rest.HandleFunc(`/{locator:[0-9a-f]{32}\+.*}`, h.Put).Methods("PUT")
318 rest.HandleFunc(`/{locator:[0-9a-f]{32}}`, h.Put).Methods("PUT")
319 rest.HandleFunc(`/`, h.Put).Methods("POST")
320 rest.HandleFunc(`/{any}`, h.Options).Methods("OPTIONS")
321 rest.HandleFunc(`/`, h.Options).Methods("OPTIONS")
323 rest.Handle("/_health/{check}", &health.Handler{
328 rest.NotFoundHandler = InvalidPathHandler{}
332 var errLoopDetected = errors.New("loop detected")
334 func (*proxyHandler) checkLoop(resp http.ResponseWriter, req *http.Request) error {
335 if via := req.Header.Get("Via"); strings.Index(via, " "+viaAlias) >= 0 {
336 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)
337 http.Error(resp, errLoopDetected.Error(), http.StatusInternalServerError)
338 return errLoopDetected
343 func SetCorsHeaders(resp http.ResponseWriter) {
344 resp.Header().Set("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, OPTIONS")
345 resp.Header().Set("Access-Control-Allow-Origin", "*")
346 resp.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Length, Content-Type, X-Keep-Desired-Replicas")
347 resp.Header().Set("Access-Control-Max-Age", "86486400")
350 type InvalidPathHandler struct{}
352 func (InvalidPathHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
353 log.Printf("%s: %s %s unroutable", GetRemoteAddress(req), req.Method, req.URL.Path)
354 http.Error(resp, "Bad request", http.StatusBadRequest)
357 func (h *proxyHandler) Options(resp http.ResponseWriter, req *http.Request) {
358 log.Printf("%s: %s %s", GetRemoteAddress(req), req.Method, req.URL.Path)
362 var BadAuthorizationHeader = errors.New("Missing or invalid Authorization header")
363 var ContentLengthMismatch = errors.New("Actual length != expected content length")
364 var MethodNotSupported = errors.New("Method not supported")
366 var removeHint, _ = regexp.Compile("\\+K@[a-z0-9]{5}(\\+|$)")
368 func (h *proxyHandler) Get(resp http.ResponseWriter, req *http.Request) {
369 if err := h.checkLoop(resp, req); err != nil {
373 resp.Header().Set("Via", req.Proto+" "+viaAlias)
375 locator := mux.Vars(req)["locator"]
378 var expectLength, responseLength int64
382 log.Println(GetRemoteAddress(req), req.Method, req.URL.Path, status, expectLength, responseLength, proxiedURI, err)
383 if status != http.StatusOK {
384 http.Error(resp, err.Error(), status)
388 kc := h.makeKeepClient(req)
392 if pass, tok = CheckAuthorizationHeader(kc, h.ApiTokenCache, req); !pass {
393 status, err = http.StatusForbidden, BadAuthorizationHeader
397 // Copy ArvadosClient struct and use the client's API token
398 arvclient := *kc.Arvados
399 arvclient.ApiToken = tok
400 kc.Arvados = &arvclient
402 var reader io.ReadCloser
404 locator = removeHint.ReplaceAllString(locator, "$1")
408 expectLength, proxiedURI, err = kc.Ask(locator)
410 reader, expectLength, proxiedURI, err = kc.Get(locator)
415 status, err = http.StatusNotImplemented, MethodNotSupported
419 if expectLength == -1 {
420 log.Println("Warning:", GetRemoteAddress(req), req.Method, proxiedURI, "Content-Length not provided")
423 switch respErr := err.(type) {
425 status = http.StatusOK
426 resp.Header().Set("Content-Length", fmt.Sprint(expectLength))
431 responseLength, err = io.Copy(resp, reader)
432 if err == nil && expectLength > -1 && responseLength != expectLength {
433 err = ContentLengthMismatch
436 case keepclient.Error:
437 if respErr == keepclient.BlockNotFound {
438 status = http.StatusNotFound
439 } else if respErr.Temporary() {
440 status = http.StatusBadGateway
445 status = http.StatusInternalServerError
449 var LengthRequiredError = errors.New(http.StatusText(http.StatusLengthRequired))
450 var LengthMismatchError = errors.New("Locator size hint does not match Content-Length header")
452 func (h *proxyHandler) Put(resp http.ResponseWriter, req *http.Request) {
453 if err := h.checkLoop(resp, req); err != nil {
457 resp.Header().Set("Via", "HTTP/1.1 "+viaAlias)
459 kc := h.makeKeepClient(req)
462 var expectLength int64
463 var status = http.StatusInternalServerError
464 var wroteReplicas int
465 var locatorOut string = "-"
468 log.Println(GetRemoteAddress(req), req.Method, req.URL.Path, status, expectLength, kc.Want_replicas, wroteReplicas, locatorOut, err)
469 if status != http.StatusOK {
470 http.Error(resp, err.Error(), status)
474 locatorIn := mux.Vars(req)["locator"]
476 // Check if the client specified storage classes
477 if req.Header.Get("X-Keep-Storage-Classes") != "" {
479 for _, sc := range strings.Split(req.Header.Get("X-Keep-Storage-Classes"), ",") {
480 scl = append(scl, strings.Trim(sc, " "))
482 kc.StorageClasses = scl
485 _, err = fmt.Sscanf(req.Header.Get("Content-Length"), "%d", &expectLength)
486 if err != nil || expectLength < 0 {
487 err = LengthRequiredError
488 status = http.StatusLengthRequired
493 var loc *keepclient.Locator
494 if loc, err = keepclient.MakeLocator(locatorIn); err != nil {
495 status = http.StatusBadRequest
497 } else if loc.Size > 0 && int64(loc.Size) != expectLength {
498 err = LengthMismatchError
499 status = http.StatusBadRequest
506 if pass, tok = CheckAuthorizationHeader(kc, h.ApiTokenCache, req); !pass {
507 err = BadAuthorizationHeader
508 status = http.StatusForbidden
512 // Copy ArvadosClient struct and use the client's API token
513 arvclient := *kc.Arvados
514 arvclient.ApiToken = tok
515 kc.Arvados = &arvclient
517 // Check if the client specified the number of replicas
518 if req.Header.Get("X-Keep-Desired-Replicas") != "" {
520 _, err := fmt.Sscanf(req.Header.Get(keepclient.X_Keep_Desired_Replicas), "%d", &r)
526 // Now try to put the block through
528 bytes, err2 := ioutil.ReadAll(req.Body)
530 err = fmt.Errorf("Error reading request body: %s", err2)
531 status = http.StatusInternalServerError
534 locatorOut, wroteReplicas, err = kc.PutB(bytes)
536 locatorOut, wroteReplicas, err = kc.PutHR(locatorIn, req.Body, expectLength)
539 // Tell the client how many successful PUTs we accomplished
540 resp.Header().Set(keepclient.X_Keep_Replicas_Stored, fmt.Sprintf("%d", wroteReplicas))
544 status = http.StatusOK
545 _, err = io.WriteString(resp, locatorOut)
547 case keepclient.OversizeBlockError:
549 status = http.StatusRequestEntityTooLarge
551 case keepclient.InsufficientReplicasError:
552 if wroteReplicas > 0 {
553 // At least one write is considered success. The
554 // client can decide if getting less than the number of
555 // replications it asked for is a fatal error.
556 status = http.StatusOK
557 _, err = io.WriteString(resp, locatorOut)
559 status = http.StatusServiceUnavailable
563 status = http.StatusBadGateway
567 // ServeHTTP implementation for IndexHandler
568 // Supports only GET requests for /index/{prefix:[0-9a-f]{0,32}}
569 // For each keep server found in LocalRoots:
570 // Invokes GetIndex using keepclient
571 // Expects "complete" response (terminating with blank new line)
572 // Aborts on any errors
573 // Concatenates responses from all those keep servers and returns
574 func (h *proxyHandler) Index(resp http.ResponseWriter, req *http.Request) {
577 prefix := mux.Vars(req)["prefix"]
582 if status != http.StatusOK {
583 http.Error(resp, err.Error(), status)
587 kc := h.makeKeepClient(req)
588 ok, token := CheckAuthorizationHeader(kc, h.ApiTokenCache, req)
590 status, err = http.StatusForbidden, BadAuthorizationHeader
594 // Copy ArvadosClient struct and use the client's API token
595 arvclient := *kc.Arvados
596 arvclient.ApiToken = token
597 kc.Arvados = &arvclient
599 // Only GET method is supported
600 if req.Method != "GET" {
601 status, err = http.StatusNotImplemented, MethodNotSupported
605 // Get index from all LocalRoots and write to resp
607 for uuid := range kc.LocalRoots() {
608 reader, err = kc.GetIndex(uuid, prefix)
610 status = http.StatusBadGateway
614 _, err = io.Copy(resp, reader)
616 status = http.StatusBadGateway
621 // Got index from all the keep servers and wrote to resp
622 status = http.StatusOK
623 resp.Write([]byte("\n"))
626 func (h *proxyHandler) makeKeepClient(req *http.Request) *keepclient.KeepClient {
628 kc.RequestID = req.Header.Get("X-Request-Id")
629 kc.HTTPClient = &proxyClient{
630 client: &http.Client{
632 Transport: h.transport,