-
Notifications
You must be signed in to change notification settings - Fork 31
/
storage_cloud.go
209 lines (184 loc) · 5.52 KB
/
storage_cloud.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
package service
import (
"context"
"errors"
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"gocloud.dev/blob"
"gocloud.dev/blob/s3blob"
"log"
"log/slog"
"os"
"path"
"path/filepath"
"strings"
"sync"
)
type CloudStorage struct {
BucketRef *blob.Bucket
BucketName string
Prefix string
StorageName string
}
const (
CloudType = "cloud_type"
BucketName = "bucket_name"
Prefix = "prefix"
Kind = "kind"
Custom = "custom"
AccessId = "access_id"
SecretKey = "secret_key"
Endpoint = "endpoint"
Region = "region"
SSLEnabled = "ssl_enabled"
InitBucket = "init_bucket"
)
var (
stringEmpty = func(key string) bool {
return key == ""
}
initBucketOnce sync.Once
)
// getCloudLocation appends prefix to path
func (s *CloudStorage) getCloudLocation(fileName string) string {
if s.Prefix == "<nil>" {
s.Prefix = ""
}
//Skip if prefix is already in Path.
if len(s.Prefix) > 0 && strings.Contains(fileName, s.Prefix) {
return fileName
}
if fileName[0] != '/' && s.Prefix != "" {
return path.Join(s.Prefix, "/", fileName)
}
return path.Join(s.Prefix, fileName)
}
// ReadFile read file from Cloud Provider and return byte array
func (s *CloudStorage) ReadFile(filename string) ([]byte, error) {
if s.BucketRef == nil {
return nil, errors.New("unable to find valid bucket to read file from")
}
ctx := context.Background()
return s.BucketRef.ReadAll(ctx, s.getCloudLocation(filename))
}
// WriteFile persists data to Cloud Provider Storage returning error if operation failed
func (s *CloudStorage) WriteFile(filename string, data []byte) error {
if s.BucketRef == nil {
return errors.New("unable to get valid bucket ")
}
return s.BucketRef.WriteAll(context.Background(), s.getCloudLocation(filename), data, nil)
}
func (s *CloudStorage) Name() string {
return s.StorageName
}
func (s *CloudStorage) FindAllFiles(folder string, fullPath bool) ([]string, error) {
if s.BucketRef == nil {
return nil, errors.New("unable to find valid bucket to list files from")
}
folderName := s.getCloudLocation(folder)
var fileList []string
opts := blob.ListOptions{}
if s.Prefix != "" {
opts.Prefix = folderName
}
iterator := s.BucketRef.List(&opts)
for {
obj, err := iterator.Next(context.Background())
if err != nil {
break
}
if fullPath {
if strings.Contains(obj.Key, folderName) {
fileList = append(fileList, obj.Key)
} else {
slog.Debug("key does not match folder path", "key", obj.Key)
}
} else {
fileList = append(fileList, filepath.Base(obj.Key))
}
}
return fileList, nil
}
func NewCloudStorage(c context.Context) (Storage, error) {
var (
err error
bucketObj *blob.Bucket
errorMsg string
)
contextVal := c.Value(StorageContext)
if contextVal == nil {
return nil, errors.New("cannot configure GCP storage, context missing")
}
appData, ok := contextVal.(map[string]string)
if !ok {
return nil, errors.New("cannot convert appData to string map")
}
//Pattern specifically for Self hosted S3 compatible instances Minio / Ceph
if boolStrCheck(getMapValue(Custom, "false", stringEmpty, appData)) {
var sess *session.Session
creds := credentials.NewStaticCredentials(
getMapValue(AccessId, os.Getenv("AWS_ACCESS_KEY"), stringEmpty, appData),
getMapValue(SecretKey, os.Getenv("AWS_SECRET_KEY"), stringEmpty, appData), "")
sess, err = session.NewSession(&aws.Config{
Credentials: creds,
Endpoint: aws.String(getMapValue(Endpoint, "http://localhost:9000", stringEmpty, appData)),
DisableSSL: aws.Bool(getMapValue(SSLEnabled, "false", stringEmpty, appData) != "true"),
S3ForcePathStyle: aws.Bool(true),
Region: aws.String(getMapValue(Region, "us-east-1", stringEmpty, appData)),
})
if err != nil {
errorMsg = err.Error()
}
bucketObj, err = s3blob.OpenBucket(context.Background(), sess, appData["bucket_name"], nil)
if err != nil {
errorMsg = err.Error()
}
if err == nil && boolStrCheck(getMapValue(InitBucket, "false", stringEmpty, appData)) {
//Attempts to initiate bucket
initBucketOnce.Do(func() {
client := s3.New(sess)
m := s3.CreateBucketInput{
Bucket: aws.String(appData[BucketName]),
}
//attempt to create bucket
_, err := client.CreateBucket(&m)
if err != nil {
slog.Warn("bucket already exists or cannot be created", "bucket", *m.Bucket)
} else {
slog.Info("bucket has been created", "bucket", *m.Bucket)
}
})
}
} else {
var cloudURL = fmt.Sprintf("%s://%s", appData["cloud_type"], appData["bucket_name"])
bucketObj, err = blob.OpenBucket(c, cloudURL)
errorMsg = fmt.Sprintf("failed to open bucket %s", cloudURL)
}
if err != nil {
log.Fatalf("unable to connect to cloud provider, err: %v, message: %s", err, errorMsg)
}
entity := &CloudStorage{
BucketName: appData[BucketName],
BucketRef: bucketObj,
}
if val, ok := appData[Prefix]; ok {
entity.Prefix = val
}
return entity, nil
}
// boolStrCheck does a more intelligent bool check as yaml values are converted to "1" or "true" depending
// on how the user configures quotes the value.
func boolStrCheck(val string) bool {
return strings.ToLower(val) == "true" || val == "1"
}
// getMapValue a generic utility that will get a value from a map and return a default if key does not exist
func getMapValue[T comparable](key, defaultValue T, emptyTest func(key T) bool, data map[T]T) T {
val, ok := data[key]
if ok && !emptyTest(val) {
return val
}
return defaultValue
}