-
Notifications
You must be signed in to change notification settings - Fork 342
/
b2_storage.go
293 lines (231 loc) · 6.64 KB
/
b2_storage.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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
// Package b2 implements Storage based on an Backblaze B2 bucket.
package b2
import (
"context"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/pkg/errors"
"gopkg.in/kothar/go-backblaze.v0"
"github.com/kopia/kopia/internal/iocopy"
"github.com/kopia/kopia/internal/timestampmeta"
"github.com/kopia/kopia/repo/blob"
"github.com/kopia/kopia/repo/blob/retrying"
)
const (
b2storageType = "b2"
timeMapKey = "kopia-mtime" // case is important, must be all-lowercase
)
type b2Storage struct {
Options
cli *backblaze.B2
bucket *backblaze.Bucket
}
func (s *b2Storage) GetBlob(ctx context.Context, id blob.ID, offset, length int64, output blob.OutputBuffer) error {
fileName := s.getObjectNameString(id)
if offset < 0 {
return blob.ErrInvalidRange
}
output.Reset()
attempt := func() error {
var fileRange *backblaze.FileRange
if length > 0 {
fileRange = &backblaze.FileRange{
Start: offset,
End: offset + length - 1,
}
}
_, r, err := s.bucket.DownloadFileRangeByName(fileName, fileRange)
if err != nil {
return errors.Wrap(err, "DownloadFileRangeByName")
}
defer r.Close() //nolint:errcheck
if length == 0 {
return nil
}
// nolint:wrapcheck
return iocopy.JustCopy(output, r)
}
if err := attempt(); err != nil {
return translateError(err)
}
// nolint:wrapcheck
return blob.EnsureLengthExactly(output.Length(), length)
}
func (s *b2Storage) resolveFileID(fileName string) (string, error) {
resp, err := s.bucket.ListFileVersions(fileName, "", 1)
if err != nil {
return "", errors.Wrap(err, "ListFileVersions")
}
if len(resp.Files) > 0 {
if resp.Files[0].Name == fileName && resp.Files[0].Action == backblaze.Upload {
return resp.Files[0].ID, nil
}
}
return "", nil
}
func (s *b2Storage) GetMetadata(ctx context.Context, id blob.ID) (blob.Metadata, error) {
fileName := s.getObjectNameString(id)
fileID, err := s.resolveFileID(fileName)
if err != nil {
return blob.Metadata{}, translateError(err)
}
fi, err := s.bucket.GetFileInfo(fileID)
if err != nil {
return blob.Metadata{}, errors.Wrap(translateError(err), "GetFileInfo")
}
bm := blob.Metadata{
BlobID: id,
Length: fi.ContentLength,
Timestamp: time.Unix(0, fi.UploadTimestamp*1e6),
}
if t, ok := timestampmeta.FromValue(fi.FileInfo[timeMapKey]); ok {
bm.Timestamp = t
}
return bm, nil
}
func translateError(err error) error {
if err == nil {
return nil
}
var b2err *backblaze.B2Error
if errors.As(err, &b2err) {
switch b2err.Status {
case http.StatusNotFound:
// Normal "not found". That's fine.
return blob.ErrBlobNotFound
case http.StatusBadRequest:
if b2err.Code == "already_hidden" || b2err.Code == "no_such_file" {
// Special case when hiding a file that is already hidden. It's basically
// not found.
return blob.ErrBlobNotFound
}
if b2err.Code == "bad_request" && strings.HasPrefix(b2err.Message, "Bad file") {
// returned in GetMetadata() when fileId is not found.
return blob.ErrBlobNotFound
}
case http.StatusRequestedRangeNotSatisfiable:
return blob.ErrInvalidRange
}
}
return err
}
func (s *b2Storage) PutBlob(ctx context.Context, id blob.ID, data blob.Bytes, opts blob.PutOptions) error {
switch {
case opts.HasRetentionOptions():
return errors.Wrap(blob.ErrUnsupportedPutBlobOption, "blob-retention")
case opts.DoNotRecreate:
return errors.Wrap(blob.ErrUnsupportedPutBlobOption, "do-not-recreate")
}
fileName := s.getObjectNameString(id)
// Backblaze always expects Content-Length to be set, even in http.Request ContentLength==0
// can mean "unknown" or "zero". http.Request used by B2 client requires http.NoBody to
// reliably pass zero length to the server as opposed to not passing it at all.
var r io.Reader = data.Reader()
if data.Length() == 0 {
r = http.NoBody
}
fi, err := s.bucket.UploadFile(fileName, timestampmeta.ToMap(opts.SetModTime, timeMapKey), r)
if err != nil {
return translateError(err)
}
if opts.GetModTime != nil {
*opts.GetModTime = time.Unix(0, fi.UploadTimestamp*1e6)
}
return nil
}
func (s *b2Storage) DeleteBlob(ctx context.Context, id blob.ID) error {
_, err := s.bucket.HideFile(s.getObjectNameString(id))
err = translateError(err)
if errors.Is(err, blob.ErrBlobNotFound) {
// Deleting failed because it already is deleted? Fine.
return nil
}
return nil
}
func (s *b2Storage) getObjectNameString(id blob.ID) string {
return s.Prefix + string(id)
}
func (s *b2Storage) ListBlobs(ctx context.Context, prefix blob.ID, callback func(blob.Metadata) error) error {
const maxFileQuery = 1000
fullPrefix := s.getObjectNameString(prefix)
nextFile := ""
for {
resp, err := s.bucket.ListFileNamesWithPrefix(nextFile, maxFileQuery, fullPrefix, "")
if err != nil {
// nolint:wrapcheck
return err
}
for i := range resp.Files {
f := &resp.Files[i]
bm := blob.Metadata{
BlobID: blob.ID(f.Name[len(s.Prefix):]),
Length: f.ContentLength,
Timestamp: time.Unix(0, f.UploadTimestamp*int64(time.Millisecond)),
}
if t, ok := timestampmeta.FromValue(f.FileInfo[timeMapKey]); ok {
bm.Timestamp = t
}
if err := callback(bm); err != nil {
return err
}
}
nextFile = resp.NextFileName
if nextFile == "" {
break
}
}
return nil
}
func (s *b2Storage) ConnectionInfo() blob.ConnectionInfo {
return blob.ConnectionInfo{
Type: b2storageType,
Config: &s.Options,
}
}
func (s *b2Storage) DisplayName() string {
return fmt.Sprintf("B2: %v", s.BucketName)
}
func (s *b2Storage) Close(ctx context.Context) error {
return nil
}
func (s *b2Storage) FlushCaches(ctx context.Context) error {
return nil
}
func (s *b2Storage) String() string {
return fmt.Sprintf("b2://%s/%s", s.BucketName, s.Prefix)
}
// New creates new B2-backed storage with specified options.
func New(ctx context.Context, opt *Options) (blob.Storage, error) {
if opt.BucketName == "" {
return nil, errors.New("bucket name must be specified")
}
cli, err := backblaze.NewB2(backblaze.Credentials{KeyID: opt.KeyID, ApplicationKey: opt.Key})
if err != nil {
return nil, errors.Wrap(err, "unable to create client")
}
bucket, err := cli.Bucket(opt.BucketName)
if err != nil {
return nil, errors.Wrapf(err, "cannot open bucket %q", opt.BucketName)
}
if bucket == nil {
return nil, errors.Errorf("bucket not found: %s", opt.BucketName)
}
return retrying.NewWrapper(&b2Storage{
Options: *opt,
cli: cli,
bucket: bucket,
}), nil
}
func init() {
blob.AddSupportedStorage(
b2storageType,
func() interface{} {
return &Options{}
},
func(ctx context.Context, o interface{}, isCreate bool) (blob.Storage, error) {
return New(ctx, o.(*Options)) // nolint:forcetypeassert
})
}