cd0a872b9b9c2c13e70ef4ab38375629d06dcadd
[arvados.git] / services / keepproxy / keepproxy.go
1 package main
2
3 import (
4         "git.curoverse.com/arvados.git/sdk/go/keepclient"
5         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
6         "flag"
7         "fmt"
8         "github.com/gorilla/mux"
9         "io"
10         "log"
11         "net"
12         "net/http"
13         "os"
14         "os/signal"
15         "sync"
16         "syscall"
17         "time"
18 )
19
20 // Default TCP address on which to listen for requests.
21 // Initialized by the -listen flag.
22 const DEFAULT_ADDR = ":25107"
23
24 var listener net.Listener
25
26 func main() {
27         var (
28                 listen           string
29                 no_get           bool
30                 no_put           bool
31                 default_replicas int
32                 pidfile          string
33         )
34
35         flagset := flag.NewFlagSet("default", flag.ExitOnError)
36
37         flagset.StringVar(
38                 &listen,
39                 "listen",
40                 DEFAULT_ADDR,
41                 "Interface on which to listen for requests, in the format "+
42                         "ipaddr:port. e.g. -listen=10.0.1.24:8000. Use -listen=:port "+
43                         "to listen on all network interfaces.")
44
45         flagset.BoolVar(
46                 &no_get,
47                 "no-get",
48                 false,
49                 "If set, disable GET operations")
50
51         flagset.BoolVar(
52                 &no_put,
53                 "no-put",
54                 false,
55                 "If set, disable PUT operations")
56
57         flagset.IntVar(
58                 &default_replicas,
59                 "default-replicas",
60                 2,
61                 "Default number of replicas to write if not specified by the client.")
62
63         flagset.StringVar(
64                 &pidfile,
65                 "pid",
66                 "",
67                 "Path to write pid file")
68
69         flagset.Parse(os.Args[1:])
70
71         arv, err := arvadosclient.MakeArvadosClient()
72         if err != nil {
73                 log.Fatalf("Error setting up arvados client %s", err.Error())
74         }
75
76         kc, err := keepclient.MakeKeepClient(&arv)
77         if err != nil {
78                 log.Fatalf("Error setting up keep client %s", err.Error())
79         }
80
81         if pidfile != "" {
82                 f, err := os.Create(pidfile)
83                 if err != nil {
84                         log.Fatalf("Error writing pid file (%s): %s", pidfile, err.Error())
85                 }
86                 fmt.Fprint(f, os.Getpid())
87                 f.Close()
88                 defer os.Remove(pidfile)
89         }
90
91         kc.Want_replicas = default_replicas
92
93         listener, err = net.Listen("tcp", listen)
94         if err != nil {
95                 log.Fatalf("Could not listen on %v", listen)
96         }
97
98         go RefreshServicesList(&kc)
99
100         // Shut down the server gracefully (by closing the listener)
101         // if SIGTERM is received.
102         term := make(chan os.Signal, 1)
103         go func(sig <-chan os.Signal) {
104                 s := <-sig
105                 log.Println("caught signal:", s)
106                 listener.Close()
107         }(term)
108         signal.Notify(term, syscall.SIGTERM)
109         signal.Notify(term, syscall.SIGINT)
110
111         log.Printf("Arvados Keep proxy started listening on %v with server list %v", listener.Addr(), kc.ServiceRoots())
112
113         // Start listening for requests.
114         http.Serve(listener, MakeRESTRouter(!no_get, !no_put, &kc))
115
116         log.Println("shutting down")
117 }
118
119 type ApiTokenCache struct {
120         tokens     map[string]int64
121         lock       sync.Mutex
122         expireTime int64
123 }
124
125 // Refresh the keep service list every five minutes.
126 func RefreshServicesList(kc *keepclient.KeepClient) {
127         for {
128                 time.Sleep(300 * time.Second)
129                 oldservices := kc.ServiceRoots()
130                 kc.DiscoverKeepServers()
131                 newservices := kc.ServiceRoots()
132                 s1 := fmt.Sprint(oldservices)
133                 s2 := fmt.Sprint(newservices)
134                 if s1 != s2 {
135                         log.Printf("Updated server list to %v", s2)
136                 }
137         }
138 }
139
140 // Cache the token and set an expire time.  If we already have an expire time
141 // on the token, it is not updated.
142 func (this *ApiTokenCache) RememberToken(token string) {
143         this.lock.Lock()
144         defer this.lock.Unlock()
145
146         now := time.Now().Unix()
147         if this.tokens[token] == 0 {
148                 this.tokens[token] = now + this.expireTime
149         }
150 }
151
152 // Check if the cached token is known and still believed to be valid.
153 func (this *ApiTokenCache) RecallToken(token string) bool {
154         this.lock.Lock()
155         defer this.lock.Unlock()
156
157         now := time.Now().Unix()
158         if this.tokens[token] == 0 {
159                 // Unknown token
160                 return false
161         } else if now < this.tokens[token] {
162                 // Token is known and still valid
163                 return true
164         } else {
165                 // Token is expired
166                 this.tokens[token] = 0
167                 return false
168         }
169 }
170
171 func GetRemoteAddress(req *http.Request) string {
172         if realip := req.Header.Get("X-Real-IP"); realip != "" {
173                 if forwarded := req.Header.Get("X-Forwarded-For"); forwarded != realip {
174                         return fmt.Sprintf("%s (X-Forwarded-For %s)", realip, forwarded)
175                 } else {
176                         return realip
177                 }
178         }
179         return req.RemoteAddr
180 }
181
182 func CheckAuthorizationHeader(kc keepclient.KeepClient, cache *ApiTokenCache, req *http.Request) (pass bool, tok string) {
183         var auth string
184         if auth = req.Header.Get("Authorization"); auth == "" {
185                 return false, ""
186         }
187
188         _, err := fmt.Sscanf(auth, "OAuth2 %s", &tok)
189         if err != nil {
190                 // Scanning error
191                 return false, ""
192         }
193
194         if cache.RecallToken(tok) {
195                 // Valid in the cache, short circut
196                 return true, tok
197         }
198
199         arv := *kc.Arvados
200         arv.ApiToken = tok
201         if err := arv.Call("HEAD", "users", "", "current", nil, nil); err != nil {
202                 log.Printf("%s: CheckAuthorizationHeader error: %v", GetRemoteAddress(req), err)
203                 return false, ""
204         }
205
206         // Success!  Update cache
207         cache.RememberToken(tok)
208
209         return true, tok
210 }
211
212 type GetBlockHandler struct {
213         *keepclient.KeepClient
214         *ApiTokenCache
215 }
216
217 type PutBlockHandler struct {
218         *keepclient.KeepClient
219         *ApiTokenCache
220 }
221
222 type InvalidPathHandler struct{}
223
224 // MakeRESTRouter
225 //     Returns a mux.Router that passes GET and PUT requests to the
226 //     appropriate handlers.
227 //
228 func MakeRESTRouter(
229         enable_get bool,
230         enable_put bool,
231         kc *keepclient.KeepClient) *mux.Router {
232
233         t := &ApiTokenCache{tokens: make(map[string]int64), expireTime: 300}
234
235         rest := mux.NewRouter()
236
237         if enable_get {
238                 rest.Handle(`/{hash:[0-9a-f]{32}}+{hints}`,
239                         GetBlockHandler{kc, t}).Methods("GET", "HEAD")
240                 rest.Handle(`/{hash:[0-9a-f]{32}}`, GetBlockHandler{kc, t}).Methods("GET", "HEAD")
241         }
242
243         if enable_put {
244                 rest.Handle(`/{hash:[0-9a-f]{32}}+{hints}`, PutBlockHandler{kc, t}).Methods("PUT")
245                 rest.Handle(`/{hash:[0-9a-f]{32}}`, PutBlockHandler{kc, t}).Methods("PUT")
246         }
247
248         rest.NotFoundHandler = InvalidPathHandler{}
249
250         return rest
251 }
252
253 func (this InvalidPathHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
254         log.Printf("%s: %s %s unroutable", GetRemoteAddress(req), req.Method, req.URL.Path)
255         http.Error(resp, "Bad request", http.StatusBadRequest)
256 }
257
258 func (this GetBlockHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
259
260         kc := *this.KeepClient
261
262         hash := mux.Vars(req)["hash"]
263         hints := mux.Vars(req)["hints"]
264
265         locator := keepclient.MakeLocator2(hash, hints)
266
267         log.Printf("%s: %s %s", GetRemoteAddress(req), req.Method, hash)
268
269         var pass bool
270         var tok string
271         if pass, tok = CheckAuthorizationHeader(kc, this.ApiTokenCache, req); !pass {
272                 http.Error(resp, "Missing or invalid Authorization header", http.StatusForbidden)
273                 return
274         }
275
276         // Copy ArvadosClient struct and use the client's API token
277         arvclient := *kc.Arvados
278         arvclient.ApiToken = tok
279         kc.Arvados = &arvclient
280
281         var reader io.ReadCloser
282         var err error
283         var blocklen int64
284
285         if req.Method == "GET" {
286                 reader, blocklen, _, err = kc.AuthorizedGet(hash, locator.Signature, locator.Timestamp)
287                 defer reader.Close()
288         } else if req.Method == "HEAD" {
289                 blocklen, _, err = kc.AuthorizedAsk(hash, locator.Signature, locator.Timestamp)
290         }
291
292         if blocklen > 0 {
293                 resp.Header().Set("Content-Length", fmt.Sprint(blocklen))
294         }
295
296         switch err {
297         case nil:
298                 if reader != nil {
299                         n, err2 := io.Copy(resp, reader)
300                         if n != blocklen {
301                                 log.Printf("%s: %s %s mismatched return %v with Content-Length %v error %v", GetRemoteAddress(req), req.Method, hash, n, blocklen, err2)
302                         } else if err2 == nil {
303                                 log.Printf("%s: %s %s success returned %v bytes", GetRemoteAddress(req), req.Method, hash, n)
304                         } else {
305                                 log.Printf("%s: %s %s returned %v bytes error %v", GetRemoteAddress(req), req.Method, hash, n, err.Error())
306                         }
307                 } else {
308                         log.Printf("%s: %s %s success", GetRemoteAddress(req), req.Method, hash)
309                 }
310         case keepclient.BlockNotFound:
311                 http.Error(resp, "Not found", http.StatusNotFound)
312         default:
313                 http.Error(resp, err.Error(), http.StatusBadGateway)
314         }
315
316         if err != nil {
317                 log.Printf("%s: %s %s error %s", GetRemoteAddress(req), req.Method, hash, err.Error())
318         }
319 }
320
321 func (this PutBlockHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
322
323         kc := *this.KeepClient
324
325         hash := mux.Vars(req)["hash"]
326         hints := mux.Vars(req)["hints"]
327
328         locator := keepclient.MakeLocator2(hash, hints)
329
330         var contentLength int64 = -1
331         if req.Header.Get("Content-Length") != "" {
332                 _, err := fmt.Sscanf(req.Header.Get("Content-Length"), "%d", &contentLength)
333                 if err != nil {
334                         resp.Header().Set("Content-Length", fmt.Sprintf("%d", contentLength))
335                 }
336
337         }
338
339         log.Printf("%s: %s %s Content-Length %v", GetRemoteAddress(req), req.Method, hash, contentLength)
340
341         if contentLength < 1 {
342                 http.Error(resp, "Must include Content-Length header", http.StatusLengthRequired)
343                 return
344         }
345
346         if locator.Size > 0 && int64(locator.Size) != contentLength {
347                 http.Error(resp, "Locator size hint does not match Content-Length header", http.StatusBadRequest)
348                 return
349         }
350
351         var pass bool
352         var tok string
353         if pass, tok = CheckAuthorizationHeader(kc, this.ApiTokenCache, req); !pass {
354                 http.Error(resp, "Missing or invalid Authorization header", http.StatusForbidden)
355                 return
356         }
357
358         // Copy ArvadosClient struct and use the client's API token
359         arvclient := *kc.Arvados
360         arvclient.ApiToken = tok
361         kc.Arvados = &arvclient
362
363         // Check if the client specified the number of replicas
364         if req.Header.Get("X-Keep-Desired-Replicas") != "" {
365                 var r int
366                 _, err := fmt.Sscanf(req.Header.Get(keepclient.X_Keep_Desired_Replicas), "%d", &r)
367                 if err != nil {
368                         kc.Want_replicas = r
369                 }
370         }
371
372         // Now try to put the block through
373         hash, replicas, err := kc.PutHR(hash, req.Body, contentLength)
374
375         // Tell the client how many successful PUTs we accomplished
376         resp.Header().Set(keepclient.X_Keep_Replicas_Stored, fmt.Sprintf("%d", replicas))
377
378         switch err {
379         case nil:
380                 // Default will return http.StatusOK
381                 log.Printf("%s: %s %s finished, stored %v replicas (desired %v)", GetRemoteAddress(req), req.Method, hash, replicas, kc.Want_replicas)
382                 n, err2 := io.WriteString(resp, hash)
383                 if err2 != nil {
384                         log.Printf("%s: wrote %v bytes to response body and got error %v", n, err2.Error())
385                 }
386
387         case keepclient.OversizeBlockError:
388                 // Too much data
389                 http.Error(resp, fmt.Sprintf("Exceeded maximum blocksize %d", keepclient.BLOCKSIZE), http.StatusRequestEntityTooLarge)
390
391         case keepclient.InsufficientReplicasError:
392                 if replicas > 0 {
393                         // At least one write is considered success.  The
394                         // client can decide if getting less than the number of
395                         // replications it asked for is a fatal error.
396                         // Default will return http.StatusOK
397                         n, err2 := io.WriteString(resp, hash)
398                         if err2 != nil {
399                                 log.Printf("%s: wrote %v bytes to response body and got error %v", n, err2.Error())
400                         }
401                 } else {
402                         http.Error(resp, "", http.StatusServiceUnavailable)
403                 }
404
405         default:
406                 http.Error(resp, err.Error(), http.StatusBadGateway)
407         }
408
409         if err != nil {
410                 log.Printf("%s: %s %s stored %v replicas (desired %v) got error %v", GetRemoteAddress(req), req.Method, hash, replicas, kc.Want_replicas, err.Error())
411         }
412
413 }