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