-
Notifications
You must be signed in to change notification settings - Fork 4
/
awsi.go
291 lines (259 loc) · 8.66 KB
/
awsi.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
package awsi
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/aws/aws-sdk-go-v2/service/secretsmanager"
"github.com/aws/aws-sdk-go-v2/service/sfn"
"github.com/prozz/aws-embedded-metrics-golang/emf"
)
// This module provides aws integration for JetStore
//*TODO no need to pass bucket and region to this module
var bucket, region, kmsKeyArn string
func init() {
kmsKeyArn = os.Getenv("JETS_S3_KMS_KEY_ARN")
bucket = os.Getenv("JETS_BUCKET")
region = os.Getenv("JETS_REGION")
}
func LogMetric(metricName string, dimentions *map[string]string, count int) {
m := emf.New().Namespace("JetStore/Pipeline").Metric(metricName, count)
for k, v := range *dimentions {
m.Dimension(k, v)
}
m.Log()
}
func GetPrivateIp() (string, error) {
resp, err := http.Get(os.Getenv("ECS_CONTAINER_METADATA_URI_V4"))
if err != nil {
log.Printf("while http get $ECS_CONTAINER_METADATA_URI_V4: %v", err)
return "", err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Printf("while reading resp of http get $ECS_CONTAINER_METADATA_URI_V4: %v", err)
return "", err
}
fmt.Println("Got ECS_CONTAINER_METADATA_URI_V4:\n", string(body))
var data map[string]interface{}
err = json.Unmarshal(body, &data)
if err != nil {
return "", fmt.Errorf("** Invalid JSON from ECS_CONTAINER_METADATA_URI_V4: %v", err)
}
result := data["Networks"].([]interface{})[0].(map[string]interface{})["IPv4Addresses"].([]interface{})[0].(string)
fmt.Println("*** IPv4Addresses:", result)
return result, nil
}
func GetConfig() (aws.Config, error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
return config.LoadDefaultConfig(ctx)
}
func GetSecretValue(secret string) (string, error) {
cfg, err := GetConfig()
if err != nil {
return "", fmt.Errorf("while loading aws configuration: %v", err)
}
// Create Secrets Manager client
smClient := secretsmanager.NewFromConfig(cfg)
input := &secretsmanager.GetSecretValueInput{
SecretId: aws.String(secret),
VersionStage: aws.String("AWSCURRENT"), // VersionStage defaults to AWSCURRENT if unspecified
}
result, err := smClient.GetSecretValue(context.TODO(), input)
if err != nil {
// For a list of exceptions thrown, see
// https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html
return "", fmt.Errorf("while getting aws secret value for dsn: %v", err)
}
// Decrypts secret using the associated KMS key.
secretString := *result.SecretString
return secretString, nil
}
func GetDsnFromJson(dsnJson string, useLocalhost bool, poolSize int) (string, error) {
// Check if json is empty, if so return dsn empty
if dsnJson == "" {
return "", nil
}
// parse the json into the map m
m := make(map[string]interface{})
err := json.Unmarshal([]byte(dsnJson), &m)
if err != nil {
return "", fmt.Errorf("while umarshaling dsn json: %v", err)
}
// fmt.Println(m)
if !useLocalhost {
_, useLocalhost = os.LookupEnv("USING_SSH_TUNNEL")
}
if useLocalhost {
m["host"] = "localhost"
fmt.Println("LOCAL TESTING using ssh tunnel (expecting ssh tunnel open)")
}
if poolSize == 0 {
poolSize = 10
}
dsn := fmt.Sprintf("postgresql://%s:%s@%s:%.0f/postgres?pool_max_conns=%d",
m["username"].(string),
url.QueryEscape(m["password"].(string)),
m["host"].(string),
m["port"].(float64),
poolSize)
return dsn, nil
}
func GetDsnFromSecret(secret string, useLocalhost bool, poolSize int) (string, error) {
secretString, err := GetSecretValue(secret)
if err != nil {
return "", fmt.Errorf("while calling GetSecretValue: %v", err)
}
dsn, err := GetDsnFromJson(secretString, useLocalhost, poolSize)
if err != nil {
return "", fmt.Errorf("while calling GetDsnFromJson: %v", err)
}
return dsn, nil
}
type S3Object struct {
Key string
Size int64
}
// ListObjects lists the objects in a bucket with prefix if not nil.
func ListS3Objects(prefix *string) ([]*S3Object, error) {
cfg, err := config.LoadDefaultConfig(context.TODO(), config.WithRegion(region))
if err != nil {
return nil, fmt.Errorf("while loading aws configuration: %v", err)
}
// Create a s3 client
s3Client := s3.NewFromConfig(cfg)
// Download the keys
keys := make([]*S3Object, 0)
var token *string
for isTruncated := true; isTruncated; {
result, err := s3Client.ListObjectsV2(context.TODO(), &s3.ListObjectsV2Input{
Bucket: aws.String(bucket),
Prefix: prefix,
ContinuationToken: token,
})
if err != nil {
log.Printf("Couldn't list objects in bucket %v. Here's why: %v\n", bucket, err)
return nil, err
}
for i := range result.Contents {
// Skip the directories
if !strings.HasSuffix(*result.Contents[i].Key, "/") {
keys = append(keys, &S3Object{
Key: *result.Contents[i].Key,
Size: *result.Contents[i].Size,
})
}
}
isTruncated = *result.IsTruncated
token = result.NextContinuationToken
}
return keys, err
}
// Download obj from s3 into fileHd (must be writable), return size of download in bytes
func DownloadFromS3(bucket, region, objKey string, fileHd *os.File) (int64, error) {
cfg, err := config.LoadDefaultConfig(context.TODO(), config.WithRegion(region))
if err != nil {
return 0, fmt.Errorf("while loading aws configuration: %v", err)
}
// Create a s3 client
s3Client := s3.NewFromConfig(cfg)
// Download the object
downloader := manager.NewDownloader(s3Client)
nsz, err := downloader.Download(context.TODO(), fileHd, &s3.GetObjectInput{Bucket: &bucket, Key: &objKey})
if err != nil {
return 0, fmt.Errorf("failed to download file from s3: %v", err)
}
return nsz, nil
}
func NewDownloader(region string) (*manager.Downloader, error) {
cfg, err := config.LoadDefaultConfig(context.TODO(), config.WithRegion(region))
if err != nil {
return nil, fmt.Errorf("while loading aws configuration: %v", err)
}
// Create a s3 client
s3Client := s3.NewFromConfig(cfg)
return manager.NewDownloader(s3Client), nil
}
// Use a shared Downloader to download obj from s3 into fileHd (must be writable), return size of download in bytes
func DownloadFromS3v2(downloader *manager.Downloader, bucket, objKey string, fileHd *os.File) (int64, error) {
nsz, err := downloader.Download(context.TODO(), fileHd, &s3.GetObjectInput{Bucket: &bucket, Key: &objKey})
if err != nil {
return 0, fmt.Errorf("failed to download file from s3: %v", err)
}
return nsz, nil
}
// upload object to S3, reading the obj from fileHd (from current position to EOF)
func UploadToS3(bucket, region, objKey string, fileHd *os.File) error {
cfg, err := config.LoadDefaultConfig(context.TODO(), config.WithRegion(region))
if err != nil {
return fmt.Errorf("while loading aws configuration: %v", err)
}
// Create a s3 client
s3Client := s3.NewFromConfig(cfg)
// Create an uploader with the client and custom options
uploader := manager.NewUploader(s3Client)
putObjInput := &s3.PutObjectInput{
Bucket: &bucket,
Key: &objKey,
Body: bufio.NewReader(fileHd),
}
if len(kmsKeyArn) > 0 {
putObjInput.ServerSideEncryption = types.ServerSideEncryptionAwsKms
putObjInput.SSEKMSKeyId = &kmsKeyArn
}
// uout, err := uploader.Upload(context.TODO(), putObjInput)
_, err = uploader.Upload(context.TODO(), putObjInput)
if err != nil {
return fmt.Errorf("failed to upload file to s3: %v", err)
}
// if uout != nil {
// log.Println("Uploaded",*uout.Key,"to location",uout.Location)
// }
return nil
}
func StartExecution(stateMachineARN string, stateMachineInput map[string]interface{}, name string) (string, error) {
// Load the SDK's configuration from environment and shared config, and
// create the client with this.
cfg, err := config.LoadDefaultConfig(context.TODO())
if err != nil {
return "", fmt.Errorf("while load SDK configuration: %v", err)
}
smInputJson, err := json.Marshal(stateMachineInput)
if err != nil {
return "", fmt.Errorf("while marshalling smInput: %v", err)
}
smInputStr := string(smInputJson)
// Generate a name for the execution
if name == "" {
name = strconv.FormatInt(time.Now().UnixMilli(), 10)
}
fmt.Println("Start Machine Exec Name is:", name)
// Set the parameters for starting a process
params := &sfn.StartExecutionInput{
StateMachineArn: &stateMachineARN,
Input: &smInputStr,
Name: &name,
}
// Step Function client
client := sfn.NewFromConfig(cfg)
_, err = client.StartExecution(context.TODO(), params)
if err != nil {
return "", fmt.Errorf("while calling StartExecution: %v", err)
}
return name, nil
}