-
Notifications
You must be signed in to change notification settings - Fork 44
/
s3.go
227 lines (205 loc) · 6.09 KB
/
s3.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
package desync
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"net/url"
"strings"
minio "github.com/minio/minio-go/v6"
"github.com/minio/minio-go/v6/pkg/credentials"
"github.com/pkg/errors"
)
var _ WriteStore = S3Store{}
// S3StoreBase is the base object for all chunk and index stores with S3 backing
type S3StoreBase struct {
Location string
client *minio.Client
bucket string
prefix string
opt StoreOptions
converters Converters
}
// S3Store is a read-write store with S3 backing
type S3Store struct {
S3StoreBase
}
// NewS3StoreBase initializes a base object used for chunk or index stores backed by S3.
func NewS3StoreBase(u *url.URL, s3Creds *credentials.Credentials, region string, opt StoreOptions, lookupType minio.BucketLookupType) (S3StoreBase, error) {
var err error
s := S3StoreBase{Location: u.String(), opt: opt, converters: opt.converters()}
if !strings.HasPrefix(u.Scheme, "s3+http") {
return s, fmt.Errorf("invalid scheme '%s', expected 's3+http' or 's3+https'", u.Scheme)
}
var useSSL bool
if strings.Contains(u.Scheme, "https") {
useSSL = true
}
// Pull the bucket as well as the prefix from a path-style URL
bPath := strings.Trim(u.Path, "/")
if bPath == "" {
return s, fmt.Errorf("expected bucket name in path of '%s'", u.Scheme)
}
f := strings.Split(bPath, "/")
s.bucket = f[0]
s.prefix = strings.Join(f[1:], "/")
if s.prefix != "" {
s.prefix += "/"
}
s.client, err = minio.NewWithOptions(u.Host, &minio.Options{
Creds: s3Creds,
Secure: useSSL,
Region: region,
BucketLookup: lookupType,
})
if err != nil {
return s, errors.Wrap(err, u.String())
}
return s, nil
}
func (s S3StoreBase) String() string {
return s.Location
}
// Close the S3 base store. NOP operation but needed to implement the store interface.
func (s S3StoreBase) Close() error { return nil }
// NewS3Store creates a chunk store with S3 backing. The URL
// should be provided like this: s3+http://host:port/bucket
// Credentials are passed in via the environment variables S3_ACCESS_KEY
// and S3S3_SECRET_KEY, or via the desync config file.
func NewS3Store(location *url.URL, s3Creds *credentials.Credentials, region string, opt StoreOptions, lookupType minio.BucketLookupType) (s S3Store, e error) {
b, err := NewS3StoreBase(location, s3Creds, region, opt, lookupType)
if err != nil {
return s, err
}
return S3Store{b}, nil
}
// GetChunk reads and returns one chunk from the store
func (s S3Store) GetChunk(id ChunkID) (*Chunk, error) {
name := s.nameFromID(id)
var attempt int
retry:
attempt++
obj, err := s.client.GetObject(s.bucket, name, minio.GetObjectOptions{})
if err != nil {
if attempt <= s.opt.ErrorRetry {
goto retry
}
return nil, errors.Wrap(err, s.String())
}
defer obj.Close()
b, err := ioutil.ReadAll(obj)
if err != nil {
if attempt <= s.opt.ErrorRetry {
goto retry
}
if e, ok := err.(minio.ErrorResponse); ok {
switch e.Code {
case "NoSuchBucket":
err = fmt.Errorf("bucket '%s' does not exist", s.bucket)
case "NoSuchKey":
err = ChunkMissing{ID: id}
default: // Without ListBucket perms in AWS, we get Permission Denied for a missing chunk, not 404
err = errors.Wrap(err, fmt.Sprintf("chunk %s could not be retrieved from s3 store", id))
}
}
return nil, err
}
return NewChunkFromStorage(id, b, s.converters, s.opt.SkipVerify)
}
// StoreChunk adds a new chunk to the store
func (s S3Store) StoreChunk(chunk *Chunk) error {
contentType := "application/zstd"
name := s.nameFromID(chunk.ID())
b, err := chunk.Data()
if err != nil {
return err
}
b, err = s.converters.toStorage(b)
if err != nil {
return err
}
var attempt int
retry:
attempt++
_, err = s.client.PutObject(s.bucket, name, bytes.NewReader(b), int64(len(b)), minio.PutObjectOptions{ContentType: contentType})
if err != nil {
if attempt < s.opt.ErrorRetry {
goto retry
}
}
return errors.Wrap(err, s.String())
}
// HasChunk returns true if the chunk is in the store
func (s S3Store) HasChunk(id ChunkID) (bool, error) {
name := s.nameFromID(id)
_, err := s.client.StatObject(s.bucket, name, minio.StatObjectOptions{})
return err == nil, nil
}
// RemoveChunk deletes a chunk, typically an invalid one, from the filesystem.
// Used when verifying and repairing caches.
func (s S3Store) RemoveChunk(id ChunkID) error {
name := s.nameFromID(id)
return s.client.RemoveObject(s.bucket, name)
}
// Prune removes any chunks from the store that are not contained in a list (map)
func (s S3Store) Prune(ctx context.Context, ids map[ChunkID]struct{}) error {
doneCh := make(chan struct{})
defer close(doneCh)
objectCh := s.client.ListObjectsV2(s.bucket, s.prefix, true, doneCh)
for object := range objectCh {
if object.Err != nil {
return object.Err
}
// See if we're meant to stop
select {
case <-ctx.Done():
return Interrupted{}
default:
}
id, err := s.idFromName(object.Key)
if err != nil {
continue
}
// Drop the chunk if it's not on the list
if _, ok := ids[id]; !ok {
if err = s.RemoveChunk(id); err != nil {
return err
}
}
}
return nil
}
func (s S3Store) nameFromID(id ChunkID) string {
sID := id.String()
name := s.prefix + sID[0:4] + "/" + sID
if s.opt.Uncompressed {
name += UncompressedChunkExt
} else {
name += CompressedChunkExt
}
return name
}
func (s S3Store) idFromName(name string) (ChunkID, error) {
var n string
if s.opt.Uncompressed {
if !strings.HasSuffix(name, UncompressedChunkExt) {
return ChunkID{}, fmt.Errorf("object %s is not a chunk", name)
}
n = strings.TrimSuffix(strings.TrimPrefix(name, s.prefix), UncompressedChunkExt)
} else {
if !strings.HasSuffix(name, CompressedChunkExt) {
return ChunkID{}, fmt.Errorf("object %s is not a chunk", name)
}
n = strings.TrimSuffix(strings.TrimPrefix(name, s.prefix), CompressedChunkExt)
}
fragments := strings.Split(n, "/")
if len(fragments) != 2 {
return ChunkID{}, fmt.Errorf("incorrect chunk name for object %s", name)
}
idx := fragments[0]
sid := fragments[1]
if !strings.HasPrefix(sid, idx) {
return ChunkID{}, fmt.Errorf("incorrect chunk name for object %s", name)
}
return ChunkIDFromString(sid)
}