-
Notifications
You must be signed in to change notification settings - Fork 466
/
blobstorage.go
248 lines (202 loc) · 6.75 KB
/
blobstorage.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
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
Azure Blob Storage state store.
Sample configuration in yaml:
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: statestore
spec:
type: state.azure.blobstorage
metadata:
- name: accountName
value: <storage account name>
- name: accountKey
value: <key>
- name: containerName
value: <container Name>
Concurrency is supported with ETags according to https://docs.microsoft.com/en-us/azure/storage/common/storage-concurrency#managing-concurrency-in-blob-storage
*/
package blobstorage
import (
"context"
"fmt"
"io"
"reflect"
"strings"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blob"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/bloberror"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/container"
jsoniter "github.com/json-iterator/go"
storageinternal "github.com/dapr/components-contrib/internal/component/azure/blobstorage"
mdutils "github.com/dapr/components-contrib/metadata"
"github.com/dapr/components-contrib/state"
"github.com/dapr/kit/logger"
"github.com/dapr/kit/ptr"
)
const (
keyDelimiter = "||"
)
// StateStore Type.
type StateStore struct {
state.BulkStore
containerClient *container.Client
logger logger.Logger
}
// Init the connection to blob storage, optionally creates a blob container if it doesn't exist.
func (r *StateStore) Init(ctx context.Context, metadata state.Metadata) error {
var err error
r.containerClient, _, err = storageinternal.CreateContainerStorageClient(ctx, r.logger, metadata.Properties)
if err != nil {
return err
}
return nil
}
// Features returns the features available in this state store.
func (r *StateStore) Features() []state.Feature {
return []state.Feature{state.FeatureETag}
}
// Delete the state.
func (r *StateStore) Delete(ctx context.Context, req *state.DeleteRequest) error {
return r.deleteFile(ctx, req)
}
// Get the state.
func (r *StateStore) Get(ctx context.Context, req *state.GetRequest) (*state.GetResponse, error) {
return r.readFile(ctx, req)
}
// Set the state.
func (r *StateStore) Set(ctx context.Context, req *state.SetRequest) error {
return r.writeFile(ctx, req)
}
func (r *StateStore) Ping(ctx context.Context) error {
if _, err := r.containerClient.GetProperties(ctx, nil); err != nil {
return fmt.Errorf("blob storage: error connecting to Blob storage at %s: %s", r.containerClient.URL(), err)
}
return nil
}
func (r *StateStore) GetComponentMetadata() (metadataInfo mdutils.MetadataMap) {
metadataStruct := storageinternal.BlobStorageMetadata{}
mdutils.GetMetadataInfoFromStructType(reflect.TypeOf(metadataStruct), &metadataInfo, mdutils.StateStoreType)
return
}
// NewAzureBlobStorageStore instance.
func NewAzureBlobStorageStore(logger logger.Logger) state.Store {
s := &StateStore{
logger: logger,
}
s.BulkStore = state.NewDefaultBulkStore(s)
return s
}
func (r *StateStore) readFile(ctx context.Context, req *state.GetRequest) (*state.GetResponse, error) {
blockBlobClient := r.containerClient.NewBlockBlobClient(getFileName(req.Key))
blobDownloadResponse, err := blockBlobClient.DownloadStream(ctx, nil)
if err != nil {
if isNotFoundError(err) {
return &state.GetResponse{}, nil
}
return &state.GetResponse{}, err
}
reader := blobDownloadResponse.Body
defer reader.Close()
blobData, err := io.ReadAll(reader)
if err != nil {
return &state.GetResponse{}, fmt.Errorf("error reading az blob: %w", err)
}
contentType := blobDownloadResponse.ContentType
return &state.GetResponse{
Data: blobData,
ETag: ptr.Of(string(*blobDownloadResponse.ETag)),
ContentType: contentType,
}, nil
}
func (r *StateStore) writeFile(ctx context.Context, req *state.SetRequest) error {
modifiedAccessConditions := blob.ModifiedAccessConditions{}
if req.HasETag() {
modifiedAccessConditions.IfMatch = ptr.Of(azcore.ETag(*req.ETag))
}
if req.Options.Concurrency == state.FirstWrite && !req.HasETag() {
modifiedAccessConditions.IfNoneMatch = ptr.Of(azcore.ETagAny)
}
accessConditions := blob.AccessConditions{
ModifiedAccessConditions: &modifiedAccessConditions,
}
blobHTTPHeaders, err := storageinternal.CreateBlobHTTPHeadersFromRequest(req.Metadata, req.ContentType, r.logger)
if err != nil {
return err
}
uploadOptions := azblob.UploadBufferOptions{
AccessConditions: &accessConditions,
Metadata: storageinternal.SanitizeMetadata(r.logger, req.Metadata),
HTTPHeaders: &blobHTTPHeaders,
}
blockBlobClient := r.containerClient.NewBlockBlobClient(getFileName(req.Key))
_, err = blockBlobClient.UploadBuffer(ctx, r.marshal(req), &uploadOptions)
if err != nil {
// Check if the error is due to ETag conflict
if req.HasETag() && isETagConflictError(err) {
return state.NewETagError(state.ETagMismatch, err)
}
return fmt.Errorf("error uploading az blob: %w", err)
}
return nil
}
func (r *StateStore) deleteFile(ctx context.Context, req *state.DeleteRequest) error {
blockBlobClient := r.containerClient.NewBlockBlobClient(getFileName(req.Key))
modifiedAccessConditions := blob.ModifiedAccessConditions{}
if req.HasETag() {
modifiedAccessConditions.IfMatch = ptr.Of(azcore.ETag(*req.ETag))
}
deleteOptions := blob.DeleteOptions{
DeleteSnapshots: nil,
AccessConditions: &blob.AccessConditions{
ModifiedAccessConditions: &modifiedAccessConditions,
},
}
_, err := blockBlobClient.Delete(ctx, &deleteOptions)
if err != nil {
if req.HasETag() && isETagConflictError(err) {
return state.NewETagError(state.ETagMismatch, err)
} else if isNotFoundError(err) {
// deleting an item that doesn't exist without specifying an ETAG is a noop
return nil
}
return err
}
return nil
}
func getFileName(key string) string {
pr := strings.Split(key, keyDelimiter)
if len(pr) != 2 {
return pr[0]
}
return pr[1]
}
func (r *StateStore) marshal(req *state.SetRequest) []byte {
var v string
b, ok := req.Value.([]byte)
if ok {
v = string(b)
} else {
v, _ = jsoniter.MarshalToString(req.Value)
}
return []byte(v)
}
func isNotFoundError(err error) bool {
return bloberror.HasCode(err, bloberror.BlobNotFound)
}
func isETagConflictError(err error) bool {
return bloberror.HasCode(err, bloberror.ConditionNotMet)
}