-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathprovision_build.go
1634 lines (1510 loc) · 53.8 KB
/
provision_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"
"bytes"
"crypto/sha1"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/url"
"os"
"path"
"path/filepath"
"reflect"
"runtime"
"strings"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"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/lambda"
humanize "github.com/dustin/go-humanize"
spartaAWS "github.com/mweagle/Sparta/aws"
spartaCF "github.com/mweagle/Sparta/aws/cloudformation"
spartaS3 "github.com/mweagle/Sparta/aws/s3"
"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"
)
////////////////////////////////////////////////////////////////////////////////
// CONSTANTS
////////////////////////////////////////////////////////////////////////////////
func spartaTagName(baseKey string) string {
return fmt.Sprintf("io:gosparta:%s", baseKey)
}
var (
// SpartaTagBuildIDKey is the keyname used in the CloudFormation Output
// that stores the user-supplied or automatically generated BuildID
// for this run
SpartaTagBuildIDKey = spartaTagName("buildId")
// SpartaTagBuildTagsKey is the keyname used in the CloudFormation Output
// that stores the optional user-supplied golang build tags
SpartaTagBuildTagsKey = spartaTagName("buildTags")
)
// finalizerFunction is the type of function pushed onto the cleanup stack
type finalizerFunction func(logger *logrus.Logger)
////////////////////////////////////////////////////////////////////////////////
// Type that encapsulates an S3 URL with accessors to return either the
// full URL or just the valid S3 Keyname
type s3UploadURL struct {
location string
path string
version string
}
func (s3URL *s3UploadURL) keyName() string {
return s3URL.path
}
func newS3UploadURL(s3URL string) *s3UploadURL {
urlParts, urlPartsErr := url.Parse(s3URL)
if nil != urlPartsErr {
return nil
}
queryParams, queryParamsErr := url.ParseQuery(urlParts.RawQuery)
if nil != queryParamsErr {
return nil
}
versionIDValues := queryParams["versionId"]
version := ""
if len(versionIDValues) == 1 {
version = versionIDValues[0]
}
return &s3UploadURL{location: s3URL,
path: strings.TrimPrefix(urlParts.Path, "/"),
version: version}
}
////////////////////////////////////////////////////////////////////////////////
func codeZipKey(url *s3UploadURL) string {
if url == nil {
return ""
}
return url.keyName()
}
func codeZipVersion(url *s3UploadURL) string {
if url == nil {
return ""
}
return url.version
}
////////////////////////////////////////////////////////////////////////////////
// Represents data associated with provisioning the S3 Site iff defined
type s3SiteContext struct {
s3Site *S3Site
s3UploadURL *s3UploadURL
}
// 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)
// workflowStepDuration represents a discrete step in the provisioning
// workflow.
type workflowStepDuration struct {
name string
duration time.Duration
}
// 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
// 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 provisioning workflow
type provisionContext struct {
// Information about the ZIP archive that contains the LambdaCode source
s3CodeZipURL *s3UploadURL
// 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
// Is versioning enabled for s3 Bucket?
s3BucketVersioningEnabled bool
// name of the binary inside the ZIP archive
binaryName string
// Context to pass between workflow operations
workflowHooksContext map[string]interface{}
}
// similar to context, transaction scopes values that span the entire
// provisioning step
type transaction struct {
startTime time.Time
// Optional rollback functions that workflow steps may append to if they
// have made mutations during provisioning.
rollbackFunctions []spartaS3.RollbackFunction
// Optional finalizer functions that are unconditionally executed following
// workflow completion, success or failure
finalizerFunctions []finalizerFunction
// Timings that measure how long things actually took
stepDurations []*workflowStepDuration
}
////////////////////////////////////////////////////////////////////////////////
// Workflow context
// The workflow context is created by `provision` and provided to all
// functions that constitute the provisioning workflow.
type workflowContext struct {
// User supplied data that's Lambda specific
userdata userdata
// Context that's mutated across the workflow steps
context provisionContext
// Transaction-scoped information thats mutated across the workflow
// steps
transaction transaction
// Preconfigured logger
logger *logrus.Logger
}
// recordDuration is a utility function to record how long
func recordDuration(start time.Time, name string, ctx *workflowContext) {
elapsed := time.Since(start)
ctx.transaction.stepDurations = append(ctx.transaction.stepDurations,
&workflowStepDuration{
name: name,
duration: elapsed,
})
}
// Register a rollback function in the event that the provisioning
// function failed.
func (ctx *workflowContext) registerRollback(userFunction spartaS3.RollbackFunction) {
if nil == ctx.transaction.rollbackFunctions || len(ctx.transaction.rollbackFunctions) <= 0 {
ctx.transaction.rollbackFunctions = make([]spartaS3.RollbackFunction, 0)
}
ctx.transaction.rollbackFunctions = append(ctx.transaction.rollbackFunctions, userFunction)
}
// Register a rollback function in the event that the provisioning
// function failed.
func (ctx *workflowContext) registerFinalizer(userFunction finalizerFunction) {
if nil == ctx.transaction.finalizerFunctions || len(ctx.transaction.finalizerFunctions) <= 0 {
ctx.transaction.finalizerFunctions = make([]finalizerFunction, 0)
}
ctx.transaction.finalizerFunctions = append(ctx.transaction.finalizerFunctions, userFunction)
}
// Register a finalizer that cleans up local artifacts
func (ctx *workflowContext) registerFileCleanupFinalizer(localPath string) {
cleanup := func(logger *logrus.Logger) {
errRemove := os.Remove(localPath)
if nil != errRemove {
logger.WithFields(logrus.Fields{
"Path": localPath,
"Error": errRemove,
}).Warn("Failed to cleanup intermediate artifact")
} else {
logger.WithFields(logrus.Fields{
"Path": relativePath(localPath),
}).Debug("Build artifact deleted")
}
}
ctx.registerFinalizer(cleanup)
}
// Run any provided rollback functions
func (ctx *workflowContext) rollback() {
defer recordDuration(time.Now(), "Rollback", ctx)
// 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...
ctx.logger.Info("Invoking rollback functions")
var wg sync.WaitGroup
wg.Add(len(ctx.transaction.rollbackFunctions))
rollbackErr := callRollbackHook(ctx, &wg)
if rollbackErr != nil {
ctx.logger.WithFields(logrus.Fields{
"Error": rollbackErr,
}).Warning("Rollback Hook failed to execute")
}
for _, eachCleanup := range ctx.transaction.rollbackFunctions {
go func(cleanupFunc spartaS3.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
//
// logFilesize outputs a friendly filesize for the given filepath
func logFilesize(message string, filePath string, logger *logrus.Logger) {
// Binary size
stat, err := os.Stat(filePath)
if err == nil {
logger.WithFields(logrus.Fields{
"Size": humanize.Bytes(uint64(stat.Size())),
}).Info(message)
}
}
// Encapsulate calling the rollback hooks
func callRollbackHook(ctx *workflowContext, wg *sync.WaitGroup) error {
if ctx.userdata.workflowHooks == nil {
return nil
}
rollbackHooks := ctx.userdata.workflowHooks.Rollbacks
if ctx.userdata.workflowHooks.Rollback != nil {
ctx.logger.Warn("DEPRECATED: Single RollbackHook superseded by RollbackHookHandler slice")
rollbackHooks = append(rollbackHooks,
RollbackHookFunc(ctx.userdata.workflowHooks.Rollback))
}
for _, eachRollbackHook := range rollbackHooks {
wg.Add(1)
go func(handler RollbackHookHandler, context map[string]interface{},
serviceName string,
awsSession *session.Session,
noop bool,
logger *logrus.Logger) {
// Decrement the counter when the goroutine completes.
defer wg.Done()
rollbackErr := handler.Rollback(context,
serviceName,
awsSession,
noop,
logger)
logger.WithFields(logrus.Fields{
"Error": rollbackErr,
}).Warn("Rollback function failed to complete")
}(eachRollbackHook,
ctx.context.workflowHooksContext,
ctx.userdata.serviceName,
ctx.context.awsSession,
ctx.userdata.noop,
ctx.logger)
}
return nil
}
// Encapsulate calling the service decorator hooks
func callServiceDecoratorHook(ctx *workflowContext) error {
if ctx.userdata.workflowHooks == nil {
return nil
}
serviceHooks := ctx.userdata.workflowHooks.ServiceDecorators
if ctx.userdata.workflowHooks.ServiceDecorator != nil {
ctx.logger.Warn("DEPRECATED: Single ServiceDecorator hook superseded by ServiceDecorators slice")
serviceHooks = append(serviceHooks,
ServiceDecoratorHookFunc(ctx.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 _, eachServiceHook := range serviceHooks {
hookName := runtime.FuncForPC(reflect.ValueOf(eachServiceHook).Pointer()).Name()
ctx.logger.WithFields(logrus.Fields{
"ServiceDecoratorHook": hookName,
"WorkflowHookContext": ctx.context.workflowHooksContext,
}).Info("Calling WorkflowHook")
serviceTemplate := gocf.NewTemplate()
decoratorError := eachServiceHook.DecorateService(ctx.context.workflowHooksContext,
ctx.userdata.serviceName,
serviceTemplate,
ctx.userdata.s3Bucket,
codeZipKey(ctx.context.s3CodeZipURL),
ctx.userdata.buildID,
ctx.context.awsSession,
ctx.userdata.noop,
ctx.logger)
if nil != decoratorError {
return decoratorError
}
safeMergeErrs := gocc.SafeMerge(serviceTemplate, ctx.context.cfTemplate)
if len(safeMergeErrs) != 0 {
return errors.Errorf("Failed to merge templates: %#v", safeMergeErrs)
}
}
return nil
}
// Encapsulate calling the archive hooks
func callArchiveHook(lambdaArchive *zip.Writer,
ctx *workflowContext) error {
if ctx.userdata.workflowHooks == nil {
return nil
}
archiveHooks := ctx.userdata.workflowHooks.Archives
if ctx.userdata.workflowHooks.Archive != nil {
ctx.logger.Warn("DEPRECATED: Single ArchiveHook hook superseded by ArchiveHooks slice")
archiveHooks = append(archiveHooks,
ArchiveHookFunc(ctx.userdata.workflowHooks.Archive))
}
for _, eachArchiveHook := range archiveHooks {
// Run the hook
ctx.logger.WithFields(logrus.Fields{
"WorkflowHookContext": ctx.context.workflowHooksContext,
}).Info("Calling ArchiveHook")
hookErr := eachArchiveHook.DecorateArchive(ctx.context.workflowHooksContext,
ctx.userdata.serviceName,
lambdaArchive,
ctx.context.awsSession,
ctx.userdata.noop,
ctx.logger)
if hookErr != nil {
return errors.Wrapf(hookErr, "DecorateArchive returned an error")
}
}
return nil
}
// Encapsulate calling a workflow hook
func callWorkflowHook(hookPhase string,
hook WorkflowHook,
hooks []WorkflowHookHandler,
ctx *workflowContext) error {
if hook != nil {
ctx.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
ctx.logger.WithFields(logrus.Fields{
"Phase": hookPhase,
"WorkflowHookContext": ctx.context.workflowHooksContext,
}).Info("Calling WorkflowHook")
hookErr := eachHook.DecorateWorkflow(ctx.context.workflowHooksContext,
ctx.userdata.serviceName,
ctx.userdata.s3Bucket,
ctx.userdata.buildID,
ctx.context.awsSession,
ctx.userdata.noop,
ctx.logger)
if hookErr != nil {
return errors.Wrapf(hookErr, "DecorateWorkflow returned an error")
}
}
return nil
}
// Encapsulate calling the validation hooks
func callValidationHooks(validationHooks []ServiceValidationHookHandler,
template *gocf.Template,
ctx *workflowContext) 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
ctx.logger.WithFields(logrus.Fields{
"Phase": "Validation",
"ValidationHookContext": ctx.context.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")
}
hookErr := eachHook.ValidateService(ctx.context.workflowHooksContext,
ctx.userdata.serviceName,
&loopTemplate,
ctx.userdata.s3Bucket,
codeZipKey(ctx.context.s3CodeZipURL),
ctx.userdata.buildID,
ctx.context.awsSession,
ctx.userdata.noop,
ctx.logger)
if hookErr != nil {
return errors.Wrapf(hookErr, "Service failed to pass validation")
}
}
return nil
}
// versionAwareS3KeyName returns a keyname that provides the correct cache
// invalidation semantics based on whether the target bucket
// has versioning enabled
func versionAwareS3KeyName(s3DefaultKey string, s3VersioningEnabled bool, logger *logrus.Logger) (string, error) {
versionKeyName := s3DefaultKey
if !s3VersioningEnabled {
var extension = path.Ext(s3DefaultKey)
var prefixString = strings.TrimSuffix(s3DefaultKey, extension)
hash := sha1.New()
salt := fmt.Sprintf("%s-%d", s3DefaultKey, time.Now().UnixNano())
_, writeErr := hash.Write([]byte(salt))
if writeErr != nil {
return "", errors.Wrapf(writeErr, "Failed to update hash digest")
}
versionKeyName = fmt.Sprintf("%s-%s%s",
prefixString,
hex.EncodeToString(hash.Sum(nil)),
extension)
logger.WithFields(logrus.Fields{
"Default": s3DefaultKey,
"Extension": extension,
"PrefixString": prefixString,
"Unique": versionKeyName,
}).Debug("Created unique S3 keyname")
}
return versionKeyName, nil
}
// Upload a local file to S3. Returns the full S3 URL to the file that was
// uploaded. If the target bucket does not have versioning enabled,
// this function will automatically make a new key to ensure uniqueness
func uploadLocalFileToS3(localPath string, s3ObjectKey string, ctx *workflowContext) (string, error) {
// If versioning is enabled, use a stable name, otherwise use a name
// that's dynamically created. By default assume that the bucket is
// enabled for versioning
if s3ObjectKey == "" {
defaultS3KeyName := fmt.Sprintf("%s/%s", ctx.userdata.serviceName, filepath.Base(localPath))
s3KeyName, s3KeyNameErr := versionAwareS3KeyName(defaultS3KeyName,
ctx.context.s3BucketVersioningEnabled,
ctx.logger)
if nil != s3KeyNameErr {
return "", errors.Wrapf(s3KeyNameErr, "Failed to create version aware S3 keyname")
}
s3ObjectKey = s3KeyName
}
s3URL := ""
if ctx.userdata.noop {
// Binary size
filesize := int64(0)
stat, statErr := os.Stat(localPath)
if statErr == nil {
filesize = stat.Size()
}
ctx.logger.WithFields(logrus.Fields{
"Bucket": ctx.userdata.s3Bucket,
"Key": s3ObjectKey,
"File": filepath.Base(localPath),
"Size": humanize.Bytes(uint64(filesize)),
}).Info(noopMessage("S3 upload"))
s3URL = fmt.Sprintf("https://%s-s3.amazonaws.com/%s",
ctx.userdata.s3Bucket,
s3ObjectKey)
} else {
// Make sure we mark things for cleanup in case there's a problem
ctx.registerFileCleanupFinalizer(localPath)
// Then upload it
uploadLocation, uploadURLErr := spartaS3.UploadLocalFileToS3(localPath,
ctx.context.awsSession,
ctx.userdata.s3Bucket,
s3ObjectKey,
ctx.logger)
if nil != uploadURLErr {
return "", errors.Wrapf(uploadURLErr, "Failed to upload local file to S3")
}
s3URL = uploadLocation
ctx.registerRollback(spartaS3.CreateS3RollbackFunc(ctx.context.awsSession, uploadLocation))
}
return s3URL, nil
}
// Private - END
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Workflow steps
////////////////////////////////////////////////////////////////////////////////
func showOptionalAWSUsageInfo(err error, logger *logrus.Logger) {
if err == nil {
return
}
userAWSErr, userAWSErrOk := err.(awserr.Error)
if userAWSErrOk {
if strings.Contains(userAWSErr.Error(), "could not find region configuration") {
logger.Error("")
logger.Error("Consider setting env.AWS_REGION, env.AWS_DEFAULT_REGION, or env.AWS_SDK_LOAD_CONFIG to resolve this issue.")
logger.Error("See the documentation at https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/configuring-sdk.html for more information.")
logger.Error("")
}
}
}
// Verify & cache the IAM rolename to ARN mapping
func verifyIAMRoles(ctx *workflowContext) (workflowStep, error) {
defer recordDuration(time.Now(), "Verifying IAM roles", ctx)
// 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.context.lambdaIAMRoleNameMap = make(map[string]*gocf.StringExpr)
iamSvc := iam.New(ctx.context.awsSession)
// Assemble all the RoleNames and validate the inline IAMRoleDefinitions
var allRoleNames []string
for _, eachLambdaInfo := range ctx.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(ctx.userdata.serviceName,
eachLambdaInfo,
ctx.userdata.s3Bucket,
ctx.logger)
if profileErr != nil {
return nil, errors.Wrapf(profileErr, "Failed to call lambda profile decorator")
}
}
// Validate the IAMRoleDefinitions associated
if nil != eachLambdaInfo.RoleDefinition {
logicalName := eachLambdaInfo.RoleDefinition.logicalName(ctx.userdata.serviceName, eachLambdaInfo.lambdaFunctionName())
_, exists := ctx.context.lambdaIAMRoleNameMap[logicalName]
if !exists {
// Insert it into the resource creation map and add
// the "Ref" entry to the hashmap
ctx.context.cfTemplate.AddResource(logicalName,
eachLambdaInfo.RoleDefinition.toResource(eachLambdaInfo.EventSourceMappings,
eachLambdaInfo.Options,
ctx.logger))
ctx.context.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.userdata.serviceName,
eachCustomResource.userFunctionName)
_, exists := ctx.context.lambdaIAMRoleNameMap[customResourceLogicalName]
if !exists {
ctx.context.cfTemplate.AddResource(customResourceLogicalName,
eachCustomResource.roleDefinition.toResource(nil,
eachCustomResource.options,
ctx.logger))
ctx.context.lambdaIAMRoleNameMap[customResourceLogicalName] = gocf.GetAtt(customResourceLogicalName, "Arn")
}
}
}
}
// Then check all the RoleName literals
for _, eachRoleName := range allRoleNames {
_, exists := ctx.context.lambdaIAMRoleNameMap[eachRoleName]
if !exists {
// Check the role
params := &iam.GetRoleInput{
RoleName: aws.String(eachRoleName),
}
ctx.logger.Debug("Checking IAM RoleName: ", eachRoleName)
resp, err := iamSvc.GetRole(params)
if err != nil {
return nil, err
}
// Cache it - we'll need it later when we create the
// CloudFormation template which needs the execution Arn (not role)
ctx.context.lambdaIAMRoleNameMap[eachRoleName] = gocf.String(*resp.Role.Arn)
}
}
ctx.logger.WithFields(logrus.Fields{
"Count": len(ctx.context.lambdaIAMRoleNameMap),
}).Info("IAM roles verified")
return verifyAWSPreconditions, nil
}
// Verify that everything is setup in AWS before we start building things
func verifyAWSPreconditions(ctx *workflowContext) (workflowStep, error) {
defer recordDuration(time.Now(), "Verifying AWS preconditions", ctx)
// If this a NOOP, assume that versioning is not enabled
if ctx.userdata.noop {
ctx.logger.WithFields(logrus.Fields{
"VersioningEnabled": false,
"Bucket": ctx.userdata.s3Bucket,
"Region": *ctx.context.awsSession.Config.Region,
}).Info(noopMessage("S3 preconditions check"))
} else if len(ctx.userdata.lambdaAWSInfos) != 0 {
// We only need to check this if we're going to upload a ZIP, which
// isn't always true in the case of a Step function...
// Bucket versioning
// Get the S3 bucket and see if it has versioning enabled
isEnabled, versioningPolicyErr := spartaS3.BucketVersioningEnabled(ctx.context.awsSession,
ctx.userdata.s3Bucket,
ctx.logger)
if nil != versioningPolicyErr {
// If this is an error and suggests missing region, output some helpful error text
return nil, versioningPolicyErr
}
ctx.logger.WithFields(logrus.Fields{
"VersioningEnabled": isEnabled,
"Bucket": ctx.userdata.s3Bucket,
}).Info("Checking S3 versioning")
ctx.context.s3BucketVersioningEnabled = isEnabled
if ctx.userdata.codePipelineTrigger != "" && !isEnabled {
return nil, fmt.Errorf("s3 Bucket (%s) for CodePipeline trigger doesn't have a versioning policy enabled", ctx.userdata.s3Bucket)
}
// Bucket region should match region
/*
The name of the Amazon S3 bucket where the .zip file that contains your deployment package is stored. This bucket must reside in the same AWS Region that you're creating the Lambda function in. You can specify a bucket from another AWS account as long as the Lambda function and the bucket are in the same region.
*/
bucketRegion, bucketRegionErr := spartaS3.BucketRegion(ctx.context.awsSession,
ctx.userdata.s3Bucket,
ctx.logger)
if bucketRegionErr != nil {
return nil, fmt.Errorf("failed to determine region for %s. Error: %s",
ctx.userdata.s3Bucket,
bucketRegionErr)
}
ctx.logger.WithFields(logrus.Fields{
"Bucket": ctx.userdata.s3Bucket,
"Region": bucketRegion,
}).Info("Checking S3 region")
if bucketRegion != *ctx.context.awsSession.Config.Region {
return nil, fmt.Errorf("region (%s) does not match bucket region (%s)",
*ctx.context.awsSession.Config.Region,
bucketRegion)
}
// Nothing else to do...
ctx.logger.WithFields(logrus.Fields{
"Region": bucketRegion,
}).Debug("Confirmed S3 region match")
}
// 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
}
ctx.logger.WithFields(fields).Warn("CodePipeline environments do not define equivalent environment keys")
}
}
return createPackageStep(), nil
}
// Build and package the application
func createPackageStep() workflowStep {
return func(ctx *workflowContext) (workflowStep, error) {
defer recordDuration(time.Now(), "Creating code bundle", ctx)
// PreBuild Hook
if ctx.userdata.workflowHooks != nil {
preBuildErr := callWorkflowHook("PreBuild",
ctx.userdata.workflowHooks.PreBuild,
ctx.userdata.workflowHooks.PreBuilds,
ctx)
if nil != preBuildErr {
return nil, preBuildErr
}
}
sanitizedServiceName := sanitizedName(ctx.userdata.serviceName)
buildErr := system.BuildGoBinary(ctx.userdata.serviceName,
ctx.context.binaryName,
ctx.userdata.useCGO,
ctx.userdata.buildID,
ctx.userdata.buildTags,
ctx.userdata.linkFlags,
ctx.userdata.noop,
ctx.logger)
if nil != buildErr {
return nil, buildErr
}
// Cleanup the temporary binary
defer func() {
errRemove := os.Remove(ctx.context.binaryName)
if nil != errRemove {
ctx.logger.WithFields(logrus.Fields{
"File": ctx.context.binaryName,
"Error": errRemove,
}).Warn("Failed to delete binary")
}
}()
// PostBuild Hook
if ctx.userdata.workflowHooks != nil {
postBuildErr := callWorkflowHook("PostBuild",
ctx.userdata.workflowHooks.PostBuild,
ctx.userdata.workflowHooks.PostBuilds,
ctx)
if nil != postBuildErr {
return nil, postBuildErr
}
}
tmpFile, err := system.TemporaryFile(ScratchDirectory,
fmt.Sprintf("%s-code.zip", sanitizedServiceName))
if err != nil {
return nil, err
}
// Strip the local directory in case it's in there...
ctx.logger.WithFields(logrus.Fields{
"TempName": relativePath(tmpFile.Name()),
}).Info("Creating code ZIP archive for upload")
lambdaArchive := zip.NewWriter(tmpFile)
// Archive Hook
archiveErr := callArchiveHook(lambdaArchive, ctx)
if nil != archiveErr {
return nil, 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,
ctx.context.binaryName,
"",
fileHeaderAnnotator,
ctx.logger)
if nil != readerErr {
return nil, readerErr
}
archiveCloseErr := lambdaArchive.Close()
if nil != archiveCloseErr {
return nil, archiveCloseErr
}
tempfileCloseErr := tmpFile.Close()
if nil != tempfileCloseErr {
return nil, tempfileCloseErr
}
return createUploadStep(tmpFile.Name()), nil
}
}
// 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) {
defer recordDuration(time.Now(), "Uploading code", ctx)
var uploadTasks []*workTask
if len(ctx.userdata.lambdaAWSInfos) != 0 {
// We always upload the primary binary...
uploadBinaryTask := func() workResult {
logFilesize("Lambda code archive size", packagePath, ctx.logger)
// Create the S3 key...
zipS3URL, zipS3URLErr := uploadLocalFileToS3(packagePath, "", ctx)
if nil != zipS3URLErr {
return newTaskResult(nil, zipS3URLErr)
}
ctx.context.s3CodeZipURL = newS3UploadURL(zipS3URL)
return newTaskResult(ctx.context.s3CodeZipURL, nil)
}
uploadTasks = append(uploadTasks, newWorkTask(uploadBinaryTask))
} else {
ctx.logger.Info("Bypassing S3 upload as no Lambda functions were provided")
}
// We might need to upload some other things...
if nil != ctx.userdata.s3SiteContext.s3Site {
uploadSiteTask := func() workResult {
tempName := fmt.Sprintf("%s-S3Site.zip", ctx.userdata.serviceName)
tmpFile, err := system.TemporaryFile(ScratchDirectory, tempName)
if err != nil {
return newTaskResult(nil,
errors.Wrapf(err, "Failed to create temporary S3 site archive file"))
}
// Add the contents to the Zip file
zipArchive := zip.NewWriter(tmpFile)
absResourcePath, err := filepath.Abs(ctx.userdata.s3SiteContext.s3Site.resources)
if nil != err {
return newTaskResult(nil, errors.Wrapf(err, "Failed to get absolute filepath"))
}
// Ensure that the directory exists...
_, existsErr := os.Stat(ctx.userdata.s3SiteContext.s3Site.resources)
if existsErr != nil && os.IsNotExist(existsErr) {
return newTaskResult(nil,
errors.Wrapf(existsErr,
"TheS3 Site resources directory (%s) does not exist",
ctx.userdata.s3SiteContext.s3Site.resources))
}
ctx.logger.WithFields(logrus.Fields{
"S3Key": path.Base(tmpFile.Name()),
"SourcePath": absResourcePath,
}).Info("Creating S3Site archive")
err = spartaZip.AddToZip(zipArchive, absResourcePath, absResourcePath, ctx.logger)
if nil != err {
return newTaskResult(nil, err)
}
errClose := zipArchive.Close()
if errClose != nil {
return newTaskResult(nil, errClose)
}
// Upload it & save the key
s3SiteLambdaZipURL, s3SiteLambdaZipURLErr := uploadLocalFileToS3(tmpFile.Name(), "", ctx)
if s3SiteLambdaZipURLErr != nil {
return newTaskResult(nil,
errors.Wrapf(s3SiteLambdaZipURLErr, "Failed to upload local file to S3"))
}
ctx.userdata.s3SiteContext.s3UploadURL = newS3UploadURL(s3SiteLambdaZipURL)
return newTaskResult(ctx.userdata.s3SiteContext.s3UploadURL, nil)
}
uploadTasks = append(uploadTasks, newWorkTask(uploadSiteTask))
}
// Run it and figure out what happened
p := newWorkerPool(uploadTasks, len(uploadTasks))
_, uploadErrors := p.Run()
if len(uploadErrors) > 0 {
return nil, errors.Errorf("Encountered multiple errors during upload: %#v", uploadErrors)
}
return validateSpartaPostconditions(), nil
}
}
// maximumStackOperationTimeout returns the timeout
// value to use for a stack operation based on the type
// of resources that it provisions. In general the timeout
// is short with an exception made for CloudFront
// distributions
func maximumStackOperationTimeout(template *gocf.Template, logger *logrus.Logger) time.Duration {
stackOperationTimeout := 20 * time.Minute
// If there is a CloudFront distributon in there then
// let's give that a bit more time to settle down...In general
// the initial CloudFront distribution takes ~30 minutes
for _, eachResource := range template.Resources {
if eachResource.Properties.CfnResourceType() == "AWS::CloudFront::Distribution" {
stackOperationTimeout = 60 * time.Minute