19 "git.curoverse.com/arvados.git/sdk/go/arvados"
20 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
21 "git.curoverse.com/arvados.git/sdk/go/config"
22 "git.curoverse.com/arvados.git/sdk/go/keepclient"
23 "github.com/coreos/go-systemd/daemon"
24 "github.com/ghodss/yaml"
25 "github.com/gorilla/mux"
34 Timeout arvados.Duration
39 func DefaultConfig() *Config {
42 Timeout: arvados.Duration(15 * time.Second),
46 var listener net.Listener
49 cfg := DefaultConfig()
51 flagset := flag.NewFlagSet("keepproxy", flag.ExitOnError)
54 const deprecated = " (DEPRECATED -- use config file instead)"
55 flagset.StringVar(&cfg.Listen, "listen", cfg.Listen, "Local port to listen on."+deprecated)
56 flagset.BoolVar(&cfg.DisableGet, "no-get", cfg.DisableGet, "Disable GET operations."+deprecated)
57 flagset.BoolVar(&cfg.DisablePut, "no-put", cfg.DisablePut, "Disable PUT operations."+deprecated)
58 flagset.IntVar(&cfg.DefaultReplicas, "default-replicas", cfg.DefaultReplicas, "Default number of replicas to write if not specified by the client. If 0, use site default."+deprecated)
59 flagset.StringVar(&cfg.PIDFile, "pid", cfg.PIDFile, "Path to write pid file."+deprecated)
60 timeoutSeconds := flagset.Int("timeout", int(time.Duration(cfg.Timeout)/time.Second), "Timeout (in seconds) on requests to internal Keep services."+deprecated)
63 const defaultCfgPath = "/etc/arvados/keepproxy/keepproxy.yml"
64 flagset.StringVar(&cfgPath, "config", defaultCfgPath, "Configuration file `path`")
65 dumpConfig := flagset.Bool("dump-config", false, "write current configuration to stdout and exit")
66 flagset.Parse(os.Args[1:])
68 err := config.LoadFile(cfg, cfgPath)
70 h := os.Getenv("ARVADOS_API_HOST")
71 t := os.Getenv("ARVADOS_API_TOKEN")
72 if h == "" || t == "" || !os.IsNotExist(err) || cfgPath != defaultCfgPath {
75 log.Print("DEPRECATED: No config file found, but ARVADOS_API_HOST and ARVADOS_API_TOKEN environment variables are set. Please use a config file instead.")
76 cfg.Client.APIHost = h
77 cfg.Client.AuthToken = t
78 if regexp.MustCompile("^(?i:1|yes|true)$").MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE")) {
79 cfg.Client.Insecure = true
81 if y, err := yaml.Marshal(cfg); err == nil && !*dumpConfig {
82 log.Print("Current configuration:\n", string(y))
84 cfg.Timeout = arvados.Duration(time.Duration(*timeoutSeconds) * time.Second)
88 log.Fatal(config.DumpAndExit(cfg))
91 arv, err := arvadosclient.New(&cfg.Client)
93 log.Fatalf("Error setting up arvados client %s", err.Error())
97 keepclient.DebugPrintf = log.Printf
99 kc, err := keepclient.MakeKeepClient(arv)
101 log.Fatalf("Error setting up keep client %s", err.Error())
104 if cfg.PIDFile != "" {
105 f, err := os.Create(cfg.PIDFile)
110 err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
112 log.Fatalf("flock(%s): %s", cfg.PIDFile, err)
114 defer os.Remove(cfg.PIDFile)
117 log.Fatalf("truncate(%s): %s", cfg.PIDFile, err)
119 _, err = fmt.Fprint(f, os.Getpid())
121 log.Fatalf("write(%s): %s", cfg.PIDFile, err)
125 log.Fatal("sync(%s): %s", cfg.PIDFile, err)
129 if cfg.DefaultReplicas > 0 {
130 kc.Want_replicas = cfg.DefaultReplicas
132 kc.Client.Timeout = time.Duration(cfg.Timeout)
133 go kc.RefreshServices(5*time.Minute, 3*time.Second)
135 listener, err = net.Listen("tcp", cfg.Listen)
137 log.Fatalf("listen(%s): %s", cfg.Listen, err)
139 if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
140 log.Printf("Error notifying init daemon: %v", err)
142 log.Println("Listening at", listener.Addr())
144 // Shut down the server gracefully (by closing the listener)
145 // if SIGTERM is received.
146 term := make(chan os.Signal, 1)
147 go func(sig <-chan os.Signal) {
149 log.Println("caught signal:", s)
152 signal.Notify(term, syscall.SIGTERM)
153 signal.Notify(term, syscall.SIGINT)
155 // Start serving requests.
156 http.Serve(listener, MakeRESTRouter(!cfg.DisableGet, !cfg.DisablePut, kc))
158 log.Println("shutting down")
161 type ApiTokenCache struct {
162 tokens map[string]int64
167 // Cache the token and set an expire time. If we already have an expire time
168 // on the token, it is not updated.
169 func (this *ApiTokenCache) RememberToken(token string) {
171 defer this.lock.Unlock()
173 now := time.Now().Unix()
174 if this.tokens[token] == 0 {
175 this.tokens[token] = now + this.expireTime
179 // Check if the cached token is known and still believed to be valid.
180 func (this *ApiTokenCache) RecallToken(token string) bool {
182 defer this.lock.Unlock()
184 now := time.Now().Unix()
185 if this.tokens[token] == 0 {
188 } else if now < this.tokens[token] {
189 // Token is known and still valid
193 this.tokens[token] = 0
198 func GetRemoteAddress(req *http.Request) string {
199 if xff := req.Header.Get("X-Forwarded-For"); xff != "" {
200 return xff + "," + req.RemoteAddr
202 return req.RemoteAddr
205 func CheckAuthorizationHeader(kc *keepclient.KeepClient, cache *ApiTokenCache, req *http.Request) (pass bool, tok string) {
207 if auth = req.Header.Get("Authorization"); auth == "" {
211 _, err := fmt.Sscanf(auth, "OAuth2 %s", &tok)
217 if cache.RecallToken(tok) {
218 // Valid in the cache, short circuit
224 if err := arv.Call("HEAD", "users", "", "current", nil, nil); err != nil {
225 log.Printf("%s: CheckAuthorizationHeader error: %v", GetRemoteAddress(req), err)
229 // Success! Update cache
230 cache.RememberToken(tok)
235 type GetBlockHandler struct {
236 *keepclient.KeepClient
240 type PutBlockHandler struct {
241 *keepclient.KeepClient
245 type IndexHandler struct {
246 *keepclient.KeepClient
250 type InvalidPathHandler struct{}
252 type OptionsHandler struct{}
255 // Returns a mux.Router that passes GET and PUT requests to the
256 // appropriate handlers.
261 kc *keepclient.KeepClient) *mux.Router {
263 t := &ApiTokenCache{tokens: make(map[string]int64), expireTime: 300}
265 rest := mux.NewRouter()
268 rest.Handle(`/{locator:[0-9a-f]{32}\+.*}`,
269 GetBlockHandler{kc, t}).Methods("GET", "HEAD")
270 rest.Handle(`/{locator:[0-9a-f]{32}}`, GetBlockHandler{kc, t}).Methods("GET", "HEAD")
273 rest.Handle(`/index`, IndexHandler{kc, t}).Methods("GET")
275 // List blocks whose hash has the given prefix
276 rest.Handle(`/index/{prefix:[0-9a-f]{0,32}}`, IndexHandler{kc, t}).Methods("GET")
280 rest.Handle(`/{locator:[0-9a-f]{32}\+.*}`, PutBlockHandler{kc, t}).Methods("PUT")
281 rest.Handle(`/{locator:[0-9a-f]{32}}`, PutBlockHandler{kc, t}).Methods("PUT")
282 rest.Handle(`/`, PutBlockHandler{kc, t}).Methods("POST")
283 rest.Handle(`/{any}`, OptionsHandler{}).Methods("OPTIONS")
284 rest.Handle(`/`, OptionsHandler{}).Methods("OPTIONS")
287 rest.NotFoundHandler = InvalidPathHandler{}
292 func SetCorsHeaders(resp http.ResponseWriter) {
293 resp.Header().Set("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, OPTIONS")
294 resp.Header().Set("Access-Control-Allow-Origin", "*")
295 resp.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Length, Content-Type, X-Keep-Desired-Replicas")
296 resp.Header().Set("Access-Control-Max-Age", "86486400")
299 func (this InvalidPathHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
300 log.Printf("%s: %s %s unroutable", GetRemoteAddress(req), req.Method, req.URL.Path)
301 http.Error(resp, "Bad request", http.StatusBadRequest)
304 func (this OptionsHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
305 log.Printf("%s: %s %s", GetRemoteAddress(req), req.Method, req.URL.Path)
309 var BadAuthorizationHeader = errors.New("Missing or invalid Authorization header")
310 var ContentLengthMismatch = errors.New("Actual length != expected content length")
311 var MethodNotSupported = errors.New("Method not supported")
313 var removeHint, _ = regexp.Compile("\\+K@[a-z0-9]{5}(\\+|$)")
315 func (this GetBlockHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
318 locator := mux.Vars(req)["locator"]
321 var expectLength, responseLength int64
325 log.Println(GetRemoteAddress(req), req.Method, req.URL.Path, status, expectLength, responseLength, proxiedURI, err)
326 if status != http.StatusOK {
327 http.Error(resp, err.Error(), status)
331 kc := *this.KeepClient
335 if pass, tok = CheckAuthorizationHeader(&kc, this.ApiTokenCache, req); !pass {
336 status, err = http.StatusForbidden, BadAuthorizationHeader
340 // Copy ArvadosClient struct and use the client's API token
341 arvclient := *kc.Arvados
342 arvclient.ApiToken = tok
343 kc.Arvados = &arvclient
345 var reader io.ReadCloser
347 locator = removeHint.ReplaceAllString(locator, "$1")
351 expectLength, proxiedURI, err = kc.Ask(locator)
353 reader, expectLength, proxiedURI, err = kc.Get(locator)
358 status, err = http.StatusNotImplemented, MethodNotSupported
362 if expectLength == -1 {
363 log.Println("Warning:", GetRemoteAddress(req), req.Method, proxiedURI, "Content-Length not provided")
366 switch respErr := err.(type) {
368 status = http.StatusOK
369 resp.Header().Set("Content-Length", fmt.Sprint(expectLength))
374 responseLength, err = io.Copy(resp, reader)
375 if err == nil && expectLength > -1 && responseLength != expectLength {
376 err = ContentLengthMismatch
379 case keepclient.Error:
380 if respErr == keepclient.BlockNotFound {
381 status = http.StatusNotFound
382 } else if respErr.Temporary() {
383 status = http.StatusBadGateway
388 status = http.StatusInternalServerError
392 var LengthRequiredError = errors.New(http.StatusText(http.StatusLengthRequired))
393 var LengthMismatchError = errors.New("Locator size hint does not match Content-Length header")
395 func (this PutBlockHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
398 kc := *this.KeepClient
400 var expectLength int64
401 var status = http.StatusInternalServerError
402 var wroteReplicas int
403 var locatorOut string = "-"
406 log.Println(GetRemoteAddress(req), req.Method, req.URL.Path, status, expectLength, kc.Want_replicas, wroteReplicas, locatorOut, err)
407 if status != http.StatusOK {
408 http.Error(resp, err.Error(), status)
412 locatorIn := mux.Vars(req)["locator"]
414 _, err = fmt.Sscanf(req.Header.Get("Content-Length"), "%d", &expectLength)
415 if err != nil || expectLength < 0 {
416 err = LengthRequiredError
417 status = http.StatusLengthRequired
422 var loc *keepclient.Locator
423 if loc, err = keepclient.MakeLocator(locatorIn); err != nil {
424 status = http.StatusBadRequest
426 } else if loc.Size > 0 && int64(loc.Size) != expectLength {
427 err = LengthMismatchError
428 status = http.StatusBadRequest
435 if pass, tok = CheckAuthorizationHeader(&kc, this.ApiTokenCache, req); !pass {
436 err = BadAuthorizationHeader
437 status = http.StatusForbidden
441 // Copy ArvadosClient struct and use the client's API token
442 arvclient := *kc.Arvados
443 arvclient.ApiToken = tok
444 kc.Arvados = &arvclient
446 // Check if the client specified the number of replicas
447 if req.Header.Get("X-Keep-Desired-Replicas") != "" {
449 _, err := fmt.Sscanf(req.Header.Get(keepclient.X_Keep_Desired_Replicas), "%d", &r)
455 // Now try to put the block through
457 if bytes, err := ioutil.ReadAll(req.Body); err != nil {
458 err = errors.New(fmt.Sprintf("Error reading request body: %s", err))
459 status = http.StatusInternalServerError
462 locatorOut, wroteReplicas, err = kc.PutB(bytes)
465 locatorOut, wroteReplicas, err = kc.PutHR(locatorIn, req.Body, expectLength)
468 // Tell the client how many successful PUTs we accomplished
469 resp.Header().Set(keepclient.X_Keep_Replicas_Stored, fmt.Sprintf("%d", wroteReplicas))
473 status = http.StatusOK
474 _, err = io.WriteString(resp, locatorOut)
476 case keepclient.OversizeBlockError:
478 status = http.StatusRequestEntityTooLarge
480 case keepclient.InsufficientReplicasError:
481 if wroteReplicas > 0 {
482 // At least one write is considered success. The
483 // client can decide if getting less than the number of
484 // replications it asked for is a fatal error.
485 status = http.StatusOK
486 _, err = io.WriteString(resp, locatorOut)
488 status = http.StatusServiceUnavailable
492 status = http.StatusBadGateway
496 // ServeHTTP implementation for IndexHandler
497 // Supports only GET requests for /index/{prefix:[0-9a-f]{0,32}}
498 // For each keep server found in LocalRoots:
499 // Invokes GetIndex using keepclient
500 // Expects "complete" response (terminating with blank new line)
501 // Aborts on any errors
502 // Concatenates responses from all those keep servers and returns
503 func (handler IndexHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
506 prefix := mux.Vars(req)["prefix"]
511 if status != http.StatusOK {
512 http.Error(resp, err.Error(), status)
516 kc := *handler.KeepClient
518 ok, token := CheckAuthorizationHeader(&kc, handler.ApiTokenCache, req)
520 status, err = http.StatusForbidden, BadAuthorizationHeader
524 // Copy ArvadosClient struct and use the client's API token
525 arvclient := *kc.Arvados
526 arvclient.ApiToken = token
527 kc.Arvados = &arvclient
529 // Only GET method is supported
530 if req.Method != "GET" {
531 status, err = http.StatusNotImplemented, MethodNotSupported
535 // Get index from all LocalRoots and write to resp
537 for uuid := range kc.LocalRoots() {
538 reader, err = kc.GetIndex(uuid, prefix)
540 status = http.StatusBadGateway
544 _, err = io.Copy(resp, reader)
546 status = http.StatusBadGateway
551 // Got index from all the keep servers and wrote to resp
552 status = http.StatusOK
553 resp.Write([]byte("\n"))