-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathcmd_build.go
1122 lines (1034 loc) · 35.2 KB
/
cmd_build.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"
"context"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"reflect"
"runtime"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
humanize "github.com/dustin/go-humanize"
spartaAWS "github.com/mweagle/Sparta/aws"
"github.com/mweagle/Sparta/system"
spartaZip "github.com/mweagle/Sparta/zip"
gocc "github.com/mweagle/go-cloudcondenser"
gocf "github.com/mweagle/go-cloudformation"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
// userdata is user-supplied, code related values
type userdata struct {
// Is this is a -dry-run?
noop bool
// Is this a CGO enabled build?
useCGO bool
// To do in-place updates we'd need to find all the function ARNs
// and then update them. That requires the names to be stable. Interesting.
// Are in-place updates enabled?
inPlace bool
// The user-supplied or automatically generated BuildID
buildID string
// Optional user-supplied build tags
buildTags string
// Optional link flags
linkFlags string
// 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
// User supplied workflow hooks
workflowHooks *WorkflowHooks
// Code pipeline S3 trigger keyname
codePipelineTrigger string
// Optional APIGateway definition to associate with this service
api APIGateway
// Optional S3 site data to provision together with this service
s3SiteContext *s3SiteContext
// The user-supplied S3 bucket where service artifacts should be posted.
s3Bucket string
}
// context is data that is mutated during the building workflow
type buildContext struct {
// Output location for files
outputDirectory string
// AWS Session to be used for all API calls made in the process of provisioning
// this service.
awsSession *session.Session
// 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
// IO writer for autogenerated template results
templateWriter io.Writer
// CloudFormation Template
cfTemplate *gocf.Template
// name of the binary inside the ZIP archive
compiledBinaryOutput string
// Context to pass between workflow operations
workflowHooksContext context.Context
}
// Encapsulate calling the archive hooks
func callArchiveHook(lambdaArchive *zip.Writer,
userdata *userdata,
buildContext *buildContext,
logger *logrus.Logger) error {
if userdata.workflowHooks == nil {
return nil
}
archiveHooks := userdata.workflowHooks.Archives
if userdata.workflowHooks.Archive != nil {
logger.Warn("DEPRECATED: Single ArchiveHook hook superseded by ArchiveHooks slice")
archiveHooks = append(archiveHooks,
ArchiveHookFunc(userdata.workflowHooks.Archive))
}
for _, eachArchiveHook := range archiveHooks {
// Run the hook
logger.WithFields(logrus.Fields{
"WorkflowHookContext": buildContext.workflowHooksContext,
}).Info("Calling ArchiveHook")
hookCtx, hookErr := eachArchiveHook.DecorateArchive(buildContext.workflowHooksContext,
userdata.serviceName,
lambdaArchive,
buildContext.awsSession,
userdata.noop,
logger)
if hookErr != nil {
return errors.Wrapf(hookErr, "DecorateArchive returned an error")
}
buildContext.workflowHooksContext = hookCtx
}
return nil
}
// create a new gocf.Parameter struct and return it...
func newStackParameter(paramType string,
description string,
defaultValue string,
allowedPattern string,
minLength int64) *gocf.Parameter {
return &gocf.Parameter{
Type: paramType,
Description: description,
Default: defaultValue,
AllowedPattern: allowedPattern,
MinLength: gocf.Integer(minLength),
}
}
// Encapsulate calling a workflow hook
func callWorkflowHook(hookPhase string,
hook WorkflowHook,
hooks []WorkflowHookHandler,
userdata *userdata,
buildContext *buildContext,
logger *logrus.Logger) error {
if hook != nil {
logger.Warn(fmt.Sprintf("DEPRECATED: Single %s hook superseded by %ss slice",
hookPhase,
hookPhase))
hooks = append(hooks, WorkflowHookFunc(hook))
}
for _, eachHook := range hooks {
// Run the hook
logger.WithFields(logrus.Fields{
"Phase": hookPhase,
"WorkflowHookContext": buildContext.workflowHooksContext,
}).Info("Calling WorkflowHook")
hookCtx, hookErr := eachHook.DecorateWorkflow(buildContext.workflowHooksContext,
userdata.serviceName,
gocf.Ref(StackParamS3CodeBucketName),
userdata.buildID,
buildContext.awsSession,
userdata.noop,
logger)
if hookErr != nil {
return errors.Wrapf(hookErr, "DecorateWorkflow returned an error")
}
buildContext.workflowHooksContext = hookCtx
}
return nil
}
// Encapsulate calling the service decorator hooks
func callServiceDecoratorHook(lambdaFunctionCode *gocf.LambdaFunctionCode,
userdata *userdata,
buildContext *buildContext,
logger *logrus.Logger) error {
if userdata.workflowHooks == nil {
return nil
}
serviceHooks := userdata.workflowHooks.ServiceDecorators
if userdata.workflowHooks.ServiceDecorator != nil {
logger.Warn("DEPRECATED: Single ServiceDecorator hook superseded by ServiceDecorators slice")
serviceHooks = append(serviceHooks,
ServiceDecoratorHookFunc(userdata.workflowHooks.ServiceDecorator))
}
// If there's an API gateway definition, include the resources that provision it.
// Since this export will likely
// generate outputs that the s3 site needs, we'll use a temporary outputs accumulator,
// pass that to the S3Site
// if it's defined, and then merge it with the normal output map.-
for eachIndex, eachServiceHook := range serviceHooks {
funcPtr := reflect.ValueOf(eachServiceHook).Pointer()
funcForPC := runtime.FuncForPC(funcPtr)
hookName := funcForPC.Name()
if hookName == "" {
hookName = fmt.Sprintf("ServiceHook[%d]", eachIndex)
}
logger.WithFields(logrus.Fields{
"ServiceDecoratorHook": hookName,
"WorkflowHookContext": buildContext.workflowHooksContext,
}).Info("Calling WorkflowHook")
serviceTemplate := gocf.NewTemplate()
decoratorCtx, decoratorError := eachServiceHook.DecorateService(buildContext.workflowHooksContext,
userdata.serviceName,
serviceTemplate,
lambdaFunctionCode,
userdata.buildID,
buildContext.awsSession,
userdata.noop,
logger)
if nil != decoratorError {
return decoratorError
}
buildContext.workflowHooksContext = decoratorCtx
safeMergeErrs := gocc.SafeMerge(serviceTemplate, buildContext.cfTemplate)
if len(safeMergeErrs) != 0 {
return errors.Errorf("Failed to merge templates: %#v", safeMergeErrs)
}
}
return nil
}
// Encapsulate calling the validation hooks
func callValidationHooks(validationHooks []ServiceValidationHookHandler,
template *gocf.Template,
lambdaFunctionCode *gocf.LambdaFunctionCode,
userdata *userdata,
buildContext *buildContext,
logger *logrus.Logger) error {
var marshaledTemplate []byte
if len(validationHooks) != 0 {
jsonBytes, jsonBytesErr := json.Marshal(template)
if jsonBytesErr != nil {
return errors.Wrapf(jsonBytesErr, "Failed to marshal template for validation")
}
marshaledTemplate = jsonBytes
}
for _, eachHook := range validationHooks {
// Run the hook
logger.WithFields(logrus.Fields{
"Phase": "Validation",
"ValidationHookContext": buildContext.workflowHooksContext,
}).Info("Calling WorkflowHook")
var loopTemplate gocf.Template
unmarshalErr := json.Unmarshal(marshaledTemplate, &loopTemplate)
if unmarshalErr != nil {
return errors.Wrapf(unmarshalErr,
"Failed to unmarshal read-only copy of template for Validation")
}
hookCtx, hookErr := eachHook.ValidateService(buildContext.workflowHooksContext,
userdata.serviceName,
&loopTemplate,
lambdaFunctionCode,
userdata.buildID,
buildContext.awsSession,
userdata.noop,
logger)
if hookErr != nil {
return errors.Wrapf(hookErr, "Service failed to pass validation")
}
buildContext.workflowHooksContext = hookCtx
}
return nil
}
////////////////////////////////////////////////////////////////////////////////
//
// BEGIN - Private
//
type validatePreconditionsOp struct {
userdata *userdata
}
func (vpo *validatePreconditionsOp) Rollback(ctx context.Context, logger *logrus.Logger) error {
return nil
}
func (vpo *validatePreconditionsOp) Invoke(ctx context.Context, logger *logrus.Logger) error {
var errorText []string
collisionMemo := make(map[string]int)
incrementCounter := func(keyName string) {
_, exists := collisionMemo[keyName]
if !exists {
collisionMemo[keyName] = 1
} else {
collisionMemo[keyName] = collisionMemo[keyName] + 1
}
}
// 00 - check for possibly empty function set...
if len(vpo.userdata.lambdaAWSInfos) <= 0 {
// Warning? Maybe it's just decorators?
if vpo.userdata.workflowHooks == nil {
return errors.New("No lambda functions were provided to Sparta.Provision(). WorkflowHooks are undefined")
}
logger.Warn("No lambda functions provided to Sparta.Provision()")
}
// 0 - check for nil
for eachIndex, eachLambda := range vpo.userdata.lambdaAWSInfos {
if eachLambda == nil {
errorText = append(errorText,
fmt.Sprintf("Lambda at position %d is `nil`", eachIndex))
}
}
// Semantic checks only iff lambdas are non-nil
if len(errorText) == 0 {
// 1 - check for invalid signatures
for _, eachLambda := range vpo.userdata.lambdaAWSInfos {
validationErr := ensureValidSignature(eachLambda.userSuppliedFunctionName,
eachLambda.handlerSymbol)
if validationErr != nil {
errorText = append(errorText, validationErr.Error())
}
}
// 2 - check for duplicate golang function references.
for _, eachLambda := range vpo.userdata.lambdaAWSInfos {
incrementCounter(eachLambda.lambdaFunctionName())
for _, eachCustom := range eachLambda.customResources {
incrementCounter(eachCustom.userFunctionName)
}
}
// Duplicates?
for eachLambdaName, eachCount := range collisionMemo {
if eachCount > 1 {
logger.WithFields(logrus.Fields{
"CollisionCount": eachCount,
"Name": eachLambdaName,
}).Error("NewAWSLambda")
errorText = append(errorText,
fmt.Sprintf("Multiple definitions of lambda: %s", eachLambdaName))
}
}
logger.WithFields(logrus.Fields{
"CollisionMap": collisionMemo,
}).Debug("Lambda collision map")
}
if len(errorText) != 0 {
return errors.New(strings.Join(errorText[:], "\n"))
}
return nil
}
type verifyIAMRolesOp struct {
userdata *userdata
buildContext *buildContext
}
func (viro *verifyIAMRolesOp) Invoke(ctx context.Context, logger *logrus.Logger) 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...
viro.buildContext.lambdaIAMRoleNameMap = make(map[string]*gocf.StringExpr)
iamSvc := iam.New(viro.buildContext.awsSession)
// Assemble all the RoleNames and validate the inline IAMRoleDefinitions
var allRoleNames []string
for _, eachLambdaInfo := range viro.userdata.lambdaAWSInfos {
if eachLambdaInfo.RoleName != "" {
allRoleNames = append(allRoleNames, eachLambdaInfo.RoleName)
}
// Custom resources?
for _, eachCustomResource := range eachLambdaInfo.customResources {
if eachCustomResource.roleName != "" {
allRoleNames = append(allRoleNames, eachCustomResource.roleName)
}
}
// Profiling enabled?
if profileDecorator != nil {
profileErr := profileDecorator(viro.userdata.serviceName,
eachLambdaInfo,
viro.userdata.s3Bucket,
logger)
if profileErr != nil {
return errors.Wrapf(profileErr, "Failed to call lambda profile decorator")
}
}
// Validate the IAMRoleDefinitions associated
if nil != eachLambdaInfo.RoleDefinition {
logicalName := eachLambdaInfo.RoleDefinition.logicalName(viro.userdata.serviceName,
eachLambdaInfo.lambdaFunctionName())
_, exists := viro.buildContext.lambdaIAMRoleNameMap[logicalName]
if !exists {
// Insert it into the resource creation map and add
// the "Ref" entry to the hashmap
viro.buildContext.cfTemplate.AddResource(logicalName,
eachLambdaInfo.RoleDefinition.toResource(eachLambdaInfo.EventSourceMappings,
eachLambdaInfo.Options,
logger))
viro.buildContext.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(viro.userdata.serviceName,
eachCustomResource.userFunctionName)
_, exists := viro.buildContext.lambdaIAMRoleNameMap[customResourceLogicalName]
if !exists {
viro.buildContext.cfTemplate.AddResource(customResourceLogicalName,
eachCustomResource.roleDefinition.toResource(nil,
eachCustomResource.options,
logger))
viro.buildContext.lambdaIAMRoleNameMap[customResourceLogicalName] = gocf.GetAtt(customResourceLogicalName, "Arn")
}
}
}
}
// Then check all the RoleName literals
totalRemoteChecks := 0
for _, eachRoleName := range allRoleNames {
_, exists := viro.buildContext.lambdaIAMRoleNameMap[eachRoleName]
if !exists {
totalRemoteChecks++
// Check the role
params := &iam.GetRoleInput{
RoleName: aws.String(eachRoleName),
}
logger.Debug("Checking IAM RoleName: ", eachRoleName)
resp, err := iamSvc.GetRole(params)
if err != nil {
return err
}
// Cache it - we'll need it later when we create the
// CloudFormation template which needs the execution Arn (not role)
viro.buildContext.lambdaIAMRoleNameMap[eachRoleName] = gocf.String(*resp.Role.Arn)
}
}
logger.WithFields(logrus.Fields{
"GetRoleCount": totalRemoteChecks,
"Total": len(viro.buildContext.lambdaIAMRoleNameMap),
}).Info("Verified IAM Roles")
return nil
}
func (viro *verifyIAMRolesOp) Rollback(ctx context.Context, logger *logrus.Logger) error {
return nil
}
//
// END - Private
//
////////////////////////////////////////////////////////////////////////////////
type verifyAWSPreconditionsOp struct {
userdata *userdata
buildContext *buildContext
}
func (vapo *verifyAWSPreconditionsOp) Invoke(ctx context.Context, logger *logrus.Logger) error {
// If there are codePipeline environments defined, warn if they don't include
// the same keysets
if nil != codePipelineEnvironments {
mapKeys := func(inboundMap map[string]string) []string {
keys := make([]string, len(inboundMap))
i := 0
for k := range inboundMap {
keys[i] = k
i++
}
return keys
}
aggregatedKeys := make([][]string, len(codePipelineEnvironments))
i := 0
for _, eachEnvMap := range codePipelineEnvironments {
aggregatedKeys[i] = mapKeys(eachEnvMap)
i++
}
i = 0
keysEqual := true
for _, eachKeySet := range aggregatedKeys {
j := 0
for _, eachKeySetTest := range aggregatedKeys {
if j != i {
if !reflect.DeepEqual(eachKeySet, eachKeySetTest) {
keysEqual = false
}
}
j++
}
i++
}
if !keysEqual {
// Setup an interface with the fields so that the log message
fields := make(logrus.Fields, len(codePipelineEnvironments))
for eachEnv, eachEnvMap := range codePipelineEnvironments {
fields[eachEnv] = eachEnvMap
}
logger.WithFields(fields).Warn("CodePipeline environments do not define equivalent environment keys")
}
}
return nil
}
type createPackageOp struct {
userdata *userdata
buildContext *buildContext
}
func (cpo *createPackageOp) Rollback(ctx context.Context, logger *logrus.Logger) error {
return nil
}
func (cpo *createPackageOp) Invoke(ctx context.Context, logger *logrus.Logger) error {
// PreBuild Hook
if cpo.userdata.workflowHooks != nil {
preBuildErr := callWorkflowHook("PreBuild",
cpo.userdata.workflowHooks.PreBuild,
cpo.userdata.workflowHooks.PreBuilds,
cpo.userdata,
cpo.buildContext,
logger)
if nil != preBuildErr {
return preBuildErr
}
}
sanitizedServiceName := sanitizedName(cpo.userdata.serviceName)
// Output location
buildErr := system.BuildGoBinary(cpo.userdata.serviceName,
cpo.buildContext.compiledBinaryOutput,
cpo.userdata.useCGO,
cpo.userdata.buildID,
cpo.userdata.buildTags,
cpo.userdata.linkFlags,
cpo.userdata.noop,
logger)
if nil != buildErr {
return buildErr
}
//////////////////////////////////////////////////////////////////////////////
// Build the Site ZIP?
// We might need to upload some other things...
if nil != cpo.userdata.s3SiteContext.s3Site {
absResourcePath, err := filepath.Abs(cpo.userdata.s3SiteContext.s3Site.resources)
if nil != err {
return errors.Wrapf(err,
"Failed to get absolute filepath for S3 Site contents directory (%s)",
cpo.userdata.s3SiteContext.s3Site.resources)
}
// Ensure that the directory exists...
_, existsErr := os.Stat(cpo.userdata.s3SiteContext.s3Site.resources)
if existsErr != nil && os.IsNotExist(existsErr) {
return errors.Wrapf(existsErr,
"The S3 Site resources directory (%s) does not exist",
cpo.userdata.s3SiteContext.s3Site.resources)
}
// Create ZIP output archive
siteZIPArchiveName := fmt.Sprintf("%s-S3Site.zip", cpo.userdata.serviceName)
siteZIPArchivePath := filepath.Join(cpo.buildContext.outputDirectory, siteZIPArchiveName)
zipOutputFile, zipOutputFileErr := os.Create(siteZIPArchivePath)
if zipOutputFileErr != nil {
return errors.Wrapf(zipOutputFileErr, "Failed to create temporary S3 site archive file")
}
// Add the contents to the Zip file
zipArchive := zip.NewWriter(zipOutputFile)
addToZipErr := spartaZip.AddToZip(zipArchive,
absResourcePath,
absResourcePath,
logger)
if addToZipErr != nil {
return errors.Wrapf(addToZipErr, "Failed to create S3 site ZIP archive")
}
// Else, save it...
cpo.buildContext.cfTemplate.Metadata[MetadataParamS3SiteArchivePath] = zipOutputFile.Name()
archiveCloseErr := zipArchive.Close()
if nil != archiveCloseErr {
return errors.Wrapf(archiveCloseErr, "Failed to close S3 site ZIP stream")
}
zipCloseErr := zipOutputFile.Close()
if zipCloseErr != nil {
return errors.Wrapf(zipCloseErr, "Failed to close S3 site ZIP archive")
}
logger.WithFields(logrus.Fields{
"Path": zipOutputFile.Name(),
}).Info("Created S3Site archive")
// Put the path into the template metadata, include the stack parameter...
cpo.buildContext.cfTemplate.Metadata[MetadataParamS3SiteArchivePath] = zipOutputFile.Name()
// Add this as a stack param. By default it's going to have
// the same keyname as the file we just created...
cpo.buildContext.cfTemplate.Parameters[StackParamS3SiteArchiveKey] = newStackParameter(
"String",
"Object key that stores the S3 site archive.",
filepath.Base(zipOutputFile.Name()),
".+",
3)
cpo.buildContext.cfTemplate.Parameters[StackParamS3SiteArchiveVersion] = newStackParameter(
"String",
"Object version of the S3 archive.",
"",
"",
0)
}
// PostBuild Hook
if cpo.userdata.workflowHooks != nil {
postBuildErr := callWorkflowHook("PostBuild",
cpo.userdata.workflowHooks.PostBuild,
cpo.userdata.workflowHooks.PostBuilds,
cpo.userdata,
cpo.buildContext,
logger)
if nil != postBuildErr {
return postBuildErr
}
}
//////////////////////////////////////////////////////////////////////////////
// Build the code ZIP
codeArchiveName := fmt.Sprintf("%s-code.zip", sanitizedServiceName)
codeZIPArchivePath := filepath.Join(cpo.buildContext.outputDirectory, codeArchiveName)
zipOutputFile, zipOutputFileErr := os.Create(codeZIPArchivePath)
if zipOutputFileErr != nil {
return errors.Wrapf(zipOutputFileErr, "Failed to create ZIP archive for code")
}
// Strip the local directory in case it's in there...
relativeTempFilePath := relativePath(zipOutputFile.Name())
lambdaArchive := zip.NewWriter(zipOutputFile)
// Pass the state through the Metdata
cpo.buildContext.cfTemplate.Metadata[MetadataParamCodeArchivePath] = relativeTempFilePath
cpo.buildContext.cfTemplate.Metadata[MetadataParamServiceName] = cpo.userdata.serviceName
cpo.buildContext.cfTemplate.Metadata[MetadataParamS3Bucket] = cpo.userdata.s3Bucket
// Archive Hook
archiveErr := callArchiveHook(lambdaArchive, cpo.userdata, cpo.buildContext, logger)
if nil != archiveErr {
return archiveErr
}
// Issue: https://github.com/mweagle/Sparta/issues/103. If the executable
// bit isn't set, then AWS Lambda won't be able to fork the binary. This tends
// to be set properly on a mac/linux os, but not on others. So pre-emptively
// always set the bit.
// Ref: https://github.com/mweagle/Sparta/issues/158
fileHeaderAnnotator := func(header *zip.FileHeader) (*zip.FileHeader, error) {
// Make the binary executable
// Ref: https://github.com/aws/aws-lambda-go/blob/master/cmd/build-lambda-zip/main.go#L51
header.CreatorVersion = 3 << 8
header.ExternalAttrs = 0777 << 16
return header, nil
}
// File info for the binary executable
readerErr := spartaZip.AnnotateAddToZip(lambdaArchive,
cpo.buildContext.compiledBinaryOutput,
"",
fileHeaderAnnotator,
logger)
if nil != readerErr {
return readerErr
}
// Flush it...
archiveCloseErr := lambdaArchive.Close()
if nil != archiveCloseErr {
return errors.Wrapf(archiveCloseErr, "Failed to close code ZIP stream")
}
zipCloseErr := zipOutputFile.Close()
if zipCloseErr != nil {
return errors.Wrapf(zipCloseErr, "Failed to close code ZIP archive")
}
logger.WithFields(logrus.Fields{
"Path": zipOutputFile.Name(),
}).Info("Code Archive")
return nil
}
type createTemplateOp struct {
userdata *userdata
buildContext *buildContext
}
func (cto *createTemplateOp) Rollback(ctx context.Context, logger *logrus.Logger) error {
return nil
}
func (cto *createTemplateOp) insertTemplateParameters(ctx context.Context, logger *logrus.Logger) (map[string]gocf.Stringable, error) {
// Code archive...
if cto.buildContext.cfTemplate.Parameters == nil {
cto.buildContext.cfTemplate.Parameters = make(map[string]*gocf.Parameter)
}
paramRefMap := make(map[string]gocf.Stringable, 0)
// Code S3 info
cto.buildContext.cfTemplate.Parameters[StackParamS3CodeKeyName] = newStackParameter(
"String",
"S3 key for object storing Sparta payload (required)",
"",
".+",
3)
paramRefMap[StackParamS3CodeKeyName] = gocf.Ref(StackParamS3CodeKeyName)
cto.buildContext.cfTemplate.Parameters[StackParamS3CodeBucketName] = newStackParameter(
"String",
"S3 bucket for object storing Sparta payload (required)",
"",
".+",
3)
paramRefMap[StackParamS3CodeBucketName] = gocf.Ref(StackParamS3CodeBucketName)
cto.buildContext.cfTemplate.Parameters[StackParamS3CodeVersion] = newStackParameter(
"String",
"S3 object version",
"",
".*",
0)
paramRefMap[StackParamS3CodeVersion] = gocf.Ref(StackParamS3CodeVersion)
// Code Pipeline?
if nil != codePipelineEnvironments {
for _, eachEnvironment := range codePipelineEnvironments {
for eachKey := range eachEnvironment {
cto.buildContext.cfTemplate.Parameters[eachKey] = &gocf.Parameter{
Type: "String",
Default: "",
}
}
}
}
// Add the build time to the outputs...
// Add the output
cto.buildContext.cfTemplate.Outputs[StackOutputBuildTime] = &gocf.Output{
Description: "UTC time template was created",
Value: gocf.String(time.Now().UTC().Format(time.RFC3339)),
}
cto.buildContext.cfTemplate.Outputs[StackOutputBuildID] = &gocf.Output{
Description: "BuildID",
Value: gocf.String(cto.userdata.buildID),
}
return paramRefMap, nil
}
func (cto *createTemplateOp) ensureDiscoveryInfo(ctx context.Context, logger *logrus.Logger) error {
validateErrs := make([]error, 0)
requiredEnvVars := []string{envVarDiscoveryInformation,
envVarLogLevel}
// Verify that all Lambda functions have discovery information
for eachResourceID, eachResourceDef := range cto.buildContext.cfTemplate.Resources {
switch typedResource := eachResourceDef.Properties.(type) {
case *gocf.LambdaFunction:
if typedResource.Environment == nil {
validateErrs = append(validateErrs,
errors.Errorf("Lambda function %s does not include environment info", eachResourceID))
} else {
vars, varsOk := typedResource.Environment.Variables.(map[string]interface{})
if !varsOk {
validateErrs = append(validateErrs,
errors.Errorf("Lambda function %s environment vars are unsupported type: %T",
eachResourceID,
typedResource.Environment.Variables))
} else {
for _, eachKey := range requiredEnvVars {
_, exists := vars[eachKey]
if !exists {
validateErrs = append(validateErrs,
errors.Errorf("Lambda function %s environment does not include key: %s",
eachResourceID,
eachKey))
}
}
}
}
}
}
if len(validateErrs) != 0 {
return errors.Errorf("Problems validating template contents: %v", validateErrs)
}
return nil
}
func (cto *createTemplateOp) Invoke(ctx context.Context, logger *logrus.Logger) error {
// PreMarshall Hook
if cto.userdata.workflowHooks != nil {
preMarshallErr := callWorkflowHook("PreMarshall",
cto.userdata.workflowHooks.PreMarshall,
cto.userdata.workflowHooks.PreMarshalls,
cto.userdata,
cto.buildContext,
logger)
if nil != preMarshallErr {
return preMarshallErr
}
}
//////////////////////////////////////////////////////////////////////////////
// Add the "Parameters" to the template...
paramMap, paramErrs := cto.insertTemplateParameters(ctx, logger)
if paramErrs != nil {
return paramErrs
}
//////////////////////////////////////////////////////////////////////////////
// Add the tags
stackTags := map[string]string{
SpartaTagBuildIDKey: cto.userdata.buildID,
}
if len(cto.userdata.buildTags) != 0 {
stackTags[SpartaTagBuildTagsKey] = cto.userdata.buildTags
}
// Canonical code resource definition...
s3CodeResource := &gocf.LambdaFunctionCode{
S3Bucket: paramMap[StackParamS3CodeBucketName].String(),
S3Key: paramMap[StackParamS3CodeKeyName].String(),
S3ObjectVersion: paramMap[StackParamS3CodeVersion].String(),
}
// Marshall the objects...
for _, eachEntry := range cto.userdata.lambdaAWSInfos {
verifyErr := verifyLambdaPreconditions(eachEntry, logger)
if verifyErr != nil {
return verifyErr
}
annotateCodePipelineEnvironments(eachEntry, logger)
exportContext, exportErr := eachEntry.export(cto.buildContext.workflowHooksContext,
cto.userdata.serviceName,
s3CodeResource,
cto.userdata.buildID,
cto.buildContext.lambdaIAMRoleNameMap,
cto.buildContext.cfTemplate,
logger)
if nil != exportErr {
return exportErr
}
cto.buildContext.workflowHooksContext = exportContext
}
// If there's an API gateway definition, include the resources that provision it. Since this export will likely
// generate outputs that the s3 site needs, we'll use a temporary outputs accumulator, pass that to the S3Site
// if it's defined, and then merge it with the normal output map.
apiGatewayTemplate := gocf.NewTemplate()
if nil != cto.userdata.api {
err := cto.userdata.api.Marshal(
cto.userdata.serviceName,
cto.buildContext.awsSession,
s3CodeResource,
cto.buildContext.lambdaIAMRoleNameMap,
apiGatewayTemplate,
cto.userdata.noop,
logger)
if nil == err {
safeMergeErrs := gocc.SafeMerge(apiGatewayTemplate,
cto.buildContext.cfTemplate)
if len(safeMergeErrs) != 0 {
err = errors.Errorf("APIGateway template merge failed: %v", safeMergeErrs)
}
}
if nil != err {
return errors.Wrapf(err, "APIGateway template export failed")
}
}
// Service decorator?
// This is run before the S3 Site in case the decorators
// need to publish data to the MANIFEST for the site
serviceDecoratorErr := callServiceDecoratorHook(s3CodeResource,
cto.userdata,
cto.buildContext,
logger)
if serviceDecoratorErr != nil {
return serviceDecoratorErr
}
// Discovery info on a per-function basis
for _, eachEntry := range cto.userdata.lambdaAWSInfos {
_, annotateErr := annotateDiscoveryInfo(eachEntry, cto.buildContext.cfTemplate, logger)
if annotateErr != nil {
return annotateErr
}
_, annotateErr = annotateBuildInformation(eachEntry,
cto.buildContext.cfTemplate,
cto.userdata.buildID,
logger)
if annotateErr != nil {
return annotateErr
}
// Any custom resources? These may also need discovery info
// so that they can self-discover the stack name
for _, eachCustomResource := range eachEntry.customResources {
discoveryInfo, discoveryInfoErr := discoveryInfoForResource(eachCustomResource.logicalName(),
nil)
if discoveryInfoErr != nil {
return discoveryInfoErr
}
logger.WithFields(logrus.Fields{
"Discovery": discoveryInfo,
"Resource": eachCustomResource.logicalName(),
}).Info("Annotating discovery info for custom resource")
// Update the env map
eachCustomResource.options.Environment[envVarDiscoveryInformation] = discoveryInfo
}
}
// There is no way to get this unless it's a param ref...
// If there's a Site defined, include the resources the provision it
// TODO - turn this into a Parameter block with defaults...
if nil != cto.userdata.s3SiteContext.s3Site {
exportErr := cto.userdata.s3SiteContext.s3Site.export(cto.userdata.serviceName,
cto.buildContext.compiledBinaryOutput,
gocf.Ref(StackParamS3CodeBucketName),
s3CodeResource,
gocf.Ref(StackParamS3SiteArchiveKey).String(),
apiGatewayTemplate.Outputs,
cto.buildContext.lambdaIAMRoleNameMap,
cto.buildContext.cfTemplate,
logger)
if exportErr != nil {
return errors.Wrapf(exportErr, "Failed to export S3 site")
}
}
// PostMarshall Hook
if cto.userdata.workflowHooks != nil {
postMarshallErr := callWorkflowHook("PostMarshall",
cto.userdata.workflowHooks.PostMarshall,
cto.userdata.workflowHooks.PostMarshalls,
cto.userdata,
cto.buildContext,
logger)
if nil != postMarshallErr {
return postMarshallErr
}
}
// Last step, run the annotation steps to patch
// up any references that depends on the entire
// template being constructed
_, annotateErr := annotateMaterializedTemplate(cto.userdata.lambdaAWSInfos,
cto.buildContext.cfTemplate,
logger)
if annotateErr != nil {
return errors.Wrapf(annotateErr,
"Failed to perform final template annotations")
}
// validations?
if cto.userdata.workflowHooks != nil {
validationErr := callValidationHooks(cto.userdata.workflowHooks.Validators,
cto.buildContext.cfTemplate,
s3CodeResource,
cto.userdata,
cto.buildContext,
logger)
if validationErr != nil {
return validationErr
}
}
// Ensure there is discovery info in the template
discoveryInfoErr := cto.ensureDiscoveryInfo(ctx, logger)
if nil != discoveryInfoErr {
return discoveryInfoErr
}
// Generate it & write it out...
cfTemplateJSON, cfTemplateJSONErr := json.Marshal(cto.buildContext.cfTemplate)
if cfTemplateJSONErr != nil {
logger.Error("Failed to Marshal CloudFormation template: ", cfTemplateJSONErr)
return cfTemplateJSONErr
}
// Write out the template to the templateWriter
if nil != cto.buildContext.templateWriter {
_, writeErr := cto.buildContext.templateWriter.Write(cfTemplateJSON)
if nil != writeErr {
return writeErr
}
}
if logger.Level <= logrus.DebugLevel {
formatted, formattedErr := json.Marshal(string(cfTemplateJSON))
if formattedErr == nil {
logger.WithFields(logrus.Fields{
"Body": string(formatted),
}).Debug("CloudFormation template body")
}
}
return nil
}
// Build is just build the artifacts - update template to take params
// If we decouple build and deploy then there's a spot for user to plug in UPX