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 go kc.RefreshServices(5*time.Minute, 3*time.Second)
138 listener, err = net.Listen("tcp", cfg.Listen)
140 log.Fatalf("listen(%s): %s", cfg.Listen, err)
142 if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
143 log.Printf("Error notifying init daemon: %v", err)
145 log.Println("Listening at", listener.Addr())
147 // Shut down the server gracefully (by closing the listener)
148 // if SIGTERM is received.
149 term := make(chan os.Signal, 1)
150 go func(sig <-chan os.Signal) {
152 log.Println("caught signal:", s)
155 signal.Notify(term, syscall.SIGTERM)
156 signal.Notify(term, syscall.SIGINT)
158 // Start serving requests.
159 router = MakeRESTRouter(!cfg.DisableGet, !cfg.DisablePut, kc, time.Duration(cfg.Timeout))
160 http.Serve(listener, router)
162 log.Println("shutting down")
165 type ApiTokenCache struct {
166 tokens map[string]int64
171 // Cache the token and set an expire time. If we already have an expire time
172 // on the token, it is not updated.
173 func (this *ApiTokenCache) RememberToken(token string) {
175 defer this.lock.Unlock()
177 now := time.Now().Unix()
178 if this.tokens[token] == 0 {
179 this.tokens[token] = now + this.expireTime
183 // Check if the cached token is known and still believed to be valid.
184 func (this *ApiTokenCache) RecallToken(token string) bool {
186 defer this.lock.Unlock()
188 now := time.Now().Unix()
189 if this.tokens[token] == 0 {
192 } else if now < this.tokens[token] {
193 // Token is known and still valid
197 this.tokens[token] = 0
202 func GetRemoteAddress(req *http.Request) string {
203 if xff := req.Header.Get("X-Forwarded-For"); xff != "" {
204 return xff + "," + req.RemoteAddr
206 return req.RemoteAddr
209 func CheckAuthorizationHeader(kc *keepclient.KeepClient, cache *ApiTokenCache, req *http.Request) (pass bool, tok string) {
211 if auth = req.Header.Get("Authorization"); auth == "" {
215 _, err := fmt.Sscanf(auth, "OAuth2 %s", &tok)
221 if cache.RecallToken(tok) {
222 // Valid in the cache, short circuit
228 if err := arv.Call("HEAD", "users", "", "current", nil, nil); err != nil {
229 log.Printf("%s: CheckAuthorizationHeader error: %v", GetRemoteAddress(req), err)
233 // Success! Update cache
234 cache.RememberToken(tok)
239 type proxyHandler struct {
241 *keepclient.KeepClient
243 timeout time.Duration
244 transport *http.Transport
247 // MakeRESTRouter returns an http.Handler that passes GET and PUT
248 // requests to the appropriate handlers.
249 func MakeRESTRouter(enable_get bool, enable_put bool, kc *keepclient.KeepClient, timeout time.Duration) http.Handler {
250 rest := mux.NewRouter()
255 transport: &http.Transport{
257 Timeout: 20 * time.Second,
258 KeepAlive: 10 * time.Second,
260 TLSClientConfig: arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure),
261 TLSHandshakeTimeout: 10 * time.Second,
263 ApiTokenCache: &ApiTokenCache{
264 tokens: make(map[string]int64),
269 go func(t *http.Transport) {
270 for range time.NewTicker(5 * time.Minute).C {
271 t.CloseIdleConnections()
276 rest.HandleFunc(`/{locator:[0-9a-f]{32}\+.*}`, h.Get).Methods("GET", "HEAD")
277 rest.HandleFunc(`/{locator:[0-9a-f]{32}}`, h.Get).Methods("GET", "HEAD")
280 rest.HandleFunc(`/index`, h.Index).Methods("GET")
282 // List blocks whose hash has the given prefix
283 rest.HandleFunc(`/index/{prefix:[0-9a-f]{0,32}}`, h.Index).Methods("GET")
287 rest.HandleFunc(`/{locator:[0-9a-f]{32}\+.*}`, h.Put).Methods("PUT")
288 rest.HandleFunc(`/{locator:[0-9a-f]{32}}`, h.Put).Methods("PUT")
289 rest.HandleFunc(`/`, h.Put).Methods("POST")
290 rest.HandleFunc(`/{any}`, h.Options).Methods("OPTIONS")
291 rest.HandleFunc(`/`, h.Options).Methods("OPTIONS")
294 rest.NotFoundHandler = InvalidPathHandler{}
298 var errLoopDetected = errors.New("loop detected")
300 func (*proxyHandler) checkLoop(resp http.ResponseWriter, req *http.Request) error {
301 if via := req.Header.Get("Via"); strings.Index(via, " "+viaAlias) >= 0 {
302 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)
303 http.Error(resp, errLoopDetected.Error(), http.StatusInternalServerError)
304 return errLoopDetected
309 func SetCorsHeaders(resp http.ResponseWriter) {
310 resp.Header().Set("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, OPTIONS")
311 resp.Header().Set("Access-Control-Allow-Origin", "*")
312 resp.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Length, Content-Type, X-Keep-Desired-Replicas")
313 resp.Header().Set("Access-Control-Max-Age", "86486400")
316 type InvalidPathHandler struct{}
318 func (InvalidPathHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
319 log.Printf("%s: %s %s unroutable", GetRemoteAddress(req), req.Method, req.URL.Path)
320 http.Error(resp, "Bad request", http.StatusBadRequest)
323 func (h *proxyHandler) Options(resp http.ResponseWriter, req *http.Request) {
324 log.Printf("%s: %s %s", GetRemoteAddress(req), req.Method, req.URL.Path)
328 var BadAuthorizationHeader = errors.New("Missing or invalid Authorization header")
329 var ContentLengthMismatch = errors.New("Actual length != expected content length")
330 var MethodNotSupported = errors.New("Method not supported")
332 var removeHint, _ = regexp.Compile("\\+K@[a-z0-9]{5}(\\+|$)")
334 func (h *proxyHandler) Get(resp http.ResponseWriter, req *http.Request) {
335 if err := h.checkLoop(resp, req); err != nil {
339 resp.Header().Set("Via", req.Proto+" "+viaAlias)
341 locator := mux.Vars(req)["locator"]
344 var expectLength, responseLength int64
348 log.Println(GetRemoteAddress(req), req.Method, req.URL.Path, status, expectLength, responseLength, proxiedURI, err)
349 if status != http.StatusOK {
350 http.Error(resp, err.Error(), status)
354 kc := h.makeKeepClient(req)
358 if pass, tok = CheckAuthorizationHeader(kc, h.ApiTokenCache, req); !pass {
359 status, err = http.StatusForbidden, BadAuthorizationHeader
363 // Copy ArvadosClient struct and use the client's API token
364 arvclient := *kc.Arvados
365 arvclient.ApiToken = tok
366 kc.Arvados = &arvclient
368 var reader io.ReadCloser
370 locator = removeHint.ReplaceAllString(locator, "$1")
374 expectLength, proxiedURI, err = kc.Ask(locator)
376 reader, expectLength, proxiedURI, err = kc.Get(locator)
381 status, err = http.StatusNotImplemented, MethodNotSupported
385 if expectLength == -1 {
386 log.Println("Warning:", GetRemoteAddress(req), req.Method, proxiedURI, "Content-Length not provided")
389 switch respErr := err.(type) {
391 status = http.StatusOK
392 resp.Header().Set("Content-Length", fmt.Sprint(expectLength))
397 responseLength, err = io.Copy(resp, reader)
398 if err == nil && expectLength > -1 && responseLength != expectLength {
399 err = ContentLengthMismatch
402 case keepclient.Error:
403 if respErr == keepclient.BlockNotFound {
404 status = http.StatusNotFound
405 } else if respErr.Temporary() {
406 status = http.StatusBadGateway
411 status = http.StatusInternalServerError
415 var LengthRequiredError = errors.New(http.StatusText(http.StatusLengthRequired))
416 var LengthMismatchError = errors.New("Locator size hint does not match Content-Length header")
418 func (h *proxyHandler) Put(resp http.ResponseWriter, req *http.Request) {
419 if err := h.checkLoop(resp, req); err != nil {
423 resp.Header().Set("Via", "HTTP/1.1 "+viaAlias)
425 kc := h.makeKeepClient(req)
428 var expectLength int64
429 var status = http.StatusInternalServerError
430 var wroteReplicas int
431 var locatorOut string = "-"
434 log.Println(GetRemoteAddress(req), req.Method, req.URL.Path, status, expectLength, kc.Want_replicas, wroteReplicas, locatorOut, err)
435 if status != http.StatusOK {
436 http.Error(resp, err.Error(), status)
440 locatorIn := mux.Vars(req)["locator"]
442 _, err = fmt.Sscanf(req.Header.Get("Content-Length"), "%d", &expectLength)
443 if err != nil || expectLength < 0 {
444 err = LengthRequiredError
445 status = http.StatusLengthRequired
450 var loc *keepclient.Locator
451 if loc, err = keepclient.MakeLocator(locatorIn); err != nil {
452 status = http.StatusBadRequest
454 } else if loc.Size > 0 && int64(loc.Size) != expectLength {
455 err = LengthMismatchError
456 status = http.StatusBadRequest
463 if pass, tok = CheckAuthorizationHeader(kc, h.ApiTokenCache, req); !pass {
464 err = BadAuthorizationHeader
465 status = http.StatusForbidden
469 // Copy ArvadosClient struct and use the client's API token
470 arvclient := *kc.Arvados
471 arvclient.ApiToken = tok
472 kc.Arvados = &arvclient
474 // Check if the client specified the number of replicas
475 if req.Header.Get("X-Keep-Desired-Replicas") != "" {
477 _, err := fmt.Sscanf(req.Header.Get(keepclient.X_Keep_Desired_Replicas), "%d", &r)
483 // Now try to put the block through
485 if bytes, err := ioutil.ReadAll(req.Body); err != nil {
486 err = errors.New(fmt.Sprintf("Error reading request body: %s", err))
487 status = http.StatusInternalServerError
490 locatorOut, wroteReplicas, err = kc.PutB(bytes)
493 locatorOut, wroteReplicas, err = kc.PutHR(locatorIn, req.Body, expectLength)
496 // Tell the client how many successful PUTs we accomplished
497 resp.Header().Set(keepclient.X_Keep_Replicas_Stored, fmt.Sprintf("%d", wroteReplicas))
501 status = http.StatusOK
502 _, err = io.WriteString(resp, locatorOut)
504 case keepclient.OversizeBlockError:
506 status = http.StatusRequestEntityTooLarge
508 case keepclient.InsufficientReplicasError:
509 if wroteReplicas > 0 {
510 // At least one write is considered success. The
511 // client can decide if getting less than the number of
512 // replications it asked for is a fatal error.
513 status = http.StatusOK
514 _, err = io.WriteString(resp, locatorOut)
516 status = http.StatusServiceUnavailable
520 status = http.StatusBadGateway
524 // ServeHTTP implementation for IndexHandler
525 // Supports only GET requests for /index/{prefix:[0-9a-f]{0,32}}
526 // For each keep server found in LocalRoots:
527 // Invokes GetIndex using keepclient
528 // Expects "complete" response (terminating with blank new line)
529 // Aborts on any errors
530 // Concatenates responses from all those keep servers and returns
531 func (h *proxyHandler) Index(resp http.ResponseWriter, req *http.Request) {
534 prefix := mux.Vars(req)["prefix"]
539 if status != http.StatusOK {
540 http.Error(resp, err.Error(), status)
544 kc := h.makeKeepClient(req)
545 ok, token := CheckAuthorizationHeader(kc, h.ApiTokenCache, req)
547 status, err = http.StatusForbidden, BadAuthorizationHeader
551 // Copy ArvadosClient struct and use the client's API token
552 arvclient := *kc.Arvados
553 arvclient.ApiToken = token
554 kc.Arvados = &arvclient
556 // Only GET method is supported
557 if req.Method != "GET" {
558 status, err = http.StatusNotImplemented, MethodNotSupported
562 // Get index from all LocalRoots and write to resp
564 for uuid := range kc.LocalRoots() {
565 reader, err = kc.GetIndex(uuid, prefix)
567 status = http.StatusBadGateway
571 _, err = io.Copy(resp, reader)
573 status = http.StatusBadGateway
578 // Got index from all the keep servers and wrote to resp
579 status = http.StatusOK
580 resp.Write([]byte("\n"))
583 func (h *proxyHandler) makeKeepClient(req *http.Request) *keepclient.KeepClient {
585 kc.HTTPClient = &proxyClient{
586 client: &http.Client{
588 Transport: h.transport,