3828: Wait for listener to start before connecting to it. Fix test
[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                 listener = nil
108         }(term)
109         signal.Notify(term, syscall.SIGTERM)
110         signal.Notify(term, syscall.SIGINT)
111
112         log.Printf("Arvados Keep proxy started listening on %v with server list %v", listener.Addr(), kc.ServiceRoots())
113
114         // Start listening for requests.
115         http.Serve(listener, MakeRESTRouter(!no_get, !no_put, &kc))
116
117         log.Println("shutting down")
118 }
119
120 type ApiTokenCache struct {
121         tokens     map[string]int64
122         lock       sync.Mutex
123         expireTime int64
124 }
125
126 // Refresh the keep service list every five minutes.
127 func RefreshServicesList(kc *keepclient.KeepClient) {
128         for {
129                 time.Sleep(300 * time.Second)
130                 oldservices := kc.ServiceRoots()
131                 kc.DiscoverKeepServers()
132                 newservices := kc.ServiceRoots()
133                 s1 := fmt.Sprint(oldservices)
134                 s2 := fmt.Sprint(newservices)
135                 if s1 != s2 {
136                         log.Printf("Updated server list to %v", s2)
137                 }
138         }
139 }
140
141 // Cache the token and set an expire time.  If we already have an expire time
142 // on the token, it is not updated.
143 func (this *ApiTokenCache) RememberToken(token string) {
144         this.lock.Lock()
145         defer this.lock.Unlock()
146
147         now := time.Now().Unix()
148         if this.tokens[token] == 0 {
149                 this.tokens[token] = now + this.expireTime
150         }
151 }
152
153 // Check if the cached token is known and still believed to be valid.
154 func (this *ApiTokenCache) RecallToken(token string) bool {
155         this.lock.Lock()
156         defer this.lock.Unlock()
157
158         now := time.Now().Unix()
159         if this.tokens[token] == 0 {
160                 // Unknown token
161                 return false
162         } else if now < this.tokens[token] {
163                 // Token is known and still valid
164                 return true
165         } else {
166                 // Token is expired
167                 this.tokens[token] = 0
168                 return false
169         }
170 }
171
172 func GetRemoteAddress(req *http.Request) string {
173         if realip := req.Header.Get("X-Real-IP"); realip != "" {
174                 if forwarded := req.Header.Get("X-Forwarded-For"); forwarded != realip {
175                         return fmt.Sprintf("%s (X-Forwarded-For %s)", realip, forwarded)
176                 } else {
177                         return realip
178                 }
179         }
180         return req.RemoteAddr
181 }
182
183 func CheckAuthorizationHeader(kc keepclient.KeepClient, cache *ApiTokenCache, req *http.Request) (pass bool, tok string) {
184         var auth string
185         if auth = req.Header.Get("Authorization"); auth == "" {
186                 return false, ""
187         }
188
189         _, err := fmt.Sscanf(auth, "OAuth2 %s", &tok)
190         if err != nil {
191                 // Scanning error
192                 return false, ""
193         }
194
195         if cache.RecallToken(tok) {
196                 // Valid in the cache, short circut
197                 return true, tok
198         }
199
200         arv := *kc.Arvados
201         arv.ApiToken = tok
202         if err := arv.Call("HEAD", "users", "", "current", nil, nil); err != nil {
203                 log.Printf("%s: CheckAuthorizationHeader error: %v", GetRemoteAddress(req), err)
204                 return false, ""
205         }
206
207         // Success!  Update cache
208         cache.RememberToken(tok)
209
210         return true, tok
211 }
212
213 type GetBlockHandler struct {
214         *keepclient.KeepClient
215         *ApiTokenCache
216 }
217
218 type PutBlockHandler struct {
219         *keepclient.KeepClient
220         *ApiTokenCache
221 }
222
223 type InvalidPathHandler struct{}
224
225 // MakeRESTRouter
226 //     Returns a mux.Router that passes GET and PUT requests to the
227 //     appropriate handlers.
228 //
229 func MakeRESTRouter(
230         enable_get bool,
231         enable_put bool,
232         kc *keepclient.KeepClient) *mux.Router {
233
234         t := &ApiTokenCache{tokens: make(map[string]int64), expireTime: 300}
235
236         rest := mux.NewRouter()
237
238         if enable_get {
239                 rest.Handle(`/{hash:[0-9a-f]{32}}+{hints}`,
240                         GetBlockHandler{kc, t}).Methods("GET", "HEAD")
241                 rest.Handle(`/{hash:[0-9a-f]{32}}`, GetBlockHandler{kc, t}).Methods("GET", "HEAD")
242         }
243
244         if enable_put {
245                 rest.Handle(`/{hash:[0-9a-f]{32}}+{hints}`, PutBlockHandler{kc, t}).Methods("PUT")
246                 rest.Handle(`/{hash:[0-9a-f]{32}}`, PutBlockHandler{kc, t}).Methods("PUT")
247         }
248
249         rest.NotFoundHandler = InvalidPathHandler{}
250
251         return rest
252 }
253
254 func (this InvalidPathHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
255         log.Printf("%s: %s %s unroutable", GetRemoteAddress(req), req.Method, req.URL.Path)
256         http.Error(resp, "Bad request", http.StatusBadRequest)
257 }
258
259 func (this GetBlockHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
260
261         kc := *this.KeepClient
262
263         hash := mux.Vars(req)["hash"]
264         hints := mux.Vars(req)["hints"]
265
266         locator := keepclient.MakeLocator2(hash, hints)
267
268         log.Printf("%s: %s %s", GetRemoteAddress(req), req.Method, hash)
269
270         var pass bool
271         var tok string
272         if pass, tok = CheckAuthorizationHeader(kc, this.ApiTokenCache, req); !pass {
273                 http.Error(resp, "Missing or invalid Authorization header", http.StatusForbidden)
274                 return
275         }
276
277         // Copy ArvadosClient struct and use the client's API token
278         arvclient := *kc.Arvados
279         arvclient.ApiToken = tok
280         kc.Arvados = &arvclient
281
282         var reader io.ReadCloser
283         var err error
284         var blocklen int64
285
286         if req.Method == "GET" {
287                 reader, blocklen, _, err = kc.AuthorizedGet(hash, locator.Signature, locator.Timestamp)
288                 defer reader.Close()
289         } else if req.Method == "HEAD" {
290                 blocklen, _, err = kc.AuthorizedAsk(hash, locator.Signature, locator.Timestamp)
291         }
292
293         if blocklen > 0 {
294                 resp.Header().Set("Content-Length", fmt.Sprint(blocklen))
295         }
296
297         switch err {
298         case nil:
299                 if reader != nil {
300                         n, err2 := io.Copy(resp, reader)
301                         if n != blocklen {
302                                 log.Printf("%s: %s %s mismatched return %v with Content-Length %v error %v", GetRemoteAddress(req), req.Method, hash, n, blocklen, err2)
303                         } else if err2 == nil {
304                                 log.Printf("%s: %s %s success returned %v bytes", GetRemoteAddress(req), req.Method, hash, n)
305                         } else {
306                                 log.Printf("%s: %s %s returned %v bytes error %v", GetRemoteAddress(req), req.Method, hash, n, err.Error())
307                         }
308                 } else {
309                         log.Printf("%s: %s %s success", GetRemoteAddress(req), req.Method, hash)
310                 }
311         case keepclient.BlockNotFound:
312                 http.Error(resp, "Not found", http.StatusNotFound)
313         default:
314                 http.Error(resp, err.Error(), http.StatusBadGateway)
315         }
316
317         if err != nil {
318                 log.Printf("%s: %s %s error %s", GetRemoteAddress(req), req.Method, hash, err.Error())
319         }
320 }
321
322 func (this PutBlockHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
323
324         kc := *this.KeepClient
325
326         hash := mux.Vars(req)["hash"]
327         hints := mux.Vars(req)["hints"]
328
329         locator := keepclient.MakeLocator2(hash, hints)
330
331         var contentLength int64 = -1
332         if req.Header.Get("Content-Length") != "" {
333                 _, err := fmt.Sscanf(req.Header.Get("Content-Length"), "%d", &contentLength)
334                 if err != nil {
335                         resp.Header().Set("Content-Length", fmt.Sprintf("%d", contentLength))
336                 }
337
338         }
339
340         log.Printf("%s: %s %s Content-Length %v", GetRemoteAddress(req), req.Method, hash, contentLength)
341
342         if contentLength < 1 {
343                 http.Error(resp, "Must include Content-Length header", http.StatusLengthRequired)
344                 return
345         }
346
347         if locator.Size > 0 && int64(locator.Size) != contentLength {
348                 http.Error(resp, "Locator size hint does not match Content-Length header", http.StatusBadRequest)
349                 return
350         }
351
352         var pass bool
353         var tok string
354         if pass, tok = CheckAuthorizationHeader(kc, this.ApiTokenCache, req); !pass {
355                 http.Error(resp, "Missing or invalid Authorization header", http.StatusForbidden)
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         // Check if the client specified the number of replicas
365         if req.Header.Get("X-Keep-Desired-Replicas") != "" {
366                 var r int
367                 _, err := fmt.Sscanf(req.Header.Get(keepclient.X_Keep_Desired_Replicas), "%d", &r)
368                 if err != nil {
369                         kc.Want_replicas = r
370                 }
371         }
372
373         // Now try to put the block through
374         hash, replicas, err := kc.PutHR(hash, req.Body, contentLength)
375
376         // Tell the client how many successful PUTs we accomplished
377         resp.Header().Set(keepclient.X_Keep_Replicas_Stored, fmt.Sprintf("%d", replicas))
378
379         switch err {
380         case nil:
381                 // Default will return http.StatusOK
382                 log.Printf("%s: %s %s finished, stored %v replicas (desired %v)", GetRemoteAddress(req), req.Method, hash, replicas, kc.Want_replicas)
383                 n, err2 := io.WriteString(resp, hash)
384                 if err2 != nil {
385                         log.Printf("%s: wrote %v bytes to response body and got error %v", n, err2.Error())
386                 }
387
388         case keepclient.OversizeBlockError:
389                 // Too much data
390                 http.Error(resp, fmt.Sprintf("Exceeded maximum blocksize %d", keepclient.BLOCKSIZE), http.StatusRequestEntityTooLarge)
391
392         case keepclient.InsufficientReplicasError:
393                 if replicas > 0 {
394                         // At least one write is considered success.  The
395                         // client can decide if getting less than the number of
396                         // replications it asked for is a fatal error.
397                         // Default will return http.StatusOK
398                         n, err2 := io.WriteString(resp, hash)
399                         if err2 != nil {
400                                 log.Printf("%s: wrote %v bytes to response body and got error %v", n, err2.Error())
401                         }
402                 } else {
403                         http.Error(resp, "", http.StatusServiceUnavailable)
404                 }
405
406         default:
407                 http.Error(resp, err.Error(), http.StatusBadGateway)
408         }
409
410         if err != nil {
411                 log.Printf("%s: %s %s stored %v replicas (desired %v) got error %v", GetRemoteAddress(req), req.Method, hash, replicas, kc.Want_replicas, err.Error())
412         }
413
414 }