forked from kopia/kopia
/
azure_storage.go
320 lines (254 loc) · 7.81 KB
/
azure_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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
// Package azure implements Azure Blob Storage.
package azure
import (
"context"
"encoding/xml"
"fmt"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
"github.com/pkg/errors"
"github.com/kopia/kopia/internal/clock"
"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 (
azStorageType = "azureBlob"
timeMapKey = "Kopiamtime" // this must be capital letter followed by lowercase, to comply with AZ tags naming convention.
)
type azStorage struct {
Options
ctx context.Context
service azblob.ServiceClient
bucket azblob.ContainerClient
}
func (az *azStorage) GetBlob(ctx context.Context, b blob.ID, offset, length int64, output blob.OutputBuffer) error {
if offset < 0 {
return errors.Wrap(blob.ErrInvalidRange, "invalid offset")
}
bc := az.bucket.NewBlockBlobClient(az.getObjectNameString(b))
opt := &azblob.DownloadBlobOptions{}
if length > 0 {
opt.Offset = &offset
opt.Count = &length
}
if length == 0 {
l1 := int64(1)
opt.Offset = &offset
opt.Count = &l1
}
resp, err := bc.Download(ctx, opt)
if err != nil {
return translateError(err)
}
body := resp.Body(azblob.RetryReaderOptions{})
defer body.Close() // nolint:errcheck
if length == 0 {
return nil
}
if err := iocopy.JustCopy(output, body); err != nil {
return translateError(err)
}
// nolint:wrapcheck
return blob.EnsureLengthExactly(output.Length(), length)
}
func (az *azStorage) GetMetadata(ctx context.Context, b blob.ID) (blob.Metadata, error) {
bc := az.bucket.NewBlockBlobClient(az.getObjectNameString(b))
fi, err := bc.GetProperties(ctx, &azblob.GetBlobPropertiesOptions{})
if err != nil {
return blob.Metadata{}, errors.Wrap(translateError(err), "Attributes")
}
bm := blob.Metadata{
BlobID: b,
Length: *fi.ContentLength,
Timestamp: *fi.LastModified,
}
if t, ok := timestampmeta.FromValue(fi.Metadata[timeMapKey]); ok {
bm.Timestamp = t
}
return bm, nil
}
func translateError(err error) error {
if err == nil {
return nil
}
var re *azblob.StorageError
if errors.As(err, &re) {
// nolint:exhaustive
switch re.ErrorCode {
case azblob.StorageErrorCodeBlobNotFound:
return blob.ErrBlobNotFound
case azblob.StorageErrorCodeInvalidRange:
return blob.ErrInvalidRange
}
}
return err
}
func (az *azStorage) PutBlob(ctx context.Context, b blob.ID, data blob.Bytes, opts blob.PutOptions) error {
switch {
case opts.HasRetentionOptions():
return errors.New("setting blob-retention is not supported")
case opts.DoNotRecreate:
return errors.New("setting blob do-not-recreate is not supported")
}
ctx, cancel := context.WithCancel(ctx)
defer cancel()
bc := az.bucket.NewBlockBlobClient(az.getObjectNameString(b))
ubo := &azblob.UploadBlockBlobOptions{
Metadata: timestampmeta.ToMap(opts.SetModTime, timeMapKey),
}
resp, err := bc.Upload(ctx, data.Reader(), ubo)
if err != nil {
return translateError(err)
}
if opts.GetModTime != nil {
*opts.GetModTime = *resp.LastModified
}
return nil
}
// DeleteBlob deletes azure blob from container with given ID.
func (az *azStorage) DeleteBlob(ctx context.Context, b blob.ID) error {
_, err := az.bucket.NewBlockBlobClient(az.getObjectNameString(b)).Delete(ctx, nil)
err = translateError(err)
// don't return error if blob is already deleted
if errors.Is(err, blob.ErrBlobNotFound) {
return nil
}
return err
}
func (az *azStorage) getObjectNameString(b blob.ID) string {
return az.Prefix + string(b)
}
// ListBlobs list azure blobs with given prefix.
func (az *azStorage) ListBlobs(ctx context.Context, prefix blob.ID, callback func(blob.Metadata) error) error {
prefixStr := az.Prefix + string(prefix)
pager := az.bucket.ListBlobsFlat(&azblob.ContainerListBlobFlatSegmentOptions{
Prefix: &prefixStr,
Include: []azblob.ListBlobsIncludeItem{
"[" + azblob.ListBlobsIncludeItemMetadata + "]",
},
})
for pager.NextPage(ctx) {
resp := pager.PageResponse()
// workaround for the XML parsing bug reported upstream
// https://github.com/Azure/azure-sdk-for-go/issues/16679
var enumerationResults struct {
Blobs struct {
Blob []struct {
Name string
Properties struct {
ContentLength int64 `xml:"Content-Length"`
LastModified string `xml:"Last-Modified"`
}
Metadata struct {
Kopiamtime string
}
}
}
}
dec := xml.NewDecoder(resp.RawResponse.Body)
if err := dec.Decode(&enumerationResults); err != nil {
return errors.Wrap(err, "unable to decode response")
}
for _, it := range enumerationResults.Blobs.Blob {
bm := blob.Metadata{
BlobID: blob.ID(it.Name[len(az.Prefix):]),
Length: it.Properties.ContentLength,
}
// see if we have 'Kopiamtime' metadata, if so - trust it.
if t, ok := timestampmeta.FromValue(it.Metadata.Kopiamtime); ok {
bm.Timestamp = t
} else {
// fall back to using last modified time.
t, err := time.Parse(time.RFC1123, it.Properties.LastModified)
if err != nil {
return errors.Wrapf(err, "invalid timestamp for BLOB '%v': %q", bm.BlobID, it.Properties.LastModified)
}
bm.Timestamp = t
}
if err := callback(bm); err != nil {
return err
}
}
}
return translateError(pager.Err())
}
func (az *azStorage) ConnectionInfo() blob.ConnectionInfo {
return blob.ConnectionInfo{
Type: azStorageType,
Config: &az.Options,
}
}
func (az *azStorage) DisplayName() string {
return fmt.Sprintf("Azure: %v", az.Options.Container)
}
func (az *azStorage) Close(ctx context.Context) error {
return nil
}
func (az *azStorage) FlushCaches(ctx context.Context) error {
return nil
}
// New creates new Azure Blob Storage-backed storage with specified options:
//
// - the 'Container', 'StorageAccount' and 'StorageKey' fields are required and all other parameters are optional.
func New(ctx context.Context, opt *Options) (blob.Storage, error) {
if opt.Container == "" {
return nil, errors.New("container name must be specified")
}
var (
service azblob.ServiceClient
serviceErr error
)
storageDomain := opt.StorageDomain
if storageDomain == "" {
storageDomain = "blob.core.windows.net"
}
storageHostname := fmt.Sprintf("%v.%v", opt.StorageAccount, storageDomain)
switch {
case opt.SASToken != "":
service, serviceErr = azblob.NewServiceClientWithNoCredential(
fmt.Sprintf("https://%s?%s", storageHostname, opt.SASToken), nil)
case opt.StorageKey != "":
// create a credentials object.
cred, err := azblob.NewSharedKeyCredential(opt.StorageAccount, opt.StorageKey)
if err != nil {
return nil, errors.Wrap(err, "unable to initialize credentials")
}
service, serviceErr = azblob.NewServiceClientWithSharedKey(
fmt.Sprintf("https://%s/", storageHostname), cred, nil,
)
default:
return nil, errors.Errorf("either storage key or SAS token must be provided")
}
if serviceErr != nil {
return nil, errors.Wrap(serviceErr, "opening azure service")
}
bucket := service.NewContainerClient(opt.Container)
raw := &azStorage{
Options: *opt,
ctx: ctx,
bucket: bucket,
service: service,
}
az := retrying.NewWrapper(raw)
// verify Azure connection is functional by listing blobs in a bucket, which will fail if the container
// does not exist. We list with a prefix that will not exist, to avoid iterating through any objects.
nonExistentPrefix := fmt.Sprintf("kopia-azure-storage-initializing-%v", clock.Now().UnixNano())
if err := raw.ListBlobs(ctx, blob.ID(nonExistentPrefix), func(md blob.Metadata) error {
return nil
}); err != nil {
return nil, errors.Wrap(err, "unable to list from the bucket")
}
return az, nil
}
func init() {
blob.AddSupportedStorage(
azStorageType,
func() interface{} {
return &Options{}
},
func(ctx context.Context, o interface{}, isCreate bool) (blob.Storage, error) {
return New(ctx, o.(*Options))
})
}