9005: Share http Transports and Clients across KeepClients.
[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         go kc.RefreshServices(5*time.Minute, 3*time.Second)
137
138         listener, err = net.Listen("tcp", cfg.Listen)
139         if err != nil {
140                 log.Fatalf("listen(%s): %s", cfg.Listen, err)
141         }
142         if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
143                 log.Printf("Error notifying init daemon: %v", err)
144         }
145         log.Println("Listening at", listener.Addr())
146
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) {
151                 s := <-sig
152                 log.Println("caught signal:", s)
153                 listener.Close()
154         }(term)
155         signal.Notify(term, syscall.SIGTERM)
156         signal.Notify(term, syscall.SIGINT)
157
158         // Start serving requests.
159         router = MakeRESTRouter(!cfg.DisableGet, !cfg.DisablePut, kc, time.Duration(cfg.Timeout))
160         http.Serve(listener, router)
161
162         log.Println("shutting down")
163 }
164
165 type ApiTokenCache struct {
166         tokens     map[string]int64
167         lock       sync.Mutex
168         expireTime int64
169 }
170
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) {
174         this.lock.Lock()
175         defer this.lock.Unlock()
176
177         now := time.Now().Unix()
178         if this.tokens[token] == 0 {
179                 this.tokens[token] = now + this.expireTime
180         }
181 }
182
183 // Check if the cached token is known and still believed to be valid.
184 func (this *ApiTokenCache) RecallToken(token string) bool {
185         this.lock.Lock()
186         defer this.lock.Unlock()
187
188         now := time.Now().Unix()
189         if this.tokens[token] == 0 {
190                 // Unknown token
191                 return false
192         } else if now < this.tokens[token] {
193                 // Token is known and still valid
194                 return true
195         } else {
196                 // Token is expired
197                 this.tokens[token] = 0
198                 return false
199         }
200 }
201
202 func GetRemoteAddress(req *http.Request) string {
203         if xff := req.Header.Get("X-Forwarded-For"); xff != "" {
204                 return xff + "," + req.RemoteAddr
205         }
206         return req.RemoteAddr
207 }
208
209 func CheckAuthorizationHeader(kc *keepclient.KeepClient, cache *ApiTokenCache, req *http.Request) (pass bool, tok string) {
210         var auth string
211         if auth = req.Header.Get("Authorization"); auth == "" {
212                 return false, ""
213         }
214
215         _, err := fmt.Sscanf(auth, "OAuth2 %s", &tok)
216         if err != nil {
217                 // Scanning error
218                 return false, ""
219         }
220
221         if cache.RecallToken(tok) {
222                 // Valid in the cache, short circuit
223                 return true, tok
224         }
225
226         arv := *kc.Arvados
227         arv.ApiToken = tok
228         if err := arv.Call("HEAD", "users", "", "current", nil, nil); err != nil {
229                 log.Printf("%s: CheckAuthorizationHeader error: %v", GetRemoteAddress(req), err)
230                 return false, ""
231         }
232
233         // Success!  Update cache
234         cache.RememberToken(tok)
235
236         return true, tok
237 }
238
239 type proxyHandler struct {
240         http.Handler
241         *keepclient.KeepClient
242         *ApiTokenCache
243         timeout   time.Duration
244         transport *http.Transport
245 }
246
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()
251         h := &proxyHandler{
252                 Handler:    rest,
253                 KeepClient: kc,
254                 timeout:    timeout,
255                 transport: &http.Transport{
256                         Dial: (&net.Dialer{
257                                 Timeout:   20 * time.Second,
258                                 KeepAlive: 10 * time.Second,
259                         }).Dial,
260                         TLSClientConfig:     arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure),
261                         TLSHandshakeTimeout: 10 * time.Second,
262                 },
263                 ApiTokenCache: &ApiTokenCache{
264                         tokens:     make(map[string]int64),
265                         expireTime: 300,
266                 },
267         }
268
269         go func(t *http.Transport) {
270                 for range time.NewTicker(5 * time.Minute).C {
271                         t.CloseIdleConnections()
272                 }
273         }(h.transport)
274
275         if enable_get {
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")
278
279                 // List all blocks
280                 rest.HandleFunc(`/index`, h.Index).Methods("GET")
281
282                 // List blocks whose hash has the given prefix
283                 rest.HandleFunc(`/index/{prefix:[0-9a-f]{0,32}}`, h.Index).Methods("GET")
284         }
285
286         if enable_put {
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")
292         }
293
294         rest.NotFoundHandler = InvalidPathHandler{}
295         return h
296 }
297
298 var errLoopDetected = errors.New("loop detected")
299
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
305         }
306         return nil
307 }
308
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")
314 }
315
316 type InvalidPathHandler struct{}
317
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)
321 }
322
323 func (h *proxyHandler) Options(resp http.ResponseWriter, req *http.Request) {
324         log.Printf("%s: %s %s", GetRemoteAddress(req), req.Method, req.URL.Path)
325         SetCorsHeaders(resp)
326 }
327
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")
331
332 var removeHint, _ = regexp.Compile("\\+K@[a-z0-9]{5}(\\+|$)")
333
334 func (h *proxyHandler) Get(resp http.ResponseWriter, req *http.Request) {
335         if err := h.checkLoop(resp, req); err != nil {
336                 return
337         }
338         SetCorsHeaders(resp)
339         resp.Header().Set("Via", req.Proto+" "+viaAlias)
340
341         locator := mux.Vars(req)["locator"]
342         var err error
343         var status int
344         var expectLength, responseLength int64
345         var proxiedURI = "-"
346
347         defer func() {
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)
351                 }
352         }()
353
354         kc := h.makeKeepClient(req)
355
356         var pass bool
357         var tok string
358         if pass, tok = CheckAuthorizationHeader(kc, h.ApiTokenCache, req); !pass {
359                 status, err = http.StatusForbidden, BadAuthorizationHeader
360                 return
361         }
362
363         // Copy ArvadosClient struct and use the client's API token
364         arvclient := *kc.Arvados
365         arvclient.ApiToken = tok
366         kc.Arvados = &arvclient
367
368         var reader io.ReadCloser
369
370         locator = removeHint.ReplaceAllString(locator, "$1")
371
372         switch req.Method {
373         case "HEAD":
374                 expectLength, proxiedURI, err = kc.Ask(locator)
375         case "GET":
376                 reader, expectLength, proxiedURI, err = kc.Get(locator)
377                 if reader != nil {
378                         defer reader.Close()
379                 }
380         default:
381                 status, err = http.StatusNotImplemented, MethodNotSupported
382                 return
383         }
384
385         if expectLength == -1 {
386                 log.Println("Warning:", GetRemoteAddress(req), req.Method, proxiedURI, "Content-Length not provided")
387         }
388
389         switch respErr := err.(type) {
390         case nil:
391                 status = http.StatusOK
392                 resp.Header().Set("Content-Length", fmt.Sprint(expectLength))
393                 switch req.Method {
394                 case "HEAD":
395                         responseLength = 0
396                 case "GET":
397                         responseLength, err = io.Copy(resp, reader)
398                         if err == nil && expectLength > -1 && responseLength != expectLength {
399                                 err = ContentLengthMismatch
400                         }
401                 }
402         case keepclient.Error:
403                 if respErr == keepclient.BlockNotFound {
404                         status = http.StatusNotFound
405                 } else if respErr.Temporary() {
406                         status = http.StatusBadGateway
407                 } else {
408                         status = 422
409                 }
410         default:
411                 status = http.StatusInternalServerError
412         }
413 }
414
415 var LengthRequiredError = errors.New(http.StatusText(http.StatusLengthRequired))
416 var LengthMismatchError = errors.New("Locator size hint does not match Content-Length header")
417
418 func (h *proxyHandler) Put(resp http.ResponseWriter, req *http.Request) {
419         if err := h.checkLoop(resp, req); err != nil {
420                 return
421         }
422         SetCorsHeaders(resp)
423         resp.Header().Set("Via", "HTTP/1.1 "+viaAlias)
424
425         kc := h.makeKeepClient(req)
426
427         var err error
428         var expectLength int64
429         var status = http.StatusInternalServerError
430         var wroteReplicas int
431         var locatorOut string = "-"
432
433         defer func() {
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)
437                 }
438         }()
439
440         locatorIn := mux.Vars(req)["locator"]
441
442         _, err = fmt.Sscanf(req.Header.Get("Content-Length"), "%d", &expectLength)
443         if err != nil || expectLength < 0 {
444                 err = LengthRequiredError
445                 status = http.StatusLengthRequired
446                 return
447         }
448
449         if locatorIn != "" {
450                 var loc *keepclient.Locator
451                 if loc, err = keepclient.MakeLocator(locatorIn); err != nil {
452                         status = http.StatusBadRequest
453                         return
454                 } else if loc.Size > 0 && int64(loc.Size) != expectLength {
455                         err = LengthMismatchError
456                         status = http.StatusBadRequest
457                         return
458                 }
459         }
460
461         var pass bool
462         var tok string
463         if pass, tok = CheckAuthorizationHeader(kc, h.ApiTokenCache, req); !pass {
464                 err = BadAuthorizationHeader
465                 status = http.StatusForbidden
466                 return
467         }
468
469         // Copy ArvadosClient struct and use the client's API token
470         arvclient := *kc.Arvados
471         arvclient.ApiToken = tok
472         kc.Arvados = &arvclient
473
474         // Check if the client specified the number of replicas
475         if req.Header.Get("X-Keep-Desired-Replicas") != "" {
476                 var r int
477                 _, err := fmt.Sscanf(req.Header.Get(keepclient.X_Keep_Desired_Replicas), "%d", &r)
478                 if err == nil {
479                         kc.Want_replicas = r
480                 }
481         }
482
483         // Now try to put the block through
484         if locatorIn == "" {
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
488                         return
489                 } else {
490                         locatorOut, wroteReplicas, err = kc.PutB(bytes)
491                 }
492         } else {
493                 locatorOut, wroteReplicas, err = kc.PutHR(locatorIn, req.Body, expectLength)
494         }
495
496         // Tell the client how many successful PUTs we accomplished
497         resp.Header().Set(keepclient.X_Keep_Replicas_Stored, fmt.Sprintf("%d", wroteReplicas))
498
499         switch err.(type) {
500         case nil:
501                 status = http.StatusOK
502                 _, err = io.WriteString(resp, locatorOut)
503
504         case keepclient.OversizeBlockError:
505                 // Too much data
506                 status = http.StatusRequestEntityTooLarge
507
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)
515                 } else {
516                         status = http.StatusServiceUnavailable
517                 }
518
519         default:
520                 status = http.StatusBadGateway
521         }
522 }
523
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) {
532         SetCorsHeaders(resp)
533
534         prefix := mux.Vars(req)["prefix"]
535         var err error
536         var status int
537
538         defer func() {
539                 if status != http.StatusOK {
540                         http.Error(resp, err.Error(), status)
541                 }
542         }()
543
544         kc := h.makeKeepClient(req)
545         ok, token := CheckAuthorizationHeader(kc, h.ApiTokenCache, req)
546         if !ok {
547                 status, err = http.StatusForbidden, BadAuthorizationHeader
548                 return
549         }
550
551         // Copy ArvadosClient struct and use the client's API token
552         arvclient := *kc.Arvados
553         arvclient.ApiToken = token
554         kc.Arvados = &arvclient
555
556         // Only GET method is supported
557         if req.Method != "GET" {
558                 status, err = http.StatusNotImplemented, MethodNotSupported
559                 return
560         }
561
562         // Get index from all LocalRoots and write to resp
563         var reader io.Reader
564         for uuid := range kc.LocalRoots() {
565                 reader, err = kc.GetIndex(uuid, prefix)
566                 if err != nil {
567                         status = http.StatusBadGateway
568                         return
569                 }
570
571                 _, err = io.Copy(resp, reader)
572                 if err != nil {
573                         status = http.StatusBadGateway
574                         return
575                 }
576         }
577
578         // Got index from all the keep servers and wrote to resp
579         status = http.StatusOK
580         resp.Write([]byte("\n"))
581 }
582
583 func (h *proxyHandler) makeKeepClient(req *http.Request) *keepclient.KeepClient {
584         kc := *h.KeepClient
585         kc.HTTPClient = &proxyClient{
586                 client: &http.Client{
587                         Timeout:   h.timeout,
588                         Transport: h.transport,
589                 },
590                 proto: req.Proto,
591         }
592         return &kc
593 }