8784: Fix test for latest firefox.
[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         keepclient.RefreshServiceDiscoveryOnSIGHUP()
108
109         if cfg.PIDFile != "" {
110                 f, err := os.Create(cfg.PIDFile)
111                 if err != nil {
112                         log.Fatal(err)
113                 }
114                 defer f.Close()
115                 err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
116                 if err != nil {
117                         log.Fatalf("flock(%s): %s", cfg.PIDFile, err)
118                 }
119                 defer os.Remove(cfg.PIDFile)
120                 err = f.Truncate(0)
121                 if err != nil {
122                         log.Fatalf("truncate(%s): %s", cfg.PIDFile, err)
123                 }
124                 _, err = fmt.Fprint(f, os.Getpid())
125                 if err != nil {
126                         log.Fatalf("write(%s): %s", cfg.PIDFile, err)
127                 }
128                 err = f.Sync()
129                 if err != nil {
130                         log.Fatal("sync(%s): %s", cfg.PIDFile, err)
131                 }
132         }
133
134         if cfg.DefaultReplicas > 0 {
135                 kc.Want_replicas = cfg.DefaultReplicas
136         }
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
252         transport := *(http.DefaultTransport.(*http.Transport))
253         transport.DialContext = (&net.Dialer{
254                 Timeout:   keepclient.DefaultConnectTimeout,
255                 KeepAlive: keepclient.DefaultKeepAlive,
256                 DualStack: true,
257         }).DialContext
258         transport.TLSClientConfig = arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure)
259         transport.TLSHandshakeTimeout = keepclient.DefaultTLSHandshakeTimeout
260
261         h := &proxyHandler{
262                 Handler:    rest,
263                 KeepClient: kc,
264                 timeout:    timeout,
265                 transport:  &transport,
266                 ApiTokenCache: &ApiTokenCache{
267                         tokens:     make(map[string]int64),
268                         expireTime: 300,
269                 },
270         }
271
272         if enable_get {
273                 rest.HandleFunc(`/{locator:[0-9a-f]{32}\+.*}`, h.Get).Methods("GET", "HEAD")
274                 rest.HandleFunc(`/{locator:[0-9a-f]{32}}`, h.Get).Methods("GET", "HEAD")
275
276                 // List all blocks
277                 rest.HandleFunc(`/index`, h.Index).Methods("GET")
278
279                 // List blocks whose hash has the given prefix
280                 rest.HandleFunc(`/index/{prefix:[0-9a-f]{0,32}}`, h.Index).Methods("GET")
281         }
282
283         if enable_put {
284                 rest.HandleFunc(`/{locator:[0-9a-f]{32}\+.*}`, h.Put).Methods("PUT")
285                 rest.HandleFunc(`/{locator:[0-9a-f]{32}}`, h.Put).Methods("PUT")
286                 rest.HandleFunc(`/`, h.Put).Methods("POST")
287                 rest.HandleFunc(`/{any}`, h.Options).Methods("OPTIONS")
288                 rest.HandleFunc(`/`, h.Options).Methods("OPTIONS")
289         }
290
291         rest.NotFoundHandler = InvalidPathHandler{}
292         return h
293 }
294
295 var errLoopDetected = errors.New("loop detected")
296
297 func (*proxyHandler) checkLoop(resp http.ResponseWriter, req *http.Request) error {
298         if via := req.Header.Get("Via"); strings.Index(via, " "+viaAlias) >= 0 {
299                 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)
300                 http.Error(resp, errLoopDetected.Error(), http.StatusInternalServerError)
301                 return errLoopDetected
302         }
303         return nil
304 }
305
306 func SetCorsHeaders(resp http.ResponseWriter) {
307         resp.Header().Set("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, OPTIONS")
308         resp.Header().Set("Access-Control-Allow-Origin", "*")
309         resp.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Length, Content-Type, X-Keep-Desired-Replicas")
310         resp.Header().Set("Access-Control-Max-Age", "86486400")
311 }
312
313 type InvalidPathHandler struct{}
314
315 func (InvalidPathHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
316         log.Printf("%s: %s %s unroutable", GetRemoteAddress(req), req.Method, req.URL.Path)
317         http.Error(resp, "Bad request", http.StatusBadRequest)
318 }
319
320 func (h *proxyHandler) Options(resp http.ResponseWriter, req *http.Request) {
321         log.Printf("%s: %s %s", GetRemoteAddress(req), req.Method, req.URL.Path)
322         SetCorsHeaders(resp)
323 }
324
325 var BadAuthorizationHeader = errors.New("Missing or invalid Authorization header")
326 var ContentLengthMismatch = errors.New("Actual length != expected content length")
327 var MethodNotSupported = errors.New("Method not supported")
328
329 var removeHint, _ = regexp.Compile("\\+K@[a-z0-9]{5}(\\+|$)")
330
331 func (h *proxyHandler) Get(resp http.ResponseWriter, req *http.Request) {
332         if err := h.checkLoop(resp, req); err != nil {
333                 return
334         }
335         SetCorsHeaders(resp)
336         resp.Header().Set("Via", req.Proto+" "+viaAlias)
337
338         locator := mux.Vars(req)["locator"]
339         var err error
340         var status int
341         var expectLength, responseLength int64
342         var proxiedURI = "-"
343
344         defer func() {
345                 log.Println(GetRemoteAddress(req), req.Method, req.URL.Path, status, expectLength, responseLength, proxiedURI, err)
346                 if status != http.StatusOK {
347                         http.Error(resp, err.Error(), status)
348                 }
349         }()
350
351         kc := h.makeKeepClient(req)
352
353         var pass bool
354         var tok string
355         if pass, tok = CheckAuthorizationHeader(kc, h.ApiTokenCache, req); !pass {
356                 status, err = http.StatusForbidden, BadAuthorizationHeader
357                 return
358         }
359
360         // Copy ArvadosClient struct and use the client's API token
361         arvclient := *kc.Arvados
362         arvclient.ApiToken = tok
363         kc.Arvados = &arvclient
364
365         var reader io.ReadCloser
366
367         locator = removeHint.ReplaceAllString(locator, "$1")
368
369         switch req.Method {
370         case "HEAD":
371                 expectLength, proxiedURI, err = kc.Ask(locator)
372         case "GET":
373                 reader, expectLength, proxiedURI, err = kc.Get(locator)
374                 if reader != nil {
375                         defer reader.Close()
376                 }
377         default:
378                 status, err = http.StatusNotImplemented, MethodNotSupported
379                 return
380         }
381
382         if expectLength == -1 {
383                 log.Println("Warning:", GetRemoteAddress(req), req.Method, proxiedURI, "Content-Length not provided")
384         }
385
386         switch respErr := err.(type) {
387         case nil:
388                 status = http.StatusOK
389                 resp.Header().Set("Content-Length", fmt.Sprint(expectLength))
390                 switch req.Method {
391                 case "HEAD":
392                         responseLength = 0
393                 case "GET":
394                         responseLength, err = io.Copy(resp, reader)
395                         if err == nil && expectLength > -1 && responseLength != expectLength {
396                                 err = ContentLengthMismatch
397                         }
398                 }
399         case keepclient.Error:
400                 if respErr == keepclient.BlockNotFound {
401                         status = http.StatusNotFound
402                 } else if respErr.Temporary() {
403                         status = http.StatusBadGateway
404                 } else {
405                         status = 422
406                 }
407         default:
408                 status = http.StatusInternalServerError
409         }
410 }
411
412 var LengthRequiredError = errors.New(http.StatusText(http.StatusLengthRequired))
413 var LengthMismatchError = errors.New("Locator size hint does not match Content-Length header")
414
415 func (h *proxyHandler) Put(resp http.ResponseWriter, req *http.Request) {
416         if err := h.checkLoop(resp, req); err != nil {
417                 return
418         }
419         SetCorsHeaders(resp)
420         resp.Header().Set("Via", "HTTP/1.1 "+viaAlias)
421
422         kc := h.makeKeepClient(req)
423
424         var err error
425         var expectLength int64
426         var status = http.StatusInternalServerError
427         var wroteReplicas int
428         var locatorOut string = "-"
429
430         defer func() {
431                 log.Println(GetRemoteAddress(req), req.Method, req.URL.Path, status, expectLength, kc.Want_replicas, wroteReplicas, locatorOut, err)
432                 if status != http.StatusOK {
433                         http.Error(resp, err.Error(), status)
434                 }
435         }()
436
437         locatorIn := mux.Vars(req)["locator"]
438
439         _, err = fmt.Sscanf(req.Header.Get("Content-Length"), "%d", &expectLength)
440         if err != nil || expectLength < 0 {
441                 err = LengthRequiredError
442                 status = http.StatusLengthRequired
443                 return
444         }
445
446         if locatorIn != "" {
447                 var loc *keepclient.Locator
448                 if loc, err = keepclient.MakeLocator(locatorIn); err != nil {
449                         status = http.StatusBadRequest
450                         return
451                 } else if loc.Size > 0 && int64(loc.Size) != expectLength {
452                         err = LengthMismatchError
453                         status = http.StatusBadRequest
454                         return
455                 }
456         }
457
458         var pass bool
459         var tok string
460         if pass, tok = CheckAuthorizationHeader(kc, h.ApiTokenCache, req); !pass {
461                 err = BadAuthorizationHeader
462                 status = http.StatusForbidden
463                 return
464         }
465
466         // Copy ArvadosClient struct and use the client's API token
467         arvclient := *kc.Arvados
468         arvclient.ApiToken = tok
469         kc.Arvados = &arvclient
470
471         // Check if the client specified the number of replicas
472         if req.Header.Get("X-Keep-Desired-Replicas") != "" {
473                 var r int
474                 _, err := fmt.Sscanf(req.Header.Get(keepclient.X_Keep_Desired_Replicas), "%d", &r)
475                 if err == nil {
476                         kc.Want_replicas = r
477                 }
478         }
479
480         // Now try to put the block through
481         if locatorIn == "" {
482                 if bytes, err := ioutil.ReadAll(req.Body); err != nil {
483                         err = errors.New(fmt.Sprintf("Error reading request body: %s", err))
484                         status = http.StatusInternalServerError
485                         return
486                 } else {
487                         locatorOut, wroteReplicas, err = kc.PutB(bytes)
488                 }
489         } else {
490                 locatorOut, wroteReplicas, err = kc.PutHR(locatorIn, req.Body, expectLength)
491         }
492
493         // Tell the client how many successful PUTs we accomplished
494         resp.Header().Set(keepclient.X_Keep_Replicas_Stored, fmt.Sprintf("%d", wroteReplicas))
495
496         switch err.(type) {
497         case nil:
498                 status = http.StatusOK
499                 _, err = io.WriteString(resp, locatorOut)
500
501         case keepclient.OversizeBlockError:
502                 // Too much data
503                 status = http.StatusRequestEntityTooLarge
504
505         case keepclient.InsufficientReplicasError:
506                 if wroteReplicas > 0 {
507                         // At least one write is considered success.  The
508                         // client can decide if getting less than the number of
509                         // replications it asked for is a fatal error.
510                         status = http.StatusOK
511                         _, err = io.WriteString(resp, locatorOut)
512                 } else {
513                         status = http.StatusServiceUnavailable
514                 }
515
516         default:
517                 status = http.StatusBadGateway
518         }
519 }
520
521 // ServeHTTP implementation for IndexHandler
522 // Supports only GET requests for /index/{prefix:[0-9a-f]{0,32}}
523 // For each keep server found in LocalRoots:
524 //   Invokes GetIndex using keepclient
525 //   Expects "complete" response (terminating with blank new line)
526 //   Aborts on any errors
527 // Concatenates responses from all those keep servers and returns
528 func (h *proxyHandler) Index(resp http.ResponseWriter, req *http.Request) {
529         SetCorsHeaders(resp)
530
531         prefix := mux.Vars(req)["prefix"]
532         var err error
533         var status int
534
535         defer func() {
536                 if status != http.StatusOK {
537                         http.Error(resp, err.Error(), status)
538                 }
539         }()
540
541         kc := h.makeKeepClient(req)
542         ok, token := CheckAuthorizationHeader(kc, h.ApiTokenCache, req)
543         if !ok {
544                 status, err = http.StatusForbidden, BadAuthorizationHeader
545                 return
546         }
547
548         // Copy ArvadosClient struct and use the client's API token
549         arvclient := *kc.Arvados
550         arvclient.ApiToken = token
551         kc.Arvados = &arvclient
552
553         // Only GET method is supported
554         if req.Method != "GET" {
555                 status, err = http.StatusNotImplemented, MethodNotSupported
556                 return
557         }
558
559         // Get index from all LocalRoots and write to resp
560         var reader io.Reader
561         for uuid := range kc.LocalRoots() {
562                 reader, err = kc.GetIndex(uuid, prefix)
563                 if err != nil {
564                         status = http.StatusBadGateway
565                         return
566                 }
567
568                 _, err = io.Copy(resp, reader)
569                 if err != nil {
570                         status = http.StatusBadGateway
571                         return
572                 }
573         }
574
575         // Got index from all the keep servers and wrote to resp
576         status = http.StatusOK
577         resp.Write([]byte("\n"))
578 }
579
580 func (h *proxyHandler) makeKeepClient(req *http.Request) *keepclient.KeepClient {
581         kc := *h.KeepClient
582         kc.HTTPClient = &proxyClient{
583                 client: &http.Client{
584                         Timeout:   h.timeout,
585                         Transport: h.transport,
586                 },
587                 proto: req.Proto,
588         }
589         return &kc
590 }