forked from mweagle/Sparta
/
sparta_main_build.go
333 lines (298 loc) · 9.96 KB
/
sparta_main_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
// +build !lambdabinary
package sparta
import (
"fmt"
"log"
"os"
"time"
validator "gopkg.in/go-playground/validator.v9"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
func platformLogSysInfo(lambdaFunc string, logger *logrus.Logger) {
// NOP
}
// RegisterCodePipelineEnvironment is part of a CodePipeline deployment
// and defines the environments available for deployment. Environments
// are defined the `environmentName`. The values defined in the
// environmentVariables are made available to each service as
// environment variables. The environment key will be transformed into
// a configuration file for a CodePipeline CloudFormation action:
// TemplateConfiguration: !Sub "TemplateSource::${environmentName}".
func RegisterCodePipelineEnvironment(environmentName string,
environmentVariables map[string]string) error {
if _, exists := codePipelineEnvironments[environmentName]; exists {
return errors.Errorf("Environment (%s) has already been defined", environmentName)
}
codePipelineEnvironments[environmentName] = environmentVariables
return nil
}
// NewLoggerWithFormatter returns a logger with the given formatter. If formatter
// is nil, a TTY-aware formatter is used
func NewLoggerWithFormatter(level string, formatter logrus.Formatter) (*logrus.Logger, error) {
logger := logrus.New()
// If there is an environment override, use that
envLogLevel := os.Getenv(envVarLogLevel)
if envLogLevel != "" {
level = envLogLevel
}
logLevel, err := logrus.ParseLevel(level)
if err != nil {
return nil, err
}
logger.Level = logLevel
if nil != formatter {
logger.Formatter = formatter
}
logger.Out = os.Stdout
return logger, nil
}
// Main defines the primary handler for transforming an application into a Sparta package. The
// serviceName is used to uniquely identify your service within a region and will
// be used for subsequent updates. For provisioning, ensure that you've
// properly configured AWS credentials for the golang SDK.
// See http://docs.aws.amazon.com/sdk-for-go/api/aws/defaults.html#DefaultChainCredentials-constant
// for more information.
func Main(serviceName string, serviceDescription string, lambdaAWSInfos []*LambdaAWSInfo, api *API, site *S3Site) error {
return MainEx(serviceName,
serviceDescription,
lambdaAWSInfos,
api,
site,
nil,
false)
}
// MainEx provides an "extended" Main that supports customizing the standard Sparta
// workflow via the `workflowHooks` parameter.
func MainEx(serviceName string,
serviceDescription string,
lambdaAWSInfos []*LambdaAWSInfo,
api *API,
site *S3Site,
workflowHooks *WorkflowHooks,
useCGO bool) error {
//////////////////////////////////////////////////////////////////////////////
// cmdRoot defines the root, non-executable command
CommandLineOptions.Root.Short = fmt.Sprintf("%s - Sparta v.%s powered AWS Lambda Microservice",
serviceName,
SpartaVersion)
CommandLineOptions.Root.Long = serviceDescription
CommandLineOptions.Root.PersistentPreRunE = func(cmd *cobra.Command, args []string) error {
// Save the ServiceName in case a custom command wants it
OptionsGlobal.ServiceName = serviceName
OptionsGlobal.ServiceDescription = serviceDescription
validateErr := validate.Struct(OptionsGlobal)
if nil != validateErr {
return validateErr
}
// Format?
// Running in AWS?
disableColors := OptionsGlobal.DisableColors || isRunningInAWS()
var formatter logrus.Formatter
switch OptionsGlobal.LogFormat {
case "text", "txt":
formatter = &logrus.TextFormatter{
DisableColors: disableColors,
FullTimestamp: OptionsGlobal.TimeStamps,
}
case "json":
formatter = &logrus.JSONFormatter{}
disableColors = true
}
logger, loggerErr := NewLoggerWithFormatter(OptionsGlobal.LogLevel, formatter)
if nil != loggerErr {
return loggerErr
}
// This is a NOP, but makes megacheck happy b/c it doesn't know about
// build flags
platformLogSysInfo("", logger)
OptionsGlobal.Logger = logger
welcomeMessage := fmt.Sprintf("Service: %s", serviceName)
// Header information...
displayPrettyHeader(headerDivider, disableColors, logger)
// Metadata about the build...
logger.WithFields(logrus.Fields{
"Option": cmd.Name(),
"UTC": (time.Now().UTC().Format(time.RFC3339)),
"LinkFlags": OptionsGlobal.LinkerFlags,
}).Info(welcomeMessage)
logger.Info(headerDivider)
return nil
}
//////////////////////////////////////////////////////////////////////////////
// Version
CommandLineOptions.Root.AddCommand(CommandLineOptions.Version)
//////////////////////////////////////////////////////////////////////////////
// Provision
CommandLineOptions.Provision.PreRunE = func(cmd *cobra.Command, args []string) error {
validateErr := validate.Struct(optionsProvision)
OptionsGlobal.Logger.WithFields(logrus.Fields{
"validateErr": validateErr,
"optionsProvision": optionsProvision,
}).Debug("Provision validation results")
return validateErr
}
if nil == CommandLineOptions.Provision.RunE {
CommandLineOptions.Provision.RunE = func(cmd *cobra.Command, args []string) error {
buildID, buildIDErr := provisionBuildID(optionsProvision.BuildID, OptionsGlobal.Logger)
if nil != buildIDErr {
return buildIDErr
}
// Save the BuildID
StampedBuildID = buildID
return Provision(OptionsGlobal.Noop,
serviceName,
serviceDescription,
lambdaAWSInfos,
api,
site,
optionsProvision.S3Bucket,
useCGO,
optionsProvision.InPlace,
buildID,
optionsProvision.PipelineTrigger,
OptionsGlobal.BuildTags,
OptionsGlobal.LinkerFlags,
nil,
workflowHooks,
OptionsGlobal.Logger)
}
}
CommandLineOptions.Root.AddCommand(CommandLineOptions.Provision)
//////////////////////////////////////////////////////////////////////////////
// Delete
CommandLineOptions.Delete.RunE = func(cmd *cobra.Command, args []string) error {
return Delete(serviceName, OptionsGlobal.Logger)
}
CommandLineOptions.Root.AddCommand(CommandLineOptions.Delete)
//////////////////////////////////////////////////////////////////////////////
// Execute
if nil == CommandLineOptions.Execute.RunE {
CommandLineOptions.Execute.RunE = func(cmd *cobra.Command, args []string) error {
OptionsGlobal.Logger.Formatter = new(logrus.JSONFormatter)
// Ensure the discovery service is initialized
initializeDiscovery(OptionsGlobal.Logger)
return Execute(serviceName,
lambdaAWSInfos,
OptionsGlobal.Logger)
}
}
CommandLineOptions.Root.AddCommand(CommandLineOptions.Execute)
//////////////////////////////////////////////////////////////////////////////
// Describe
if nil == CommandLineOptions.Describe.RunE {
CommandLineOptions.Describe.RunE = func(cmd *cobra.Command, args []string) error {
validateErr := validate.Struct(optionsDescribe)
if nil != validateErr {
return validateErr
}
fileWriter, fileWriterErr := os.Create(optionsDescribe.OutputFile)
if fileWriterErr != nil {
return fileWriterErr
}
defer fileWriter.Close()
describeErr := Describe(serviceName,
serviceDescription,
lambdaAWSInfos,
api,
site,
optionsDescribe.S3Bucket,
OptionsGlobal.BuildTags,
OptionsGlobal.LinkerFlags,
fileWriter,
workflowHooks,
OptionsGlobal.Logger)
if describeErr == nil {
describeErr = fileWriter.Sync()
}
return describeErr
}
}
CommandLineOptions.Root.AddCommand(CommandLineOptions.Describe)
//////////////////////////////////////////////////////////////////////////////
// Explore
if nil == CommandLineOptions.Explore.RunE {
CommandLineOptions.Explore.RunE = func(cmd *cobra.Command, args []string) error {
validateErr := validate.Struct(optionsExplore)
if nil != validateErr {
return validateErr
}
return Explore(serviceName,
serviceDescription,
lambdaAWSInfos,
api,
site,
optionsDescribe.S3Bucket,
OptionsGlobal.BuildTags,
OptionsGlobal.LinkerFlags,
OptionsGlobal.Logger)
}
}
CommandLineOptions.Root.AddCommand(CommandLineOptions.Explore)
//////////////////////////////////////////////////////////////////////////////
// Profile
if nil == CommandLineOptions.Profile.RunE {
CommandLineOptions.Profile.RunE = func(cmd *cobra.Command, args []string) error {
validateErr := validate.Struct(optionsProfile)
if nil != validateErr {
return validateErr
}
return Profile(serviceName,
serviceDescription,
optionsProfile.S3Bucket,
optionsProfile.Port,
OptionsGlobal.Logger)
}
}
CommandLineOptions.Root.AddCommand(CommandLineOptions.Profile)
//////////////////////////////////////////////////////////////////////////////
// Status
if nil == CommandLineOptions.Status.RunE {
CommandLineOptions.Status.RunE = func(cmd *cobra.Command, args []string) error {
validateErr := validate.Struct(optionsStatus)
if nil != validateErr {
return validateErr
}
return Status(serviceName,
serviceDescription,
optionsStatus.Redact,
OptionsGlobal.Logger)
}
}
CommandLineOptions.Root.AddCommand(CommandLineOptions.Status)
// Run it!
executedCmd, executeErr := CommandLineOptions.Root.ExecuteC()
if executeErr != nil {
if OptionsGlobal.Logger == nil {
newLogger, newLoggerErr := NewLogger("info")
if newLoggerErr != nil {
fmt.Printf("Failed to create new logger: %v", newLoggerErr)
newLogger = logrus.New()
}
OptionsGlobal.Logger = newLogger
}
if OptionsGlobal.Logger != nil {
validationErr, validationErrOk := executeErr.(validator.ValidationErrors)
if validationErrOk {
for _, eachError := range validationErr {
OptionsGlobal.Logger.Error(eachError)
}
// Only show the usage if there were input validation errors
if executedCmd != nil {
usageErr := executedCmd.Usage()
if usageErr != nil {
OptionsGlobal.Logger.Error(usageErr)
}
}
} else {
OptionsGlobal.Logger.Error(executeErr)
}
} else {
log.Printf("ERROR: %s", executeErr)
}
}
// Cleanup, if for some reason the caller wants to re-execute later...
CommandLineOptions.Root.PersistentPreRunE = nil
return executeErr
}