/
timestream-dependency-helper.go
727 lines (623 loc) · 21.7 KB
/
timestream-dependency-helper.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
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
package utils
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/iam"
"github.com/aws/aws-sdk-go-v2/service/iam/types"
"github.com/aws/aws-sdk-go-v2/service/s3"
s3types "github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/aws/aws-sdk-go-v2/service/sns"
"github.com/aws/aws-sdk-go-v2/service/sqs"
sqstypes "github.com/aws/aws-sdk-go-v2/service/sqs/types"
"github.com/aws/aws-sdk-go-v2/service/sts"
"github.com/aws/smithy-go"
"math/rand"
"os"
"runtime"
"time"
)
/**
*/
const (
POLICY_DOCUMENT = "{" +
" \"Version\": \"2012-10-17\"," +
" \"Statement\": [" +
" {" +
" \"Action\": [" +
" \"kms:Decrypt\"," +
" \"sns:Publish\"," +
" \"timestream:describeEndpoints\"," +
" \"timestream:Select\"," +
" \"timestream:SelectValues\"," +
" \"timestream:WriteRecords\"," +
" \"s3:PutObject\"" +
" ]," +
" \"Resource\": \"*\"," +
" \"Effect\": \"Allow\"" +
" }" +
" ]" +
"}"
SQS_POLICY_FORMAT = "{" +
"\"Version\":\"2012-10-17\"," +
"\"Statement\": [" +
" {" +
" \"Sid\":\"topic-subscription-%s\", " +
" \"Effect\": \"Allow\", " +
" \"Principal\":{\"AWS\":\"*\"}, " +
" \"Action\": \"sqs:SendMessage\", " +
" \"Resource\": \"%s\", " +
" \"Condition\":{" +
" \"ArnEquals\":{" +
" \"aws:SourceArn\":\"%s\"" +
" }" +
" }" +
" }" +
" ]" +
"}"
ROLE_POLICY_FORMAT = "{" +
"\"Version\":\"2012-10-17\"," +
"\"Statement\":[" +
" {" +
" \"Effect\":\"Allow\"," +
" \"Principal\":{" +
" \"Service\": \"timestream.amazonaws.com\"" +
" }," +
" \"Action\":\"sts:AssumeRole\"" +
" }" +
" ]" +
"}"
)
type TimestreamDependencyHelper struct {
SnsSvc *sns.Client
SqsSvc *sqs.Client
S3Svc *s3.Client
IamSvc *iam.Client
StsSvc *sts.Client
}
type NotificationMessage struct {
ParseFlag bool
TopicArn string `json:"TopicArn"`
ReceiptHandle string
MessageAttributes struct {
QueryArn struct {
Type string `json:"type"`
Value string `json:"value"`
} `json:"queryArn"`
NotificationType struct {
Type string `json:"type"`
Value string `json:"value"`
} `json:"notificationType"`
} `json:"MessageAttributes"`
Type string `json:"Type"`
MessageString string `json:"Message"`
Message struct {
Type string `json:"type"`
Arn string `json:"arn"`
NextInvocationEpochSecond int64 `json:"NextInvocationEpochSecond"`
ScheduledQueryRunSummary struct {
FailureReason string `json:"failureReason"`
RunStatus string `json:"runStatus"`
InvocationEpochSecond int64 `json:"invocationEpochSecond"`
TriggerTimeMillis int64 `json:"triggerTimeMillis"`
ErrorReportLocation struct {
S3ReportLocation struct {
BucketName string `json:"bucketName"`
ObjectKey string `json:"objectKey"`
} `json:"s3ReportLocation"`
ExecutionStats map[string]interface{} `json:"executionStats"`
} `json:"errorReportLocation"`
} `json:"scheduledQueryRunSummary"`
}
}
type Resource struct {
Type string
Identifier string
AdditionalDetails string
}
func CleanUp(timestreamBuilder TimestreamBuilder, timestreamDependencyHelper TimestreamDependencyHelper,
databaseName string, tableName string, s3BucketName string) {
fmt.Println("Cleaning created resources as part of this sample..")
if s3BucketName != "" {
err := timestreamDependencyHelper.DeleteS3Bucket(s3BucketName)
if err != nil {
fmt.Printf("\nFailed to delete s3BucketName='%s', please delete it manually\n", s3BucketName)
}
}
if tableName != "" {
fmt.Printf("\nDeleting table %s\n", tableName)
timestreamBuilder.DeleteTable(databaseName, tableName)
}
if databaseName != "" {
fmt.Printf("\nDeleting database %s\n", databaseName)
timestreamBuilder.DeleteDatabase(databaseName)
}
}
func JsonMarshalIgnoreError(input interface{}) string {
jsonString, _ := json.Marshal(input)
return fmt.Sprintf("%s\n", string(jsonString))
}
func HandleError(err error, errorMessage string, exitFlag bool) {
if err != nil {
_, fn, line, _ := runtime.Caller(1)
fmt.Printf("[error] %s:%d %s with error %v\n", fn, line, errorMessage, err)
if exitFlag == true {
panic(err)
}
}
}
func FileExists(name string) (bool, error) {
_, err := os.Stat(name)
if err == nil {
return true, nil
}
return false, err
}
func GenerateRandomStringWithSize(size int) string {
rand.Seed(time.Now().UnixNano())
alphaNumericList := []rune("abcdefghijklmnopqrstuvwxyz0123456789")
randomPrefix := make([]rune, size)
for i := range randomPrefix {
randomPrefix[i] = alphaNumericList[rand.Intn(len(alphaNumericList))]
}
return string(randomPrefix)
}
func parseNotificationMessage(message string) (NotificationMessage, error) {
var notificationMessage NotificationMessage
err := json.Unmarshal([]byte(message), ¬ificationMessage)
if err != nil {
HandleError(err, "", false)
return notificationMessage, err
}
err = json.Unmarshal([]byte(notificationMessage.MessageString), ¬ificationMessage.Message)
if err != nil {
HandleError(err, "", false)
return notificationMessage, err
}
notificationMessage.MessageString = ""
return notificationMessage, err
}
func (timestreamDependencyHelper TimestreamDependencyHelper) CreateSnsTopic(topicName string) (string, error) {
createTopicInput := &sns.CreateTopicInput{
Name: aws.String(topicName),
Attributes: map[string]string{"FifoTopic": "true", "ContentBasedDeduplication": "false"},
}
createTopicOutput, err := timestreamDependencyHelper.SnsSvc.CreateTopic(context.TODO(), createTopicInput)
if err != nil {
fmt.Printf("Error: %s\n", err.Error())
} else {
fmt.Println("Creating SNS topic is successful")
return *createTopicOutput.TopicArn, nil
}
return "", err
}
func (timestreamDependencyHelper TimestreamDependencyHelper) CreateSqsQueue(queueName string) (string, error) {
createQueueInput := &sqs.CreateQueueInput{
QueueName: aws.String(queueName),
Attributes: map[string]string{"FifoQueue": "true", "ContentBasedDeduplication": "false"},
}
createQueueOutput, err := timestreamDependencyHelper.SqsSvc.CreateQueue(context.TODO(), createQueueInput)
if err != nil {
fmt.Printf("Error: %s\n", err.Error())
} else {
fmt.Printf("Create SQS Queue with name %s is successful\n", queueName)
return *createQueueOutput.QueueUrl, nil
}
return "", err
}
func (timestreamDependencyHelper TimestreamDependencyHelper) GetSqsQueryUrl(queueName string) (string, error) {
getQueueUrlInput := &sqs.GetQueueUrlInput{
QueueName: aws.String(queueName),
}
getQueueUrlOutput, err := timestreamDependencyHelper.SqsSvc.GetQueueUrl(context.TODO(), getQueueUrlInput)
if err != nil {
var apiErr smithy.APIError
if errors.As(err, &apiErr) {
switch apiErr.ErrorCode() {
case "ConflictException":
fmt.Println("ConflictException", apiErr.Error())
return "", nil
default:
fmt.Println(apiErr.Error())
}
} else {
fmt.Println(err.Error())
}
return "", err
} else {
return *getQueueUrlOutput.QueueUrl, nil
}
}
func (timestreamDependencyHelper TimestreamDependencyHelper) DeleteSqsQueue(queueUrl string) error {
deleteQueueInput := &sqs.DeleteQueueInput{
QueueUrl: aws.String(queueUrl),
}
_, err := timestreamDependencyHelper.SqsSvc.DeleteQueue(context.TODO(), deleteQueueInput)
if err != nil {
fmt.Printf("Error: %s\n", err.Error())
} else {
fmt.Println("delete_sqs_queue is successful")
}
return err
}
func (timestreamDependencyHelper TimestreamDependencyHelper) ReceiveMessage(queueUrl string) (NotificationMessage, error) {
receiveMessageInput := &sqs.ReceiveMessageInput{
QueueUrl: aws.String(queueUrl),
WaitTimeSeconds: 20,
MaxNumberOfMessages: 1,
}
receiveMessageOutput, err := timestreamDependencyHelper.SqsSvc.ReceiveMessage(context.TODO(), receiveMessageInput)
if err != nil {
fmt.Printf("Error: %s\n", err.Error())
} else {
fmt.Println("received Message successfully")
messages := receiveMessageOutput.Messages
if len(messages) > 0 {
messageBody := messages[0].Body
response, err := parseNotificationMessage(*messageBody)
if err == nil {
response.ReceiptHandle = *messages[0].ReceiptHandle
response.ParseFlag = true
return response, nil
}
}
}
return NotificationMessage{}, err
}
func (timestreamDependencyHelper TimestreamDependencyHelper) DeleteMessage(queueUrl string, receiptHandle string) error {
deleteMessageInput := &sqs.DeleteMessageInput{
QueueUrl: aws.String(queueUrl),
ReceiptHandle: aws.String(receiptHandle),
}
_, err := timestreamDependencyHelper.SqsSvc.DeleteMessage(context.TODO(), deleteMessageInput)
if err != nil {
fmt.Printf("sqs DeleteMessage is failed with error: %s\n", err.Error())
} else {
fmt.Println("sqs DeleteMessage is successful")
}
return err
}
func (timestreamDependencyHelper TimestreamDependencyHelper) DeleteSnsTopic(topicArn string) error {
deleteTopicInput := &sns.DeleteTopicInput{
TopicArn: aws.String(topicArn),
}
_, err := timestreamDependencyHelper.SnsSvc.DeleteTopic(context.TODO(), deleteTopicInput)
if err != nil {
fmt.Printf("Error: %s\n", err.Error())
} else {
fmt.Println("DeleteTopic is successful")
}
return err
}
func (timestreamDependencyHelper TimestreamDependencyHelper) GetSqsQueueArn(queueUrl string) (string, error) {
createGetQueueAttributesInput := &sqs.GetQueueAttributesInput{
QueueUrl: aws.String(queueUrl),
AttributeNames: []sqstypes.QueueAttributeName{sqstypes.QueueAttributeName("QueueArn")},
}
createGetQueueAttributesOutput, err := timestreamDependencyHelper.SqsSvc.GetQueueAttributes(context.TODO(), createGetQueueAttributesInput)
if err != nil {
fmt.Printf("Error: %s\n", err.Error())
} else {
fmt.Printf("GetQueueAttributes is successful : %s", JsonMarshalIgnoreError(&createGetQueueAttributesOutput.Attributes))
return createGetQueueAttributesOutput.Attributes["QueueArn"], nil
}
return "", err
}
func (timestreamDependencyHelper TimestreamDependencyHelper) SetSqsAccessPolicy(queueUrl string, topicArn string, queueArn string) error {
setQueueAttributesInput := &sqs.SetQueueAttributesInput{
QueueUrl: aws.String(queueUrl),
Attributes: map[string]string{"Policy": fmt.Sprintf(SQS_POLICY_FORMAT, topicArn, queueArn, topicArn)},
}
setQueueAttributesOutput, err := timestreamDependencyHelper.SqsSvc.SetQueueAttributes(context.TODO(), setQueueAttributesInput)
if err != nil {
fmt.Printf("Error: %s\n", err.Error())
} else {
fmt.Printf("setQueueAttributesOutput is successful : %s",
JsonMarshalIgnoreError(setQueueAttributesOutput.ResultMetadata))
}
return err
}
func (timestreamDependencyHelper TimestreamDependencyHelper) getIamRole(roleName string) (string, error) {
getRoleInput := &iam.GetRoleInput{
RoleName: aws.String(roleName),
}
getRoleOutput, err := timestreamDependencyHelper.IamSvc.GetRole(context.TODO(), getRoleInput)
if err != nil {
var apiErr smithy.APIError
if errors.As(err, &apiErr) {
switch apiErr.ErrorCode() {
case "NoSuchEntityException":
fmt.Println("NoSuchEntityException", apiErr.Error())
return "", nil
default:
fmt.Println(apiErr.Error())
}
} else {
fmt.Println(err.Error())
}
return "", err
}
fmt.Printf("getIamRole is successful : %s\n", JsonMarshalIgnoreError(&getRoleOutput.Role))
return *getRoleOutput.Role.Arn, nil
}
func (timestreamDependencyHelper TimestreamDependencyHelper) CreateIamRole(roleName string) (string, error) {
roleArn, err := timestreamDependencyHelper.getIamRole(roleName)
if err == nil && roleArn != "" {
return roleArn, err
}
createRoleInput := &iam.CreateRoleInput{
RoleName: aws.String(roleName),
Description: aws.String("Created using the AWS SDK for Go"),
AssumeRolePolicyDocument: aws.String(ROLE_POLICY_FORMAT),
}
createRoleOutput, err := timestreamDependencyHelper.IamSvc.CreateRole(context.TODO(), createRoleInput)
if err != nil {
fmt.Printf("Error: %s\n", err.Error())
} else {
fmt.Printf("createRoleOutput is successful : %s\n", JsonMarshalIgnoreError(&createRoleOutput.Role))
return *createRoleOutput.Role.Arn, nil
}
return "", err
}
func (timestreamDependencyHelper TimestreamDependencyHelper) AttachIamPolicy(roleName string, policyArn string) error {
attachRolePolicyInput := &iam.AttachRolePolicyInput{
RoleName: aws.String(roleName),
PolicyArn: aws.String(policyArn),
}
_, err := timestreamDependencyHelper.IamSvc.AttachRolePolicy(context.TODO(), attachRolePolicyInput)
if err != nil {
fmt.Printf("Error: %s\n", err.Error())
} else {
fmt.Printf("attaching RolePolicy is successful\n")
}
return err
}
func (timestreamDependencyHelper TimestreamDependencyHelper) DetachIamPolicy(roleName string, policyArn string) error {
detachRolePolicyInput := &iam.DetachRolePolicyInput{
RoleName: aws.String(roleName),
PolicyArn: aws.String(policyArn),
}
_, err := timestreamDependencyHelper.IamSvc.DetachRolePolicy(context.TODO(), detachRolePolicyInput)
if err != nil {
fmt.Printf("Error: %s\n", err.Error())
} else {
fmt.Println("DetachRolePolicy is successful")
}
return err
}
func (timestreamDependencyHelper TimestreamDependencyHelper) DeleteIamPolicy(policyArn string) error {
deletePolicyInput := &iam.DeletePolicyInput{
PolicyArn: aws.String(policyArn),
}
_, err := timestreamDependencyHelper.IamSvc.DeletePolicy(context.TODO(), deletePolicyInput)
if err != nil {
fmt.Printf("Error: %s\n", err.Error())
} else {
fmt.Println("DeletePolicy is successful")
}
return err
}
func (timestreamDependencyHelper TimestreamDependencyHelper) DeleteIamRole(roleName string) error {
deleteRoleInput := &iam.DeleteRoleInput{
RoleName: aws.String(roleName),
}
_, err := timestreamDependencyHelper.IamSvc.DeleteRole(context.TODO(), deleteRoleInput)
if err != nil {
fmt.Printf("Error: %s\n", err.Error())
} else {
fmt.Println("delete_IAM_role is successful")
}
return err
}
func (timestreamDependencyHelper TimestreamDependencyHelper) CreateIamPolicy(policyName string) (string, error) {
createPolicyInput := &iam.CreatePolicyInput{
PolicyName: aws.String(policyName),
PolicyDocument: aws.String(POLICY_DOCUMENT),
}
createPolicyOutput, err := timestreamDependencyHelper.IamSvc.CreatePolicy(context.TODO(), createPolicyInput)
if err != nil {
var ENTITY_ALREADY_EXISTS *types.EntityAlreadyExistsException
if errors.As(err, &ENTITY_ALREADY_EXISTS) {
fmt.Printf("EntityAlreadyExistsException : %s\n", err.Error())
return timestreamDependencyHelper.getPolicyArn(policyName), nil
} else {
fmt.Printf("Error while creating policy : %s\n", err.Error())
return "", err
}
} else {
fmt.Printf("CreatePolicy is successful : %v\n", createPolicyOutput.ResultMetadata)
return *createPolicyOutput.Policy.Arn, nil
}
}
func (timestreamDependencyHelper TimestreamDependencyHelper) SubscribeToSnsTopic(topicArn string, queueArn string) (string, error) {
createSubscribeInput := &sns.SubscribeInput{
TopicArn: aws.String(topicArn),
Protocol: aws.String("sqs"),
Endpoint: aws.String(queueArn),
}
createQueueOutput, err := timestreamDependencyHelper.SnsSvc.Subscribe(context.TODO(), createSubscribeInput)
if err != nil {
fmt.Printf("Error: %s\n", err.Error())
} else {
fmt.Printf("Subscribe to SNS Topic %s using SQS Queue %s is successful\n", topicArn, queueArn)
return *createQueueOutput.SubscriptionArn, nil
}
return "", err
}
func (timestreamDependencyHelper TimestreamDependencyHelper) UnsubscribeToSnsTopic(subscriptionArn string) error {
unsubscribeInput := &sns.UnsubscribeInput{
SubscriptionArn: aws.String(subscriptionArn),
}
_, err := timestreamDependencyHelper.SnsSvc.Unsubscribe(context.TODO(), unsubscribeInput)
if err != nil {
fmt.Printf("Error: %s\n", err.Error())
} else {
fmt.Println("unsubscribe_to_sns_topic is successful")
}
return err
}
func (timestreamDependencyHelper TimestreamDependencyHelper) CreateS3Bucket(bucketName string, region string) error {
fmt.Printf("Creating S3 Bucket with name %s in region %s\n", bucketName, region)
createBucketInput := &s3.CreateBucketInput{
Bucket: aws.String(bucketName),
}
if region != "us-east-1" {
createBucketInput.CreateBucketConfiguration = &s3types.CreateBucketConfiguration{
LocationConstraint: s3types.BucketLocationConstraint(region),
}
}
createBucketOutput, err := timestreamDependencyHelper.S3Svc.CreateBucket(context.TODO(), createBucketInput)
if err != nil {
fmt.Printf("Error: %s\n", err.Error())
} else {
fmt.Println("Create S3 Bucket is successful : %s", *createBucketOutput.Location)
}
return err
}
func (timestreamDependencyHelper TimestreamDependencyHelper) S3BucketExists(bucketName string) (bool, error) {
input := &s3.HeadBucketInput{
Bucket: aws.String(bucketName),
}
var RESOURCE_NOT_FOUND *s3types.NotFound
_, err := timestreamDependencyHelper.S3Svc.HeadBucket(context.TODO(), input)
if err != nil {
if errors.As(err, &RESOURCE_NOT_FOUND) {
fmt.Printf("Bucket %s does not exists\n", bucketName)
return false,nil
}
fmt.Printf("Failed to locate Bucket %s with error %+v\n", bucketName, err)
return false,err
}
return true,nil
}
func (timestreamDependencyHelper TimestreamDependencyHelper) DeleteS3Bucket(bucketName string) error {
bucketExistsFlag, err := timestreamDependencyHelper.S3BucketExists(bucketName)
if bucketExistsFlag == false {
return err
}
// Setup BatchDeleteIterator to iterate through a list of objects.
deleteObject := func(bucket, key, versionId *string) {
fmt.Printf("Object: %s/%s\n", *key, aws.ToString(versionId))
_, err := timestreamDependencyHelper.S3Svc.DeleteObject(context.TODO(), &s3.DeleteObjectInput{
Bucket: bucket,
Key: key,
VersionId: versionId,
})
if err != nil {
fmt.Printf("Failed to delete object: %v", err)
}
}
in := &s3.ListObjectsV2Input{Bucket: aws.String(bucketName)}
for {
out, err := timestreamDependencyHelper.S3Svc.ListObjectsV2(context.TODO(), in)
if err != nil {
fmt.Printf("Failed to list objects: %v", err)
}
for _, item := range out.Contents {
deleteObject(&bucketName, item.Key, nil)
}
if out.IsTruncated {
in.ContinuationToken = out.NextContinuationToken
} else {
break
}
}
inVer := &s3.ListObjectVersionsInput{Bucket: aws.String(bucketName)}
for {
out, err := timestreamDependencyHelper.S3Svc.ListObjectVersions(context.TODO(), inVer)
if err != nil {
fmt.Printf("Failed to list version objects: %v", err)
}
for _, item := range out.DeleteMarkers {
deleteObject(&bucketName, item.Key, item.VersionId)
}
for _, item := range out.Versions {
deleteObject(&bucketName, item.Key, item.VersionId)
}
if out.IsTruncated {
inVer.VersionIdMarker = out.NextVersionIdMarker
inVer.KeyMarker = out.NextKeyMarker
} else {
break
}
}
fmt.Printf("Deleted object(s) from bucket: %s\n", bucketName)
deleteBucketInput := &s3.DeleteBucketInput{
Bucket: aws.String(bucketName),
}
_, err = timestreamDependencyHelper.S3Svc.DeleteBucket(context.TODO(), deleteBucketInput)
if err != nil {
fmt.Printf("Error: %s\n", err.Error())
} else {
fmt.Println("delete S3 Bucket is successful")
}
return err
}
func (timestreamDependencyHelper TimestreamDependencyHelper) getAccountId() (string, error) {
getCallerIdentityInput := &sts.GetCallerIdentityInput{}
getCallerIdentityOutput, err := timestreamDependencyHelper.StsSvc.GetCallerIdentity(context.TODO(), getCallerIdentityInput)
if err != nil {
fmt.Printf("Error: %s\n", err.Error())
return "", nil
} else {
fmt.Printf("get_account_id is successful : %s\n", JsonMarshalIgnoreError(getCallerIdentityOutput))
return *getCallerIdentityOutput.Account, nil
}
}
func (timestreamDependencyHelper TimestreamDependencyHelper) getPolicyArn(policyName string) string {
accountId, _ := timestreamDependencyHelper.getAccountId()
return fmt.Sprintf("arn:aws:iam::%s:policy/%s", accountId, policyName)
}
func (timestreamDependencyHelper TimestreamDependencyHelper) listReportFilesInS3(s3ErrorReportBucketName string,
errorReportPrefix string) ([]s3types.Object, error) {
listObjectsInput := &s3.ListObjectsV2Input{
Bucket: aws.String(s3ErrorReportBucketName),
Prefix: aws.String(errorReportPrefix),
}
var reports []s3types.Object
for {
listObjectsOutput, err := timestreamDependencyHelper.S3Svc.ListObjectsV2(context.TODO(), listObjectsInput)
if err != nil {
fmt.Printf("Failed to listObjects Error: %s\n", err.Error())
return reports, err
}
reports = append(reports, listObjectsOutput.Contents...)
if listObjectsOutput.IsTruncated {
listObjectsInput.ContinuationToken = listObjectsOutput.NextContinuationToken
} else {
break
}
}
fmt.Printf("listObjectsOutput is successful : %+v\n", reports)
return reports, nil
}
func (timestreamDependencyHelper TimestreamDependencyHelper) ParseS3ErrorReport(s3ErrorReportBucketName string,
errorReportPrefix string) error {
s3Objects, err := timestreamDependencyHelper.listReportFilesInS3(s3ErrorReportBucketName, errorReportPrefix)
if err != nil {
return err
}
fmt.Printf("s3Objects first object contents : %+v\n", s3Objects[0])
err = timestreamDependencyHelper.readErrorReport(&s3Objects[0], s3ErrorReportBucketName)
return err
}
func (timestreamDependencyHelper TimestreamDependencyHelper) readErrorReport(s3Object *s3types.Object,
s3ErrorReportBucketName string) error {
getObjectInput := &s3.GetObjectInput{
Key: s3Object.Key,
Bucket: aws.String(s3ErrorReportBucketName),
}
getObjectOutput, err := timestreamDependencyHelper.S3Svc.GetObject(context.TODO(), getObjectInput)
if err != nil {
fmt.Printf("Error: %s\n", err.Error())
return err
}
buf := new(bytes.Buffer)
buf.ReadFrom(getObjectOutput.Body)
objectContents := buf.String()
fmt.Printf("S3 Error Report Contents : %+v\n", objectContents)
return nil
}