forked from wallix/awless
-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.go
312 lines (259 loc) · 8.25 KB
/
run.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
/*
Copyright 2017 WALLIX
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package commands
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"strings"
"github.com/fatih/color"
"github.com/spf13/cobra"
"github.com/wallix/awless/cloud"
awscloud "github.com/wallix/awless/cloud/aws"
"github.com/wallix/awless/cloud/aws/validation"
"github.com/wallix/awless/database"
"github.com/wallix/awless/graph"
"github.com/wallix/awless/logger"
"github.com/wallix/awless/sync"
"github.com/wallix/awless/template"
"github.com/wallix/awless/template/driver/aws"
)
var renderGreenFn = color.New(color.FgGreen).SprintFunc()
var renderRedFn = color.New(color.FgRed).SprintFunc()
func init() {
RootCmd.AddCommand(runCmd)
for action, entities := range aws.DriverSupportedActions() {
RootCmd.AddCommand(
createDriverCommands(action, entities),
)
}
}
var runCmd = &cobra.Command{
Use: "run",
Short: "Run a template given a filepath",
PersistentPreRun: applyHooks(initLoggerHook, initAwlessEnvHook, initCloudServicesHook, initSyncerHook, checkStatsHook),
PersistentPostRunE: saveHistoryHook,
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return errors.New("missing awless template file path")
}
content, err := ioutil.ReadFile(args[0])
if err != nil {
return err
}
templ, err := template.Parse(string(content))
exitOn(err)
exitOn(runTemplate(templ, getCurrentDefaults()))
return nil
},
}
func runTemplate(templ *template.Template, defaults map[string]interface{}) error {
resolved, err := templ.ResolveHoles(defaults)
exitOn(err)
logger.Infof("used default params: %s", sprintProcessedParams(resolved))
fills := make(map[string]interface{})
if holes := templ.GetHolesValuesSet(); len(holes) > 0 {
fmt.Println("\nMissing required params (Ctrl+C to quit):")
for _, hole := range holes {
var resp string
ask := func() error {
fmt.Printf("%s ? ", hole)
_, err := fmt.Scanln(&resp)
return err
}
for err := ask(); err != nil; err = ask() {
logger.Errorf("invalid value: %s", err)
}
fills[hole] = resp
}
}
if len(fills) > 0 {
templ.ResolveHoles(fills)
}
awsDriver := aws.NewDriver(
awscloud.InfraService.ProviderRunnableAPI(),
awscloud.AccessService.ProviderRunnableAPI(),
awscloud.StorageService.ProviderRunnableAPI(),
)
awsDriver.SetLogger(logger.DefaultLogger)
for _, cmd := range templ.CommandNodesIterator() {
if validators, ok := validation.ValidatorsPerActions[cmd.Action]; ok {
graph := sync.LoadCurrentLocalGraph(awscloud.ServicePerResourceType[cmd.Entity])
for _, v := range validators {
if err := v.Validate(graph, cmd.Params); err != nil {
return err
}
}
}
}
_, err = templ.Compile(awsDriver)
exitOn(err)
fmt.Println()
fmt.Printf("%s\n", renderGreenFn(templ))
fmt.Println()
fmt.Print("Run verified operations above? (y/n): ")
var yesorno string
_, err = fmt.Scanln(&yesorno)
if strings.TrimSpace(yesorno) == "y" {
newTempl, err := templ.Run(awsDriver)
executed := template.NewTemplateExecution(newTempl)
fmt.Println()
printReport(executed)
db, err, close := database.Current()
exitOn(err)
defer close()
db.AddTemplateExecution(executed)
if err == nil && !executed.HasErrors() {
if autoSync, ok := defaults[database.SyncAuto]; ok && autoSync.(bool) {
runSyncFor(newTempl)
}
}
}
return nil
}
func createDriverCommands(action string, entities []string) *cobra.Command {
actionCmd := &cobra.Command{
Use: action,
Short: fmt.Sprintf("Allow to %s: %v", action, strings.Join(entities, ", ")),
}
for _, entity := range entities {
templDef, ok := aws.AWSTemplatesDefinitions[fmt.Sprintf("%s%s", action, entity)]
if !ok {
exitOn(errors.New("command unsupported on inline mode"))
}
run := func(def template.TemplateDefinition) func(cmd *cobra.Command, args []string) error {
return func(cmd *cobra.Command, args []string) error {
text := fmt.Sprintf("%s %s %s", def.Action, def.Entity, strings.Join(args, " "))
cliTpl, err := template.Parse(text)
exitOn(err)
templ, err := template.Parse(def.String())
if err != nil {
exitOn(fmt.Errorf("internal error parsing template definition\n`%s`\n%s", def, err))
}
logger.Verbosef("template definition: %s", def)
resolved, err := templ.ResolveHoles(
cliTpl.GetNormalizedParams(),
resolveAlias(cliTpl.GetNormalizedAliases(), def.Entity),
)
exitOn(err)
logger.Infof("used provided params: %s.", sprintProcessedParams(resolved))
templ.MergeParams(cliTpl.GetNormalizedParams())
exitOn(runTemplate(templ, getCurrentDefaults()))
return nil
}
}
actionCmd.AddCommand(
&cobra.Command{
Use: templDef.Entity,
PersistentPreRun: applyHooks(initLoggerHook, initAwlessEnvHook, initCloudServicesHook, initSyncerHook, checkStatsHook),
PersistentPostRunE: saveHistoryHook,
Short: fmt.Sprintf("%s a %s", strings.Title(action), templDef.Entity),
Long: fmt.Sprintf("%s a %s\n\tRequired params: %s\n\tExtra params: %s", strings.Title(templDef.Action), templDef.Entity, strings.Join(templDef.Required(), ", "), strings.Join(templDef.Extra(), ", ")),
RunE: run(templDef),
},
)
}
return actionCmd
}
func runSyncFor(tpl *template.Template) {
lookup := func(key string) (t template.TemplateDefinition, ok bool) {
t, ok = aws.AWSTemplatesDefinitions[key]
return
}
collector := &template.CollectDefinitions{L: lookup}
tpl.Visit(collector)
uniqueNames := make(map[string]bool)
for _, def := range collector.C {
name, ok := awscloud.ServicePerAPI[def.Api]
if ok {
uniqueNames[name] = true
}
}
var srvNames []string
for name, _ := range uniqueNames {
srvNames = append(srvNames, name)
}
var services []cloud.Service
for _, name := range srvNames {
srv, ok := cloud.ServiceRegistry[name]
if !ok {
logger.Errorf("internal: cannot resolve service name '%s'", name)
} else {
services = append(services, srv)
}
}
if _, err := sync.DefaultSyncer.Sync(services...); err != nil {
logger.Errorf("error while synching for %s\n", strings.Join(srvNames, ", "))
} else {
logger.Verbosef("performed sync for %s", strings.Join(srvNames, ", "))
}
}
func getCurrentDefaults() map[string]interface{} {
db, err, dbclose := database.Current()
exitOn(err)
defaults, err := db.GetDefaults()
exitOn(err)
dbclose()
return defaults
}
func printReport(t *template.TemplateExecution) {
for _, done := range t.Executed {
var line bytes.Buffer
if done.Result != "" {
line.WriteString(fmt.Sprintf("%s %s ", done.Result, renderGreenFn("<-")))
}
line.WriteString(fmt.Sprintf("%s", done.Line))
if done.Err != "" {
line.WriteString(fmt.Sprintf("\n\terror: %s", done.Err))
}
if done.Err == "" {
logger.Info(line.String())
} else {
logger.Error(line.String())
}
}
if t.IsRevertible() {
logger.Infof("revert this template with `awless revert %s`", t.ID)
}
}
func resolveAlias(aliases map[string]string, entity string) map[string]interface{} {
graphForResource := sync.LoadCurrentLocalGraph(awscloud.ServicePerResourceType[entity])
resolved := make(map[string]interface{})
for k, v := range aliases {
var t string
if strings.Split(k, ".")[1] == "id" {
t = strings.Split(k, ".")[0]
} else {
t = strings.Split(k, ".")[1]
}
rT := graph.ResourceType(t)
a := graph.Alias(v)
if id, ok := a.ResolveToId(graphForResource, rT); ok {
resolved[k] = id
} else {
logger.Infof("alias '%s' not in local snapshot. You might want to perform an `awless sync`\n", a)
}
}
return resolved
}
func sprintProcessedParams(processed map[string]interface{}) string {
if len(processed) == 0 {
return "<none>"
}
var str []string
for k, v := range processed {
str = append(str, fmt.Sprintf("%s=%v", k, v))
}
return strings.Join(str, ", ")
}