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