-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstorage_s3.go
198 lines (161 loc) · 4.86 KB
/
storage_s3.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
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"os"
"strings"
"time"
)
const s3Timeout = 5 * time.Second
type s3Storage struct {
client *s3.S3
memStorage *memStorage
bucketName string
}
func CreateS3Storage(serviceNames []string) (*s3Storage, error) {
endpoint := os.Getenv("AWS_S3_ENDPOINT")
requiredVariables := []string{
"AWS_ACCESS_KEY",
"AWS_SECRET_KEY",
"AWS_BUCKET_NAME",
"AWS_REGION",
}
for _, variable := range requiredVariables {
if os.Getenv(variable) == "" {
return nil, fmt.Errorf("could not found environment variable %q for s3 configuration", variable)
}
}
var configs []*aws.Config
if endpoint != "" {
configs = append(configs, &aws.Config{Endpoint: &endpoint})
if !strings.HasPrefix(endpoint, "https") {
configs = append(configs, &aws.Config{
DisableSSL: aws.Bool(true),
})
}
}
configs = append(configs, &aws.Config{
S3ForcePathStyle: aws.Bool(true),
})
sess := session.Must(session.NewSession(configs...))
s3Client := s3.New(sess)
storage := &s3Storage{
client: s3Client,
memStorage: CreateMemStorage(serviceNames),
bucketName: os.Getenv("AWS_BUCKET_NAME"),
}
if err := storage.loadServices(serviceNames); err != nil {
return nil, fmt.Errorf("could not load existing entities from s3 object storage: %w", err)
}
return storage, nil
}
// loadServices iterates through all known services and load them
func (storage *s3Storage) loadServices(serviceNames []string) error {
for _, serviceName := range serviceNames {
if err := storage.loadService(serviceName); err != nil {
return err
}
}
return nil
}
// loadService lists service objects on s3 storage and initiate download
func (storage *s3Storage) loadService(serviceName string) error {
prefix := fmt.Sprintf("%s/", serviceName)
list, err := storage.client.ListObjects(&s3.ListObjectsInput{
Bucket: &storage.bucketName,
Prefix: &prefix,
})
if err != nil {
return fmt.Errorf("could not list s3 objects with prefix %s: %w", prefix, err)
}
for _, object := range list.Contents {
if err = storage.loadEntity(serviceName, *object.Key); err != nil {
return err
}
}
return nil
}
// loadEntity downloads entity file, decode content and puts entity to memory cache
func (storage *s3Storage) loadEntity(serviceName, objectKey string) error {
objectOutput, err := storage.client.GetObject(&s3.GetObjectInput{
Bucket: &storage.bucketName,
Key: &objectKey,
})
if err != nil {
return fmt.Errorf("could not download %q object content from s3 object storage, %w", objectKey, err)
}
buf := new(bytes.Buffer)
_, err = buf.ReadFrom(objectOutput.Body)
if err != nil {
return fmt.Errorf("could not read data from %q output object, %w", objectKey, err)
}
var e Entity
err = json.Unmarshal(buf.Bytes(), &e)
_ = objectOutput.Body.Close()
if err != nil {
return fmt.Errorf("could not decode json from %q output object, %w", objectKey, err)
}
storage.memStorage.AddEntity(serviceName, e)
return nil
}
// Add creates new record in memory and uploads entity to s3 object storage
func (storage *s3Storage) Add(serviceName string, payload interface{}) (Entity, error) {
e, err := createEntity(payload)
if err != nil {
return e, err
}
data, err := json.Marshal(e)
if err != nil {
return Entity{}, fmt.Errorf("could not marshal data for s3 upload: %w", err)
}
ctx := context.Background()
var cancelFn func()
ctx, cancelFn = context.WithTimeout(ctx, s3Timeout)
if cancelFn != nil {
defer cancelFn()
}
key := getS3ObjectKey(serviceName, e.Id)
contentType := "application/json"
_, err = storage.client.PutObjectWithContext(ctx, &s3.PutObjectInput{
Bucket: &storage.bucketName,
Key: aws.String(key),
Body: bytes.NewReader(data),
ContentType: &contentType,
})
if err != nil {
return Entity{}, fmt.Errorf("could not upload to s3: %w", err)
}
storage.memStorage.AddEntity(serviceName, e)
return e, nil
}
func (storage *s3Storage) List(serviceName string) ([]Entity, error) {
return storage.memStorage.List(serviceName)
}
func (storage *s3Storage) Get(serviceName, id string) (Entity, error) {
return storage.memStorage.Get(serviceName, id)
}
func (storage *s3Storage) Delete(serviceName, id string) error {
ctx := context.Background()
var cancelFn func()
ctx, cancelFn = context.WithTimeout(ctx, s3Timeout)
if cancelFn != nil {
defer cancelFn()
}
key := getS3ObjectKey(serviceName, id)
_, err := storage.client.DeleteObjectWithContext(ctx, &s3.DeleteObjectInput{
Bucket: &storage.bucketName,
Key: &key,
})
if err != nil {
return fmt.Errorf("could not delete object from s3 bucket: %w", err)
}
return storage.memStorage.Delete(serviceName, id)
}
func getS3ObjectKey(serviceName, entityId string) string {
return fmt.Sprintf("%s/%s.json", serviceName, entityId)
}