17464: Replace cache with LRU cache
[arvados.git] / services / keepproxy / keepproxy.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package main
6
7 import (
8         "errors"
9         "flag"
10         "fmt"
11         "io"
12         "io/ioutil"
13         "net"
14         "net/http"
15         "os"
16         "os/signal"
17         "regexp"
18         "strings"
19         "syscall"
20         "time"
21
22         "git.arvados.org/arvados.git/lib/config"
23         "git.arvados.org/arvados.git/sdk/go/arvados"
24         "git.arvados.org/arvados.git/sdk/go/arvadosclient"
25         "git.arvados.org/arvados.git/sdk/go/health"
26         "git.arvados.org/arvados.git/sdk/go/httpserver"
27         "git.arvados.org/arvados.git/sdk/go/keepclient"
28         "github.com/coreos/go-systemd/daemon"
29         "github.com/ghodss/yaml"
30         "github.com/gorilla/mux"
31         lru "github.com/hashicorp/golang-lru"
32         log "github.com/sirupsen/logrus"
33 )
34
35 var version = "dev"
36
37 var (
38         listener net.Listener
39         router   http.Handler
40 )
41
42 const rfc3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00"
43
44 func configure(logger log.FieldLogger, args []string) (*arvados.Cluster, error) {
45         flags := flag.NewFlagSet(args[0], flag.ExitOnError)
46
47         dumpConfig := flags.Bool("dump-config", false, "write current configuration to stdout and exit")
48         getVersion := flags.Bool("version", false, "Print version information and exit.")
49
50         loader := config.NewLoader(os.Stdin, logger)
51         loader.SetupFlags(flags)
52
53         args = loader.MungeLegacyConfigArgs(logger, args[1:], "-legacy-keepproxy-config")
54         flags.Parse(args)
55
56         // Print version information if requested
57         if *getVersion {
58                 fmt.Printf("keepproxy %s\n", version)
59                 return nil, nil
60         }
61
62         cfg, err := loader.Load()
63         if err != nil {
64                 return nil, err
65         }
66         cluster, err := cfg.GetCluster("")
67         if err != nil {
68                 return nil, err
69         }
70
71         if *dumpConfig {
72                 out, err := yaml.Marshal(cfg)
73                 if err != nil {
74                         return nil, err
75                 }
76                 if _, err := os.Stdout.Write(out); err != nil {
77                         return nil, err
78                 }
79                 return nil, nil
80         }
81         return cluster, nil
82 }
83
84 func main() {
85         logger := log.New()
86         logger.Formatter = &log.JSONFormatter{
87                 TimestampFormat: rfc3339NanoFixed,
88         }
89
90         cluster, err := configure(logger, os.Args)
91         if err != nil {
92                 log.Fatal(err)
93         }
94         if cluster == nil {
95                 return
96         }
97
98         log.Printf("keepproxy %s started", version)
99
100         if err := run(logger, cluster); err != nil {
101                 log.Fatal(err)
102         }
103
104         log.Println("shutting down")
105 }
106
107 func run(logger log.FieldLogger, cluster *arvados.Cluster) error {
108         client, err := arvados.NewClientFromConfig(cluster)
109         if err != nil {
110                 return err
111         }
112         client.AuthToken = cluster.SystemRootToken
113
114         arv, err := arvadosclient.New(client)
115         if err != nil {
116                 return fmt.Errorf("Error setting up arvados client %v", err)
117         }
118
119         // If a config file is available, use the keepstores defined there
120         // instead of the legacy autodiscover mechanism via the API server
121         for k := range cluster.Services.Keepstore.InternalURLs {
122                 arv.KeepServiceURIs = append(arv.KeepServiceURIs, strings.TrimRight(k.String(), "/"))
123         }
124
125         if cluster.SystemLogs.LogLevel == "debug" {
126                 keepclient.DebugPrintf = log.Printf
127         }
128         kc, err := keepclient.MakeKeepClient(arv)
129         if err != nil {
130                 return fmt.Errorf("Error setting up keep client %v", err)
131         }
132         keepclient.RefreshServiceDiscoveryOnSIGHUP()
133
134         if cluster.Collections.DefaultReplication > 0 {
135                 kc.Want_replicas = cluster.Collections.DefaultReplication
136         }
137
138         var listen arvados.URL
139         for listen = range cluster.Services.Keepproxy.InternalURLs {
140                 break
141         }
142
143         var lErr error
144         listener, lErr = net.Listen("tcp", listen.Host)
145         if lErr != nil {
146                 return fmt.Errorf("listen(%s): %v", listen.Host, lErr)
147         }
148
149         if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
150                 log.Printf("Error notifying init daemon: %v", err)
151         }
152         log.Println("listening at", listener.Addr())
153
154         // Shut down the server gracefully (by closing the listener)
155         // if SIGTERM is received.
156         term := make(chan os.Signal, 1)
157         go func(sig <-chan os.Signal) {
158                 s := <-sig
159                 log.Println("caught signal:", s)
160                 listener.Close()
161         }(term)
162         signal.Notify(term, syscall.SIGTERM)
163         signal.Notify(term, syscall.SIGINT)
164
165         // Start serving requests.
166         router = MakeRESTRouter(kc, time.Duration(keepclient.DefaultProxyRequestTimeout), cluster, logger)
167         return http.Serve(listener, httpserver.AddRequestIDs(httpserver.LogRequests(router)))
168 }
169
170 type TokenCacheEntry struct {
171         expire int64
172         user   *arvados.User
173 }
174
175 type APITokenCache struct {
176         tokens     *lru.TwoQueueCache
177         expireTime int64
178 }
179
180 // RememberToken caches the token and set an expire time.  If the
181 // token is already in the cache, it is not updated.
182 func (cache *APITokenCache) RememberToken(token string, user *arvados.User) {
183         now := time.Now().Unix()
184         _, ok := cache.tokens.Get(token)
185         if !ok {
186                 cache.tokens.Add(token, TokenCacheEntry{
187                         expire: now + cache.expireTime,
188                         user:   user,
189                 })
190         }
191 }
192
193 // RecallToken checks if the cached token is known and still believed to be
194 // valid.
195 func (cache *APITokenCache) RecallToken(token string) (bool, *arvados.User) {
196         val, ok := cache.tokens.Get(token)
197         if !ok {
198                 return false, nil
199         }
200
201         cacheEntry := val.(TokenCacheEntry)
202         now := time.Now().Unix()
203         if now < cacheEntry.expire {
204                 // Token is known and still valid
205                 return true, cacheEntry.user
206         } else {
207                 // Token is expired
208                 cache.tokens.Remove(token)
209                 return false, nil
210         }
211 }
212
213 // GetRemoteAddress returns a string with the remote address for the request.
214 // If the X-Forwarded-For header is set and has a non-zero length, it returns a
215 // string made from a comma separated list of all the remote addresses,
216 // starting with the one(s) from the X-Forwarded-For header.
217 func GetRemoteAddress(req *http.Request) string {
218         if xff := req.Header.Get("X-Forwarded-For"); xff != "" {
219                 return xff + "," + req.RemoteAddr
220         }
221         return req.RemoteAddr
222 }
223
224 func (h *proxyHandler) CheckAuthorizationHeader(req *http.Request) (pass bool, tok string, user *arvados.User) {
225         parts := strings.SplitN(req.Header.Get("Authorization"), " ", 2)
226         if len(parts) < 2 || !(parts[0] == "OAuth2" || parts[0] == "Bearer") || len(parts[1]) == 0 {
227                 return false, "", nil
228         }
229         tok = parts[1]
230
231         // Tokens are validated differently depending on what kind of
232         // operation is being performed. For example, tokens in
233         // collection-sharing links permit GET requests, but not
234         // PUT requests.
235         var op string
236         if req.Method == "GET" || req.Method == "HEAD" {
237                 op = "read"
238         } else {
239                 op = "write"
240         }
241
242         if ok, user := h.APITokenCache.RecallToken(op + ":" + tok); ok {
243                 // Valid in the cache, short circuit
244                 return true, tok, user
245         }
246
247         var err error
248         arv := *h.KeepClient.Arvados
249         arv.ApiToken = tok
250         arv.RequestID = req.Header.Get("X-Request-Id")
251         user = &arvados.User{}
252         userCurrentError := arv.Call("GET", "users", "", "current", nil, user)
253         err = userCurrentError
254         if err != nil && op == "read" {
255                 apiError, ok := err.(arvadosclient.APIServerError)
256                 if ok && apiError.HttpStatusCode == http.StatusForbidden {
257                         // If it was a scoped "sharing" token it will
258                         // return 403 instead of 401 for the current
259                         // user check.  If it is a download operation
260                         // and they have permission to read the
261                         // keep_services table, we can allow it.
262                         err = arv.Call("HEAD", "keep_services", "", "accessible", nil, nil)
263                 }
264         }
265         if err != nil {
266                 log.Printf("%s: CheckAuthorizationHeader error: %v", GetRemoteAddress(req), err)
267                 return false, "", nil
268         }
269
270         if userCurrentError == nil && user.IsAdmin {
271                 // checking userCurrentError is probably redundant,
272                 // IsAdmin would be false anyway. But can't hurt.
273                 if op == "read" && !h.cluster.Collections.KeepproxyPermission.Admin.Download {
274                         return false, "", nil
275                 }
276                 if op == "write" && !h.cluster.Collections.KeepproxyPermission.Admin.Upload {
277                         return false, "", nil
278                 }
279         } else {
280                 if op == "read" && !h.cluster.Collections.KeepproxyPermission.User.Download {
281                         return false, "", nil
282                 }
283                 if op == "write" && !h.cluster.Collections.KeepproxyPermission.User.Upload {
284                         return false, "", nil
285                 }
286         }
287
288         // Success!  Update cache
289         h.APITokenCache.RememberToken(op+":"+tok, user)
290
291         return true, tok, user
292 }
293
294 // We need to make a private copy of the default http transport early
295 // in initialization, then make copies of our private copy later. It
296 // won't be safe to copy http.DefaultTransport itself later, because
297 // its private mutexes might have already been used. (Without this,
298 // the test suite sometimes panics "concurrent map writes" in
299 // net/http.(*Transport).removeIdleConnLocked().)
300 var defaultTransport = *(http.DefaultTransport.(*http.Transport))
301
302 type proxyHandler struct {
303         http.Handler
304         *keepclient.KeepClient
305         *APITokenCache
306         timeout   time.Duration
307         transport *http.Transport
308         logger    log.FieldLogger
309         cluster   *arvados.Cluster
310 }
311
312 // MakeRESTRouter returns an http.Handler that passes GET and PUT
313 // requests to the appropriate handlers.
314 func MakeRESTRouter(kc *keepclient.KeepClient, timeout time.Duration, cluster *arvados.Cluster, logger log.FieldLogger) http.Handler {
315         rest := mux.NewRouter()
316
317         transport := defaultTransport
318         transport.DialContext = (&net.Dialer{
319                 Timeout:   keepclient.DefaultConnectTimeout,
320                 KeepAlive: keepclient.DefaultKeepAlive,
321                 DualStack: true,
322         }).DialContext
323         transport.TLSClientConfig = arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure)
324         transport.TLSHandshakeTimeout = keepclient.DefaultTLSHandshakeTimeout
325
326         cacheQ, err := lru.New2Q(500)
327         if err != nil {
328                 panic("Could not create 2Q")
329         }
330
331         h := &proxyHandler{
332                 Handler:    rest,
333                 KeepClient: kc,
334                 timeout:    timeout,
335                 transport:  &transport,
336                 APITokenCache: &APITokenCache{
337                         tokens:     cacheQ,
338                         expireTime: 300,
339                 },
340                 logger:  logger,
341                 cluster: cluster,
342         }
343
344         rest.HandleFunc(`/{locator:[0-9a-f]{32}\+.*}`, h.Get).Methods("GET", "HEAD")
345         rest.HandleFunc(`/{locator:[0-9a-f]{32}}`, h.Get).Methods("GET", "HEAD")
346
347         // List all blocks
348         rest.HandleFunc(`/index`, h.Index).Methods("GET")
349
350         // List blocks whose hash has the given prefix
351         rest.HandleFunc(`/index/{prefix:[0-9a-f]{0,32}}`, h.Index).Methods("GET")
352
353         rest.HandleFunc(`/{locator:[0-9a-f]{32}\+.*}`, h.Put).Methods("PUT")
354         rest.HandleFunc(`/{locator:[0-9a-f]{32}}`, h.Put).Methods("PUT")
355         rest.HandleFunc(`/`, h.Put).Methods("POST")
356         rest.HandleFunc(`/{any}`, h.Options).Methods("OPTIONS")
357         rest.HandleFunc(`/`, h.Options).Methods("OPTIONS")
358
359         rest.Handle("/_health/{check}", &health.Handler{
360                 Token:  cluster.ManagementToken,
361                 Prefix: "/_health/",
362         }).Methods("GET")
363
364         rest.NotFoundHandler = InvalidPathHandler{}
365         return h
366 }
367
368 var errLoopDetected = errors.New("loop detected")
369
370 func (h *proxyHandler) checkLoop(resp http.ResponseWriter, req *http.Request) error {
371         if via := req.Header.Get("Via"); strings.Index(via, " "+viaAlias) >= 0 {
372                 h.logger.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)
373                 http.Error(resp, errLoopDetected.Error(), http.StatusInternalServerError)
374                 return errLoopDetected
375         }
376         return nil
377 }
378
379 func SetCorsHeaders(resp http.ResponseWriter) {
380         resp.Header().Set("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, OPTIONS")
381         resp.Header().Set("Access-Control-Allow-Origin", "*")
382         resp.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Length, Content-Type, X-Keep-Desired-Replicas")
383         resp.Header().Set("Access-Control-Max-Age", "86486400")
384 }
385
386 type InvalidPathHandler struct{}
387
388 func (InvalidPathHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
389         log.Printf("%s: %s %s unroutable", GetRemoteAddress(req), req.Method, req.URL.Path)
390         http.Error(resp, "Bad request", http.StatusBadRequest)
391 }
392
393 func (h *proxyHandler) Options(resp http.ResponseWriter, req *http.Request) {
394         log.Printf("%s: %s %s", GetRemoteAddress(req), req.Method, req.URL.Path)
395         SetCorsHeaders(resp)
396 }
397
398 var errBadAuthorizationHeader = errors.New("Missing or invalid Authorization header, or method not allowed")
399 var errContentLengthMismatch = errors.New("Actual length != expected content length")
400 var errMethodNotSupported = errors.New("Method not supported")
401
402 var removeHint, _ = regexp.Compile("\\+K@[a-z0-9]{5}(\\+|$)")
403
404 func (h *proxyHandler) Get(resp http.ResponseWriter, req *http.Request) {
405         if err := h.checkLoop(resp, req); err != nil {
406                 return
407         }
408         SetCorsHeaders(resp)
409         resp.Header().Set("Via", req.Proto+" "+viaAlias)
410
411         locator := mux.Vars(req)["locator"]
412         var err error
413         var status int
414         var expectLength, responseLength int64
415         var proxiedURI = "-"
416
417         defer func() {
418                 log.Println(GetRemoteAddress(req), req.Method, req.URL.Path, status, expectLength, responseLength, proxiedURI, err)
419                 if status != http.StatusOK {
420                         http.Error(resp, err.Error(), status)
421                 }
422         }()
423
424         kc := h.makeKeepClient(req)
425
426         var pass bool
427         var tok string
428         var user *arvados.User
429         if pass, tok, user = h.CheckAuthorizationHeader(req); !pass {
430                 status, err = http.StatusForbidden, errBadAuthorizationHeader
431                 return
432         }
433
434         // Copy ArvadosClient struct and use the client's API token
435         arvclient := *kc.Arvados
436         arvclient.ApiToken = tok
437         kc.Arvados = &arvclient
438
439         var reader io.ReadCloser
440
441         locator = removeHint.ReplaceAllString(locator, "$1")
442
443         if locator != "" {
444                 parts := strings.SplitN(locator, "+", 3)
445                 if len(parts) >= 2 {
446                         logger := h.logger
447                         if user != nil {
448                                 logger = logger.WithField("user_uuid", user.UUID).
449                                         WithField("user_full_name", user.FullName)
450                         }
451                         logger.WithField("locator", fmt.Sprintf("%s+%s", parts[0], parts[1])).Infof("Block download")
452                 }
453         }
454
455         switch req.Method {
456         case "HEAD":
457                 expectLength, proxiedURI, err = kc.Ask(locator)
458         case "GET":
459                 reader, expectLength, proxiedURI, err = kc.Get(locator)
460                 if reader != nil {
461                         defer reader.Close()
462                 }
463         default:
464                 status, err = http.StatusNotImplemented, errMethodNotSupported
465                 return
466         }
467
468         if expectLength == -1 {
469                 log.Println("Warning:", GetRemoteAddress(req), req.Method, proxiedURI, "Content-Length not provided")
470         }
471
472         switch respErr := err.(type) {
473         case nil:
474                 status = http.StatusOK
475                 resp.Header().Set("Content-Length", fmt.Sprint(expectLength))
476                 switch req.Method {
477                 case "HEAD":
478                         responseLength = 0
479                 case "GET":
480                         responseLength, err = io.Copy(resp, reader)
481                         if err == nil && expectLength > -1 && responseLength != expectLength {
482                                 err = errContentLengthMismatch
483                         }
484                 }
485         case keepclient.Error:
486                 if respErr == keepclient.BlockNotFound {
487                         status = http.StatusNotFound
488                 } else if respErr.Temporary() {
489                         status = http.StatusBadGateway
490                 } else {
491                         status = 422
492                 }
493         default:
494                 status = http.StatusInternalServerError
495         }
496 }
497
498 var errLengthRequired = errors.New(http.StatusText(http.StatusLengthRequired))
499 var errLengthMismatch = errors.New("Locator size hint does not match Content-Length header")
500
501 func (h *proxyHandler) Put(resp http.ResponseWriter, req *http.Request) {
502         if err := h.checkLoop(resp, req); err != nil {
503                 return
504         }
505         SetCorsHeaders(resp)
506         resp.Header().Set("Via", "HTTP/1.1 "+viaAlias)
507
508         kc := h.makeKeepClient(req)
509
510         var err error
511         var expectLength int64
512         var status = http.StatusInternalServerError
513         var wroteReplicas int
514         var locatorOut string = "-"
515
516         defer func() {
517                 log.Println(GetRemoteAddress(req), req.Method, req.URL.Path, status, expectLength, kc.Want_replicas, wroteReplicas, locatorOut, err)
518                 if status != http.StatusOK {
519                         http.Error(resp, err.Error(), status)
520                 }
521         }()
522
523         locatorIn := mux.Vars(req)["locator"]
524
525         // Check if the client specified storage classes
526         if req.Header.Get("X-Keep-Storage-Classes") != "" {
527                 var scl []string
528                 for _, sc := range strings.Split(req.Header.Get("X-Keep-Storage-Classes"), ",") {
529                         scl = append(scl, strings.Trim(sc, " "))
530                 }
531                 kc.StorageClasses = scl
532         }
533
534         _, err = fmt.Sscanf(req.Header.Get("Content-Length"), "%d", &expectLength)
535         if err != nil || expectLength < 0 {
536                 err = errLengthRequired
537                 status = http.StatusLengthRequired
538                 return
539         }
540
541         if locatorIn != "" {
542                 var loc *keepclient.Locator
543                 if loc, err = keepclient.MakeLocator(locatorIn); err != nil {
544                         status = http.StatusBadRequest
545                         return
546                 } else if loc.Size > 0 && int64(loc.Size) != expectLength {
547                         err = errLengthMismatch
548                         status = http.StatusBadRequest
549                         return
550                 }
551         }
552
553         var pass bool
554         var tok string
555         var user *arvados.User
556         if pass, tok, user = h.CheckAuthorizationHeader(req); !pass {
557                 err = errBadAuthorizationHeader
558                 status = http.StatusForbidden
559                 return
560         }
561
562         // Copy ArvadosClient struct and use the client's API token
563         arvclient := *kc.Arvados
564         arvclient.ApiToken = tok
565         kc.Arvados = &arvclient
566
567         // Check if the client specified the number of replicas
568         if req.Header.Get("X-Keep-Desired-Replicas") != "" {
569                 var r int
570                 _, err := fmt.Sscanf(req.Header.Get(keepclient.XKeepDesiredReplicas), "%d", &r)
571                 if err == nil {
572                         kc.Want_replicas = r
573                 }
574         }
575
576         // Now try to put the block through
577         if locatorIn == "" {
578                 bytes, err2 := ioutil.ReadAll(req.Body)
579                 if err2 != nil {
580                         err = fmt.Errorf("Error reading request body: %s", err2)
581                         status = http.StatusInternalServerError
582                         return
583                 }
584                 locatorOut, wroteReplicas, err = kc.PutB(bytes)
585         } else {
586                 locatorOut, wroteReplicas, err = kc.PutHR(locatorIn, req.Body, expectLength)
587         }
588
589         if locatorOut != "" {
590                 parts := strings.SplitN(locatorOut, "+", 3)
591                 if len(parts) >= 2 {
592                         logger := h.logger
593                         if user != nil {
594                                 logger = logger.WithField("user_uuid", user.UUID).
595                                         WithField("user_full_name", user.FullName)
596                         }
597                         logger.WithField("locator", fmt.Sprintf("%s+%s", parts[0], parts[1])).Infof("Block upload")
598                 }
599         }
600
601         // Tell the client how many successful PUTs we accomplished
602         resp.Header().Set(keepclient.XKeepReplicasStored, fmt.Sprintf("%d", wroteReplicas))
603
604         switch err.(type) {
605         case nil:
606                 status = http.StatusOK
607                 _, err = io.WriteString(resp, locatorOut)
608
609         case keepclient.OversizeBlockError:
610                 // Too much data
611                 status = http.StatusRequestEntityTooLarge
612
613         case keepclient.InsufficientReplicasError:
614                 if wroteReplicas > 0 {
615                         // At least one write is considered success.  The
616                         // client can decide if getting less than the number of
617                         // replications it asked for is a fatal error.
618                         status = http.StatusOK
619                         _, err = io.WriteString(resp, locatorOut)
620                 } else {
621                         status = http.StatusServiceUnavailable
622                 }
623
624         default:
625                 status = http.StatusBadGateway
626         }
627 }
628
629 // ServeHTTP implementation for IndexHandler
630 // Supports only GET requests for /index/{prefix:[0-9a-f]{0,32}}
631 // For each keep server found in LocalRoots:
632 //   Invokes GetIndex using keepclient
633 //   Expects "complete" response (terminating with blank new line)
634 //   Aborts on any errors
635 // Concatenates responses from all those keep servers and returns
636 func (h *proxyHandler) Index(resp http.ResponseWriter, req *http.Request) {
637         SetCorsHeaders(resp)
638
639         prefix := mux.Vars(req)["prefix"]
640         var err error
641         var status int
642
643         defer func() {
644                 if status != http.StatusOK {
645                         http.Error(resp, err.Error(), status)
646                 }
647         }()
648
649         kc := h.makeKeepClient(req)
650         ok, token, _ := h.CheckAuthorizationHeader(req)
651         if !ok {
652                 status, err = http.StatusForbidden, errBadAuthorizationHeader
653                 return
654         }
655
656         // Copy ArvadosClient struct and use the client's API token
657         arvclient := *kc.Arvados
658         arvclient.ApiToken = token
659         kc.Arvados = &arvclient
660
661         // Only GET method is supported
662         if req.Method != "GET" {
663                 status, err = http.StatusNotImplemented, errMethodNotSupported
664                 return
665         }
666
667         // Get index from all LocalRoots and write to resp
668         var reader io.Reader
669         for uuid := range kc.LocalRoots() {
670                 reader, err = kc.GetIndex(uuid, prefix)
671                 if err != nil {
672                         status = http.StatusBadGateway
673                         return
674                 }
675
676                 _, err = io.Copy(resp, reader)
677                 if err != nil {
678                         status = http.StatusBadGateway
679                         return
680                 }
681         }
682
683         // Got index from all the keep servers and wrote to resp
684         status = http.StatusOK
685         resp.Write([]byte("\n"))
686 }
687
688 func (h *proxyHandler) makeKeepClient(req *http.Request) *keepclient.KeepClient {
689         kc := *h.KeepClient
690         kc.RequestID = req.Header.Get("X-Request-Id")
691         kc.HTTPClient = &proxyClient{
692                 client: &http.Client{
693                         Timeout:   h.timeout,
694                         Transport: h.transport,
695                 },
696                 proto: req.Proto,
697         }
698         return &kc
699 }