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