forked from spinnaker/roer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathactions.go
567 lines (470 loc) · 16.1 KB
/
actions.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
package roer
import (
"encoding/json"
"fmt"
"io/ioutil"
"time"
"github.com/ghodss/yaml"
"github.com/mitchellh/mapstructure"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/spinnaker/roer/spinnaker"
"github.com/urfave/cli"
)
// PipelineExecAction requests a pipeline execution and optionally waits for
// it to complete. Arguments are the name of the app and the name of the
// pipeline to start.
func PipelineExecAction(clientConfig spinnaker.ClientConfig) cli.ActionFunc {
return func(cc *cli.Context) error {
appName := cc.Args().Get(0)
pipelineName := cc.Args().Get(1)
monitor := cc.Bool("monitor")
numRetries := cc.Int("retry")
logrus.WithFields(logrus.Fields{
"app": appName,
"pipeline": pipelineName,
"monitor": monitor,
"retries": numRetries,
}).Info("Executing Pipeline...")
client, err := clientFromContext(cc, clientConfig)
if err != nil {
return errors.Wrapf(err, "creating spinnaker client")
}
resp, err := client.ExecPipeline(appName, pipelineName)
if err != nil {
return errors.Wrapf(err, "couldn't execute pipeline")
}
logrus.Infof("Ref task id: %s", resp.Ref)
if monitor {
var err error
var execResp *spinnaker.ExecutionResponse
for retryCounter := 0; retryCounter <= numRetries; {
retryCounter++
logrus.Infof("Polling tasks status, retry number: %d", retryCounter)
execResp, err = client.PollTaskStatus(resp.Ref, 30*time.Minute)
if err != nil {
logrus.WithField("exec_response", execResp).Errorf("Executing response error: %v", err)
}
}
if err != nil {
return err
}
if execResp != nil && execResp.Status != "SUCCEEDED" {
return fmt.Errorf("pipeline did not complete with a SUCCESS status. Ended with status: %s", execResp.Status)
}
}
return nil
}
}
// PipelineSaveAction creates the ActionFunc for saving pipeline configurations.
func PipelineSaveAction(clientConfig spinnaker.ClientConfig) cli.ActionFunc {
return func(cc *cli.Context) error {
configFile := cc.Args().Get(0)
logrus.WithField("file", configFile).Debug("Reading config")
dat, err := ioutil.ReadFile(configFile)
if err != nil {
return errors.Wrapf(err, "reading config file: %s", configFile)
}
client, err := clientFromContext(cc, clientConfig)
if err != nil {
return errors.Wrapf(err, "creating spinnaker client")
}
var m map[string]interface{}
if err := yaml.Unmarshal(dat, &m); err != nil {
return errors.Wrapf(err, "unmarshaling config")
}
if _, ok := m["schema"]; !ok {
logrus.Error("Pipeline save command currently only supports pipeline template configurations")
}
var config PipelineConfiguration
if err := mapstructure.Decode(m, &config); err != nil {
return errors.Wrap(err, "converting map to struct")
}
existingConfig, err := client.GetPipelineConfig(config.Pipeline.Application, config.Pipeline.Name)
if err != nil {
return errors.Wrap(err, "searching for existing pipeline config")
}
// TODO rz - orca should probably auto-set the pipeline config id somehow so
// executions correctly show up in the UI.
payload := config.ToClient()
if existingConfig != nil {
payload.ID = existingConfig.ID
}
if err := client.SavePipelineConfig(payload); err != nil {
return errors.Wrap(err, "saving pipeline config")
}
return nil
}
}
// AppCreateAction creates the ActionFunc for creating a spinnaker application
func AppCreateAction(clientConfig spinnaker.ClientConfig) cli.ActionFunc {
return func(cc *cli.Context) error {
appName := cc.Args().Get(0)
configFile := cc.Args().Get(1)
logrus.WithField("appName", appName).Debug("Filling in create application task")
logrus.WithField("file", configFile).Debug("Reading application config")
config, err := readYamlFile(configFile)
if err != nil {
return errors.Wrapf(err, "reading config file: %s", configFile)
}
config["name"] = appName
createAppJob := spinnaker.ApplicationJob{
Application: config,
Type: "createApplication",
}
createApp := spinnaker.Task{
Application: appName,
Description: "Create Application: " + appName,
Job: []interface{}{createAppJob},
}
client, err := clientFromContext(cc, clientConfig)
if err != nil {
return errors.Wrapf(err, "creating spinnaker client")
}
logrus.Info("Sending create app task")
ref, err := client.ApplicationSubmitTask(appName, createApp)
if err != nil {
return errors.Wrapf(err, "submitting task")
}
resp, err := client.PollTaskStatus(ref.Ref, time.Duration(cc.GlobalInt("timeout"))*time.Second)
if err != nil {
return errors.Wrap(err, "poll create app status")
}
if resp.Status == "TERMINAL" {
logrus.WithField("status", resp.Status).Error("Task failed")
if retrofitErr := resp.ExtractRetrofitError(); retrofitErr != nil {
prettyPrintJSON([]byte(retrofitErr.ResponseBody))
} else {
logrus.Debugf("Response data %#v", resp)
}
} else {
logrus.WithField("status", resp.Status).Info("Task completed")
}
return nil
}
}
// AppDeleteAction delete an application
func AppDeleteAction(clientConfig spinnaker.ClientConfig) cli.ActionFunc {
return func(cc *cli.Context) error {
appName := cc.Args().Get(0)
config := make(map[string]interface{})
config["name"] = appName
deleteAppJob := spinnaker.ApplicationJob{
Application: config,
Type: "deleteApplication",
}
deleteApp := spinnaker.Task{
Application: appName,
Description: "Delete Application: " + appName,
Job: []interface{}{deleteAppJob},
}
client, err := clientFromContext(cc, clientConfig)
if err != nil {
return errors.Wrapf(err, "creating spinnaker client")
}
logrus.Info("Sending delete app task")
ref, err := client.ApplicationSubmitTask(appName, deleteApp)
if err != nil {
return errors.Wrapf(err, "submitting task")
}
resp, err := client.PollTaskStatus(ref.Ref, time.Duration(cc.GlobalInt("timeout"))*time.Second)
if err != nil {
return errors.Wrap(err, "poll delete app status")
}
if resp.Status == "TERMINAL" {
logrus.WithField("status", resp.Status).Error("Task failed")
if retrofitErr := resp.ExtractRetrofitError(); retrofitErr != nil {
prettyPrintJSON([]byte(retrofitErr.ResponseBody))
} else {
fmt.Printf("%#v\n", resp)
}
} else {
logrus.WithField("status", resp.Status).Info("Task completed")
}
return nil
}
}
// AppGetAction creates the ActionFunc for fetching spinnaker application configuration
func AppGetAction(clientConfig spinnaker.ClientConfig) cli.ActionFunc {
return func(cc *cli.Context) error {
appName := cc.Args().Get(0)
client, err := clientFromContext(cc, clientConfig)
if err != nil {
return errors.Wrapf(err, "creating spinnaker client")
}
logrus.WithField("appName", appName).Info("Fetching application")
exists, appInfo, err := client.ApplicationGet(appName)
if err != nil {
return errors.Wrap(err, "Fetching app info")
}
if exists == false {
logrus.Error("App does not exist or insufficient permission")
return fmt.Errorf("Could not fetch app info")
}
appYaml, err := yaml.JSONToYAML(appInfo)
if err != nil {
return fmt.Errorf("could not unmarshal: %v", err)
}
fmt.Printf("%s", appYaml)
return nil
}
}
// AppListAction creates the ActionFunc for listing applications
func AppListAction(clientConfig spinnaker.ClientConfig) cli.ActionFunc {
return func(cc *cli.Context) error {
client, err := clientFromContext(cc, clientConfig)
if err != nil {
return errors.Wrapf(err, "creating spinnaker client")
}
logrus.Info("Fetching application list")
appInfo, err := client.ApplicationList()
if err != nil {
return errors.Wrap(err, "Fetching application list")
}
for _, app := range appInfo {
logrus.Info(app.Name)
}
return nil
}
}
// PipelineSaveJSONAction creates the ActionFunc for saving a pipeline from json source
func PipelineSaveJSONAction(clientConfig spinnaker.ClientConfig) cli.ActionFunc {
return func(cc *cli.Context) error {
jsonFile := cc.Args().Get(0)
logrus.WithField("file", jsonFile).Debug("Reading JSON payload")
dat, err := ioutil.ReadFile(jsonFile)
if err != nil {
return errors.Wrapf(err, "reading JSON file: %s", jsonFile)
}
client, err := clientFromContext(cc, clientConfig)
if err != nil {
return errors.Wrapf(err, "creating spinnaker client")
}
var newConfig spinnaker.PipelineConfig
if err := json.Unmarshal(dat, &newConfig); err != nil {
return errors.Wrap(err, "Unmarshaling JSON pipeline")
}
existingConfig, err := client.GetPipelineConfig(newConfig.Application, newConfig.Name)
if err != nil {
return errors.Wrap(err, "searching for existing pipeline config")
}
if existingConfig != nil {
newConfig.ID = existingConfig.ID
}
if err := client.SavePipelineConfig(newConfig); err != nil {
return errors.Wrap(err, "saving pipeline config")
}
return nil
}
}
// PipelineListConfigsAction creates the ActionFunc for listing pipeline configs
func PipelineListConfigsAction(clientConfig spinnaker.ClientConfig) cli.ActionFunc {
return func(cc *cli.Context) error {
appName := cc.Args().Get(0)
logrus.WithField("app", appName).Debug("Fetching pipelines")
client, err := clientFromContext(cc, clientConfig)
if err != nil {
return errors.Wrapf(err, "creating spinnaker client")
}
pipelineInfo, err := client.ListPipelineConfigs(appName)
if err != nil {
return errors.Wrap(err, "Fetching pipelines")
}
for _, pipeline := range pipelineInfo {
logrus.Info(pipeline.Name)
}
return nil
}
}
// PipelineGetConfigAction creates the ActionFunc for fetching a pipeline config
func PipelineGetConfigAction(clientConfig spinnaker.ClientConfig) cli.ActionFunc {
return func(cc *cli.Context) error {
appName := cc.Args().Get(0)
pipelineName := cc.Args().Get(1)
logrus.WithField("app", appName).WithField("pipelineName", pipelineName).Debug("Fetching pipeline")
client, err := clientFromContext(cc, clientConfig)
if err != nil {
return errors.Wrapf(err, "creating spinnaker client")
}
pipelineConfig, err := client.GetPipelineConfig(appName, pipelineName)
if err != nil {
return errors.Wrap(err, "Fetching pipeline")
}
jsonStr, _ := json.Marshal(pipelineConfig)
prettyPrintJSON(jsonStr)
return nil
}
}
// PipelineTemplatePublishAction creates the ActionFunc for publishing pipeline
// templates.
func PipelineTemplatePublishAction(clientConfig spinnaker.ClientConfig) cli.ActionFunc {
return func(cc *cli.Context) error {
if cc.Bool("update") {
logrus.Warn("The `update` flag is deprecated, `publish` always creates or updates the template")
}
templateFile := cc.Args().Get(0)
logrus.WithField("file", templateFile).Debug("Reading template")
template, err := readYamlFile(templateFile)
if err != nil {
return errors.Wrapf(err, "reading template file: %s", templateFile)
}
client, err := clientFromContext(cc, clientConfig)
if err != nil {
return errors.Wrapf(err, "creating spinnaker client")
}
logrus.Info("Publishing template")
ref, err := client.PublishTemplate(template, spinnaker.PublishTemplateOptions{
SkipPlan: cc.Bool("skipPlan"),
TemplateID: cc.String("templateId"),
Source: cc.String("source"),
})
if err != nil {
return errors.Wrap(err, "publishing template")
}
resp, err := client.PollTaskStatus(ref.Ref, time.Duration(cc.GlobalInt("timeout"))*time.Second)
if err != nil {
return errors.Wrap(err, "polling task status")
}
if resp.Status == "TERMINAL" {
logrus.WithField("status", resp.Status).Error("Task failed")
if retrofitErr := resp.ExtractRetrofitError(); retrofitErr != nil {
prettyPrintJSON([]byte(retrofitErr.ResponseBody))
} else {
logrus.Debugf("Response data %#v", resp)
}
} else {
logrus.WithField("status", resp.Status).Info("Task completed")
}
return nil
}
}
// PipelineTemplatePlanAction creates the ActionFunc for planning a pipeline
// template with a given configuration.
func PipelineTemplatePlanAction(clientConfig spinnaker.ClientConfig) cli.ActionFunc {
return func(cc *cli.Context) error {
configFile := cc.Args().Get(0)
logrus.WithField("file", configFile).Debug("Reading config")
config, err := readYamlFile(configFile)
var template map[string]interface{}
if cc.IsSet("template") {
logrus.WithField("file", cc.String("template")).Debug("Reading template")
template, err = readYamlFile(cc.String("template"))
}
client, err := clientFromContext(cc, clientConfig)
if err != nil {
return errors.Wrapf(err, "creating spinnaker client")
}
resp, err := client.Plan(config, template)
if err != nil {
if err == spinnaker.ErrInvalidPipelineTemplate {
prettyPrintJSON(resp)
return nil
}
logrus.Info(string(resp))
return errors.Wrap(err, "planning configuration")
}
prettyPrintJSON(resp)
return nil
}
}
// PipelineTemplateConvertAction creates the ActionFunc for converting an existing pipeline
// into a pipeline template
func PipelineTemplateConvertAction(clientConfig spinnaker.ClientConfig) cli.ActionFunc {
return func(cc *cli.Context) error {
app := cc.Args().Get(0)
pipelineConfigID := cc.Args().Get(1)
client, err := clientFromContext(cc, clientConfig)
if err != nil {
return errors.Wrap(err, "creating spinnaker client")
}
resp, err := client.GetPipelineConfig(app, pipelineConfigID)
if err != nil {
logrus.Debug(resp)
return errors.Wrap(err, "getting pipeline config")
}
if resp == nil {
logrus.Error("could not find pipeline config")
}
// TODO rz - Write custom marshaler to preserve key order
template, err := yaml.Marshal(convertPipelineToTemplate(*resp))
if err != nil {
return errors.Wrap(err, "marshaling template to YAML")
}
logrus.Info(generatedTemplateHeader)
logrus.Info(string(template))
return nil
}
}
// PipelineTemplateDeleteAction creates the ActionFunc for deleting a pipeline template
func PipelineTemplateDeleteAction(clientConfig spinnaker.ClientConfig) cli.ActionFunc {
return func(cc *cli.Context) error {
pipelineTemplateID := cc.Args().Get(0)
client, err := clientFromContext(cc, clientConfig)
if err != nil {
return errors.Wrap(err, "creating spinnaker client")
}
logrus.Info("Deleting template")
ref, err := client.DeleteTemplate(pipelineTemplateID)
if err != nil {
return errors.Wrap(err, "deleting pipeline template")
}
resp, err := client.PollTaskStatus(ref.Ref, time.Duration(cc.GlobalInt("timeout"))*time.Second)
if err != nil {
return errors.Wrap(err, "polling task status")
}
if resp.Status == "TERMINAL" {
logrus.WithField("status", resp.Status).Error("Task failed")
if retrofitErr := resp.ExtractRetrofitError(); retrofitErr != nil {
prettyPrintJSON([]byte(retrofitErr.ResponseBody))
} else {
logrus.Debugf("Response data %#v", resp)
}
} else {
logrus.WithField("status", resp.Status).Info("Task completed")
}
return nil
}
}
// PipelineDeleteAction creates the ActionFunc for deleting a pipeline
func PipelineDeleteAction(clientConfig spinnaker.ClientConfig) cli.ActionFunc {
return func(cc *cli.Context) error {
app := cc.Args().Get(0)
pipelineID := cc.Args().Get(1)
client, err := clientFromContext(cc, clientConfig)
if err != nil {
return errors.Wrap(err, "creating spinnaker client")
}
logrus.Info("Deleting pipeline")
err = client.DeletePipeline(app, pipelineID)
if err != nil {
return errors.Wrap(err, "deleting pipeline template")
}
return nil
}
}
func clientFromContext(cc *cli.Context, config spinnaker.ClientConfig) (spinnaker.Client, error) {
hc, err := config.HTTPClientFactory(cc)
if err != nil {
return nil, errors.Wrap(err, "creating http client from context")
}
var sc spinnaker.Client
sc = spinnaker.New(config.Endpoint, hc)
if cc.GlobalIsSet("fiatUser") && cc.GlobalIsSet("fiatPass") {
err := sc.FiatLogin(cc.GlobalString("fiatUser"), cc.GlobalString("fiatPass"))
if err != nil {
return nil, errors.Wrap(err, "fiat auth login attempt")
}
}
return sc, nil
}
func readYamlFile(f string) (map[string]interface{}, error) {
configDat, err := ioutil.ReadFile(f)
if err != nil {
return nil, errors.Wrapf(err, "reading file: %s", f)
}
var m map[string]interface{}
if err := yaml.Unmarshal(configDat, &m); err != nil {
return nil, errors.Wrapf(err, "unmarshaling yaml in %s", f)
}
return m, nil
}