forked from openshift/cluster-image-registry-operator
/
oss.go
659 lines (570 loc) · 21 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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
package oss
import (
"bytes"
"context"
"fmt"
"net/http"
"os"
"path/filepath"
"reflect"
"sync"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/klog/v2"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
configv1 "github.com/openshift/api/config/v1"
imageregistryv1 "github.com/openshift/api/imageregistry/v1"
operatorapi "github.com/openshift/api/operator/v1"
regopclient "github.com/openshift/cluster-image-registry-operator/pkg/client"
"github.com/openshift/cluster-image-registry-operator/pkg/defaults"
"github.com/openshift/cluster-image-registry-operator/pkg/envvar"
"github.com/openshift/cluster-image-registry-operator/pkg/storage/util"
)
const (
imageRegistrySecretMountpoint = "/var/run/secrets/cloud"
imageRegistrySecretDataKey = "credentials"
)
var mutex sync.Mutex
type driver struct {
Context context.Context
Config *imageregistryv1.ImageRegistryConfigStorageAlibabaOSS
Listers *regopclient.StorageListers
credentials *credentials.AccessKeyCredential
// roundTripper is used only during tests.
roundTripper http.RoundTripper
}
// NewDriver creates a new OSS storage driver
// Used during bootstrapping
func NewDriver(ctx context.Context, c *imageregistryv1.ImageRegistryConfigStorageAlibabaOSS, listers *regopclient.StorageListers) *driver {
return &driver{
Context: ctx,
Config: c,
Listers: listers,
}
}
func (d *driver) CABundle() (string, bool, error) {
return "", true, nil
}
// UpdateEffectiveConfig updates the driver's local effective OSS configuration
// based on infrastructure settings and any custom overrides.
func (d *driver) UpdateEffectiveConfig() error {
effectiveConfig := d.Config.DeepCopy()
if effectiveConfig == nil {
effectiveConfig = &imageregistryv1.ImageRegistryConfigStorageAlibabaOSS{}
}
// Load infrastructure values
infra, err := util.GetInfrastructure(d.Listers.Infrastructures)
if err != nil {
return err
}
var clusterRegion string
if infra.Status.PlatformStatus != nil && infra.Status.PlatformStatus.Type == configv1.AlibabaCloudPlatformType {
clusterRegion = infra.Status.PlatformStatus.AlibabaCloud.Region
}
// Use cluster defaults when custom config doesn't define values
if d.Config == nil || len(effectiveConfig.Region) == 0 {
effectiveConfig.Region = clusterRegion
}
err = d.getCredentialsConfigData()
if err != nil {
return err
}
d.Config = effectiveConfig.DeepCopy()
return nil
}
func fetchCredentialsIniFromSecret(secret *corev1.Secret) (auth.Credential, error) {
mutex.Lock()
defer mutex.Unlock()
creds, ok := secret.Data[imageRegistrySecretDataKey]
if !ok {
return nil, fmt.Errorf("failed to fetch key 'credentials' in secret data")
}
f, err := os.CreateTemp("", "alibaba-creds-*")
if err != nil {
return nil, err
}
defer f.Close()
defer os.Remove(f.Name())
defer os.Unsetenv(provider.ENVCredentialFile)
_, err = f.Write(creds)
if err != nil {
return nil, err
}
os.Setenv(provider.ENVCredentialFile, f.Name())
// use Alibaba provider initialization
p := provider.NewProfileProvider("default")
// return a valid auth credential
return p.Resolve()
}
func (d *driver) getCredentialsConfigData() error {
if d.credentials != nil {
return nil
}
// Look for a user defined secret to get the Alibaba Cloud credentials from first
sec, err := d.Listers.Secrets.Get(defaults.ImageRegistryPrivateConfigurationUser)
if err != nil {
if errors.IsNotFound(err) {
// Fall back to those provided by the credential minter if nothing is provided by the user
sec, err = d.Listers.Secrets.Get(defaults.CloudCredentialsName)
if err != nil {
return fmt.Errorf("unable to get cluster minted credentials %q: %v", fmt.Sprintf("%s/%s", defaults.ImageRegistryOperatorNamespace, defaults.CloudCredentialsName), err)
}
} else {
return fmt.Errorf("unable to get cluster minted credentials %q: %v", fmt.Sprintf("%s/%s", defaults.ImageRegistryPrivateConfigurationUser, defaults.CloudCredentialsName), err)
}
}
credential, err := fetchCredentialsIniFromSecret(sec)
if err != nil {
return fmt.Errorf("failed to generate shared secrets data: %v", err)
}
// This must be an AccessKeyCrential because the oss.New requires accessKeyID and accessSecretKey
if akCredentials, ok := credential.(*credentials.AccessKeyCredential); ok {
d.credentials = akCredentials
return nil
}
return fmt.Errorf("an invalid credential type ")
}
// isInternal Identifies whether to use a public or private oss endpoint.
func (d *driver) isInternal() bool {
return d.Config.EndpointAccessibility != imageregistryv1.PublicEndpoint
}
// getOSSEndpoint returns an endpoint that allows us to interact
// with the Alibaba Cloud OSS service, details in https://www.alibabacloud.com/help/doc-detail/31837.htm
func (d *driver) getOSSEndpoint() string {
if d.isInternal() {
return fmt.Sprintf("oss-%s-internal.aliyuncs.com", d.Config.Region)
}
return fmt.Sprintf("oss-%s.aliyuncs.com", d.Config.Region)
}
func (d *driver) getOSSService() (*oss.Client, error) {
err := d.getCredentialsConfigData()
if err != nil {
return nil, err
}
err = d.UpdateEffectiveConfig()
if err != nil {
return nil, err
}
endpoint := d.getOSSEndpoint()
clientOptions := []oss.ClientOption{}
if d.roundTripper != nil {
clientOptions = append(clientOptions, oss.HTTPClient(&http.Client{Transport: d.roundTripper}))
}
return oss.New(endpoint, d.credentials.AccessKeyId, d.credentials.AccessKeySecret, clientOptions...)
}
// ConfigEnv configures the environment variables that will be
// used in the image registry deployment.
func (d *driver) ConfigEnv() (envs envvar.List, err error) {
err = d.UpdateEffectiveConfig()
if err != nil {
return
}
envs = append(envs,
envvar.EnvVar{Name: "REGISTRY_STORAGE_OSS_ENDPOINT", Value: fmt.Sprintf("%s.%s", d.Config.Bucket, d.getOSSEndpoint())},
envvar.EnvVar{Name: "REGISTRY_STORAGE", Value: "oss"},
envvar.EnvVar{Name: "REGISTRY_STORAGE_OSS_BUCKET", Value: d.Config.Bucket},
envvar.EnvVar{Name: "REGISTRY_STORAGE_OSS_REGION", Value: fmt.Sprintf("oss-%s", d.Config.Region)},
envvar.EnvVar{Name: "REGISTRY_STORAGE_OSS_INTERNAL", Value: d.isInternal()},
envvar.EnvVar{Name: "REGISTRY_STORAGE_OSS_ENCRYPT", Value: true},
envvar.EnvVar{Name: "REGISTRY_STORAGE_OSS_CREDENTIALSCONFIGPATH", Value: filepath.Join(imageRegistrySecretMountpoint, imageRegistrySecretDataKey)},
envvar.EnvVar{Name: "REGISTRY_STORAGE_OSS_ACCESSKEYID", Value: d.credentials.AccessKeyId},
envvar.EnvVar{Name: "REGISTRY_STORAGE_OSS_ACCESSKEYSECRET", Value: d.credentials.AccessKeySecret},
)
return
}
func (d *driver) Volumes() ([]corev1.Volume, []corev1.VolumeMount, error) {
var volumes []corev1.Volume
var volumeMounts []corev1.VolumeMount
// Mount the registry config secret containing the credentials file data
credsVolume := corev1.Volume{
Name: defaults.ImageRegistryPrivateConfiguration,
VolumeSource: corev1.VolumeSource{
Secret: &corev1.SecretVolumeSource{
SecretName: defaults.ImageRegistryPrivateConfiguration,
},
},
}
credsVolumeMount := corev1.VolumeMount{
Name: credsVolume.Name,
MountPath: imageRegistrySecretMountpoint,
ReadOnly: true,
}
volumes = append(volumes, credsVolume)
volumeMounts = append(volumeMounts, credsVolumeMount)
return volumes, volumeMounts, nil
}
func (d *driver) VolumeSecrets() (map[string]string, error) {
// Return the same credentials data that the image-registry-operator is using
// so that it can be stored in the image-registry Pod's Secret.
err := d.getCredentialsConfigData()
if err != nil {
return nil, err
}
confData, err := d.sharedCredentialsDataFromStaticCreds()
if err != nil {
return nil, err
}
return map[string]string{
imageRegistrySecretDataKey: string(confData),
}, nil
}
func (d *driver) sharedCredentialsDataFromStaticCreds() ([]byte, error) {
if d.credentials == nil || d.credentials.AccessKeyId == "" || d.credentials.AccessKeySecret == "" {
return []byte{}, fmt.Errorf("invalid credentials for Alibaba Cloud")
}
buf := &bytes.Buffer{}
fmt.Fprint(buf, "[default]\n")
fmt.Fprint(buf, "type = access_key\n")
fmt.Fprintf(buf, "access_key_id = %s\n", d.credentials.AccessKeyId)
fmt.Fprintf(buf, "access_key_secret = %s\n", d.credentials.AccessKeySecret)
return buf.Bytes(), nil
}
// bucketExists checks whether or not the OSS bucket exists
func (d *driver) bucketExists(bucketName string) (bool, error) {
if len(bucketName) == 0 {
return false, nil
}
svc, err := d.getOSSService()
if err != nil {
return false, err
}
_, err = svc.GetBucketInfo(bucketName)
if err != nil {
return false, err
}
return true, nil
}
// StorageExists checks if an OSS bucket with the given name exists
// and we can access it
func (d *driver) StorageExists(cr *imageregistryv1.Config) (bool, error) {
if len(d.Config.Bucket) == 0 {
return false, nil
}
bucketExists, err := d.bucketExists(d.Config.Bucket)
if bucketExists {
util.UpdateCondition(cr, defaults.StorageExists, operatorapi.ConditionTrue, "OSS Bucket Exists", "")
}
if err != nil {
if svcErr, ok := err.(oss.ServiceError); ok && svcErr.Code == "NoSuchBucket" {
util.UpdateCondition(cr, defaults.StorageExists, operatorapi.ConditionFalse, svcErr.Code, svcErr.Error())
return false, nil
}
util.UpdateCondition(cr, defaults.StorageExists, operatorapi.ConditionUnknown, "Unknown Error Occurred", err.Error())
return false, err
}
return true, nil
}
// StorageChanged checks to see if the name of the storage medium
// has changed
func (d *driver) StorageChanged(cr *imageregistryv1.Config) bool {
if !reflect.DeepEqual(cr.Status.Storage.OSS, cr.Spec.Storage.OSS) {
util.UpdateCondition(cr, defaults.StorageExists, operatorapi.ConditionUnknown, "OSS Configuration Changed", "OSS storage is in an unknown state")
return true
}
return false
}
// CreateStorage attempts to create an OSS bucket
// and apply any provided tags
func (d *driver) CreateStorage(cr *imageregistryv1.Config) error {
infra, err := util.GetInfrastructure(d.Listers.Infrastructures)
if err != nil {
return err
}
if err := d.UpdateEffectiveConfig(); err != nil {
return err
}
svc, err := d.getOSSService()
if err != nil {
return err
}
// If a bucket name is supplied, and it already exists and we can access it
// just update the config
var bucketExists bool
if len(d.Config.Bucket) != 0 {
bucketExists, err = d.bucketExists(d.Config.Bucket)
if bucketExists {
util.UpdateCondition(cr, defaults.StorageExists, operatorapi.ConditionTrue, "OSS Bucket Exists", "")
}
if err != nil {
if oerr, ok := err.(oss.ServiceError); ok {
switch oerr.Code {
case "NoSuchBucket", "NotFound":
// If the bucket doesn't exist that's ok, we'll try to create it
klog.Infof("The bucket %s not found ", d.Config.Bucket)
default:
util.UpdateCondition(cr, defaults.StorageExists, operatorapi.ConditionUnknown, "Unknown Error Occurred", err.Error())
return err
}
} else {
util.UpdateCondition(cr, defaults.StorageExists, operatorapi.ConditionUnknown, "Unknown Error Occurred", err.Error())
return err
}
}
}
if len(d.Config.Bucket) != 0 && bucketExists {
if cr.Spec.Storage.ManagementState == "" {
cr.Spec.Storage.ManagementState = imageregistryv1.StorageManagementStateUnmanaged
}
cr.Status.Storage = imageregistryv1.ImageRegistryConfigStorage{
OSS: d.Config.DeepCopy(),
}
util.UpdateCondition(cr, defaults.StorageExists, operatorapi.ConditionTrue, "OSS Bucket Exists", "User supplied OSS bucket exists and is accessible")
} else {
generatedName := false
// Retry up to 500 times if we get a naming conflict
const numRetries = 500
for i := 0; i < numRetries; i++ {
// If the bucket name is blank, let's generate one
if len(d.Config.Bucket) == 0 {
if d.Config.Bucket, err = util.GenerateStorageName(d.Listers, d.Config.Region); err != nil {
return err
}
generatedName = true
}
err := svc.CreateBucket(d.Config.Bucket)
if err != nil {
if oerr, ok := err.(oss.ServiceError); ok {
switch oerr.Code {
case "BucketAlreadyExists":
if d.Config.Bucket != "" && !generatedName {
util.UpdateCondition(cr, defaults.StorageExists, operatorapi.ConditionFalse, "Unable to Access Bucket", "The bucket exists, but we do not have permission to access it")
break
}
d.Config.Bucket = ""
continue
default:
util.UpdateCondition(cr, defaults.StorageExists, operatorapi.ConditionFalse, oerr.Code, oerr.Error())
return err
}
}
}
if cr.Spec.Storage.ManagementState == "" {
cr.Spec.Storage.ManagementState = imageregistryv1.StorageManagementStateManaged
}
cr.Status.Storage = imageregistryv1.ImageRegistryConfigStorage{
OSS: d.Config.DeepCopy(),
}
cr.Spec.Storage.OSS = d.Config.DeepCopy()
util.UpdateCondition(cr, defaults.StorageExists, operatorapi.ConditionTrue, "Creation Successful", "OSS bucket was successfully created")
break
}
if len(d.Config.Bucket) == 0 {
util.UpdateCondition(cr, defaults.StorageExists, operatorapi.ConditionFalse, "Unable to Generate Unique Bucket Name", "")
return fmt.Errorf("unable to generate a unique OSS bucket name")
}
}
// Block public access to the OSS bucket and its objects by default
if cr.Spec.Storage.ManagementState == imageregistryv1.StorageManagementStateManaged {
err := svc.SetBucketACL(d.Config.Bucket, oss.ACLPrivate)
if err != nil {
if oerr, ok := err.(oss.ServiceError); ok {
util.UpdateCondition(cr, defaults.StoragePublicAccessBlocked, operatorapi.ConditionFalse, oerr.Code, oerr.Error())
} else {
util.UpdateCondition(cr, defaults.StoragePublicAccessBlocked, operatorapi.ConditionFalse, "Unknown Error Occurred", err.Error())
}
} else {
util.UpdateCondition(cr, defaults.StoragePublicAccessBlocked, operatorapi.ConditionTrue, "Public Access Block Successful", "Public access to the OSS bucket and its contents have been successfully blocked.")
cr.Status.Storage = imageregistryv1.ImageRegistryConfigStorage{
OSS: d.Config.DeepCopy(),
}
cr.Spec.Storage.OSS = d.Config.DeepCopy()
}
}
// Tag the bucket with the openshiftClusterID
// along with any user defined tags from the cluster configuration
if cr.Spec.Storage.ManagementState == imageregistryv1.StorageManagementStateManaged {
klog.Info("setting Alibaba Cloud OSS bucket tags")
tagset := []oss.Tag{
{
Key: "kubernetes.io/cluster/" + infra.Status.InfrastructureName,
Value: "owned",
},
{
Key: "Name",
Value: infra.Status.InfrastructureName + "-image-registry",
},
{
Key: "sigs.k8s.io/cloud-provider-alibaba/origin",
Value: "ocp",
},
{
Key: "GISV",
Value: "ocp",
},
}
// at this stage we are not keeping user tags in sync. as per enhancement proposal
// we only set user provided tags when we created the bucket.
hasOSSStatus := infra.Status.PlatformStatus != nil && infra.Status.PlatformStatus.AlibabaCloud != nil
if hasOSSStatus {
klog.Infof("user provided %d tags", len(infra.Status.PlatformStatus.AlibabaCloud.ResourceTags))
for _, tag := range infra.Status.PlatformStatus.AlibabaCloud.ResourceTags {
klog.Infof("user provided bucket tag: %s: %s", tag.Key, tag.Value)
tagset = append(tagset, oss.Tag{
Key: tag.Key,
Value: tag.Value,
})
}
}
klog.V(5).Infof("tagging bucket with tags: %+v", tagset)
tagging := oss.Tagging{
Tags: tagset,
}
err := svc.SetBucketTagging(d.Config.Bucket, tagging)
if err != nil {
if oerr, ok := err.(oss.ServiceError); ok {
util.UpdateCondition(cr, defaults.StorageTagged, operatorapi.ConditionFalse, oerr.Code, oerr.Error())
} else {
util.UpdateCondition(cr, defaults.StorageTagged, operatorapi.ConditionFalse, "Unknown Error Occurred", err.Error())
}
} else {
util.UpdateCondition(cr, defaults.StorageTagged, operatorapi.ConditionTrue, "Tagging Successful", "Tags were successfully applied to the OSS bucket")
}
} else {
klog.Info("ignoring bucket tags, storage is not managed")
}
// Enable default encryption on the bucket
if cr.Spec.Storage.ManagementState == imageregistryv1.StorageManagementStateManaged {
encryptionRule := oss.ServerEncryptionRule{}
// kms encryption
if d.Config.Encryption != nil && d.Config.Encryption.Method == imageregistryv1.KMS && d.Config.Encryption.KMS != nil && len(d.Config.Encryption.KMS.KeyID) > 0 {
encryptionRule.SSEDefault.SSEAlgorithm = string(oss.KMSAlgorithm)
encryptionRule.SSEDefault.KMSMasterKeyID = d.Config.Encryption.KMS.KeyID
} else {
encryptionRule.SSEDefault.SSEAlgorithm = string(oss.AESAlgorithm)
}
err = svc.SetBucketEncryption(d.Config.Bucket, encryptionRule)
if err != nil {
if oerr, ok := err.(oss.ServiceError); ok {
util.UpdateCondition(cr, defaults.StorageEncrypted, operatorapi.ConditionFalse, oerr.Code, oerr.Error())
} else {
util.UpdateCondition(cr, defaults.StorageEncrypted, operatorapi.ConditionFalse, "Unknown Error Occurred", err.Error())
}
} else {
util.UpdateCondition(cr, defaults.StorageEncrypted, operatorapi.ConditionTrue, "Encryption Successful", fmt.Sprintf("Default %s encryption was successfully enabled on the OSS bucket", encryptionRule.SSEDefault.SSEAlgorithm))
cr.Status.Storage = imageregistryv1.ImageRegistryConfigStorage{
OSS: d.Config.DeepCopy(),
}
cr.Spec.Storage.OSS = d.Config.DeepCopy()
}
} else {
if !reflect.DeepEqual(cr.Status.Storage.OSS, d.Config) {
cr.Status.Storage = imageregistryv1.ImageRegistryConfigStorage{
OSS: d.Config.DeepCopy(),
}
}
}
// Enable default incomplete multipart upload cleanup after one (1) day
if cr.Spec.Storage.ManagementState == imageregistryv1.StorageManagementStateManaged {
rules := []oss.LifecycleRule{
{
ID: "cleanup-incomplete-multipart-registry-uploads",
Prefix: "",
Status: "Enabled",
AbortMultipartUpload: &oss.LifecycleAbortMultipartUpload{
Days: 1,
},
},
}
err = svc.SetBucketLifecycle(d.Config.Bucket, rules)
if err != nil {
if oerr, ok := err.(oss.ServiceError); ok {
util.UpdateCondition(cr, defaults.StorageIncompleteUploadCleanupEnabled, operatorapi.ConditionFalse, oerr.Code, oerr.Error())
} else {
util.UpdateCondition(cr, defaults.StorageIncompleteUploadCleanupEnabled, operatorapi.ConditionFalse, "Unknown Error Occurred", err.Error())
}
} else {
util.UpdateCondition(cr, defaults.StorageIncompleteUploadCleanupEnabled, operatorapi.ConditionTrue, "Enable Cleanup Successful", "Default cleanup of incomplete multipart uploads after one (1) day was successfully enabled")
}
}
return nil
}
// RemoveStorage deletes the storage medium that we created
// The OSS bucket must be empty before it can be removed
func (d *driver) RemoveStorage(cr *imageregistryv1.Config) (bool, error) {
if cr.Spec.Storage.ManagementState != imageregistryv1.StorageManagementStateManaged ||
len(d.Config.Bucket) == 0 {
return false, nil
}
svc, err := d.getOSSService()
if err != nil {
return false, err
}
// Get bucket
bucket, err := svc.Bucket(d.Config.Bucket)
if err != nil {
return false, err
}
// Delete part
keyMarker := oss.KeyMarker("")
uploadIDMarker := oss.UploadIDMarker("")
for {
lmur, err := bucket.ListMultipartUploads(keyMarker, uploadIDMarker)
if err != nil {
return false, err
}
for _, upload := range lmur.Uploads {
imur := oss.InitiateMultipartUploadResult{
Bucket: bucket.BucketName,
Key: upload.Key, UploadID: upload.UploadID,
}
err = bucket.AbortMultipartUpload(imur)
if err != nil {
return false, err
}
}
keyMarker = oss.KeyMarker(lmur.NextKeyMarker)
uploadIDMarker = oss.UploadIDMarker(lmur.NextUploadIDMarker)
if !lmur.IsTruncated {
break
}
}
// Delete objects
marker := oss.Marker("")
for {
lor, err := bucket.ListObjects(marker)
if err != nil {
return false, err
}
for _, object := range lor.Objects {
err = bucket.DeleteObject(object.Key)
if err != nil {
return false, err
}
}
marker = oss.Marker(lor.NextMarker)
if !lor.IsTruncated {
break
}
}
// Delete bucket
err = svc.DeleteBucket(d.Config.Bucket)
if err != nil {
if oerr, ok := err.(oss.ServiceError); ok {
if oerr.Code == "NoSuchBucket" {
util.UpdateCondition(cr, defaults.StorageExists, operatorapi.ConditionFalse, "OSS Bucket Deleted", "The OSS bucket did not exist.")
return true, nil
}
util.UpdateCondition(cr, defaults.StorageExists, operatorapi.ConditionUnknown, oerr.Code, oerr.Error())
return false, err
}
return true, err
}
if len(cr.Spec.Storage.OSS.Bucket) != 0 {
cr.Spec.Storage.OSS.Bucket = ""
}
d.Config.Bucket = ""
if !reflect.DeepEqual(cr.Status.Storage.OSS, d.Config) {
cr.Status.Storage = imageregistryv1.ImageRegistryConfigStorage{
OSS: d.Config.DeepCopy(),
}
}
util.UpdateCondition(cr, defaults.StorageExists, operatorapi.ConditionFalse, "OSS Bucket Deleted", "The OSS bucket has been removed.")
return false, nil
}
// ID return the underlying storage identificator, on this case the bucket name.
func (d *driver) ID() string {
return d.Config.Bucket
}