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 cluster.SystemLogs.LogLevel == "debug" {
120 keepclient.DebugPrintf = log.Printf
122 kc, err := keepclient.MakeKeepClient(arv)
124 return fmt.Errorf("Error setting up keep client %v", err)
126 keepclient.RefreshServiceDiscoveryOnSIGHUP()
128 if cluster.Collections.DefaultReplication > 0 {
129 kc.Want_replicas = cluster.Collections.DefaultReplication
132 var listen arvados.URL
133 for listen = range cluster.Services.Keepproxy.InternalURLs {
138 listener, lErr = net.Listen("tcp", listen.Host)
140 return fmt.Errorf("listen(%s): %v", listen.Host, lErr)
143 if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
144 log.Printf("Error notifying init daemon: %v", err)
146 log.Println("listening at", listener.Addr())
148 // Shut down the server gracefully (by closing the listener)
149 // if SIGTERM is received.
150 term := make(chan os.Signal, 1)
151 go func(sig <-chan os.Signal) {
153 log.Println("caught signal:", s)
156 signal.Notify(term, syscall.SIGTERM)
157 signal.Notify(term, syscall.SIGINT)
159 // Start serving requests.
160 router = MakeRESTRouter(kc, time.Duration(cluster.API.KeepServiceRequestTimeout), cluster.SystemRootToken)
161 return http.Serve(listener, httpserver.AddRequestIDs(httpserver.LogRequests(router)))
164 type ApiTokenCache struct {
165 tokens map[string]int64
170 // Cache the token and set an expire time. If we already have an expire time
171 // on the token, it is not updated.
172 func (this *ApiTokenCache) RememberToken(token string) {
174 defer this.lock.Unlock()
176 now := time.Now().Unix()
177 if this.tokens[token] == 0 {
178 this.tokens[token] = now + this.expireTime
182 // Check if the cached token is known and still believed to be valid.
183 func (this *ApiTokenCache) RecallToken(token string) bool {
185 defer this.lock.Unlock()
187 now := time.Now().Unix()
188 if this.tokens[token] == 0 {
191 } else if now < this.tokens[token] {
192 // Token is known and still valid
196 this.tokens[token] = 0
201 func GetRemoteAddress(req *http.Request) string {
202 if xff := req.Header.Get("X-Forwarded-For"); xff != "" {
203 return xff + "," + req.RemoteAddr
205 return req.RemoteAddr
208 func CheckAuthorizationHeader(kc *keepclient.KeepClient, cache *ApiTokenCache, req *http.Request) (pass bool, tok string) {
209 parts := strings.SplitN(req.Header.Get("Authorization"), " ", 2)
210 if len(parts) < 2 || !(parts[0] == "OAuth2" || parts[0] == "Bearer") || len(parts[1]) == 0 {
215 // Tokens are validated differently depending on what kind of
216 // operation is being performed. For example, tokens in
217 // collection-sharing links permit GET requests, but not
220 if req.Method == "GET" || req.Method == "HEAD" {
226 if cache.RecallToken(op + ":" + tok) {
227 // Valid in the cache, short circuit
234 arv.RequestID = req.Header.Get("X-Request-Id")
236 err = arv.Call("HEAD", "keep_services", "", "accessible", nil, nil)
238 err = arv.Call("HEAD", "users", "", "current", nil, nil)
241 log.Printf("%s: CheckAuthorizationHeader error: %v", GetRemoteAddress(req), err)
245 // Success! Update cache
246 cache.RememberToken(op + ":" + tok)
251 // We need to make a private copy of the default http transport early
252 // in initialization, then make copies of our private copy later. It
253 // won't be safe to copy http.DefaultTransport itself later, because
254 // its private mutexes might have already been used. (Without this,
255 // the test suite sometimes panics "concurrent map writes" in
256 // net/http.(*Transport).removeIdleConnLocked().)
257 var defaultTransport = *(http.DefaultTransport.(*http.Transport))
259 type proxyHandler struct {
261 *keepclient.KeepClient
263 timeout time.Duration
264 transport *http.Transport
267 // MakeRESTRouter returns an http.Handler that passes GET and PUT
268 // requests to the appropriate handlers.
269 func MakeRESTRouter(kc *keepclient.KeepClient, timeout time.Duration, mgmtToken string) http.Handler {
270 rest := mux.NewRouter()
272 transport := defaultTransport
273 transport.DialContext = (&net.Dialer{
274 Timeout: keepclient.DefaultConnectTimeout,
275 KeepAlive: keepclient.DefaultKeepAlive,
278 transport.TLSClientConfig = arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure)
279 transport.TLSHandshakeTimeout = keepclient.DefaultTLSHandshakeTimeout
285 transport: &transport,
286 ApiTokenCache: &ApiTokenCache{
287 tokens: make(map[string]int64),
292 rest.HandleFunc(`/{locator:[0-9a-f]{32}\+.*}`, h.Get).Methods("GET", "HEAD")
293 rest.HandleFunc(`/{locator:[0-9a-f]{32}}`, h.Get).Methods("GET", "HEAD")
296 rest.HandleFunc(`/index`, h.Index).Methods("GET")
298 // List blocks whose hash has the given prefix
299 rest.HandleFunc(`/index/{prefix:[0-9a-f]{0,32}}`, h.Index).Methods("GET")
301 rest.HandleFunc(`/{locator:[0-9a-f]{32}\+.*}`, h.Put).Methods("PUT")
302 rest.HandleFunc(`/{locator:[0-9a-f]{32}}`, h.Put).Methods("PUT")
303 rest.HandleFunc(`/`, h.Put).Methods("POST")
304 rest.HandleFunc(`/{any}`, h.Options).Methods("OPTIONS")
305 rest.HandleFunc(`/`, h.Options).Methods("OPTIONS")
307 rest.Handle("/_health/{check}", &health.Handler{
312 rest.NotFoundHandler = InvalidPathHandler{}
316 var errLoopDetected = errors.New("loop detected")
318 func (*proxyHandler) checkLoop(resp http.ResponseWriter, req *http.Request) error {
319 if via := req.Header.Get("Via"); strings.Index(via, " "+viaAlias) >= 0 {
320 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)
321 http.Error(resp, errLoopDetected.Error(), http.StatusInternalServerError)
322 return errLoopDetected
327 func SetCorsHeaders(resp http.ResponseWriter) {
328 resp.Header().Set("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, OPTIONS")
329 resp.Header().Set("Access-Control-Allow-Origin", "*")
330 resp.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Length, Content-Type, X-Keep-Desired-Replicas")
331 resp.Header().Set("Access-Control-Max-Age", "86486400")
334 type InvalidPathHandler struct{}
336 func (InvalidPathHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
337 log.Printf("%s: %s %s unroutable", GetRemoteAddress(req), req.Method, req.URL.Path)
338 http.Error(resp, "Bad request", http.StatusBadRequest)
341 func (h *proxyHandler) Options(resp http.ResponseWriter, req *http.Request) {
342 log.Printf("%s: %s %s", GetRemoteAddress(req), req.Method, req.URL.Path)
346 var BadAuthorizationHeader = errors.New("Missing or invalid Authorization header")
347 var ContentLengthMismatch = errors.New("Actual length != expected content length")
348 var MethodNotSupported = errors.New("Method not supported")
350 var removeHint, _ = regexp.Compile("\\+K@[a-z0-9]{5}(\\+|$)")
352 func (h *proxyHandler) Get(resp http.ResponseWriter, req *http.Request) {
353 if err := h.checkLoop(resp, req); err != nil {
357 resp.Header().Set("Via", req.Proto+" "+viaAlias)
359 locator := mux.Vars(req)["locator"]
362 var expectLength, responseLength int64
366 log.Println(GetRemoteAddress(req), req.Method, req.URL.Path, status, expectLength, responseLength, proxiedURI, err)
367 if status != http.StatusOK {
368 http.Error(resp, err.Error(), status)
372 kc := h.makeKeepClient(req)
376 if pass, tok = CheckAuthorizationHeader(kc, h.ApiTokenCache, req); !pass {
377 status, err = http.StatusForbidden, BadAuthorizationHeader
381 // Copy ArvadosClient struct and use the client's API token
382 arvclient := *kc.Arvados
383 arvclient.ApiToken = tok
384 kc.Arvados = &arvclient
386 var reader io.ReadCloser
388 locator = removeHint.ReplaceAllString(locator, "$1")
392 expectLength, proxiedURI, err = kc.Ask(locator)
394 reader, expectLength, proxiedURI, err = kc.Get(locator)
399 status, err = http.StatusNotImplemented, MethodNotSupported
403 if expectLength == -1 {
404 log.Println("Warning:", GetRemoteAddress(req), req.Method, proxiedURI, "Content-Length not provided")
407 switch respErr := err.(type) {
409 status = http.StatusOK
410 resp.Header().Set("Content-Length", fmt.Sprint(expectLength))
415 responseLength, err = io.Copy(resp, reader)
416 if err == nil && expectLength > -1 && responseLength != expectLength {
417 err = ContentLengthMismatch
420 case keepclient.Error:
421 if respErr == keepclient.BlockNotFound {
422 status = http.StatusNotFound
423 } else if respErr.Temporary() {
424 status = http.StatusBadGateway
429 status = http.StatusInternalServerError
433 var LengthRequiredError = errors.New(http.StatusText(http.StatusLengthRequired))
434 var LengthMismatchError = errors.New("Locator size hint does not match Content-Length header")
436 func (h *proxyHandler) Put(resp http.ResponseWriter, req *http.Request) {
437 if err := h.checkLoop(resp, req); err != nil {
441 resp.Header().Set("Via", "HTTP/1.1 "+viaAlias)
443 kc := h.makeKeepClient(req)
446 var expectLength int64
447 var status = http.StatusInternalServerError
448 var wroteReplicas int
449 var locatorOut string = "-"
452 log.Println(GetRemoteAddress(req), req.Method, req.URL.Path, status, expectLength, kc.Want_replicas, wroteReplicas, locatorOut, err)
453 if status != http.StatusOK {
454 http.Error(resp, err.Error(), status)
458 locatorIn := mux.Vars(req)["locator"]
460 // Check if the client specified storage classes
461 if req.Header.Get("X-Keep-Storage-Classes") != "" {
463 for _, sc := range strings.Split(req.Header.Get("X-Keep-Storage-Classes"), ",") {
464 scl = append(scl, strings.Trim(sc, " "))
466 kc.StorageClasses = scl
469 _, err = fmt.Sscanf(req.Header.Get("Content-Length"), "%d", &expectLength)
470 if err != nil || expectLength < 0 {
471 err = LengthRequiredError
472 status = http.StatusLengthRequired
477 var loc *keepclient.Locator
478 if loc, err = keepclient.MakeLocator(locatorIn); err != nil {
479 status = http.StatusBadRequest
481 } else if loc.Size > 0 && int64(loc.Size) != expectLength {
482 err = LengthMismatchError
483 status = http.StatusBadRequest
490 if pass, tok = CheckAuthorizationHeader(kc, h.ApiTokenCache, req); !pass {
491 err = BadAuthorizationHeader
492 status = http.StatusForbidden
496 // Copy ArvadosClient struct and use the client's API token
497 arvclient := *kc.Arvados
498 arvclient.ApiToken = tok
499 kc.Arvados = &arvclient
501 // Check if the client specified the number of replicas
502 if req.Header.Get("X-Keep-Desired-Replicas") != "" {
504 _, err := fmt.Sscanf(req.Header.Get(keepclient.X_Keep_Desired_Replicas), "%d", &r)
510 // Now try to put the block through
512 bytes, err2 := ioutil.ReadAll(req.Body)
514 err = fmt.Errorf("Error reading request body: %s", err2)
515 status = http.StatusInternalServerError
518 locatorOut, wroteReplicas, err = kc.PutB(bytes)
520 locatorOut, wroteReplicas, err = kc.PutHR(locatorIn, req.Body, expectLength)
523 // Tell the client how many successful PUTs we accomplished
524 resp.Header().Set(keepclient.X_Keep_Replicas_Stored, fmt.Sprintf("%d", wroteReplicas))
528 status = http.StatusOK
529 _, err = io.WriteString(resp, locatorOut)
531 case keepclient.OversizeBlockError:
533 status = http.StatusRequestEntityTooLarge
535 case keepclient.InsufficientReplicasError:
536 if wroteReplicas > 0 {
537 // At least one write is considered success. The
538 // client can decide if getting less than the number of
539 // replications it asked for is a fatal error.
540 status = http.StatusOK
541 _, err = io.WriteString(resp, locatorOut)
543 status = http.StatusServiceUnavailable
547 status = http.StatusBadGateway
551 // ServeHTTP implementation for IndexHandler
552 // Supports only GET requests for /index/{prefix:[0-9a-f]{0,32}}
553 // For each keep server found in LocalRoots:
554 // Invokes GetIndex using keepclient
555 // Expects "complete" response (terminating with blank new line)
556 // Aborts on any errors
557 // Concatenates responses from all those keep servers and returns
558 func (h *proxyHandler) Index(resp http.ResponseWriter, req *http.Request) {
561 prefix := mux.Vars(req)["prefix"]
566 if status != http.StatusOK {
567 http.Error(resp, err.Error(), status)
571 kc := h.makeKeepClient(req)
572 ok, token := CheckAuthorizationHeader(kc, h.ApiTokenCache, req)
574 status, err = http.StatusForbidden, BadAuthorizationHeader
578 // Copy ArvadosClient struct and use the client's API token
579 arvclient := *kc.Arvados
580 arvclient.ApiToken = token
581 kc.Arvados = &arvclient
583 // Only GET method is supported
584 if req.Method != "GET" {
585 status, err = http.StatusNotImplemented, MethodNotSupported
589 // Get index from all LocalRoots and write to resp
591 for uuid := range kc.LocalRoots() {
592 reader, err = kc.GetIndex(uuid, prefix)
594 status = http.StatusBadGateway
598 _, err = io.Copy(resp, reader)
600 status = http.StatusBadGateway
605 // Got index from all the keep servers and wrote to resp
606 status = http.StatusOK
607 resp.Write([]byte("\n"))
610 func (h *proxyHandler) makeKeepClient(req *http.Request) *keepclient.KeepClient {
612 kc.RequestID = req.Header.Get("X-Request-Id")
613 kc.HTTPClient = &proxyClient{
614 client: &http.Client{
616 Transport: h.transport,