20 "git.curoverse.com/arvados.git/sdk/go/arvados"
21 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
22 "git.curoverse.com/arvados.git/sdk/go/config"
23 "git.curoverse.com/arvados.git/sdk/go/keepclient"
24 "github.com/coreos/go-systemd/daemon"
25 "github.com/ghodss/yaml"
26 "github.com/gorilla/mux"
35 Timeout arvados.Duration
40 func DefaultConfig() *Config {
43 Timeout: arvados.Duration(15 * time.Second),
53 cfg := DefaultConfig()
55 flagset := flag.NewFlagSet("keepproxy", flag.ExitOnError)
58 const deprecated = " (DEPRECATED -- use config file instead)"
59 flagset.StringVar(&cfg.Listen, "listen", cfg.Listen, "Local port to listen on."+deprecated)
60 flagset.BoolVar(&cfg.DisableGet, "no-get", cfg.DisableGet, "Disable GET operations."+deprecated)
61 flagset.BoolVar(&cfg.DisablePut, "no-put", cfg.DisablePut, "Disable PUT operations."+deprecated)
62 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)
63 flagset.StringVar(&cfg.PIDFile, "pid", cfg.PIDFile, "Path to write pid file."+deprecated)
64 timeoutSeconds := flagset.Int("timeout", int(time.Duration(cfg.Timeout)/time.Second), "Timeout (in seconds) on requests to internal Keep services."+deprecated)
67 const defaultCfgPath = "/etc/arvados/keepproxy/keepproxy.yml"
68 flagset.StringVar(&cfgPath, "config", defaultCfgPath, "Configuration file `path`")
69 dumpConfig := flagset.Bool("dump-config", false, "write current configuration to stdout and exit")
70 flagset.Parse(os.Args[1:])
72 err := config.LoadFile(cfg, cfgPath)
74 h := os.Getenv("ARVADOS_API_HOST")
75 t := os.Getenv("ARVADOS_API_TOKEN")
76 if h == "" || t == "" || !os.IsNotExist(err) || cfgPath != defaultCfgPath {
79 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.")
80 cfg.Client.APIHost = h
81 cfg.Client.AuthToken = t
82 if regexp.MustCompile("^(?i:1|yes|true)$").MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE")) {
83 cfg.Client.Insecure = true
85 if y, err := yaml.Marshal(cfg); err == nil && !*dumpConfig {
86 log.Print("Current configuration:\n", string(y))
88 cfg.Timeout = arvados.Duration(time.Duration(*timeoutSeconds) * time.Second)
92 log.Fatal(config.DumpAndExit(cfg))
95 arv, err := arvadosclient.New(&cfg.Client)
97 log.Fatalf("Error setting up arvados client %s", err.Error())
101 keepclient.DebugPrintf = log.Printf
103 kc, err := keepclient.MakeKeepClient(arv)
105 log.Fatalf("Error setting up keep client %s", err.Error())
108 if cfg.PIDFile != "" {
109 f, err := os.Create(cfg.PIDFile)
114 err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
116 log.Fatalf("flock(%s): %s", cfg.PIDFile, err)
118 defer os.Remove(cfg.PIDFile)
121 log.Fatalf("truncate(%s): %s", cfg.PIDFile, err)
123 _, err = fmt.Fprint(f, os.Getpid())
125 log.Fatalf("write(%s): %s", cfg.PIDFile, err)
129 log.Fatal("sync(%s): %s", cfg.PIDFile, err)
133 if cfg.DefaultReplicas > 0 {
134 kc.Want_replicas = cfg.DefaultReplicas
136 kc.Client.(*http.Client).Timeout = time.Duration(cfg.Timeout)
137 go kc.RefreshServices(5*time.Minute, 3*time.Second)
139 listener, err = net.Listen("tcp", cfg.Listen)
141 log.Fatalf("listen(%s): %s", cfg.Listen, err)
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(!cfg.DisableGet, !cfg.DisablePut, kc)
161 http.Serve(listener, router)
163 log.Println("shutting down")
166 type ApiTokenCache struct {
167 tokens map[string]int64
172 // Cache the token and set an expire time. If we already have an expire time
173 // on the token, it is not updated.
174 func (this *ApiTokenCache) RememberToken(token string) {
176 defer this.lock.Unlock()
178 now := time.Now().Unix()
179 if this.tokens[token] == 0 {
180 this.tokens[token] = now + this.expireTime
184 // Check if the cached token is known and still believed to be valid.
185 func (this *ApiTokenCache) RecallToken(token string) bool {
187 defer this.lock.Unlock()
189 now := time.Now().Unix()
190 if this.tokens[token] == 0 {
193 } else if now < this.tokens[token] {
194 // Token is known and still valid
198 this.tokens[token] = 0
203 func GetRemoteAddress(req *http.Request) string {
204 if xff := req.Header.Get("X-Forwarded-For"); xff != "" {
205 return xff + "," + req.RemoteAddr
207 return req.RemoteAddr
210 func CheckAuthorizationHeader(kc *keepclient.KeepClient, cache *ApiTokenCache, req *http.Request) (pass bool, tok string) {
212 if auth = req.Header.Get("Authorization"); auth == "" {
216 _, err := fmt.Sscanf(auth, "OAuth2 %s", &tok)
222 if cache.RecallToken(tok) {
223 // Valid in the cache, short circuit
229 if err := arv.Call("HEAD", "users", "", "current", nil, nil); err != nil {
230 log.Printf("%s: CheckAuthorizationHeader error: %v", GetRemoteAddress(req), err)
234 // Success! Update cache
235 cache.RememberToken(tok)
240 type proxyHandler struct {
242 *keepclient.KeepClient
246 // MakeRESTRouter returns an http.Handler that passes GET and PUT
247 // requests to the appropriate handlers.
248 func MakeRESTRouter(enable_get bool, enable_put bool, kc *keepclient.KeepClient) http.Handler {
249 rest := mux.NewRouter()
253 ApiTokenCache: &ApiTokenCache{
254 tokens: make(map[string]int64),
260 rest.HandleFunc(`/{locator:[0-9a-f]{32}\+.*}`, h.Get).Methods("GET", "HEAD")
261 rest.HandleFunc(`/{locator:[0-9a-f]{32}}`, h.Get).Methods("GET", "HEAD")
264 rest.HandleFunc(`/index`, h.Index).Methods("GET")
266 // List blocks whose hash has the given prefix
267 rest.HandleFunc(`/index/{prefix:[0-9a-f]{0,32}}`, h.Index).Methods("GET")
271 rest.HandleFunc(`/{locator:[0-9a-f]{32}\+.*}`, h.Put).Methods("PUT")
272 rest.HandleFunc(`/{locator:[0-9a-f]{32}}`, h.Put).Methods("PUT")
273 rest.HandleFunc(`/`, h.Put).Methods("POST")
274 rest.HandleFunc(`/{any}`, h.Options).Methods("OPTIONS")
275 rest.HandleFunc(`/`, h.Options).Methods("OPTIONS")
278 rest.NotFoundHandler = InvalidPathHandler{}
282 var errLoopDetected = errors.New("loop detected")
284 func (*proxyHandler) checkLoop(resp http.ResponseWriter, req *http.Request) error {
285 if via := req.Header.Get("Via"); strings.Index(via, " "+viaAlias) >= 0 {
286 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)
287 http.Error(resp, errLoopDetected.Error(), http.StatusInternalServerError)
288 return errLoopDetected
293 func SetCorsHeaders(resp http.ResponseWriter) {
294 resp.Header().Set("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, OPTIONS")
295 resp.Header().Set("Access-Control-Allow-Origin", "*")
296 resp.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Length, Content-Type, X-Keep-Desired-Replicas")
297 resp.Header().Set("Access-Control-Max-Age", "86486400")
300 type InvalidPathHandler struct{}
302 func (InvalidPathHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
303 log.Printf("%s: %s %s unroutable", GetRemoteAddress(req), req.Method, req.URL.Path)
304 http.Error(resp, "Bad request", http.StatusBadRequest)
307 func (h *proxyHandler) Options(resp http.ResponseWriter, req *http.Request) {
308 log.Printf("%s: %s %s", GetRemoteAddress(req), req.Method, req.URL.Path)
312 var BadAuthorizationHeader = errors.New("Missing or invalid Authorization header")
313 var ContentLengthMismatch = errors.New("Actual length != expected content length")
314 var MethodNotSupported = errors.New("Method not supported")
316 var removeHint, _ = regexp.Compile("\\+K@[a-z0-9]{5}(\\+|$)")
318 func (h *proxyHandler) Get(resp http.ResponseWriter, req *http.Request) {
319 if err := h.checkLoop(resp, req); err != nil {
323 resp.Header().Set("Via", req.Proto+" "+viaAlias)
325 locator := mux.Vars(req)["locator"]
328 var expectLength, responseLength int64
332 log.Println(GetRemoteAddress(req), req.Method, req.URL.Path, status, expectLength, responseLength, proxiedURI, err)
333 if status != http.StatusOK {
334 http.Error(resp, err.Error(), status)
339 kc.Client = &proxyClient{client: kc.Client, proto: req.Proto}
343 if pass, tok = CheckAuthorizationHeader(&kc, h.ApiTokenCache, req); !pass {
344 status, err = http.StatusForbidden, BadAuthorizationHeader
348 // Copy ArvadosClient struct and use the client's API token
349 arvclient := *kc.Arvados
350 arvclient.ApiToken = tok
351 kc.Arvados = &arvclient
353 var reader io.ReadCloser
355 locator = removeHint.ReplaceAllString(locator, "$1")
359 expectLength, proxiedURI, err = kc.Ask(locator)
361 reader, expectLength, proxiedURI, err = kc.Get(locator)
366 status, err = http.StatusNotImplemented, MethodNotSupported
370 if expectLength == -1 {
371 log.Println("Warning:", GetRemoteAddress(req), req.Method, proxiedURI, "Content-Length not provided")
374 switch respErr := err.(type) {
376 status = http.StatusOK
377 resp.Header().Set("Content-Length", fmt.Sprint(expectLength))
382 responseLength, err = io.Copy(resp, reader)
383 if err == nil && expectLength > -1 && responseLength != expectLength {
384 err = ContentLengthMismatch
387 case keepclient.Error:
388 if respErr == keepclient.BlockNotFound {
389 status = http.StatusNotFound
390 } else if respErr.Temporary() {
391 status = http.StatusBadGateway
396 status = http.StatusInternalServerError
400 var LengthRequiredError = errors.New(http.StatusText(http.StatusLengthRequired))
401 var LengthMismatchError = errors.New("Locator size hint does not match Content-Length header")
403 func (h *proxyHandler) Put(resp http.ResponseWriter, req *http.Request) {
404 if err := h.checkLoop(resp, req); err != nil {
408 resp.Header().Set("Via", "HTTP/1.1 "+viaAlias)
411 kc.Client = &proxyClient{client: kc.Client, proto: req.Proto}
414 var expectLength int64
415 var status = http.StatusInternalServerError
416 var wroteReplicas int
417 var locatorOut string = "-"
420 log.Println(GetRemoteAddress(req), req.Method, req.URL.Path, status, expectLength, kc.Want_replicas, wroteReplicas, locatorOut, err)
421 if status != http.StatusOK {
422 http.Error(resp, err.Error(), status)
426 locatorIn := mux.Vars(req)["locator"]
428 _, err = fmt.Sscanf(req.Header.Get("Content-Length"), "%d", &expectLength)
429 if err != nil || expectLength < 0 {
430 err = LengthRequiredError
431 status = http.StatusLengthRequired
436 var loc *keepclient.Locator
437 if loc, err = keepclient.MakeLocator(locatorIn); err != nil {
438 status = http.StatusBadRequest
440 } else if loc.Size > 0 && int64(loc.Size) != expectLength {
441 err = LengthMismatchError
442 status = http.StatusBadRequest
449 if pass, tok = CheckAuthorizationHeader(&kc, h.ApiTokenCache, req); !pass {
450 err = BadAuthorizationHeader
451 status = http.StatusForbidden
455 // Copy ArvadosClient struct and use the client's API token
456 arvclient := *kc.Arvados
457 arvclient.ApiToken = tok
458 kc.Arvados = &arvclient
460 // Check if the client specified the number of replicas
461 if req.Header.Get("X-Keep-Desired-Replicas") != "" {
463 _, err := fmt.Sscanf(req.Header.Get(keepclient.X_Keep_Desired_Replicas), "%d", &r)
469 // Now try to put the block through
471 if bytes, err := ioutil.ReadAll(req.Body); err != nil {
472 err = errors.New(fmt.Sprintf("Error reading request body: %s", err))
473 status = http.StatusInternalServerError
476 locatorOut, wroteReplicas, err = kc.PutB(bytes)
479 locatorOut, wroteReplicas, err = kc.PutHR(locatorIn, req.Body, expectLength)
482 // Tell the client how many successful PUTs we accomplished
483 resp.Header().Set(keepclient.X_Keep_Replicas_Stored, fmt.Sprintf("%d", wroteReplicas))
487 status = http.StatusOK
488 _, err = io.WriteString(resp, locatorOut)
490 case keepclient.OversizeBlockError:
492 status = http.StatusRequestEntityTooLarge
494 case keepclient.InsufficientReplicasError:
495 if wroteReplicas > 0 {
496 // At least one write is considered success. The
497 // client can decide if getting less than the number of
498 // replications it asked for is a fatal error.
499 status = http.StatusOK
500 _, err = io.WriteString(resp, locatorOut)
502 status = http.StatusServiceUnavailable
506 status = http.StatusBadGateway
510 // ServeHTTP implementation for IndexHandler
511 // Supports only GET requests for /index/{prefix:[0-9a-f]{0,32}}
512 // For each keep server found in LocalRoots:
513 // Invokes GetIndex using keepclient
514 // Expects "complete" response (terminating with blank new line)
515 // Aborts on any errors
516 // Concatenates responses from all those keep servers and returns
517 func (h *proxyHandler) Index(resp http.ResponseWriter, req *http.Request) {
520 prefix := mux.Vars(req)["prefix"]
525 if status != http.StatusOK {
526 http.Error(resp, err.Error(), status)
532 ok, token := CheckAuthorizationHeader(&kc, h.ApiTokenCache, req)
534 status, err = http.StatusForbidden, BadAuthorizationHeader
538 // Copy ArvadosClient struct and use the client's API token
539 arvclient := *kc.Arvados
540 arvclient.ApiToken = token
541 kc.Arvados = &arvclient
543 // Only GET method is supported
544 if req.Method != "GET" {
545 status, err = http.StatusNotImplemented, MethodNotSupported
549 // Get index from all LocalRoots and write to resp
551 for uuid := range kc.LocalRoots() {
552 reader, err = kc.GetIndex(uuid, prefix)
554 status = http.StatusBadGateway
558 _, err = io.Copy(resp, reader)
560 status = http.StatusBadGateway
565 // Got index from all the keep servers and wrote to resp
566 status = http.StatusOK
567 resp.Write([]byte("\n"))