Merge branch 'master' into origin-8019-crunchrun-log-throttle
[arvados.git] / services / keepproxy / keepproxy.go
1 package main
2
3 import (
4         "errors"
5         "flag"
6         "fmt"
7         "io"
8         "io/ioutil"
9         "log"
10         "net"
11         "net/http"
12         "os"
13         "os/signal"
14         "regexp"
15         "strings"
16         "sync"
17         "syscall"
18         "time"
19
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"
27 )
28
29 type Config struct {
30         Client          arvados.Client
31         Listen          string
32         DisableGet      bool
33         DisablePut      bool
34         DefaultReplicas int
35         Timeout         arvados.Duration
36         PIDFile         string
37         Debug           bool
38 }
39
40 func DefaultConfig() *Config {
41         return &Config{
42                 Listen:  ":25107",
43                 Timeout: arvados.Duration(15 * time.Second),
44         }
45 }
46
47 var (
48         listener net.Listener
49         router   http.Handler
50 )
51
52 func main() {
53         cfg := DefaultConfig()
54
55         flagset := flag.NewFlagSet("keepproxy", flag.ExitOnError)
56         flagset.Usage = usage
57
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)
65
66         var cfgPath string
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:])
71
72         err := config.LoadFile(cfg, cfgPath)
73         if err != nil {
74                 h := os.Getenv("ARVADOS_API_HOST")
75                 t := os.Getenv("ARVADOS_API_TOKEN")
76                 if h == "" || t == "" || !os.IsNotExist(err) || cfgPath != defaultCfgPath {
77                         log.Fatal(err)
78                 }
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
84                 }
85                 if y, err := yaml.Marshal(cfg); err == nil && !*dumpConfig {
86                         log.Print("Current configuration:\n", string(y))
87                 }
88                 cfg.Timeout = arvados.Duration(time.Duration(*timeoutSeconds) * time.Second)
89         }
90
91         if *dumpConfig {
92                 log.Fatal(config.DumpAndExit(cfg))
93         }
94
95         arv, err := arvadosclient.New(&cfg.Client)
96         if err != nil {
97                 log.Fatalf("Error setting up arvados client %s", err.Error())
98         }
99
100         if cfg.Debug {
101                 keepclient.DebugPrintf = log.Printf
102         }
103         kc, err := keepclient.MakeKeepClient(arv)
104         if err != nil {
105                 log.Fatalf("Error setting up keep client %s", err.Error())
106         }
107
108         if cfg.PIDFile != "" {
109                 f, err := os.Create(cfg.PIDFile)
110                 if err != nil {
111                         log.Fatal(err)
112                 }
113                 defer f.Close()
114                 err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
115                 if err != nil {
116                         log.Fatalf("flock(%s): %s", cfg.PIDFile, err)
117                 }
118                 defer os.Remove(cfg.PIDFile)
119                 err = f.Truncate(0)
120                 if err != nil {
121                         log.Fatalf("truncate(%s): %s", cfg.PIDFile, err)
122                 }
123                 _, err = fmt.Fprint(f, os.Getpid())
124                 if err != nil {
125                         log.Fatalf("write(%s): %s", cfg.PIDFile, err)
126                 }
127                 err = f.Sync()
128                 if err != nil {
129                         log.Fatal("sync(%s): %s", cfg.PIDFile, err)
130                 }
131         }
132
133         if cfg.DefaultReplicas > 0 {
134                 kc.Want_replicas = cfg.DefaultReplicas
135         }
136         kc.Client.(*http.Client).Timeout = time.Duration(cfg.Timeout)
137         go kc.RefreshServices(5*time.Minute, 3*time.Second)
138
139         listener, err = net.Listen("tcp", cfg.Listen)
140         if err != nil {
141                 log.Fatalf("listen(%s): %s", cfg.Listen, err)
142         }
143         if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
144                 log.Printf("Error notifying init daemon: %v", err)
145         }
146         log.Println("Listening at", listener.Addr())
147
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) {
152                 s := <-sig
153                 log.Println("caught signal:", s)
154                 listener.Close()
155         }(term)
156         signal.Notify(term, syscall.SIGTERM)
157         signal.Notify(term, syscall.SIGINT)
158
159         // Start serving requests.
160         router = MakeRESTRouter(!cfg.DisableGet, !cfg.DisablePut, kc)
161         http.Serve(listener, router)
162
163         log.Println("shutting down")
164 }
165
166 type ApiTokenCache struct {
167         tokens     map[string]int64
168         lock       sync.Mutex
169         expireTime int64
170 }
171
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) {
175         this.lock.Lock()
176         defer this.lock.Unlock()
177
178         now := time.Now().Unix()
179         if this.tokens[token] == 0 {
180                 this.tokens[token] = now + this.expireTime
181         }
182 }
183
184 // Check if the cached token is known and still believed to be valid.
185 func (this *ApiTokenCache) RecallToken(token string) bool {
186         this.lock.Lock()
187         defer this.lock.Unlock()
188
189         now := time.Now().Unix()
190         if this.tokens[token] == 0 {
191                 // Unknown token
192                 return false
193         } else if now < this.tokens[token] {
194                 // Token is known and still valid
195                 return true
196         } else {
197                 // Token is expired
198                 this.tokens[token] = 0
199                 return false
200         }
201 }
202
203 func GetRemoteAddress(req *http.Request) string {
204         if xff := req.Header.Get("X-Forwarded-For"); xff != "" {
205                 return xff + "," + req.RemoteAddr
206         }
207         return req.RemoteAddr
208 }
209
210 func CheckAuthorizationHeader(kc *keepclient.KeepClient, cache *ApiTokenCache, req *http.Request) (pass bool, tok string) {
211         var auth string
212         if auth = req.Header.Get("Authorization"); auth == "" {
213                 return false, ""
214         }
215
216         _, err := fmt.Sscanf(auth, "OAuth2 %s", &tok)
217         if err != nil {
218                 // Scanning error
219                 return false, ""
220         }
221
222         if cache.RecallToken(tok) {
223                 // Valid in the cache, short circuit
224                 return true, tok
225         }
226
227         arv := *kc.Arvados
228         arv.ApiToken = tok
229         if err := arv.Call("HEAD", "users", "", "current", nil, nil); err != nil {
230                 log.Printf("%s: CheckAuthorizationHeader error: %v", GetRemoteAddress(req), err)
231                 return false, ""
232         }
233
234         // Success!  Update cache
235         cache.RememberToken(tok)
236
237         return true, tok
238 }
239
240 type proxyHandler struct {
241         http.Handler
242         *keepclient.KeepClient
243         *ApiTokenCache
244 }
245
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()
250         h := &proxyHandler{
251                 Handler:    rest,
252                 KeepClient: kc,
253                 ApiTokenCache: &ApiTokenCache{
254                         tokens:     make(map[string]int64),
255                         expireTime: 300,
256                 },
257         }
258
259         if enable_get {
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")
262
263                 // List all blocks
264                 rest.HandleFunc(`/index`, h.Index).Methods("GET")
265
266                 // List blocks whose hash has the given prefix
267                 rest.HandleFunc(`/index/{prefix:[0-9a-f]{0,32}}`, h.Index).Methods("GET")
268         }
269
270         if enable_put {
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")
276         }
277
278         rest.NotFoundHandler = InvalidPathHandler{}
279         return h
280 }
281
282 var errLoopDetected = errors.New("loop detected")
283
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
289         }
290         return nil
291 }
292
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")
298 }
299
300 type InvalidPathHandler struct{}
301
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)
305 }
306
307 func (h *proxyHandler) Options(resp http.ResponseWriter, req *http.Request) {
308         log.Printf("%s: %s %s", GetRemoteAddress(req), req.Method, req.URL.Path)
309         SetCorsHeaders(resp)
310 }
311
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")
315
316 var removeHint, _ = regexp.Compile("\\+K@[a-z0-9]{5}(\\+|$)")
317
318 func (h *proxyHandler) Get(resp http.ResponseWriter, req *http.Request) {
319         if err := h.checkLoop(resp, req); err != nil {
320                 return
321         }
322         SetCorsHeaders(resp)
323         resp.Header().Set("Via", req.Proto+" "+viaAlias)
324
325         locator := mux.Vars(req)["locator"]
326         var err error
327         var status int
328         var expectLength, responseLength int64
329         var proxiedURI = "-"
330
331         defer func() {
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)
335                 }
336         }()
337
338         kc := *h.KeepClient
339         kc.Client = &proxyClient{client: kc.Client, proto: req.Proto}
340
341         var pass bool
342         var tok string
343         if pass, tok = CheckAuthorizationHeader(&kc, h.ApiTokenCache, req); !pass {
344                 status, err = http.StatusForbidden, BadAuthorizationHeader
345                 return
346         }
347
348         // Copy ArvadosClient struct and use the client's API token
349         arvclient := *kc.Arvados
350         arvclient.ApiToken = tok
351         kc.Arvados = &arvclient
352
353         var reader io.ReadCloser
354
355         locator = removeHint.ReplaceAllString(locator, "$1")
356
357         switch req.Method {
358         case "HEAD":
359                 expectLength, proxiedURI, err = kc.Ask(locator)
360         case "GET":
361                 reader, expectLength, proxiedURI, err = kc.Get(locator)
362                 if reader != nil {
363                         defer reader.Close()
364                 }
365         default:
366                 status, err = http.StatusNotImplemented, MethodNotSupported
367                 return
368         }
369
370         if expectLength == -1 {
371                 log.Println("Warning:", GetRemoteAddress(req), req.Method, proxiedURI, "Content-Length not provided")
372         }
373
374         switch respErr := err.(type) {
375         case nil:
376                 status = http.StatusOK
377                 resp.Header().Set("Content-Length", fmt.Sprint(expectLength))
378                 switch req.Method {
379                 case "HEAD":
380                         responseLength = 0
381                 case "GET":
382                         responseLength, err = io.Copy(resp, reader)
383                         if err == nil && expectLength > -1 && responseLength != expectLength {
384                                 err = ContentLengthMismatch
385                         }
386                 }
387         case keepclient.Error:
388                 if respErr == keepclient.BlockNotFound {
389                         status = http.StatusNotFound
390                 } else if respErr.Temporary() {
391                         status = http.StatusBadGateway
392                 } else {
393                         status = 422
394                 }
395         default:
396                 status = http.StatusInternalServerError
397         }
398 }
399
400 var LengthRequiredError = errors.New(http.StatusText(http.StatusLengthRequired))
401 var LengthMismatchError = errors.New("Locator size hint does not match Content-Length header")
402
403 func (h *proxyHandler) Put(resp http.ResponseWriter, req *http.Request) {
404         if err := h.checkLoop(resp, req); err != nil {
405                 return
406         }
407         SetCorsHeaders(resp)
408         resp.Header().Set("Via", "HTTP/1.1 "+viaAlias)
409
410         kc := *h.KeepClient
411         kc.Client = &proxyClient{client: kc.Client, proto: req.Proto}
412
413         var err error
414         var expectLength int64
415         var status = http.StatusInternalServerError
416         var wroteReplicas int
417         var locatorOut string = "-"
418
419         defer func() {
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)
423                 }
424         }()
425
426         locatorIn := mux.Vars(req)["locator"]
427
428         _, err = fmt.Sscanf(req.Header.Get("Content-Length"), "%d", &expectLength)
429         if err != nil || expectLength < 0 {
430                 err = LengthRequiredError
431                 status = http.StatusLengthRequired
432                 return
433         }
434
435         if locatorIn != "" {
436                 var loc *keepclient.Locator
437                 if loc, err = keepclient.MakeLocator(locatorIn); err != nil {
438                         status = http.StatusBadRequest
439                         return
440                 } else if loc.Size > 0 && int64(loc.Size) != expectLength {
441                         err = LengthMismatchError
442                         status = http.StatusBadRequest
443                         return
444                 }
445         }
446
447         var pass bool
448         var tok string
449         if pass, tok = CheckAuthorizationHeader(&kc, h.ApiTokenCache, req); !pass {
450                 err = BadAuthorizationHeader
451                 status = http.StatusForbidden
452                 return
453         }
454
455         // Copy ArvadosClient struct and use the client's API token
456         arvclient := *kc.Arvados
457         arvclient.ApiToken = tok
458         kc.Arvados = &arvclient
459
460         // Check if the client specified the number of replicas
461         if req.Header.Get("X-Keep-Desired-Replicas") != "" {
462                 var r int
463                 _, err := fmt.Sscanf(req.Header.Get(keepclient.X_Keep_Desired_Replicas), "%d", &r)
464                 if err == nil {
465                         kc.Want_replicas = r
466                 }
467         }
468
469         // Now try to put the block through
470         if locatorIn == "" {
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
474                         return
475                 } else {
476                         locatorOut, wroteReplicas, err = kc.PutB(bytes)
477                 }
478         } else {
479                 locatorOut, wroteReplicas, err = kc.PutHR(locatorIn, req.Body, expectLength)
480         }
481
482         // Tell the client how many successful PUTs we accomplished
483         resp.Header().Set(keepclient.X_Keep_Replicas_Stored, fmt.Sprintf("%d", wroteReplicas))
484
485         switch err.(type) {
486         case nil:
487                 status = http.StatusOK
488                 _, err = io.WriteString(resp, locatorOut)
489
490         case keepclient.OversizeBlockError:
491                 // Too much data
492                 status = http.StatusRequestEntityTooLarge
493
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)
501                 } else {
502                         status = http.StatusServiceUnavailable
503                 }
504
505         default:
506                 status = http.StatusBadGateway
507         }
508 }
509
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) {
518         SetCorsHeaders(resp)
519
520         prefix := mux.Vars(req)["prefix"]
521         var err error
522         var status int
523
524         defer func() {
525                 if status != http.StatusOK {
526                         http.Error(resp, err.Error(), status)
527                 }
528         }()
529
530         kc := *h.KeepClient
531
532         ok, token := CheckAuthorizationHeader(&kc, h.ApiTokenCache, req)
533         if !ok {
534                 status, err = http.StatusForbidden, BadAuthorizationHeader
535                 return
536         }
537
538         // Copy ArvadosClient struct and use the client's API token
539         arvclient := *kc.Arvados
540         arvclient.ApiToken = token
541         kc.Arvados = &arvclient
542
543         // Only GET method is supported
544         if req.Method != "GET" {
545                 status, err = http.StatusNotImplemented, MethodNotSupported
546                 return
547         }
548
549         // Get index from all LocalRoots and write to resp
550         var reader io.Reader
551         for uuid := range kc.LocalRoots() {
552                 reader, err = kc.GetIndex(uuid, prefix)
553                 if err != nil {
554                         status = http.StatusBadGateway
555                         return
556                 }
557
558                 _, err = io.Copy(resp, reader)
559                 if err != nil {
560                         status = http.StatusBadGateway
561                         return
562                 }
563         }
564
565         // Got index from all the keep servers and wrote to resp
566         status = http.StatusOK
567         resp.Write([]byte("\n"))
568 }