-
Notifications
You must be signed in to change notification settings - Fork 43
/
gcsindex.go
96 lines (78 loc) · 2.47 KB
/
gcsindex.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package desync
import (
"context"
"io"
"net/url"
"path"
"cloud.google.com/go/storage"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
// GCIndexStore is a read-write index store with Google Storage backing
type GCIndexStore struct {
GCStoreBase
}
// NewGCIndexStore creates an index store with Google Storage backing. The URL
// should be provided like this: gc://bucket/prefix
func NewGCIndexStore(location *url.URL, opt StoreOptions) (s GCIndexStore, e error) {
b, err := NewGCStoreBase(location, opt)
if err != nil {
return s, err
}
return GCIndexStore{b}, nil
}
// GetIndexReader returns a reader for an index from an Google Storage store. Fails if the specified index
// file does not exist.
func (s GCIndexStore) GetIndexReader(name string) (r io.ReadCloser, err error) {
ctx := context.TODO()
var (
log = Log.WithFields(logrus.Fields{
"bucket": s.bucket,
"name": s.prefix + name,
})
)
obj, err := s.client.Object(s.prefix + name).NewReader(ctx)
if err == storage.ErrObjectNotExist {
log.Warning("Unable to create reader for object in GCS bucket; the object may not exist, or the bucket may not exist, or you may not have permission to access it")
return nil, errors.Wrap(err, s.String())
} else if err != nil {
log.WithError(err).Error("Error when creating index reader from GCS bucket")
return nil, errors.Wrap(err, s.String())
}
log.Debug("Created index reader from GCS bucket")
return obj, nil
}
// GetIndex returns an Index structure from the store
func (s GCIndexStore) GetIndex(name string) (i Index, e error) {
obj, err := s.GetIndexReader(name)
if err != nil {
return i, err
}
defer obj.Close()
return IndexFromReader(obj)
}
// StoreIndex writes the index file to the Google Storage store
func (s GCIndexStore) StoreIndex(name string, idx Index) error {
ctx := context.TODO()
var (
log = Log.WithFields(logrus.Fields{
"bucket": s.bucket,
"name": s.prefix + name,
})
)
w := s.client.Object(s.prefix + name).NewWriter(ctx)
w.ContentType = "application/octet-stream"
_, err := idx.WriteTo(w)
if err != nil {
log.WithError(err).Error("Error when copying data from local filesystem to object in GCS bucket")
w.Close()
return errors.Wrap(err, path.Base(s.Location))
}
err = w.Close()
if err != nil {
log.WithError(err).Error("Error when finalizing copying of data from local filesystem to object in GCS bucket")
return errors.Wrap(err, path.Base(s.Location))
}
log.Debug("Index written to GCS bucket")
return nil
}