forked from mweagle/Sparta
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
1156 lines (1048 loc) · 37.9 KB
/
util.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
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package cloudformation
import (
"bytes"
"crypto/sha1"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"math/rand"
"os"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"text/template"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudformation"
"github.com/aws/aws-sdk-go/service/lambda"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
"github.com/briandowns/spinner"
humanize "github.com/dustin/go-humanize"
gocf "github.com/mweagle/go-cloudformation"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
var cloudFormationStackTemplateMap map[string]*gocf.Template
var cacheLock sync.Mutex
func init() {
cloudFormationStackTemplateMap = make(map[string]*gocf.Template, 0)
rand.Seed(time.Now().Unix())
}
// RE to ensure CloudFormation compatible resource names
// Issue: https://github.com/mweagle/Sparta/issues/8
// Ref: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resources-section-structure.html
var reCloudFormationInvalidChars = regexp.MustCompile("[^A-Za-z0-9]+")
// maximum amount of time allowed for polling CloudFormation
var cloudformationPollingTimeout = 3 * time.Minute
////////////////////////////////////////////////////////////////////////////////
// Private
////////////////////////////////////////////////////////////////////////////////
type resourceProvisionMetrics struct {
resourceType string
logicalResourceID string
startTime time.Time
endTime time.Time
elapsed time.Duration
}
// BEGIN - templateConverter
// Struct to encapsulate transforming data into
type templateConverter struct {
templateReader io.Reader
additionalTemplateProps map[string]interface{}
// internals
expandedTemplate string
contents []gocf.Stringable
conversionError error
}
func (converter *templateConverter) expandTemplate() *templateConverter {
if nil != converter.conversionError {
return converter
}
templateDataBytes, templateDataErr := ioutil.ReadAll(converter.templateReader)
if nil != templateDataErr {
converter.conversionError = templateDataErr
return converter
}
templateData := string(templateDataBytes)
parsedTemplate, templateErr := template.New("CloudFormation").Parse(templateData)
if nil != templateErr {
converter.conversionError = templateDataErr
return converter
}
output := &bytes.Buffer{}
executeErr := parsedTemplate.Execute(output, converter.additionalTemplateProps)
if nil != executeErr {
converter.conversionError = executeErr
return converter
}
converter.expandedTemplate = output.String()
return converter
}
func (converter *templateConverter) parseData() *templateConverter {
if converter.conversionError != nil {
return converter
}
reAWSProp := regexp.MustCompile("\\{\\s*\"\\s*(Ref|Fn::GetAtt|Fn::FindInMap)")
splitData := strings.Split(converter.expandedTemplate, "\n")
splitDataLineCount := len(splitData)
for eachLineIndex, eachLine := range splitData {
curContents := eachLine
for len(curContents) != 0 {
matchInfo := reAWSProp.FindStringSubmatchIndex(curContents)
if nil != matchInfo {
// If there's anything at the head, push it.
if matchInfo[0] != 0 {
head := curContents[0:matchInfo[0]]
converter.contents = append(converter.contents, gocf.String(fmt.Sprintf("%s", head)))
curContents = curContents[len(head):]
}
// There's at least one match...find the closing brace...
var parsed map[string]interface{}
for indexPos, eachChar := range curContents {
if string(eachChar) == "}" {
testBlock := curContents[0 : indexPos+1]
err := json.Unmarshal([]byte(testBlock), &parsed)
if err == nil {
parsedContents, parsedContentsErr := parseFnJoinExpr(parsed)
if nil != parsedContentsErr {
converter.conversionError = parsedContentsErr
return converter
}
converter.contents = append(converter.contents, parsedContents)
curContents = curContents[indexPos+1:]
if len(curContents) <= 0 && (eachLineIndex < (splitDataLineCount - 1)) {
converter.contents = append(converter.contents, gocf.String("\n"))
}
break
}
}
}
if nil == parsed {
// We never did find the end...
converter.conversionError = fmt.Errorf("Invalid CloudFormation JSON expression on line: %s", eachLine)
return converter
}
} else {
// No match, just include it iff there is another line afterwards
newlineValue := ""
if eachLineIndex < (splitDataLineCount - 1) {
newlineValue = "\n"
}
// Always include a newline at a minimum
appendLine := fmt.Sprintf("%s%s", curContents, newlineValue)
if len(appendLine) != 0 {
converter.contents = append(converter.contents, gocf.String(appendLine))
}
break
}
}
}
return converter
}
func (converter *templateConverter) results() (*gocf.StringExpr, error) {
if nil != converter.conversionError {
return nil, converter.conversionError
}
return gocf.Join("", converter.contents...), nil
}
// END - templateConverter
func cloudformationPollingDelay() time.Duration {
return time.Duration(3+rand.Int31n(5)) * time.Second
}
func existingStackTemplate(serviceName string,
session *session.Session,
logger *logrus.Logger) (*gocf.Template, error) {
cacheLock.Lock()
defer cacheLock.Unlock()
template, templateExists := cloudFormationStackTemplateMap[serviceName]
if !templateExists {
templateParams := &cloudformation.GetTemplateInput{
StackName: aws.String(serviceName),
}
logger.WithFields(logrus.Fields{
"Service": serviceName,
}).Info("Fetching existing CloudFormation template")
cloudformationSvc := cloudformation.New(session)
rawTemplate, rawTemplateErr := cloudformationSvc.GetTemplate(templateParams)
if nil != rawTemplateErr {
if strings.Contains(rawTemplateErr.Error(), "does not exist") {
template = nil
} else {
return nil, rawTemplateErr
}
} else {
t := gocf.Template{}
jsonDecodeErr := json.NewDecoder(strings.NewReader(*rawTemplate.TemplateBody)).Decode(&t)
if nil != jsonDecodeErr {
return nil, jsonDecodeErr
}
template = &t
}
cloudFormationStackTemplateMap[serviceName] = template
} else {
logger.WithFields(logrus.Fields{
"Service": serviceName,
}).Debug("Using cached CloudFormation Template resources")
}
return template, nil
}
func updateStackViaChangeSet(serviceName string,
cfTemplate *gocf.Template,
cfTemplateURL string,
awsTags []*cloudformation.Tag,
awsCloudFormation *cloudformation.CloudFormation,
logger *logrus.Logger) error {
// Create a change set name...
changeSetRequestName := CloudFormationResourceName(fmt.Sprintf("%sChangeSet", serviceName))
_, changesErr := CreateStackChangeSet(changeSetRequestName,
serviceName,
cfTemplate,
cfTemplateURL,
awsTags,
awsCloudFormation,
logger)
if nil != changesErr {
return changesErr
}
//////////////////////////////////////////////////////////////////////////////
// Apply the change
executeChangeSetInput := cloudformation.ExecuteChangeSetInput{
ChangeSetName: aws.String(changeSetRequestName),
StackName: aws.String(serviceName),
}
executeChangeSetOutput, executeChangeSetError := awsCloudFormation.ExecuteChangeSet(&executeChangeSetInput)
logger.WithFields(logrus.Fields{
"ExecuteChangeSetOutput": executeChangeSetOutput,
}).Debug("ExecuteChangeSet result")
if nil == executeChangeSetError {
logger.WithFields(logrus.Fields{
"StackName": serviceName,
}).Info("Issued ExecuteChangeSet request")
}
return executeChangeSetError
}
func existingLambdaResourceVersions(serviceName string,
lambdaResourceName string,
session *session.Session,
logger *logrus.Logger) (*lambda.ListVersionsByFunctionOutput, error) {
errorIsNotExist := func(apiError error) bool {
return apiError != nil && strings.Contains(apiError.Error(), "does not exist")
}
logger.WithFields(logrus.Fields{
"ResourceName": lambdaResourceName,
}).Info("Fetching existing function versions")
cloudFormationSvc := cloudformation.New(session)
describeParams := &cloudformation.DescribeStackResourceInput{
StackName: aws.String(serviceName),
LogicalResourceId: aws.String(lambdaResourceName),
}
describeResponse, describeResponseErr := cloudFormationSvc.DescribeStackResource(describeParams)
logger.WithFields(logrus.Fields{
"Response": describeResponse,
"ResponseErr": describeResponseErr,
}).Debug("Describe response")
if errorIsNotExist(describeResponseErr) {
return nil, nil
} else if describeResponseErr != nil {
return nil, describeResponseErr
}
listVersionsParams := &lambda.ListVersionsByFunctionInput{
FunctionName: describeResponse.StackResourceDetail.PhysicalResourceId,
MaxItems: aws.Int64(128),
}
lambdaSvc := lambda.New(session)
listVersionsResp, listVersionsRespErr := lambdaSvc.ListVersionsByFunction(listVersionsParams)
if errorIsNotExist(listVersionsRespErr) {
return nil, nil
} else if listVersionsRespErr != nil {
return nil, listVersionsRespErr
}
logger.WithFields(logrus.Fields{
"Response": listVersionsResp,
"ResponseErr": listVersionsRespErr,
}).Debug("ListVersionsByFunction")
return listVersionsResp, nil
}
func toExpressionSlice(input interface{}) ([]string, error) {
var expressions []string
slice, sliceOK := input.([]interface{})
if !sliceOK {
return nil, fmt.Errorf("Failed to convert to slice")
}
for _, eachValue := range slice {
switch str := eachValue.(type) {
case string:
expressions = append(expressions, str)
}
}
return expressions, nil
}
func parseFnJoinExpr(data map[string]interface{}) (*gocf.StringExpr, error) {
if len(data) <= 0 {
return nil, fmt.Errorf("FnJoinExpr data is empty")
}
for eachKey, eachValue := range data {
switch eachKey {
case "Ref":
return gocf.Ref(eachValue.(string)).String(), nil
case "Fn::GetAtt":
attrValues, attrValuesErr := toExpressionSlice(eachValue)
if nil != attrValuesErr {
return nil, attrValuesErr
}
if len(attrValues) != 2 {
return nil, fmt.Errorf("Invalid params for Fn::GetAtt: %s", eachValue)
}
return gocf.GetAtt(attrValues[0], attrValues[1]).String(), nil
case "Fn::FindInMap":
attrValues, attrValuesErr := toExpressionSlice(eachValue)
if nil != attrValuesErr {
return nil, attrValuesErr
}
if len(attrValues) != 3 {
return nil, fmt.Errorf("Invalid params for Fn::FindInMap: %s", eachValue)
}
return gocf.FindInMap(attrValues[0], gocf.String(attrValues[1]), gocf.String(attrValues[2])), nil
}
}
return nil, fmt.Errorf("Unsupported AWS Function detected: %#v", data)
}
func stackCapabilities(template *gocf.Template) []*string {
capabilitiesMap := make(map[string]bool, 0)
// Only require IAM capability if the definition requires it.
for _, eachResource := range template.Resources {
if eachResource.Properties.CfnResourceType() == "AWS::IAM::Role" {
capabilitiesMap["CAPABILITY_IAM"] = true
switch typedResource := eachResource.Properties.(type) {
case gocf.IAMRole:
capabilitiesMap["CAPABILITY_NAMED_IAM"] = (typedResource.RoleName != nil)
case *gocf.IAMRole:
capabilitiesMap["CAPABILITY_NAMED_IAM"] = (typedResource.RoleName != nil)
}
}
}
capabilities := make([]*string, len(capabilitiesMap), len(capabilitiesMap))
capabilitiesIndex := 0
for eachKey := range capabilitiesMap {
capabilities[capabilitiesIndex] = aws.String(eachKey)
capabilitiesIndex++
}
return capabilities
}
////////////////////////////////////////////////////////////////////////////////
// Public
////////////////////////////////////////////////////////////////////////////////
// DynamicValueToStringExpr is a DRY function to type assert
// a potentiall dynamic value into a gocf.Stringable
// satisfying type
func DynamicValueToStringExpr(dynamicValue interface{}) gocf.Stringable {
var stringExpr gocf.Stringable
switch typedValue := dynamicValue.(type) {
case string:
stringExpr = gocf.String(typedValue)
case gocf.Stringable:
stringExpr = typedValue.String()
case *gocf.StringExpr:
stringExpr = typedValue
case gocf.RefFunc:
stringExpr = typedValue.String()
default:
panic(fmt.Sprintf("Unsupported dynamic value type: %+v", typedValue))
}
return stringExpr
}
// S3AllKeysArnForBucket returns a CloudFormation-compatible Arn expression
// (string or Ref) for all bucket keys (`/*`). The bucket
// parameter may be either a string or an interface{} ("Ref: "myResource")
// value
func S3AllKeysArnForBucket(bucket interface{}) *gocf.StringExpr {
arnParts := []gocf.Stringable{
gocf.String("arn:aws:s3:::"),
DynamicValueToStringExpr(bucket),
gocf.String("/*"),
}
return gocf.Join("", arnParts...).String()
}
// S3ArnForBucket returns a CloudFormation-compatible Arn expression
// (string or Ref) suitable for template reference. The bucket
// parameter may be either a string or an interface{} ("Ref: "myResource")
// value
func S3ArnForBucket(bucket interface{}) *gocf.StringExpr {
arnParts := []gocf.Stringable{
gocf.String("arn:aws:s3:::"),
DynamicValueToStringExpr(bucket),
}
return gocf.Join("", arnParts...).String()
}
// MapToResourceTags transforms a go map[string]string to a CloudFormation-compliant
// Tags representation. See http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html
func MapToResourceTags(tagMap map[string]string) []interface{} {
tags := make([]interface{}, len(tagMap), len(tagMap))
tagsIndex := 0
for eachKey, eachValue := range tagMap {
tags[tagsIndex] = map[string]interface{}{
"Key": eachKey,
"Value": eachValue,
}
tagsIndex++
}
return tags
}
// ConvertToTemplateExpression transforms the templateData contents into
// an Fn::Join- compatible representation for template serialization.
// The templateData contents may include both golang text/template properties
// and single-line JSON Fn::Join supported serializations.
func ConvertToTemplateExpression(templateData io.Reader,
additionalUserTemplateProperties map[string]interface{}) (*gocf.StringExpr, error) {
converter := &templateConverter{
templateReader: templateData,
additionalTemplateProps: additionalUserTemplateProperties,
}
return converter.expandTemplate().parseData().results()
}
// AutoIncrementingLambdaVersionInfo is dynamically populated during
// a call AddAutoIncrementingLambdaVersionResource. The VersionHistory
// is a map of published versions to their CloudFormation resource names
type AutoIncrementingLambdaVersionInfo struct {
// The version that will be published as part of this operation
CurrentVersion int
// The CloudFormation resource name that defines the
// AWS::Lambda::Version resource to be included with this operation
CurrentVersionResourceName string
// The version history that maps a published version value
// to its CloudFormation resource name. Used for defining lagging
// indicator Alias values
VersionHistory map[int]string
}
// AddAutoIncrementingLambdaVersionResource inserts a new
// AWS::Lambda::Version resource into the template. It uses
// the existing CloudFormation template representation
// to determine the version index to append. The returned
// map is from `versionIndex`->`CloudFormationResourceName`
// to support second-order AWS::Lambda::Alias records on a
// per-version level
func AddAutoIncrementingLambdaVersionResource(serviceName string,
lambdaResourceName string,
cfTemplate *gocf.Template,
logger *logrus.Logger) (*AutoIncrementingLambdaVersionInfo, error) {
// Get the template
session, sessionErr := session.NewSession()
if sessionErr != nil {
return nil, sessionErr
}
// Get the current template - for each version we find in the version listing
// we look up the actual CF resource and copy it into this template
existingStackDefinition, existingStackDefinitionErr := existingStackTemplate(serviceName,
session,
logger)
if nil != existingStackDefinitionErr {
return nil, existingStackDefinitionErr
}
existingVersions, existingVersionsErr := existingLambdaResourceVersions(serviceName,
lambdaResourceName,
session,
logger)
if nil != existingVersionsErr {
return nil, existingVersionsErr
}
// Initialize the auto incrementing version struct
autoIncrementingLambdaVersionInfo := AutoIncrementingLambdaVersionInfo{
CurrentVersion: 0,
CurrentVersionResourceName: "",
VersionHistory: make(map[int]string, 0),
}
lambdaVersionResourceName := func(versionIndex int) string {
return CloudFormationResourceName(lambdaResourceName,
"version",
strconv.Itoa(versionIndex))
}
if nil != existingVersions {
// Add the CloudFormation resource
logger.WithFields(logrus.Fields{
"VersionCount": len(existingVersions.Versions) - 1, // Ignore $LATEST
"ResourceName": lambdaResourceName,
}).Info("Total number of published versions")
for _, eachEntry := range existingVersions.Versions {
versionIndex, versionIndexErr := strconv.Atoi(*eachEntry.Version)
if nil == versionIndexErr {
// Find the existing resource...
versionResourceName := lambdaVersionResourceName(versionIndex)
if nil == existingStackDefinition {
return nil, fmt.Errorf("Unable to find existing Version resource in nil Template")
}
cfResourceDefinition, cfResourceDefinitionExists := existingStackDefinition.Resources[versionResourceName]
if !cfResourceDefinitionExists {
return nil, fmt.Errorf("Unable to find existing Version resource (Resource: %s, Version: %d) in template",
versionResourceName,
versionIndex)
}
cfTemplate.Resources[versionResourceName] = cfResourceDefinition
// Add the CloudFormation resource
logger.WithFields(logrus.Fields{
"Version": versionIndex,
"ResourceName": versionResourceName,
}).Debug("Preserving Lambda version")
// Store the state, tracking the latest version
autoIncrementingLambdaVersionInfo.VersionHistory[versionIndex] = versionResourceName
if versionIndex > autoIncrementingLambdaVersionInfo.CurrentVersion {
autoIncrementingLambdaVersionInfo.CurrentVersion = versionIndex
}
}
}
}
// Bump the version and add a new entry...
autoIncrementingLambdaVersionInfo.CurrentVersion++
versionResource := &gocf.LambdaVersion{
FunctionName: gocf.GetAtt(lambdaResourceName, "Arn").String(),
}
autoIncrementingLambdaVersionInfo.CurrentVersionResourceName = lambdaVersionResourceName(autoIncrementingLambdaVersionInfo.CurrentVersion)
cfTemplate.AddResource(autoIncrementingLambdaVersionInfo.CurrentVersionResourceName, versionResource)
// Log the version we're about to publish...
logger.WithFields(logrus.Fields{
"ResourceName": lambdaResourceName,
"StackVersion": autoIncrementingLambdaVersionInfo.CurrentVersion,
}).Info("Inserting new version resource")
return &autoIncrementingLambdaVersionInfo, nil
}
// StackEvents returns the slice of cloudformation.StackEvents for the given stackID or stackName
func StackEvents(stackID string,
eventFilterLowerBoundInclusive time.Time,
awsSession *session.Session) ([]*cloudformation.StackEvent, error) {
cfService := cloudformation.New(awsSession)
var events []*cloudformation.StackEvent
nextToken := ""
for {
params := &cloudformation.DescribeStackEventsInput{
StackName: aws.String(stackID),
}
if len(nextToken) > 0 {
params.NextToken = aws.String(nextToken)
}
resp, err := cfService.DescribeStackEvents(params)
if nil != err {
return nil, err
}
for _, eachEvent := range resp.StackEvents {
if eachEvent.Timestamp.Equal(eventFilterLowerBoundInclusive) ||
eachEvent.Timestamp.After(eventFilterLowerBoundInclusive) {
events = append(events, eachEvent)
}
}
if nil == resp.NextToken {
break
} else {
nextToken = *resp.NextToken
}
}
return events, nil
}
// WaitForStackOperationCompleteResult encapsulates the stackInfo
// following a WaitForStackOperationComplete call
type WaitForStackOperationCompleteResult struct {
operationSuccessful bool
stackInfo *cloudformation.Stack
}
// WaitForStackOperationComplete is a blocking, polling based call that
// periodically fetches the stackID set of events and uses the state value
// to determine if an operation is complete
func WaitForStackOperationComplete(stackID string,
pollingMessage string,
awsCloudFormation *cloudformation.CloudFormation,
logger *logrus.Logger) (*WaitForStackOperationCompleteResult, error) {
result := &WaitForStackOperationCompleteResult{}
startTime := time.Now()
// Startup a spinner...
charSetIndex := 6
cliSpinner := spinner.New(spinner.CharSets[charSetIndex], 333*time.Millisecond)
cliSpinnerStarted := false
// Poll for the current stackID state, and
describeStacksInput := &cloudformation.DescribeStacksInput{
StackName: aws.String(stackID),
}
for waitComplete := false; !waitComplete; {
// Startup the spinner if needed...
switch logger.Formatter.(type) {
case *logrus.JSONFormatter:
{
logger.Info(pollingMessage)
}
default:
if !cliSpinnerStarted {
cliSpinner.Start()
defer cliSpinner.Stop()
cliSpinnerStarted = true
}
spinnerText := fmt.Sprintf(" %s (requested: %s)",
pollingMessage,
humanize.Time(startTime))
cliSpinner.Suffix = spinnerText
}
// Then sleep and figure out if things are done...
sleepDuration := time.Duration(11+rand.Int31n(13)) * time.Second
time.Sleep(sleepDuration)
describeStacksOutput, err := awsCloudFormation.DescribeStacks(describeStacksInput)
if nil != err {
// TODO - add retry iff we're RateExceeded due to collective access
return nil, err
}
if len(describeStacksOutput.Stacks) <= 0 {
return nil, fmt.Errorf("Failed to enumerate stack info: %v", *describeStacksInput.StackName)
}
result.stackInfo = describeStacksOutput.Stacks[0]
switch *(result.stackInfo).StackStatus {
case cloudformation.StackStatusCreateComplete,
cloudformation.StackStatusUpdateComplete:
result.operationSuccessful = true
waitComplete = true
case
// Include DeleteComplete as new provisions will automatically rollback
cloudformation.StackStatusDeleteComplete,
cloudformation.StackStatusCreateFailed,
cloudformation.StackStatusDeleteFailed,
cloudformation.StackStatusRollbackFailed,
cloudformation.StackStatusRollbackComplete,
cloudformation.StackStatusUpdateRollbackComplete:
result.operationSuccessful = false
waitComplete = true
default:
// If this is JSON output, just do the normal thing
// NOP
}
}
return result, nil
}
// CloudFormationResourceName returns a name suitable as a logical
// CloudFormation resource value. See http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resources-section-structure.html
// for more information. The `prefix` value should provide a hint as to the
// resource type (eg, `SNSConfigurator`, `ImageTranscoder`). Note that the returned
// name is not content-addressable.
func CloudFormationResourceName(prefix string, parts ...string) string {
hash := sha1.New()
_, writeErr := hash.Write([]byte(prefix))
if writeErr != nil {
// TODO
}
if len(parts) <= 0 {
randValue := rand.Int63()
_, writeErr = hash.Write([]byte(strconv.FormatInt(randValue, 10)))
if writeErr != nil {
// TODO
}
} else {
for _, eachPart := range parts {
_, writeErr = hash.Write([]byte(eachPart))
if writeErr != nil {
// TODO
}
}
}
resourceName := fmt.Sprintf("%s%s", prefix, hex.EncodeToString(hash.Sum(nil)))
// Ensure that any non alphanumeric characters are replaced with ""
return reCloudFormationInvalidChars.ReplaceAllString(resourceName, "x")
}
// UploadTemplate marshals the given cfTemplate and uploads it to the
// supplied bucket using the given KeyName
func UploadTemplate(serviceName string,
cfTemplate *gocf.Template,
s3Bucket string,
s3KeyName string,
awsSession *session.Session,
logger *logrus.Logger) (string, error) {
logger.WithFields(logrus.Fields{
"Key": s3KeyName,
"Bucket": s3Bucket,
}).Info("Uploading CloudFormation template")
s3Uploader := s3manager.NewUploader(awsSession)
// Serialize the template and upload it
cfTemplateJSON, err := json.Marshal(cfTemplate)
if err != nil {
return "", errors.Wrap(err, "Failed to Marshal CloudFormation template")
}
// Upload the actual CloudFormation template to S3 to maximize the template
// size limit
// Ref: http://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_CreateStack.html
contentBody := string(cfTemplateJSON)
uploadInput := &s3manager.UploadInput{
Bucket: &s3Bucket,
Key: &s3KeyName,
ContentType: aws.String("application/json"),
Body: strings.NewReader(contentBody),
}
templateUploadResult, templateUploadResultErr := s3Uploader.Upload(uploadInput)
if nil != templateUploadResultErr {
return "", templateUploadResultErr
}
// Be transparent
logger.WithFields(logrus.Fields{
"URL": templateUploadResult.Location,
}).Info("Template uploaded")
return templateUploadResult.Location, nil
}
// StackExists returns whether the given stackName or stackID currently exists
func StackExists(stackNameOrID string, awsSession *session.Session, logger *logrus.Logger) (bool, error) {
cf := cloudformation.New(awsSession)
describeStacksInput := &cloudformation.DescribeStacksInput{
StackName: aws.String(stackNameOrID),
}
describeStacksOutput, err := cf.DescribeStacks(describeStacksInput)
logger.WithFields(logrus.Fields{
"DescribeStackOutput": describeStacksOutput,
}).Debug("DescribeStackOutput results")
exists := false
if err != nil {
logger.WithFields(logrus.Fields{
"DescribeStackOutputError": err,
}).Debug("DescribeStackOutput")
// If the stack doesn't exist, then no worries
if strings.Contains(err.Error(), "does not exist") {
exists = false
} else {
return false, err
}
} else {
exists = true
}
return exists, nil
}
// CreateStackChangeSet returns the DescribeChangeSetOutput
// for a given stack transformation
func CreateStackChangeSet(changeSetRequestName string,
serviceName string,
cfTemplate *gocf.Template,
templateURL string,
awsTags []*cloudformation.Tag,
awsCloudFormation *cloudformation.CloudFormation,
logger *logrus.Logger) (*cloudformation.DescribeChangeSetOutput, error) {
capabilities := stackCapabilities(cfTemplate)
changeSetInput := &cloudformation.CreateChangeSetInput{
Capabilities: capabilities,
ChangeSetName: aws.String(changeSetRequestName),
ClientToken: aws.String(changeSetRequestName),
Description: aws.String(fmt.Sprintf("Change set for service: %s", serviceName)),
StackName: aws.String(serviceName),
TemplateURL: aws.String(templateURL),
}
if len(awsTags) != 0 {
changeSetInput.Tags = awsTags
}
_, changeSetError := awsCloudFormation.CreateChangeSet(changeSetInput)
if nil != changeSetError {
return nil, changeSetError
}
logger.WithFields(logrus.Fields{
"StackName": serviceName,
}).Info("Issued CreateChangeSet request")
describeChangeSetInput := cloudformation.DescribeChangeSetInput{
ChangeSetName: aws.String(changeSetRequestName),
StackName: aws.String(serviceName),
}
var describeChangeSetOutput *cloudformation.DescribeChangeSetOutput
// Loop, with a total timeout of 3 minutes
startTime := time.Now()
changeSetStabilized := false
for !changeSetStabilized {
sleepDuration := cloudformationPollingDelay()
time.Sleep(sleepDuration)
changeSetOutput, describeChangeSetError := awsCloudFormation.DescribeChangeSet(&describeChangeSetInput)
if nil != describeChangeSetError {
return nil, describeChangeSetError
}
describeChangeSetOutput = changeSetOutput
// The current status of the change set, such as CREATE_IN_PROGRESS, CREATE_COMPLETE,
// or FAILED.
if nil != describeChangeSetOutput {
switch *describeChangeSetOutput.Status {
case "CREATE_IN_PROGRESS":
// If this has taken more than 3 minutes, then that's an error
elapsedTime := time.Since(startTime)
if elapsedTime > cloudformationPollingTimeout {
return nil, fmt.Errorf("ChangeSet failed to finalize within window: %s", elapsedTime.String())
}
case "CREATE_COMPLETE":
changeSetStabilized = true
case "FAILED":
return nil, fmt.Errorf("Failed to create ChangeSet: %#v", *describeChangeSetOutput)
}
}
}
logger.WithFields(logrus.Fields{
"DescribeChangeSetOutput": describeChangeSetOutput,
}).Debug("DescribeChangeSet result")
//////////////////////////////////////////////////////////////////////////////
// If there aren't any changes, then skip it...
if len(describeChangeSetOutput.Changes) <= 0 {
logger.WithFields(logrus.Fields{
"StackName": serviceName,
}).Info("No changes detected for service")
// Delete it...
_, deleteChangeSetResultErr := DeleteChangeSet(serviceName,
changeSetRequestName,
awsCloudFormation)
return nil, deleteChangeSetResultErr
}
return describeChangeSetOutput, nil
}
// DeleteChangeSet is a utility function that attempts to delete
// an existing CloudFormation change set, with a bit of retry
// logic in case of EC
func DeleteChangeSet(stackName string,
changeSetRequestName string,
awsCloudFormation *cloudformation.CloudFormation) (*cloudformation.DeleteChangeSetOutput, error) {
// Delete request...
deleteChangeSetInput := cloudformation.DeleteChangeSetInput{
ChangeSetName: aws.String(changeSetRequestName),
StackName: aws.String(stackName),
}
startTime := time.Now()
for {
elapsedTime := time.Since(startTime)
deleteChangeSetResults, deleteChangeSetResultErr := awsCloudFormation.DeleteChangeSet(&deleteChangeSetInput)
if nil == deleteChangeSetResultErr {
return deleteChangeSetResults, nil
} else if strings.Contains(deleteChangeSetResultErr.Error(), "CREATE_IN_PROGRESS") {
if elapsedTime > cloudformationPollingTimeout {
return nil, fmt.Errorf("Failed to delete ChangeSet within timeout window: %s", elapsedTime.String())
}
sleepDuration := cloudformationPollingDelay()
time.Sleep(sleepDuration)
} else {
return nil, deleteChangeSetResultErr
}
}
}
// ConvergeStackState ensures that the serviceName converges to the template
// state defined by cfTemplate. This function establishes a polling loop to determine
// when the stack operation has completed.
func ConvergeStackState(serviceName string,
cfTemplate *gocf.Template,
templateURL string,
tags map[string]string,
startTime time.Time,
operationTimeout time.Duration,
awsSession *session.Session,
outputsDividerChar string,
dividerWidth int,
logger *logrus.Logger) (*cloudformation.Stack, error) {
awsCloudFormation := cloudformation.New(awsSession)
// Update the tags
awsTags := make([]*cloudformation.Tag, 0)
if nil != tags {
for eachKey, eachValue := range tags {
awsTags = append(awsTags,
&cloudformation.Tag{
Key: aws.String(eachKey),
Value: aws.String(eachValue),
})
}
}
exists, existsErr := StackExists(serviceName, awsSession, logger)
if nil != existsErr {
return nil, existsErr
}
stackID := ""
if exists {
updateErr := updateStackViaChangeSet(serviceName,
cfTemplate,
templateURL,
awsTags,
awsCloudFormation,
logger)
if nil != updateErr {
return nil, updateErr
}
stackID = serviceName
} else {
// Create stack
createStackInput := &cloudformation.CreateStackInput{
StackName: aws.String(serviceName),
TemplateURL: aws.String(templateURL),
TimeoutInMinutes: aws.Int64(int64(operationTimeout.Minutes())),
OnFailure: aws.String(cloudformation.OnFailureDelete),
Capabilities: stackCapabilities(cfTemplate),
}
if len(awsTags) != 0 {
createStackInput.Tags = awsTags
}
createStackResponse, createStackResponseErr := awsCloudFormation.CreateStack(createStackInput)
if nil != createStackResponseErr {
return nil, createStackResponseErr
}
logger.WithFields(logrus.Fields{
"StackID": *createStackResponse.StackId,
}).Info("Creating stack")
stackID = *createStackResponse.StackId
}
// Wait for the operation to succeed
pollingMessage := "Waiting for CloudFormation operation to complete"
convergeResult, convergeErr := WaitForStackOperationComplete(stackID,
pollingMessage,
awsCloudFormation,
logger)
if nil != convergeErr {
return nil, convergeErr
}
// Get the events and assemble them into either errors to output
// or summary information
resourceMetrics := make(map[string]*resourceProvisionMetrics)
errorMessages := []string{}
events, err := StackEvents(stackID, startTime, awsSession)
if nil != err {
return nil, fmt.Errorf("Failed to retrieve stack events: %s", err.Error())
}
for _, eachEvent := range events {
switch *eachEvent.ResourceStatus {
case cloudformation.ResourceStatusCreateFailed,
cloudformation.ResourceStatusDeleteFailed,
cloudformation.ResourceStatusUpdateFailed:
errMsg := fmt.Sprintf("\tError ensuring %s (%s): %s",