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