-
Notifications
You must be signed in to change notification settings - Fork 0
/
configparser.go
416 lines (353 loc) · 10.7 KB
/
configparser.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
package main
import (
"bytes"
"errors"
"fmt"
"github.com/byrnedo/capitan/container"
"github.com/byrnedo/capitan/helpers"
"github.com/byrnedo/capitan/logger"
"github.com/codegangsta/cli"
"github.com/codeskyblue/go-sh"
"github.com/mgutz/str"
"os"
"path"
"strconv"
"strings"
"unicode"
)
type ConfigParser struct {
// command to obtain config from
Command string
// args given to cli
Args cli.Args
// the container filter
Filter string
}
func NewSettingsParser(cmd string, args cli.Args, filter string) *ConfigParser {
return &ConfigParser{
Command: cmd,
Args: args,
Filter: filter,
}
}
func (f *ConfigParser) Run() (*ProjectConfig, error) {
var (
output []byte
err error
cmdSlice []string
cmdArgs []interface{}
)
if len(f.Command) == 0 {
return nil, errors.New("Command must not be empty")
}
if cmdSlice = str.ToArgv(f.Command); len(cmdSlice) > 1 {
cmdArgs = helpers.ToInterfaceSlice(cmdSlice[1:])
} else {
cmdArgs = []interface{}{}
}
ses := sh.NewSession()
if output, err = ses.Command(cmdSlice[0], cmdArgs...).Output(); err != nil {
return nil, err
}
settings, err := f.parseOutput(output)
return settings, err
}
func (f *ConfigParser) parseOutput(out []byte) (*ProjectConfig, error) {
lines := bytes.Split(out, []byte{'\n'})
settings, err := f.parseSettings(lines)
return settings, err
}
// The main parse function. Creates the final list of containers.
func (f *ConfigParser) parseSettings(lines [][]byte) (projSettings *ProjectConfig, err error) {
//minimum of len1 at this point in parts
cmdsMap := make(map[string]container.Container, 0)
projName, _ := os.Getwd()
projName = toSnake(path.Base(projName))
projNameArr := strings.Split(projName, "_")
projSettings = new(ProjectConfig)
projSettings.ProjectName = projNameArr[len(projNameArr)-1]
projSettings.ProjectSeparator = "_"
projSettings.Hooks = make(Hooks)
for lineNum, line := range lines {
line = bytes.TrimLeft(line, " ")
if len(line) == 0 || line[0] == '#' {
//comment
continue
}
lineParts := bytes.SplitN(line, []byte{' '}, 3)
if len(lineParts) < 2 {
//not enough args on line
continue
}
if string(lineParts[0]) == "global" {
if len(lineParts) > 2 {
switch string(lineParts[1]) {
case "project":
projSettings.ProjectName = string(lineParts[2])
case "project_sep":
projSettings.ProjectSeparator = stripChars(string(lineParts[2]), " \t")
case "blue_green":
projSettings.BlueGreenMode, _ = strconv.ParseBool(string(lineParts[2]))
case "hook":
hookAndCommand := bytes.SplitN(lineParts[2], []byte{' '}, 2)
if len(hookAndCommand) == 2 {
hookName := string(hookAndCommand[0])
hookScript := string(hookAndCommand[1])
hook := projSettings.Hooks[hookName]
if hook == nil {
hook = new(Hook)
}
hook.Scripts = append(hook.Scripts, hookScript)
projSettings.Hooks[hookName] = hook
}
}
}
continue
}
contr := string(lineParts[0])
if _, found := cmdsMap[contr]; !found {
cmdsMap[contr] = container.Container{
Placement: len(cmdsMap),
Hooks: make(map[string]*container.Hook, 0),
Scale: 1,
BlueGreenMode: container.BGModeUnknown,
Enabled: true,
}
}
action := string(lineParts[1])
setting := cmdsMap[contr]
var args string
if len(lineParts) > 2 {
args = string(lineParts[2])
}
args = strings.TrimRight(args, " ")
switch action {
case "command":
if len(args) > 0 {
parsedArgs := str.ToArgv(args)
for _, arg := range parsedArgs {
setting.Command = append(setting.Command, arg)
}
}
case "scale":
if len(args) > 0 {
scale, err := strconv.Atoi(args)
if err != nil {
return projSettings, errors.New(fmt.Sprintf("Failed to parse `scale` on line %d, %s", lineNum+1, err))
}
if scale < 1 {
scale = 1
}
setting.Scale = scale
}
case "image":
if len(args) > 0 {
setting.Image = args
}
case "build":
if len(args) > 0 {
setting.Build = args
}
case "build-args":
if len(args) > 0 {
setting.BuildArgs = str.ToArgv(args)
}
case "link":
argParts := strings.SplitN(args, ":", 2)
var alias string
if len(argParts) > 1 {
alias = argParts[1]
}
newLink := container.Link{
Container: argParts[0],
Alias: alias,
}
setting.Links = append(setting.Links, newLink)
case "rm":
setting.Remove = true
case "hook":
if len(args) > 0 {
curHooks := setting.Hooks
argParts := strings.SplitN(args, " ", 2)
hookName := argParts[0]
if len(argParts) > 1 {
hookScript := argParts[1]
hook := curHooks[hookName]
if hook == nil {
hook = new(container.Hook)
}
hook.Scripts = append(hook.Scripts, hookScript)
curHooks[hookName] = hook
}
setting.Hooks = curHooks
}
case "blue-green":
if len(args) > 0 {
isBGMode, _ := strconv.ParseBool(args)
if isBGMode {
setting.BlueGreenMode = container.BGModeOn
} else {
setting.BlueGreenMode = container.BGModeOff
}
}
case "enabled":
if len(args) > 0 {
setting.Enabled, _ = strconv.ParseBool(args)
}
case "volumes-from":
argParts := strings.SplitN(args, " ", 2)
setting.VolumesFrom = append(setting.VolumesFrom, argParts[0])
case "global":
default:
if action != "" {
setting.ContainerArgs = append(setting.ContainerArgs, "--"+action)
if args != "" {
setting.ContainerArgs = append(setting.ContainerArgs, args)
}
}
}
cmdsMap[contr] = setting
}
var containersState map[string]*helpers.ServiceState
if containersState, err = helpers.GetProjectState(projSettings.ProjectName, projSettings.ProjectSeparator); err != nil {
return
}
// Post process
err = f.postProcessConfig(cmdsMap, projSettings, containersState)
return
}
// Now that we have all settings do some house keeping and processing
func (f *ConfigParser) postProcessConfig(parsedConfig map[string]container.Container, projSettings *ProjectConfig, state map[string]*helpers.ServiceState) error {
// TODO duplicate containers for scaling
projSettings.ContainerList = make(SettingsList, 0)
for name, item := range parsedConfig {
if f.Filter != "" && f.Filter != name {
continue
}
if ! item.Enabled {
continue
}
item.Name = projSettings.ProjectName + projSettings.ProjectSeparator + name
item.ServiceType = name
item.ProjectName = projSettings.ProjectName
item.ProjectNameSeparator = projSettings.ProjectSeparator
// default image to name if 'build' is set
if item.Build != "" {
item.Image = item.Name
}
f.processBlueGreenMode(projSettings.BlueGreenMode, &item)
f.processScaleArg(&item)
f.processCleanupTasks(projSettings, &item)
// resolve links
f.processLinks(parsedConfig, &item)
// resolve volumes from
f.processVolumesFrom(parsedConfig, &item)
ctrsToAdd := f.scaleContainers(&item, state)
projSettings.ContainerList = append(projSettings.ContainerList, ctrsToAdd...)
}
return nil
}
func (f *ConfigParser) processBlueGreenMode(globalBGMode bool, item *container.Container) {
if item.BlueGreenMode == container.BGModeUnknown {
if globalBGMode {
item.BlueGreenMode = container.BGModeOn
} else {
item.BlueGreenMode = container.BGModeOff
}
}
}
// Parse the volumes-from args and try and find first container with that type
func (f *ConfigParser) processVolumesFrom(parsedConfig map[string]container.Container, item *container.Container) {
for i, ctrName := range item.VolumesFrom {
// TODO Not sure how to do this for scaling
if _, found := parsedConfig[ctrName]; found {
ctrName = item.ProjectName + item.ProjectNameSeparator + ctrName + item.ProjectNameSeparator + "1"
item.VolumesFrom[i] = ctrName
}
}
}
// Parse the link args and try and find first container with that type
func (f *ConfigParser) processLinks(parsedConfig map[string]container.Container, item *container.Container) {
for i, link := range item.Links {
// TODO right now, for scaling links are bad so just putting it to first container
container := link.Container
if _, found := parsedConfig[link.Container]; found {
container = item.ProjectName + item.ProjectNameSeparator + link.Container + item.ProjectNameSeparator + "1"
}
link.Container = container
item.Links[i] = link
}
}
// Parse the scale argument and set the container's scale property
func (f *ConfigParser) processScaleArg(ctr *container.Container) {
if f.Args.Get(0) == "scale" {
if f.Args.Get(1) == ctr.ServiceType {
if scaleArg, err := strconv.Atoi(f.Args.Get(2)); err == nil {
if scaleArg > 0 {
ctr.Scale = scaleArg
}
}
}
}
}
// Create list of containers to cleanup when scaling
func (f *ConfigParser) processCleanupTasks(projSettings *ProjectConfig, ctr *container.Container) {
var tasks SettingsList
for _, existing := range projSettings.ContainersState {
instNum, err := helpers.GetNumericSuffix(existing.Name, ctr.ProjectNameSeparator)
if err != nil || instNum < 0 || instNum > ctr.Scale {
tempCtr := new(container.Container)
*tempCtr = *ctr
tempCtr.Name = existing.Name
tasks = append(tasks, tempCtr)
}
}
projSettings.ContainerCleanupList = append(projSettings.ContainerCleanupList, tasks...)
return
}
// Create copies of containers which need to scale
func (f *ConfigParser) scaleContainers(ctr *container.Container, state map[string]*helpers.ServiceState) []*container.Container {
ctrCopies := make([]*container.Container, ctr.Scale)
for i := 0; i < ctr.Scale; i++ {
ctrCopies[i] = new(container.Container)
*ctrCopies[i] = *ctr
ctrCopies[i].InstanceNumber = i + 1
var found bool
var lookup = ctr.Name + ctr.ProjectNameSeparator + strconv.Itoa(ctrCopies[i].InstanceNumber)
if ctrCopies[i].State, found = state[lookup]; !found {
ctrCopies[i].State = &helpers.ServiceState{
Running: false,
Color: "blue",
}
}
ctrCopies[i].ServiceName = ctr.Name
ctrCopies[i].NewName()
// HACK for container logging prefix width alignment, eg 'some_container | blahbla'
if len(ctrCopies[i].Name) > logger.LongestContainerName {
logger.LongestContainerName = len(ctrCopies[i].Name)
}
}
return ctrCopies
}
func stripChars(str, chr string) string {
return strings.Map(func(r rune) rune {
if strings.IndexRune(chr, r) < 0 {
return r
}
return -1
}, str)
}
// toSnake convert the given string to snake case following the Golang format:
// acronyms are converted to lower-case and preceded by an underscore.
func toSnake(in string) string {
runes := []rune(in)
length := len(runes)
var out []rune
for i := 0; i < length; i++ {
if i > 0 && unicode.IsUpper(runes[i]) && ((i+1 < length && unicode.IsLower(runes[i+1])) || unicode.IsLower(runes[i-1])) {
out = append(out, '_')
}
out = append(out, unicode.ToLower(runes[i]))
}
return string(out)
}