/
provision.go
1435 lines (1291 loc) · 44.6 KB
/
provision.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
// +build !lambdabinary
package sparta
import (
"archive/zip"
"bytes"
"crypto/sha1"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
spartaZip "github.com/mweagle/Sparta/zip"
"github.com/mweagle/cloudformationresources"
"io"
"io/ioutil"
"math/rand"
"os"
"os/exec"
"path"
"path/filepath"
"reflect"
"runtime"
"strings"
"sync"
"time"
"github.com/Sirupsen/logrus"
"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/iam"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
gocf "github.com/crewjam/go-cloudformation"
spartaAWS "github.com/mweagle/Sparta/aws"
)
////////////////////////////////////////////////////////////////////////////////
// CONSTANTS
////////////////////////////////////////////////////////////////////////////////
const (
// OutputSpartaHomeKey is the keyname used in the CloudFormation Output
// that stores the Sparta home URL.
// @enum OutputKey
OutputSpartaHomeKey = "SpartaHome"
// OutputSpartaVersionKey is the keyname used in the CloudFormation Output
// that stores the Sparta version used to provision/update the service.
// @enum OutputKey
OutputSpartaVersionKey = "SpartaVersion"
// OutputSpartaBuildIDKey is the keyname used in the CloudFormation Output
// that stores the user-supplied or automatically generated BuildID
// for this run
OutputSpartaBuildIDKey = "SpartaBuildID"
)
// The basename of the scripts that are embedded into CONSTANTS.go
// by `esc` during the generate phase. In order to export these, there
// MUST be a corresponding PROXIED_MODULES entry for the base filename
// in resources/index.js
var customResourceScripts = []string{"sparta_utils.js",
"golang-constants.json"}
var golangCustomResourceTypes = []string{
cloudformationresources.SESLambdaEventSource,
cloudformationresources.S3LambdaEventSource,
cloudformationresources.SNSLambdaEventSource,
cloudformationresources.CloudWatchLogsLambdaEventSource,
cloudformationresources.ZipToS3Bucket,
}
// The relative path of the custom scripts that is used
// to create the filename relative path when creating the custom archive
const provisioningResourcesRelPath = "/resources/provision"
// Represents data associated with provisioning the S3 Site iff defined
type s3SiteContext struct {
s3Site *S3Site
s3SiteLambdaZipKey string
}
// Rollback function called in the event of a stack provisioning failure
type rollbackFunction func(logger *logrus.Logger) error
// Type of a workflow step. Each step is responsible
// for returning the next step or an error if the overall
// workflow should stop.
type workflowStep func(ctx *workflowContext) (workflowStep, error)
////////////////////////////////////////////////////////////////////////////////
// Workflow context
// The workflow context is created by `provision` and provided to all
// functions that constitute the provisioning workflow.
type workflowContext struct {
// Is this is a -dry-run?
noop bool
// Canonical basename of the service. Also used as the CloudFormation
// stack name
serviceName string
// Service description
serviceDescription string
// The slice of Lambda functions that constitute the service
lambdaAWSInfos []*LambdaAWSInfo
// Optional APIGateway definition to associate with this service
api *API
// Optional S3 site data to provision together with this service
s3SiteContext *s3SiteContext
// CloudFormation Template
cfTemplate *gocf.Template
// Cached IAM role name map. Used to support dynamic and static IAM role
// names. Static ARN role names are checked for existence via AWS APIs
// prior to CloudFormation provisioning.
lambdaIAMRoleNameMap map[string]*gocf.StringExpr
// The user-supplied S3 bucket where service artifacts should be posted.
s3Bucket string
// The user-supplied or automatically generated BuildID
buildID string
// The programmatically determined S3 item key for this service's cloudformation
// definition.
s3LambdaZipKey string
// AWS Session to be used for all API calls made in the process of provisioning
// this service.
awsSession *session.Session
// IO writer for autogenerated template results
templateWriter io.Writer
// User supplied workflow hooks
workflowHooks *WorkflowHooks
// Context to pass between workflow operations
workflowHooksContext map[string]interface{}
// Preconfigured logger
logger *logrus.Logger
// Optional rollback functions that workflow steps may append to if they
// have made mutations during provisioning.
rollbackFunctions []rollbackFunction
}
// Register a rollback function in the event that the provisioning
// function failed.
func (ctx *workflowContext) registerRollback(userFunction rollbackFunction) {
if nil == ctx.rollbackFunctions || len(ctx.rollbackFunctions) <= 0 {
ctx.rollbackFunctions = make([]rollbackFunction, 0)
}
ctx.rollbackFunctions = append(ctx.rollbackFunctions, userFunction)
}
// Run any provided rollback functions
func (ctx *workflowContext) rollback() {
// Run each cleanup function concurrently. If there's an error
// all we're going to do is log it as a warning, since at this
// point there's nothing to do...
var wg sync.WaitGroup
wg.Add(len(ctx.rollbackFunctions))
// Include the user defined rollback if there is one...
if ctx.workflowHooks != nil && ctx.workflowHooks.Rollback != nil {
wg.Add(1)
go func(hook RollbackHook, context map[string]interface{},
serviceName string,
awsSession *session.Session,
noop bool,
logger *logrus.Logger) {
// Decrement the counter when the goroutine completes.
defer wg.Done()
hook(context, serviceName, awsSession, noop, logger)
}(ctx.workflowHooks.Rollback,
ctx.workflowHooksContext,
ctx.serviceName,
ctx.awsSession,
ctx.noop,
ctx.logger)
}
ctx.logger.WithFields(logrus.Fields{
"RollbackCount": len(ctx.rollbackFunctions),
}).Info("Invoking rollback functions")
for _, eachCleanup := range ctx.rollbackFunctions {
go func(cleanupFunc rollbackFunction, goLogger *logrus.Logger) {
// Decrement the counter when the goroutine completes.
defer wg.Done()
// Fetch the URL.
err := cleanupFunc(goLogger)
if nil != err {
ctx.logger.WithFields(logrus.Fields{
"Error": err,
}).Warning("Failed to cleanup resource")
}
}(eachCleanup, ctx.logger)
}
wg.Wait()
}
////////////////////////////////////////////////////////////////////////////////
// Private - START
//
// Encapsulate calling a workflow hook
func callWorkflowHook(hook WorkflowHook, ctx *workflowContext) error {
if nil == hook {
return nil
}
// Run the hook
hookName := runtime.FuncForPC(reflect.ValueOf(hook).Pointer()).Name()
ctx.logger.WithFields(logrus.Fields{
"WorkflowHook": hookName,
"WorkflowHookContext": ctx.workflowHooksContext,
}).Info("Calling WorkflowHook")
return hook(ctx.workflowHooksContext,
ctx.serviceName,
ctx.s3Bucket,
ctx.buildID,
ctx.awsSession,
ctx.noop,
ctx.logger)
}
// Create a temporary file in the current working directory
func temporaryFile(name string) (*os.File, error) {
workingDir, err := os.Getwd()
if nil != err {
return nil, err
}
tmpFile, err := ioutil.TempFile(workingDir, name)
if err != nil {
return nil, errors.New("Failed to create temporary file")
}
return tmpFile, nil
}
func runOSCommand(cmd *exec.Cmd, logger *logrus.Logger) error {
logger.WithFields(logrus.Fields{
"Arguments": cmd.Args,
"Dir": cmd.Dir,
"Path": cmd.Path,
"Env": cmd.Env,
}).Debug("Running Command")
outputWriter := logger.Writer()
defer outputWriter.Close()
cmd.Stdout = outputWriter
cmd.Stderr = outputWriter
return cmd.Run()
}
// Ensure that the S3 bucket we're using for archives has an object expiration policy. The
// uploaded archives otherwise will be orphaned in S3 since the template can't manage the
// associated resources
func ensureExpirationPolicy(awsSession *session.Session, S3Bucket string, noop bool, logger *logrus.Logger) error {
if noop {
logger.WithFields(logrus.Fields{
"BucketName": S3Bucket,
}).Info("Bypassing bucket expiration policy check due to -n/-noop command line argument")
return nil
}
s3Svc := s3.New(awsSession)
params := &s3.GetBucketLifecycleConfigurationInput{
Bucket: aws.String(S3Bucket), // Required
}
showWarning := false
resp, err := s3Svc.GetBucketLifecycleConfiguration(params)
if nil != err {
showWarning = strings.Contains(err.Error(), "NoSuchLifecycleConfiguration")
if !showWarning {
return fmt.Errorf("Failed to fetch S3 Bucket Policy: %s", err.Error())
}
} else {
for _, eachRule := range resp.Rules {
if *eachRule.Status == s3.ExpirationStatusEnabled {
showWarning = false
}
}
}
if showWarning {
logger.WithFields(logrus.Fields{
"Bucket": S3Bucket,
"Reference": "http://docs.aws.amazon.com/AmazonS3/latest/dev/how-to-set-lifecycle-configuration-intro.html",
}).Warning("Bucket should have ObjectExpiration lifecycle enabled.")
} else {
logger.WithFields(logrus.Fields{
"Bucket": S3Bucket,
"Rules": resp.Rules,
}).Debug("Bucket lifecycle configuration")
}
return nil
}
// Upload a local file to S3. Returns the s3 keyname of the
// uploaded item, or an error
func uploadLocalFileToS3(packagePath string,
awsSession *session.Session,
S3Bucket string,
S3KeyPrefix string,
noop bool,
logger *logrus.Logger) (string, error) {
// Query the S3 bucket for the bucket policies. The bucket _should_ have ObjectExpiration,
// otherwise we're just going to orphan our binaries...
err := ensureExpirationPolicy(awsSession, S3Bucket, noop, logger)
if nil != err {
return "", fmt.Errorf("Failed to ensure bucket policies: %s", err.Error())
}
// Then do the actual work
reader, err := os.Open(packagePath)
if nil != err {
return "", fmt.Errorf("Failed to open local archive for S3 upload: %s", err.Error())
}
defer func() {
reader.Close()
err = os.Remove(packagePath)
if nil != err {
logger.WithFields(logrus.Fields{
"Path": packagePath,
"Error": err,
}).Warn("Failed to delete local file")
}
}()
// Make sure the key prefix ends with a trailing slash
canonicalKeyPrefix := S3KeyPrefix
if !strings.HasSuffix(canonicalKeyPrefix, "/") {
canonicalKeyPrefix += "/"
}
// Cache it in case there was an error & we need to cleanup
keyName := fmt.Sprintf("%s%s", canonicalKeyPrefix, filepath.Base(packagePath))
uploadInput := &s3manager.UploadInput{
Bucket: &S3Bucket,
Key: &keyName,
ContentType: aws.String("application/zip"),
Body: reader,
}
if noop {
logger.WithFields(logrus.Fields{
"Bucket": S3Bucket,
"Key": keyName,
}).Info("Bypassing S3 ZIP upload due to -n/-noop command line argument")
} else {
logger.WithFields(logrus.Fields{
"Source": packagePath,
}).Info("Uploading local file to S3")
uploader := s3manager.NewUploader(awsSession)
result, err := uploader.Upload(uploadInput)
if nil != err {
return "", err
}
logger.WithFields(logrus.Fields{
"URL": result.Location,
}).Info("Upload complete")
}
return keyName, nil
}
// Creates an S3 rollback function that attempts to delete a previously
// uploaded item.
func createS3RollbackFunc(awsSession *session.Session, s3Bucket string, s3Key string, noop bool) rollbackFunction {
return func(logger *logrus.Logger) error {
if !noop {
logger.Info("Attempting to cleanup S3 item: ", s3Key)
s3Client := s3.New(awsSession)
params := &s3.DeleteObjectInput{
Bucket: aws.String(s3Bucket),
Key: aws.String(s3Key),
}
_, err := s3Client.DeleteObject(params)
if err != nil {
logger.WithFields(logrus.Fields{
"Error": err,
}).Warn("Failed to delete S3 item during rollback cleanup")
} else {
logger.WithFields(logrus.Fields{
"Bucket": s3Bucket,
"Key": s3Key,
}).Debug("Item deleted during rollback cleanup")
}
return err
}
logger.WithFields(logrus.Fields{
"S3Bucket": s3Bucket,
"S3Key": s3Key,
}).Info("Bypassing rollback cleanup ")
return nil
}
}
// Private - END
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Workflow steps
////////////////////////////////////////////////////////////////////////////////
// Verify & cache the IAM rolename to ARN mapping
func verifyIAMRoles(ctx *workflowContext) (workflowStep, error) {
// The map is either a literal Arn from a pre-existing role name
// or a gocf.RefFunc() value.
// Don't verify them, just create them...
ctx.logger.Info("Verifying IAM Lambda execution roles")
ctx.lambdaIAMRoleNameMap = make(map[string]*gocf.StringExpr, 0)
svc := iam.New(ctx.awsSession)
// Assemble all the RoleNames and validate the inline IAMRoleDefinitions
var allRoleNames []string
for _, eachLambdaInfo := range ctx.lambdaAWSInfos {
if "" != eachLambdaInfo.RoleName {
allRoleNames = append(allRoleNames, eachLambdaInfo.RoleName)
}
// Custom resources?
for _, eachCustomResource := range eachLambdaInfo.customResources {
if "" != eachCustomResource.roleName {
allRoleNames = append(allRoleNames, eachCustomResource.roleName)
}
}
// Validate the IAMRoleDefinitions associated
if nil != eachLambdaInfo.RoleDefinition {
logicalName := eachLambdaInfo.RoleDefinition.logicalName(ctx.serviceName, eachLambdaInfo.lambdaFnName)
_, exists := ctx.lambdaIAMRoleNameMap[logicalName]
if !exists {
// Insert it into the resource creation map and add
// the "Ref" entry to the hashmap
ctx.cfTemplate.AddResource(logicalName,
eachLambdaInfo.RoleDefinition.toResource(eachLambdaInfo.EventSourceMappings, eachLambdaInfo.Options, ctx.logger))
ctx.lambdaIAMRoleNameMap[logicalName] = gocf.GetAtt(logicalName, "Arn")
}
}
// And the custom resource IAMRoles as well...
for _, eachCustomResource := range eachLambdaInfo.customResources {
if nil != eachCustomResource.roleDefinition {
customResourceLogicalName := eachCustomResource.roleDefinition.logicalName(ctx.serviceName,
eachCustomResource.userFunctionName)
_, exists := ctx.lambdaIAMRoleNameMap[customResourceLogicalName]
if !exists {
ctx.cfTemplate.AddResource(customResourceLogicalName,
eachCustomResource.roleDefinition.toResource(nil, eachCustomResource.options, ctx.logger))
ctx.lambdaIAMRoleNameMap[customResourceLogicalName] = gocf.GetAtt(customResourceLogicalName, "Arn")
}
}
}
}
// Then check all the RoleName literals
for _, eachRoleName := range allRoleNames {
_, exists := ctx.lambdaIAMRoleNameMap[eachRoleName]
if !exists {
// Check the role
params := &iam.GetRoleInput{
RoleName: aws.String(eachRoleName),
}
ctx.logger.Debug("Checking IAM RoleName: ", eachRoleName)
resp, err := svc.GetRole(params)
if err != nil {
ctx.logger.Error(err.Error())
return nil, err
}
// Cache it - we'll need it later when we create the
// CloudFormation template which needs the execution Arn (not role)
ctx.lambdaIAMRoleNameMap[eachRoleName] = gocf.String(*resp.Role.Arn)
}
}
ctx.logger.WithFields(logrus.Fields{
"Count": len(ctx.lambdaIAMRoleNameMap),
}).Info("IAM roles verified")
return createPackageStep(), nil
}
// Return a string representation of a JS function call that can be exposed
// to AWS Lambda
func createNewNodeJSProxyEntry(lambdaInfo *LambdaAWSInfo, logger *logrus.Logger) string {
logger.WithFields(logrus.Fields{
"FunctionName": lambdaInfo.lambdaFnName,
}).Info("Registering Sparta function")
// We do know the CF resource name here - could write this into
// index.js and expose a GET localhost:9000/lambdaMetadata
// which wraps up DescribeStackResource for the running
// lambda function
primaryEntry := fmt.Sprintf("exports[\"%s\"] = createForwarder(\"/%s\");\n",
lambdaInfo.jsHandlerName(),
lambdaInfo.lambdaFnName)
return primaryEntry
}
func createUserCustomResourceEntry(customResource *customResourceInfo, logger *logrus.Logger) string {
// The resource name is a :: delimited one, so let's sanitize that
// to make it a valid JS identifier
logger.WithFields(logrus.Fields{
"UserFunction": customResource.userFunctionName,
"NodeJSFunctionName": customResource.jsHandlerName(),
}).Debug("Registering User CustomResource function")
primaryEntry := fmt.Sprintf("exports[\"%s\"] = createForwarder(\"/%s\");\n",
customResource.jsHandlerName(),
customResource.userFunctionName)
return primaryEntry
}
func createNewSpartaCustomResourceEntry(resourceName string, logger *logrus.Logger) string {
// The resource name is a :: delimited one, so let's sanitize that
// to make it a valid JS identifier
jsName := javascriptExportNameForCustomResourceType(resourceName)
logger.WithFields(logrus.Fields{
"Resource": resourceName,
"NodeJSFunctionName": jsName,
}).Debug("Registering Sparta CustomResource function")
primaryEntry := fmt.Sprintf("exports[\"%s\"] = createForwarder(\"/%s\");\n",
jsName,
resourceName)
return primaryEntry
}
// Return the StackEvents for the given StackName/StackID
func stackEvents(stackID string, cfService *cloudformation.CloudFormation) ([]*cloudformation.StackEvent, error) {
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
}
events = append(events, resp.StackEvents...)
if nil == resp.NextToken {
break
} else {
nextToken = *resp.NextToken
}
}
return events, nil
}
func logFilesize(message string, filePath string, logger *logrus.Logger) {
// Binary size
stat, err := os.Stat(filePath)
if err == nil {
logger.WithFields(logrus.Fields{
"KB": stat.Size() / 1024,
"MB": stat.Size() / (1024 * 1024),
}).Info(message)
}
}
func buildGoBinary(executableOutput string, logger *logrus.Logger) error {
// Go generate
cmd := exec.Command("go", "generate")
if logger.Level == logrus.DebugLevel {
cmd = exec.Command("go", "generate", "-v", "-x")
}
cmd.Env = os.Environ()
commandString := fmt.Sprintf("%s", cmd.Args)
logger.Info(fmt.Sprintf("Running `%s`", strings.Trim(commandString, "[]")))
goGenerateErr := runOSCommand(cmd, logger)
if nil != goGenerateErr {
return goGenerateErr
}
// TODO: Smaller binaries via linker flags
// Ref: https://blog.filippo.io/shrink-your-go-binaries-with-this-one-weird-trick/
cmd = exec.Command("go", "build", "-o", executableOutput, "-tags", "lambdabinary", ".")
cmd.Env = os.Environ()
cmd.Env = append(cmd.Env, "GOOS=linux", "GOARCH=amd64")
logger.WithFields(logrus.Fields{
"Name": executableOutput,
}).Info("Compiling binary")
return runOSCommand(cmd, logger)
}
func writeNodeJSShim(serviceName string,
executableOutput string,
lambdaAWSInfos []*LambdaAWSInfo,
zipWriter *zip.Writer,
logger *logrus.Logger) error {
// Add the string literal adapter, which requires us to add exported
// functions to the end of index.js. These NodeJS exports will be
// linked to the AWS Lambda NodeJS function name, and are basically
// automatically generated pass through proxies to the golang HTTP handler.
nodeJSWriter, err := zipWriter.Create("index.js")
if err != nil {
return errors.New("Failed to create ZIP entry: index.js")
}
nodeJSSource := _escFSMustString(false, "/resources/index.js")
nodeJSSource += "\n// DO NOT EDIT - CONTENT UNTIL EOF IS AUTOMATICALLY GENERATED\n"
handlerNames := make(map[string]bool, 0)
for _, eachLambda := range lambdaAWSInfos {
if _, exists := handlerNames[eachLambda.jsHandlerName()]; !exists {
nodeJSSource += createNewNodeJSProxyEntry(eachLambda, logger)
handlerNames[eachLambda.jsHandlerName()] = true
}
// USER DEFINED RESOURCES
for _, eachCustomResource := range eachLambda.customResources {
if _, exists := handlerNames[eachCustomResource.jsHandlerName()]; !exists {
nodeJSSource += createUserCustomResourceEntry(eachCustomResource, logger)
handlerNames[eachCustomResource.jsHandlerName()] = true
}
}
}
// SPARTA CUSTOM RESOURCES
for _, eachCustomResourceName := range golangCustomResourceTypes {
nodeJSSource += createNewSpartaCustomResourceEntry(eachCustomResourceName, logger)
}
// Finally, replace
// SPARTA_BINARY_NAME = 'Sparta.lambda.amd64';
// with the service binary name
nodeJSSource += fmt.Sprintf("SPARTA_BINARY_NAME='%s';\n", executableOutput)
// And the service name
nodeJSSource += fmt.Sprintf("SPARTA_SERVICE_NAME='%s';\n", serviceName)
logger.WithFields(logrus.Fields{
"index.js": nodeJSSource,
}).Debug("Dynamically generated NodeJS adapter")
stringReader := strings.NewReader(nodeJSSource)
_, copyErr := io.Copy(nodeJSWriter, stringReader)
return copyErr
}
func insertNodeModulesArchive(provisioningResourcesRelPath string,
zipWriter *zip.Writer,
logger *logrus.Logger) error {
nodeModulesZipRelName := fmt.Sprintf("%s/node_modules.zip", provisioningResourcesRelPath)
nodeModuleBytes, err := _escFSByte(false, nodeModulesZipRelName)
if nil == err {
nodeModuleReader, errReader := zip.NewReader(bytes.NewReader(nodeModuleBytes), int64(len(nodeModuleBytes)))
if errReader != nil {
return errReader
}
logger.WithFields(logrus.Fields{
"Name": nodeModulesZipRelName,
}).Debug("Embedding CustomResource node_modules.zip")
for _, zipFile := range nodeModuleReader.File {
embedWriter, errCreate := zipWriter.Create(zipFile.Name)
if nil != errCreate {
return errCreate
}
sourceReader, errOpen := zipFile.Open()
if errOpen != nil {
return errOpen
}
io.Copy(embedWriter, sourceReader)
}
} else {
logger.WithFields(logrus.Fields{
"Name": nodeModulesZipRelName,
"Error": err,
}).Warn("Failed to load node_modules.zip for embedding")
}
return nil
}
func writeCustomResources(zipWriter *zip.Writer,
logger *logrus.Logger) error {
for _, eachName := range customResourceScripts {
resourceName := fmt.Sprintf("%s/%s", provisioningResourcesRelPath, eachName)
resourceContent := _escFSMustString(false, resourceName)
stringReader := strings.NewReader(resourceContent)
embedWriter, errCreate := zipWriter.Create(eachName)
if nil != errCreate {
return errCreate
}
logger.WithFields(logrus.Fields{
"Name": eachName,
}).Debug("Script name")
_, copyErr := io.Copy(embedWriter, stringReader)
if nil != copyErr {
return copyErr
}
}
return nil
}
// Build and package the application
func createPackageStep() workflowStep {
return func(ctx *workflowContext) (workflowStep, error) {
// PreBuild Hook
if ctx.workflowHooks != nil {
preBuildErr := callWorkflowHook(ctx.workflowHooks.PreBuild, ctx)
if nil != preBuildErr {
return nil, preBuildErr
}
}
sanitizedServiceName := sanitizedName(ctx.serviceName)
executableOutput := fmt.Sprintf("%s.lambda.amd64", sanitizedServiceName)
buildErr := buildGoBinary(executableOutput, ctx.logger)
if nil != buildErr {
return nil, buildErr
}
// Cleanup
defer func() {
errRemove := os.Remove(executableOutput)
if nil != errRemove {
ctx.logger.WithFields(logrus.Fields{
"File": executableOutput,
"Error": errRemove,
}).Warn("Failed to delete binary")
}
}()
// Binary size
logFilesize("Executable binary size", executableOutput, ctx.logger)
// PostBuild Hook
if ctx.workflowHooks != nil {
postBuildErr := callWorkflowHook(ctx.workflowHooks.PostBuild, ctx)
if nil != postBuildErr {
return nil, postBuildErr
}
}
tmpFile, err := temporaryFile(sanitizedServiceName)
if err != nil {
return nil, errors.New("Failed to create temporary file")
}
defer func() {
tmpFile.Close()
}()
ctx.logger.WithFields(logrus.Fields{
"TempName": tmpFile.Name(),
}).Info("Creating ZIP archive for upload")
lambdaArchive := zip.NewWriter(tmpFile)
defer lambdaArchive.Close()
// Archive Hook
if ctx.workflowHooks != nil && ctx.workflowHooks.Archive != nil {
archiveErr := ctx.workflowHooks.Archive(ctx.workflowHooksContext,
ctx.serviceName,
lambdaArchive,
ctx.awsSession,
ctx.noop,
ctx.logger)
if nil != archiveErr {
return nil, archiveErr
}
}
// File info for the binary executable
binaryWriter, err := lambdaArchive.Create(filepath.Base(executableOutput))
if err != nil {
return nil, fmt.Errorf("Failed to create ZIP entry: %s", filepath.Base(executableOutput))
}
reader, err := os.Open(executableOutput)
if err != nil {
return nil, fmt.Errorf("Failed to open file: %s", executableOutput)
}
defer reader.Close()
io.Copy(binaryWriter, reader)
// Add the string literal adapter, which requires us to add exported
// functions to the end of index.js. These NodeJS exports will be
// linked to the AWS Lambda NodeJS function name, and are basically
// automatically generated pass through proxies to the golang HTTP handler.
shimErr := writeNodeJSShim(ctx.serviceName,
executableOutput,
ctx.lambdaAWSInfos,
lambdaArchive,
ctx.logger)
if nil != shimErr {
return nil, shimErr
}
// Next embed the custom resource scripts into the package.
// TODO - conditionally include custom NodeJS scripts based on service requirement
ctx.logger.Debug("Embedding CustomResource scripts")
customResourceErr := writeCustomResources(lambdaArchive,
ctx.logger)
if nil != customResourceErr {
return nil, customResourceErr
}
// And finally, if there is a node_modules.zip file, then include it. The
// node_modules archive includes supplementary libraries that the
// CustomResource handlers may need at CloudFormation stack creation time.
insertModulesErr := insertNodeModulesArchive(provisioningResourcesRelPath,
lambdaArchive,
ctx.logger)
return createUploadStep(tmpFile.Name()), insertModulesErr
}
}
// Given the zipped binary in packagePath, upload the primary code bundle
// and optional S3 site resources iff they're defined.
func createUploadStep(packagePath string) workflowStep {
return func(ctx *workflowContext) (workflowStep, error) {
var uploadErrors []error
var wg sync.WaitGroup
// We always need to upload the primary binary
wg.Add(1)
go func() {
defer wg.Done()
logFilesize("Lambda function deployment package size", packagePath, ctx.logger)
keyName, err := uploadLocalFileToS3(packagePath,
ctx.awsSession,
ctx.s3Bucket,
ctx.serviceName,
ctx.noop,
ctx.logger)
ctx.s3LambdaZipKey = keyName
if nil != err {
uploadErrors = append(uploadErrors, err)
} else {
ctx.registerRollback(createS3RollbackFunc(ctx.awsSession, ctx.s3Bucket, ctx.s3LambdaZipKey, ctx.noop))
}
}()
// S3 site to compress & upload
if nil != ctx.s3SiteContext.s3Site {
wg.Add(1)
go func() {
defer wg.Done()
tempName := fmt.Sprintf("%s-S3Site", ctx.serviceName)
tmpFile, err := temporaryFile(tempName)
if err != nil {
uploadErrors = append(uploadErrors,
errors.New("Failed to create temporary S3 site archive file"))
return
}
// Add the contents to the Zip file
zipArchive := zip.NewWriter(tmpFile)
absResourcePath, err := filepath.Abs(ctx.s3SiteContext.s3Site.resources)
if nil != err {
uploadErrors = append(uploadErrors, err)
return
}
ctx.logger.WithFields(logrus.Fields{
"S3Key": path.Base(tmpFile.Name()),
"Source": absResourcePath,
}).Info("Creating S3Site archive")
err = spartaZip.AddToZip(zipArchive, absResourcePath, absResourcePath, ctx.logger)
if nil != err {
uploadErrors = append(uploadErrors, err)
return
}
zipArchive.Close()
tmpFile.Close()
// Upload it & save the key
s3SiteLambdaZipKey, err := uploadLocalFileToS3(tmpFile.Name(),
ctx.awsSession,
ctx.s3Bucket,
ctx.serviceName,
ctx.noop,
ctx.logger)
ctx.s3SiteContext.s3SiteLambdaZipKey = s3SiteLambdaZipKey
if nil != err {
uploadErrors = append(uploadErrors, err)
} else {
ctx.registerRollback(createS3RollbackFunc(ctx.awsSession, ctx.s3Bucket, ctx.s3SiteContext.s3SiteLambdaZipKey, ctx.noop))
}
}()
}
wg.Wait()
if len(uploadErrors) > 0 {
errorText := "Encountered multiple errors during upload:\n"
for _, eachError := range uploadErrors {
errorText += fmt.Sprintf("%s%s\n", errorText, eachError.Error())
return nil, errors.New(errorText)
}
}
return ensureCloudFormationStack(), nil
}
}
// Does a given stack exist?
func stackExists(stackNameOrID string, cf *cloudformation.CloudFormation, logger *logrus.Logger) (bool, error) {
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
}
func stackCapabilities(template *gocf.Template) []*string {
// Only require IAM capability if the definition requires it.
var capabilities []*string
for _, eachResource := range template.Resources {
if eachResource.Properties.CfnResourceType() == "AWS::IAM::Role" {
found := false
for _, eachElement := range capabilities {
found = (found || (*eachElement == "CAPABILITY_IAM"))
}
if !found {
capabilities = append(capabilities, aws.String("CAPABILITY_IAM"))
}
}
}
return capabilities
}
func updateStackViaChangeSet(serviceName string,
cfTemplateURL string,
capabilities []*string,
awsCloudFormation *cloudformation.CloudFormation,
logger *logrus.Logger) error {
changeSetRequestName := CloudFormationResourceName(fmt.Sprintf("%sChangeSet", serviceName))
changeSetInput := &cloudformation.CreateChangeSetInput{
Capabilities: capabilities,
ChangeSetName: aws.String(changeSetRequestName),
ClientToken: aws.String(changeSetRequestName),
Description: aws.String(fmt.Sprintf("Change set for service: %s (Sparta v. %s)", serviceName, SpartaVersion)),
StackName: aws.String(serviceName),
TemplateURL: aws.String(cfTemplateURL),
}
_, changeSetError := awsCloudFormation.CreateChangeSet(changeSetInput)
if nil != changeSetError {
return 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
for waitComplete := false; !waitComplete; {
sleepDuration := time.Duration(11+rand.Int31n(13)) * time.Second
time.Sleep(sleepDuration)
changeSetOutput, describeChangeSetError := awsCloudFormation.DescribeChangeSet(&describeChangeSetInput)
if nil != describeChangeSetError {
return describeChangeSetError
}
describeChangeSetOutput = changeSetOutput
waitComplete = (nil != describeChangeSetOutput)
}
logger.WithFields(logrus.Fields{
"DescribeChangeSetOutput": describeChangeSetOutput,
}).Debug("DescribeChangeSet result")
// Apply the change
executeChangeSetInput := cloudformation.ExecuteChangeSetInput{
ChangeSetName: aws.String(changeSetRequestName),
StackName: aws.String(serviceName),
}
executeChangeSetOutput, executeChangeSetError := awsCloudFormation.ExecuteChangeSet(&executeChangeSetInput)
logger.WithFields(logrus.Fields{