21227: Fix copied mutexes.
[arvados.git] / sdk / go / keepclient / keepclient.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: Apache-2.0
4
5 // Package keepclient provides low-level Get/Put primitives for accessing
6 // Arvados Keep blocks.
7 package keepclient
8
9 import (
10         "bytes"
11         "context"
12         "crypto/md5"
13         "errors"
14         "fmt"
15         "io"
16         "io/ioutil"
17         "net"
18         "net/http"
19         "regexp"
20         "strconv"
21         "strings"
22         "sync"
23         "time"
24
25         "git.arvados.org/arvados.git/sdk/go/arvados"
26         "git.arvados.org/arvados.git/sdk/go/arvadosclient"
27         "git.arvados.org/arvados.git/sdk/go/httpserver"
28 )
29
30 // BLOCKSIZE defines the length of a Keep "block", which is 64MB.
31 const BLOCKSIZE = 64 * 1024 * 1024
32
33 var (
34         DefaultRequestTimeout      = 20 * time.Second
35         DefaultConnectTimeout      = 2 * time.Second
36         DefaultTLSHandshakeTimeout = 4 * time.Second
37         DefaultKeepAlive           = 180 * time.Second
38
39         DefaultProxyRequestTimeout      = 300 * time.Second
40         DefaultProxyConnectTimeout      = 30 * time.Second
41         DefaultProxyTLSHandshakeTimeout = 10 * time.Second
42         DefaultProxyKeepAlive           = 120 * time.Second
43 )
44
45 // Error interface with an error and boolean indicating whether the error is temporary
46 type Error interface {
47         error
48         Temporary() bool
49 }
50
51 // multipleResponseError is of type Error
52 type multipleResponseError struct {
53         error
54         isTemp bool
55 }
56
57 func (e *multipleResponseError) Temporary() bool {
58         return e.isTemp
59 }
60
61 // BlockNotFound is a multipleResponseError where isTemp is false
62 var BlockNotFound = &ErrNotFound{multipleResponseError{
63         error:  errors.New("Block not found"),
64         isTemp: false,
65 }}
66
67 // ErrNotFound is a multipleResponseError where isTemp can be true or false
68 type ErrNotFound struct {
69         multipleResponseError
70 }
71
72 type InsufficientReplicasError struct{ error }
73
74 type OversizeBlockError struct{ error }
75
76 var ErrOversizeBlock = OversizeBlockError{error: errors.New("Exceeded maximum block size (" + strconv.Itoa(BLOCKSIZE) + ")")}
77 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
78 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
79 var InvalidLocatorError = errors.New("Invalid locator")
80
81 // ErrNoSuchKeepServer is returned when GetIndex is invoked with a UUID with no matching keep server
82 var ErrNoSuchKeepServer = errors.New("No keep server matching the given UUID is found")
83
84 // ErrIncompleteIndex is returned when the Index response does not end with a new empty line
85 var ErrIncompleteIndex = errors.New("Got incomplete index")
86
87 const (
88         XKeepDesiredReplicas         = "X-Keep-Desired-Replicas"
89         XKeepReplicasStored          = "X-Keep-Replicas-Stored"
90         XKeepStorageClasses          = "X-Keep-Storage-Classes"
91         XKeepStorageClassesConfirmed = "X-Keep-Storage-Classes-Confirmed"
92 )
93
94 type HTTPClient interface {
95         Do(*http.Request) (*http.Response, error)
96 }
97
98 // KeepClient holds information about Arvados and Keep servers.
99 type KeepClient struct {
100         Arvados               *arvadosclient.ArvadosClient
101         Want_replicas         int
102         localRoots            map[string]string
103         writableLocalRoots    map[string]string
104         gatewayRoots          map[string]string
105         lock                  sync.RWMutex
106         HTTPClient            HTTPClient
107         Retries               int
108         BlockCache            *BlockCache
109         RequestID             string
110         StorageClasses        []string
111         DefaultStorageClasses []string // Set by cluster's exported config
112
113         // set to 1 if all writable services are of disk type, otherwise 0
114         replicasPerService int
115
116         // Any non-disk typed services found in the list of keepservers?
117         foundNonDiskSvc bool
118
119         // Disable automatic discovery of keep services
120         disableDiscovery bool
121 }
122
123 func (kc *KeepClient) Clone() *KeepClient {
124         kc.lock.Lock()
125         defer kc.lock.Unlock()
126         return &KeepClient{
127                 Arvados:               kc.Arvados,
128                 Want_replicas:         kc.Want_replicas,
129                 localRoots:            kc.localRoots,
130                 writableLocalRoots:    kc.writableLocalRoots,
131                 gatewayRoots:          kc.gatewayRoots,
132                 HTTPClient:            kc.HTTPClient,
133                 Retries:               kc.Retries,
134                 BlockCache:            kc.BlockCache,
135                 RequestID:             kc.RequestID,
136                 StorageClasses:        kc.StorageClasses,
137                 DefaultStorageClasses: kc.DefaultStorageClasses,
138                 replicasPerService:    kc.replicasPerService,
139                 foundNonDiskSvc:       kc.foundNonDiskSvc,
140                 disableDiscovery:      kc.disableDiscovery,
141         }
142 }
143
144 func (kc *KeepClient) loadDefaultClasses() error {
145         scData, err := kc.Arvados.ClusterConfig("StorageClasses")
146         if err != nil {
147                 return err
148         }
149         classes := scData.(map[string]interface{})
150         for scName := range classes {
151                 scConf, _ := classes[scName].(map[string]interface{})
152                 isDefault, ok := scConf["Default"].(bool)
153                 if ok && isDefault {
154                         kc.DefaultStorageClasses = append(kc.DefaultStorageClasses, scName)
155                 }
156         }
157         return nil
158 }
159
160 // MakeKeepClient creates a new KeepClient, loads default storage classes, calls
161 // DiscoverKeepServices(), and returns when the client is ready to
162 // use.
163 func MakeKeepClient(arv *arvadosclient.ArvadosClient) (*KeepClient, error) {
164         kc := New(arv)
165         return kc, kc.discoverServices()
166 }
167
168 // New creates a new KeepClient. Service discovery will occur on the
169 // next read/write operation.
170 func New(arv *arvadosclient.ArvadosClient) *KeepClient {
171         defaultReplicationLevel := 2
172         value, err := arv.Discovery("defaultCollectionReplication")
173         if err == nil {
174                 v, ok := value.(float64)
175                 if ok && v > 0 {
176                         defaultReplicationLevel = int(v)
177                 }
178         }
179         kc := &KeepClient{
180                 Arvados:       arv,
181                 Want_replicas: defaultReplicationLevel,
182                 Retries:       2,
183         }
184         err = kc.loadDefaultClasses()
185         if err != nil {
186                 DebugPrintf("DEBUG: Unable to load the default storage classes cluster config")
187         }
188         return kc
189 }
190
191 // PutHR puts a block given the block hash, a reader, and the number of bytes
192 // to read from the reader (which must be between 0 and BLOCKSIZE).
193 //
194 // Returns the locator for the written block, the number of replicas
195 // written, and an error.
196 //
197 // Returns an InsufficientReplicasError if 0 <= replicas <
198 // kc.Wants_replicas.
199 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
200         resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
201                 Hash:     hash,
202                 Reader:   r,
203                 DataSize: int(dataBytes),
204         })
205         return resp.Locator, resp.Replicas, err
206 }
207
208 // PutHB writes a block to Keep. The hash of the bytes is given in
209 // hash, and the data is given in buf.
210 //
211 // Return values are the same as for PutHR.
212 func (kc *KeepClient) PutHB(hash string, buf []byte) (string, int, error) {
213         resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
214                 Hash: hash,
215                 Data: buf,
216         })
217         return resp.Locator, resp.Replicas, err
218 }
219
220 // PutB writes a block to Keep. It computes the hash itself.
221 //
222 // Return values are the same as for PutHR.
223 func (kc *KeepClient) PutB(buffer []byte) (string, int, error) {
224         resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
225                 Data: buffer,
226         })
227         return resp.Locator, resp.Replicas, err
228 }
229
230 // PutR writes a block to Keep. It first reads all data from r into a buffer
231 // in order to compute the hash.
232 //
233 // Return values are the same as for PutHR.
234 //
235 // If the block hash and data size are known, PutHR is more efficient.
236 func (kc *KeepClient) PutR(r io.Reader) (locator string, replicas int, err error) {
237         buffer, err := ioutil.ReadAll(r)
238         if err != nil {
239                 return "", 0, err
240         }
241         return kc.PutB(buffer)
242 }
243
244 func (kc *KeepClient) getOrHead(method string, locator string, header http.Header) (io.ReadCloser, int64, string, http.Header, error) {
245         if strings.HasPrefix(locator, "d41d8cd98f00b204e9800998ecf8427e+0") {
246                 return ioutil.NopCloser(bytes.NewReader(nil)), 0, "", nil, nil
247         }
248
249         reqid := kc.getRequestID()
250
251         var expectLength int64
252         if parts := strings.SplitN(locator, "+", 3); len(parts) < 2 {
253                 expectLength = -1
254         } else if n, err := strconv.ParseInt(parts[1], 10, 64); err != nil {
255                 expectLength = -1
256         } else {
257                 expectLength = n
258         }
259
260         var errs []string
261
262         triesRemaining := 1 + kc.Retries
263
264         serversToTry := kc.getSortedRoots(locator)
265
266         numServers := len(serversToTry)
267         count404 := 0
268
269         var retryList []string
270
271         for triesRemaining > 0 {
272                 triesRemaining--
273                 retryList = nil
274
275                 for _, host := range serversToTry {
276                         url := host + "/" + locator
277
278                         req, err := http.NewRequest(method, url, nil)
279                         if err != nil {
280                                 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
281                                 continue
282                         }
283                         for k, v := range header {
284                                 req.Header[k] = append([]string(nil), v...)
285                         }
286                         if req.Header.Get("Authorization") == "" {
287                                 req.Header.Set("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
288                         }
289                         if req.Header.Get("X-Request-Id") == "" {
290                                 req.Header.Set("X-Request-Id", reqid)
291                         }
292                         resp, err := kc.httpClient().Do(req)
293                         if err != nil {
294                                 // Probably a network error, may be transient,
295                                 // can try again.
296                                 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
297                                 retryList = append(retryList, host)
298                                 continue
299                         }
300                         if resp.StatusCode != http.StatusOK {
301                                 var respbody []byte
302                                 respbody, _ = ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 4096})
303                                 resp.Body.Close()
304                                 errs = append(errs, fmt.Sprintf("%s: HTTP %d %q",
305                                         url, resp.StatusCode, bytes.TrimSpace(respbody)))
306
307                                 if resp.StatusCode == 408 ||
308                                         resp.StatusCode == 429 ||
309                                         resp.StatusCode >= 500 {
310                                         // Timeout, too many requests, or other
311                                         // server side failure, transient
312                                         // error, can try again.
313                                         retryList = append(retryList, host)
314                                 } else if resp.StatusCode == 404 {
315                                         count404++
316                                 }
317                                 continue
318                         }
319                         if expectLength < 0 {
320                                 if resp.ContentLength < 0 {
321                                         resp.Body.Close()
322                                         return nil, 0, "", nil, fmt.Errorf("error reading %q: no size hint, no Content-Length header in response", locator)
323                                 }
324                                 expectLength = resp.ContentLength
325                         } else if resp.ContentLength >= 0 && expectLength != resp.ContentLength {
326                                 resp.Body.Close()
327                                 return nil, 0, "", nil, fmt.Errorf("error reading %q: size hint %d != Content-Length %d", locator, expectLength, resp.ContentLength)
328                         }
329                         // Success
330                         if method == "GET" {
331                                 return HashCheckingReader{
332                                         Reader: resp.Body,
333                                         Hash:   md5.New(),
334                                         Check:  locator[0:32],
335                                 }, expectLength, url, resp.Header, nil
336                         }
337                         resp.Body.Close()
338                         return nil, expectLength, url, resp.Header, nil
339                 }
340                 serversToTry = retryList
341         }
342         DebugPrintf("DEBUG: %s %s failed: %v", method, locator, errs)
343
344         var err error
345         if count404 == numServers {
346                 err = BlockNotFound
347         } else {
348                 err = &ErrNotFound{multipleResponseError{
349                         error:  fmt.Errorf("%s %s failed: %v", method, locator, errs),
350                         isTemp: len(serversToTry) > 0,
351                 }}
352         }
353         return nil, 0, "", nil, err
354 }
355
356 // LocalLocator returns a locator equivalent to the one supplied, but
357 // with a valid signature from the local cluster. If the given locator
358 // already has a local signature, it is returned unchanged.
359 func (kc *KeepClient) LocalLocator(locator string) (string, error) {
360         if !strings.Contains(locator, "+R") {
361                 // Either it has +A, or it's unsigned and we assume
362                 // it's a local locator on a site with signatures
363                 // disabled.
364                 return locator, nil
365         }
366         sighdr := fmt.Sprintf("local, time=%s", time.Now().UTC().Format(time.RFC3339))
367         _, _, url, hdr, err := kc.getOrHead("HEAD", locator, http.Header{"X-Keep-Signature": []string{sighdr}})
368         if err != nil {
369                 return "", err
370         }
371         loc := hdr.Get("X-Keep-Locator")
372         if loc == "" {
373                 return "", fmt.Errorf("missing X-Keep-Locator header in HEAD response from %s", url)
374         }
375         return loc, nil
376 }
377
378 // Get retrieves a block, given a locator. Returns a reader, the
379 // expected data length, the URL the block is being fetched from, and
380 // an error.
381 //
382 // If the block checksum does not match, the final Read() on the
383 // reader returned by this method will return a BadChecksum error
384 // instead of EOF.
385 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
386         rdr, size, url, _, err := kc.getOrHead("GET", locator, nil)
387         return rdr, size, url, err
388 }
389
390 // ReadAt retrieves a portion of block from the cache if it's
391 // present, otherwise from the network.
392 func (kc *KeepClient) ReadAt(locator string, p []byte, off int) (int, error) {
393         return kc.cache().ReadAt(kc, locator, p, off)
394 }
395
396 // Ask verifies that a block with the given hash is available and
397 // readable, according to at least one Keep service. Unlike Get, it
398 // does not retrieve the data or verify that the data content matches
399 // the hash specified by the locator.
400 //
401 // Returns the data size (content length) reported by the Keep service
402 // and the URI reporting the data size.
403 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
404         _, size, url, _, err := kc.getOrHead("HEAD", locator, nil)
405         return size, url, err
406 }
407
408 // GetIndex retrieves a list of blocks stored on the given server whose hashes
409 // begin with the given prefix. The returned reader will return an error (other
410 // than EOF) if the complete index cannot be retrieved.
411 //
412 // This is meant to be used only by system components and admin tools.
413 // It will return an error unless the client is using a "data manager token"
414 // recognized by the Keep services.
415 func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error) {
416         url := kc.LocalRoots()[keepServiceUUID]
417         if url == "" {
418                 return nil, ErrNoSuchKeepServer
419         }
420
421         url += "/index"
422         if prefix != "" {
423                 url += "/" + prefix
424         }
425
426         req, err := http.NewRequest("GET", url, nil)
427         if err != nil {
428                 return nil, err
429         }
430
431         req.Header.Add("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
432         req.Header.Set("X-Request-Id", kc.getRequestID())
433         resp, err := kc.httpClient().Do(req)
434         if err != nil {
435                 return nil, err
436         }
437
438         defer resp.Body.Close()
439
440         if resp.StatusCode != http.StatusOK {
441                 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
442         }
443
444         var respBody []byte
445         respBody, err = ioutil.ReadAll(resp.Body)
446         if err != nil {
447                 return nil, err
448         }
449
450         // Got index; verify that it is complete
451         // The response should be "\n" if no locators matched the prefix
452         // Else, it should be a list of locators followed by a blank line
453         if !bytes.Equal(respBody, []byte("\n")) && !bytes.HasSuffix(respBody, []byte("\n\n")) {
454                 return nil, ErrIncompleteIndex
455         }
456
457         // Got complete index; strip the trailing newline and send
458         return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
459 }
460
461 // LocalRoots returns the map of local (i.e., disk and proxy) Keep
462 // services: uuid -> baseURI.
463 func (kc *KeepClient) LocalRoots() map[string]string {
464         kc.discoverServices()
465         kc.lock.RLock()
466         defer kc.lock.RUnlock()
467         return kc.localRoots
468 }
469
470 // GatewayRoots returns the map of Keep remote gateway services:
471 // uuid -> baseURI.
472 func (kc *KeepClient) GatewayRoots() map[string]string {
473         kc.discoverServices()
474         kc.lock.RLock()
475         defer kc.lock.RUnlock()
476         return kc.gatewayRoots
477 }
478
479 // WritableLocalRoots returns the map of writable local Keep services:
480 // uuid -> baseURI.
481 func (kc *KeepClient) WritableLocalRoots() map[string]string {
482         kc.discoverServices()
483         kc.lock.RLock()
484         defer kc.lock.RUnlock()
485         return kc.writableLocalRoots
486 }
487
488 // SetServiceRoots disables service discovery and updates the
489 // localRoots and gatewayRoots maps, without disrupting operations
490 // that are already in progress.
491 //
492 // The supplied maps must not be modified after calling
493 // SetServiceRoots.
494 func (kc *KeepClient) SetServiceRoots(locals, writables, gateways map[string]string) {
495         kc.disableDiscovery = true
496         kc.setServiceRoots(locals, writables, gateways)
497 }
498
499 func (kc *KeepClient) setServiceRoots(locals, writables, gateways map[string]string) {
500         kc.lock.Lock()
501         defer kc.lock.Unlock()
502         kc.localRoots = locals
503         kc.writableLocalRoots = writables
504         kc.gatewayRoots = gateways
505 }
506
507 // getSortedRoots returns a list of base URIs of Keep services, in the
508 // order they should be attempted in order to retrieve content for the
509 // given locator.
510 func (kc *KeepClient) getSortedRoots(locator string) []string {
511         var found []string
512         for _, hint := range strings.Split(locator, "+") {
513                 if len(hint) < 7 || hint[0:2] != "K@" {
514                         // Not a service hint.
515                         continue
516                 }
517                 if len(hint) == 7 {
518                         // +K@abcde means fetch from proxy at
519                         // keep.abcde.arvadosapi.com
520                         found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
521                 } else if len(hint) == 29 {
522                         // +K@abcde-abcde-abcdeabcdeabcde means fetch
523                         // from gateway with given uuid
524                         if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
525                                 found = append(found, gwURI)
526                         }
527                         // else this hint is no use to us; carry on.
528                 }
529         }
530         // After trying all usable service hints, fall back to local roots.
531         found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
532         return found
533 }
534
535 func (kc *KeepClient) cache() *BlockCache {
536         if kc.BlockCache != nil {
537                 return kc.BlockCache
538         }
539         return DefaultBlockCache
540 }
541
542 func (kc *KeepClient) ClearBlockCache() {
543         kc.cache().Clear()
544 }
545
546 func (kc *KeepClient) SetStorageClasses(sc []string) {
547         // make a copy so the caller can't mess with it.
548         kc.StorageClasses = append([]string{}, sc...)
549 }
550
551 var (
552         // There are four global http.Client objects for the four
553         // possible permutations of TLS behavior (verify/skip-verify)
554         // and timeout settings (proxy/non-proxy).
555         defaultClient = map[bool]map[bool]HTTPClient{
556                 // defaultClient[false] is used for verified TLS reqs
557                 false: {},
558                 // defaultClient[true] is used for unverified
559                 // (insecure) TLS reqs
560                 true: {},
561         }
562         defaultClientMtx sync.Mutex
563 )
564
565 // httpClient returns the HTTPClient field if it's not nil, otherwise
566 // whichever of the four global http.Client objects is suitable for
567 // the current environment (i.e., TLS verification on/off, keep
568 // services are/aren't proxies).
569 func (kc *KeepClient) httpClient() HTTPClient {
570         if kc.HTTPClient != nil {
571                 return kc.HTTPClient
572         }
573         defaultClientMtx.Lock()
574         defer defaultClientMtx.Unlock()
575         if c, ok := defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc]; ok {
576                 return c
577         }
578
579         var requestTimeout, connectTimeout, keepAlive, tlsTimeout time.Duration
580         if kc.foundNonDiskSvc {
581                 // Use longer timeouts when connecting to a proxy,
582                 // because this usually means the intervening network
583                 // is slower.
584                 requestTimeout = DefaultProxyRequestTimeout
585                 connectTimeout = DefaultProxyConnectTimeout
586                 tlsTimeout = DefaultProxyTLSHandshakeTimeout
587                 keepAlive = DefaultProxyKeepAlive
588         } else {
589                 requestTimeout = DefaultRequestTimeout
590                 connectTimeout = DefaultConnectTimeout
591                 tlsTimeout = DefaultTLSHandshakeTimeout
592                 keepAlive = DefaultKeepAlive
593         }
594
595         c := &http.Client{
596                 Timeout: requestTimeout,
597                 // It's not safe to copy *http.DefaultTransport
598                 // because it has a mutex (which might be locked)
599                 // protecting a private map (which might not be nil).
600                 // So we build our own, using the Go 1.12 default
601                 // values, ignoring any changes the application has
602                 // made to http.DefaultTransport.
603                 Transport: &http.Transport{
604                         DialContext: (&net.Dialer{
605                                 Timeout:   connectTimeout,
606                                 KeepAlive: keepAlive,
607                                 DualStack: true,
608                         }).DialContext,
609                         MaxIdleConns:          100,
610                         IdleConnTimeout:       90 * time.Second,
611                         TLSHandshakeTimeout:   tlsTimeout,
612                         ExpectContinueTimeout: 1 * time.Second,
613                         TLSClientConfig:       arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure),
614                 },
615         }
616         defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc] = c
617         return c
618 }
619
620 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
621
622 func (kc *KeepClient) getRequestID() string {
623         if kc.RequestID != "" {
624                 return kc.RequestID
625         }
626         return reqIDGen.Next()
627 }
628
629 type Locator struct {
630         Hash  string
631         Size  int      // -1 if data size is not known
632         Hints []string // Including the size hint, if any
633 }
634
635 func (loc *Locator) String() string {
636         s := loc.Hash
637         if len(loc.Hints) > 0 {
638                 s = s + "+" + strings.Join(loc.Hints, "+")
639         }
640         return s
641 }
642
643 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
644
645 func MakeLocator(path string) (*Locator, error) {
646         sm := locatorMatcher.FindStringSubmatch(path)
647         if sm == nil {
648                 return nil, InvalidLocatorError
649         }
650         loc := Locator{Hash: sm[1], Size: -1}
651         if sm[2] != "" {
652                 loc.Hints = strings.Split(sm[3], "+")
653         } else {
654                 loc.Hints = []string{}
655         }
656         if len(loc.Hints) > 0 {
657                 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {
658                         loc.Size = size
659                 }
660         }
661         return &loc, nil
662 }