-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
oss.go
380 lines (353 loc) · 11.8 KB
/
oss.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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
package oss
import (
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"github.com/argoproj/pkg/file"
log "github.com/sirupsen/logrus"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/utils/pointer"
"github.com/argoproj/argo-workflows/v3/errors"
wfv1 "github.com/argoproj/argo-workflows/v3/pkg/apis/workflow/v1alpha1"
waitutil "github.com/argoproj/argo-workflows/v3/util/wait"
"github.com/argoproj/argo-workflows/v3/workflow/artifacts/common"
wfcommon "github.com/argoproj/argo-workflows/v3/workflow/common"
)
// ArtifactDriver is a driver for OSS
type ArtifactDriver struct {
Endpoint string
AccessKey string
SecretKey string
SecurityToken string
}
var (
_ common.ArtifactDriver = &ArtifactDriver{}
defaultRetry = wait.Backoff{Duration: time.Second * 2, Factor: 2.0, Steps: 5, Jitter: 0.1}
// OSS error code reference: https://error-center.alibabacloud.com/status/product/Oss
ossTransientErrorCodes = []string{"RequestTimeout", "QuotaExceeded.Refresh", "Default", "ServiceUnavailable", "Throttling", "RequestTimeTooSkewed", "SocketException", "SocketTimeout", "ServiceBusy", "DomainNetWorkVisitedException", "ConnectionTimeout", "CachedTimeTooLarge"}
bucketLogFilePrefix = "bucket-log-"
)
func (ossDriver *ArtifactDriver) newOSSClient() (*oss.Client, error) {
var options []oss.ClientOption
if token := ossDriver.SecurityToken; token != "" {
options = append(options, oss.SecurityToken(token))
}
client, err := oss.New(ossDriver.Endpoint, ossDriver.AccessKey, ossDriver.SecretKey, options...)
if err != nil {
return nil, fmt.Errorf("failed to create new OSS client: %w", err)
}
return client, err
}
// Load downloads artifacts from OSS compliant storage, e.g., downloading an artifact into local path
func (ossDriver *ArtifactDriver) Load(inputArtifact *wfv1.Artifact, path string) error {
err := waitutil.Backoff(defaultRetry,
func() (bool, error) {
log.Infof("OSS Load path: %s, key: %s", path, inputArtifact.OSS.Key)
osscli, err := ossDriver.newOSSClient()
if err != nil {
return !isTransientOSSErr(err), err
}
bucketName := inputArtifact.OSS.Bucket
err = setBucketLogging(osscli, bucketName)
if err != nil {
return !isTransientOSSErr(err), err
}
bucket, err := osscli.Bucket(bucketName)
if err != nil {
return !isTransientOSSErr(err), err
}
objectName := inputArtifact.OSS.Key
origErr := bucket.GetObjectToFile(objectName, path)
if origErr == nil {
return true, nil
}
if !IsOssErrCode(origErr, "NoSuchKey") {
return !isTransientOSSErr(origErr), fmt.Errorf("failed to get file: %w", origErr)
}
// If we get here, the error was a NoSuchKey. The key might be a oss "directory"
isDir, err := IsOssDirectory(bucket, objectName)
if err != nil {
return !isTransientOSSErr(err), fmt.Errorf("failed to test if %s/%s is a directory: %w", bucketName, objectName, err)
}
if !isDir {
// It's neither a file, nor a directory. Return the original NoSuchKey error
return false, origErr
}
if err = GetOssDirectory(bucket, objectName, path); err != nil {
return !isTransientOSSErr(err), fmt.Errorf("failed get directory: %v", err)
}
return true, nil
})
return err
}
// Save stores an artifact to OSS compliant storage, e.g., uploading a local file to OSS bucket
func (ossDriver *ArtifactDriver) Save(path string, outputArtifact *wfv1.Artifact) error {
err := waitutil.Backoff(defaultRetry,
func() (bool, error) {
log.Infof("OSS Save path: %s, key: %s", path, outputArtifact.OSS.Key)
osscli, err := ossDriver.newOSSClient()
if err != nil {
return !isTransientOSSErr(err), err
}
isDir, err := file.IsDirectory(path)
if err != nil {
log.Warnf("Failed to test if %s is a directory: %v", path, err)
return false, nil
}
bucketName := outputArtifact.OSS.Bucket
err = setBucketLogging(osscli, bucketName)
if err != nil {
return !isTransientOSSErr(err), err
}
if outputArtifact.OSS.CreateBucketIfNotPresent {
exists, err := osscli.IsBucketExist(bucketName)
if err != nil {
return !isTransientOSSErr(err), fmt.Errorf("failed to check if bucket %s exists: %w", bucketName, err)
}
if !exists {
err = osscli.CreateBucket(bucketName)
if err != nil {
return !isTransientOSSErr(err), fmt.Errorf("failed to automatically create bucket %s when it's not present: %w", bucketName, err)
}
}
}
bucket, err := osscli.Bucket(bucketName)
if err != nil {
return !isTransientOSSErr(err), err
}
objectName := outputArtifact.OSS.Key
if outputArtifact.OSS.LifecycleRule != nil {
err = setBucketLifecycleRule(osscli, outputArtifact.OSS)
return !isTransientOSSErr(err), err
}
if isDir {
if err = putDirectory(bucket, objectName, path); err != nil {
log.Warnf("failed to put directory: %v", err)
return !isTransientOSSErr(err), err
}
} else {
if err = putFile(bucket, objectName, path); err != nil {
log.Warnf("failed to put file: %v", err)
return !isTransientOSSErr(err), err
}
}
return true, nil
})
return err
}
func (ossDriver *ArtifactDriver) ListObjects(artifact *wfv1.Artifact) ([]string, error) {
var files []string
err := waitutil.Backoff(defaultRetry,
func() (bool, error) {
osscli, err := ossDriver.newOSSClient()
if err != nil {
return !isTransientOSSErr(err), err
}
bucketName := artifact.OSS.Bucket
err = setBucketLogging(osscli, bucketName)
if err != nil {
return !isTransientOSSErr(err), err
}
bucket, err := osscli.Bucket(bucketName)
if err != nil {
return !isTransientOSSErr(err), err
}
results, err := bucket.ListObjectsV2(oss.Prefix(artifact.OSS.Key))
if err != nil {
return !isTransientOSSErr(err), err
}
for _, object := range results.Objects {
files = append(files, object.Key)
}
return true, nil
})
return files, err
}
func setBucketLogging(client *oss.Client, bucketName string) error {
if os.Getenv(wfcommon.EnvVarArgoTrace) == "1" {
err := client.SetBucketLogging(bucketName, bucketName, bucketLogFilePrefix, true)
if err != nil {
return fmt.Errorf("failed to configure bucket logging: %w", err)
}
}
return nil
}
func setBucketLifecycleRule(client *oss.Client, ossArtifact *wfv1.OSSArtifact) error {
if ossArtifact.LifecycleRule.MarkInfrequentAccessAfterDays == 0 && ossArtifact.LifecycleRule.MarkDeletionAfterDays == 0 {
return nil
}
var markInfrequentAccessAfterDays int
var markDeletionAfterDays int
if ossArtifact.LifecycleRule.MarkInfrequentAccessAfterDays != 0 {
markInfrequentAccessAfterDays = int(ossArtifact.LifecycleRule.MarkInfrequentAccessAfterDays)
}
if ossArtifact.LifecycleRule.MarkDeletionAfterDays != 0 {
markDeletionAfterDays = int(ossArtifact.LifecycleRule.MarkDeletionAfterDays)
}
if markInfrequentAccessAfterDays > markDeletionAfterDays {
return fmt.Errorf("markInfrequentAccessAfterDays cannot be large than markDeletionAfterDays")
}
// Set expiration rule.
expirationRule := oss.BuildLifecycleRuleByDays("expiration-rule", ossArtifact.Key, true, markInfrequentAccessAfterDays)
// Automatically delete the expired delete tag so we don't have to manage it ourselves.
expiration := oss.LifecycleExpiration{
ExpiredObjectDeleteMarker: pointer.BoolPtr(true),
}
// Convert to Infrequent Access (IA) storage type for objects that are expired after a period of time.
versionTransition := oss.LifecycleVersionTransition{
NoncurrentDays: markInfrequentAccessAfterDays,
StorageClass: oss.StorageIA,
}
// Mark deletion after a period of time.
versionExpiration := oss.LifecycleVersionExpiration{
NoncurrentDays: markDeletionAfterDays,
}
versionTransitionRule := oss.LifecycleRule{
ID: "version-transition-rule",
Prefix: ossArtifact.Key,
Status: string(oss.VersionEnabled),
Expiration: &expiration,
NonVersionExpiration: &versionExpiration,
NonVersionTransitions: []oss.LifecycleVersionTransition{versionTransition},
}
// Set lifecycle rules to the bucket.
rules := []oss.LifecycleRule{expirationRule, versionTransitionRule}
err := client.SetBucketLifecycle(ossArtifact.Bucket, rules)
return err
}
func isTransientOSSErr(err error) bool {
if err == nil {
return false
}
if ossErr, ok := err.(oss.ServiceError); ok {
for _, transientErrCode := range ossTransientErrorCodes {
if ossErr.Code == transientErrCode {
return true
}
}
}
return false
}
func putFile(bucket *oss.Bucket, objectName, path string) error {
log.Debugf("putFile from %s to %s", path, objectName)
return bucket.PutObjectFromFile(objectName, path)
}
func putDirectory(bucket *oss.Bucket, objectName, dir string) error {
return filepath.Walk(dir, func(fpath string, info os.FileInfo, err error) error {
if err != nil {
return errors.InternalWrapError(err)
}
// build the name to be used in OSS
nameInDir, err := filepath.Rel(dir, fpath)
if err != nil {
return errors.InternalWrapError(err)
}
fObjectName := filepath.Join(objectName, nameInDir)
// create an OSS dir explicitly for every local dir, , including empty dirs.
if info.Mode().IsDir() {
// create OSS dir
if !strings.HasSuffix(fObjectName, "/") {
fObjectName += "/"
}
err = bucket.PutObject(fObjectName, nil)
if err != nil {
return err
}
}
if !info.Mode().IsRegular() {
return nil
}
err = putFile(bucket, fObjectName, fpath)
if err != nil {
return err
}
return nil
})
}
// IsOssErrCode tests if an err is an oss.ServiceError with the specified code
func IsOssErrCode(err error, code string) bool {
if serr, ok := err.(oss.ServiceError); ok {
if serr.Code == code {
return true
}
}
return false
}
// IsDirectory tests if the key is acting like a OSS directory. This just means it has at least one
// object which is prefixed with the given key
func IsOssDirectory(bucket *oss.Bucket, objectName string) (bool, error) {
if objectName == "" {
return true, nil
}
if !strings.HasSuffix(objectName, "/") {
objectName += "/"
}
rst, err := bucket.ListObjects(oss.Prefix(objectName), oss.MaxKeys(1))
if err != nil {
return false, err
}
if len(rst.CommonPrefixes)+len(rst.Objects) > 0 {
return true, nil
}
return false, nil
}
// GetOssDirectory download an OSS "directory" to local path
func GetOssDirectory(bucket *oss.Bucket, objectName, path string) error {
files, err := ListOssDirectory(bucket, objectName)
if err != nil {
return err
}
for _, f := range files {
innerName, err := filepath.Rel(objectName, f)
if err != nil {
return fmt.Errorf("get Rel path from %s to %s error: %w", f, objectName, err)
}
fpath := filepath.Join(path, innerName)
if strings.HasSuffix(f, "/") {
err = os.MkdirAll(fpath, 0o700)
if err != nil {
return fmt.Errorf("mkdir %s error: %w", fpath, err)
}
continue
}
dirPath := filepath.Dir(fpath)
err = os.MkdirAll(dirPath, 0o700)
if err != nil {
return fmt.Errorf("mkdir %s error: %w", dirPath, err)
}
err = bucket.GetObjectToFile(f, fpath)
if err != nil {
log.Warnf("failed to load object %s to %s error: %v", f, fpath, err)
return err
}
}
return nil
}
// ListOssDirectory lists all the files which are the descendants of the specified objectKey, if a file has suffix '/', then it is an OSS directory
func ListOssDirectory(bucket *oss.Bucket, objectKey string) (files []string, err error) {
if objectKey != "" {
if !strings.HasSuffix(objectKey, "/") {
objectKey += "/"
}
}
pre := oss.Prefix(objectKey)
marker := oss.Marker("")
for {
lor, err := bucket.ListObjects(marker, pre)
if err != nil {
log.Warnf("oss list object(%s) error: %v", objectKey, err)
return files, err
}
for _, obj := range lor.Objects {
files = append(files, obj.Key)
}
marker = oss.Marker(lor.NextMarker)
if !lor.IsTruncated {
break
}
}
return files, nil
}