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