-
Notifications
You must be signed in to change notification settings - Fork 9
/
managebuckets.go
64 lines (51 loc) · 1.82 KB
/
managebuckets.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
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package s3
import (
"context"
"errors"
"fmt"
"log"
"time"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/cenkalti/backoff/v4"
)
const connBackoff = 500 * time.Millisecond
// EnsureBucketExists creates the requested bucket before it is used.
func EnsureBucketExists(ctx context.Context, client *s3.Client, bc *BucketConfig) error {
return EnsureBucketExistsByName(ctx, client, bc.BucketName, bc.Region)
}
func EnsureBucketExistsByName(ctx context.Context, client *s3.Client, name, region string) error {
log.Printf("%s (%s): creating bucket...\n", name, region)
if err := backoff.Retry(func() error {
input := &s3.CreateBucketInput{
Bucket: &name,
}
if region != "" {
input.CreateBucketConfiguration = &types.CreateBucketConfiguration{
LocationConstraint: types.BucketLocationConstraint(region),
}
}
// Speed up bucket creation through faster retries.
ctx, cancel := context.WithTimeout(ctx, connBackoff)
defer cancel()
if _, err := client.CreateBucket(ctx, input); err != nil {
var alreadyExists *types.BucketAlreadyExists
var alreadyOwned *types.BucketAlreadyOwnedByYou
if errors.As(err, &alreadyExists) || errors.As(err, &alreadyOwned) {
log.Printf("%s (%s): bucket already exists.\n", name, region)
return nil
}
err = fmt.Errorf("failed to create bucket: %w", err)
log.Println(err)
return err
}
log.Printf("%s (%s): bucket created.\n", name, region)
return nil
}, backoff.WithContext(backoff.NewConstantBackOff(connBackoff), ctx)); err != nil {
return fmt.Errorf("failed to create S3 bucket: %w", err)
}
return nil
}