-
Notifications
You must be signed in to change notification settings - Fork 13
/
parser.go
283 lines (252 loc) · 6.85 KB
/
parser.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
package aini
import (
"bufio"
"fmt"
"math"
"regexp"
"strconv"
"strings"
"github.com/google/shlex"
)
// state enum
type state int
const (
hostsState state = 0
childrenState state = 1
varsState state = 2
)
func getState(str string) (state, bool) {
var result state
var ok bool = true
if str == "" || str == "hosts" {
result = hostsState
} else if str == "children" {
result = childrenState
} else if str == "vars" {
result = varsState
} else {
ok = false
}
return result, ok
}
// state enum end
// parser performs parsing of inventory file from some Reader
func (inventory *InventoryData) parse(reader *bufio.Reader) error {
// This regexp is copy-pasted from ansible sources
sectionRegex := regexp.MustCompile(`^\[([^:\]\s]+)(?::(\w+))?\]\s*(?:\#.*)?$`)
scanner := bufio.NewScanner(reader)
inventory.Groups = make(map[string]*Group)
inventory.Hosts = make(map[string]*Host)
activeState := hostsState
activeGroup := inventory.getOrCreateGroup("ungrouped")
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if strings.HasPrefix(line, ";") || strings.HasPrefix(line, "#") || line == "" {
continue
}
matches := sectionRegex.FindAllStringSubmatch(line, -1)
if matches != nil {
activeGroup = inventory.getOrCreateGroup(matches[0][1])
var ok bool
if activeState, ok = getState(matches[0][2]); !ok {
return fmt.Errorf("section [%s] has unknown type: %s", line, matches[0][2])
}
continue
} else if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
return fmt.Errorf("invalid section entry: '%s'. Make sure that there are no spaces or other characters in the section entry", line)
}
if activeState == hostsState {
hosts, err := inventory.getHosts(line, activeGroup)
if err != nil {
return err
}
for _, host := range hosts {
host.DirectGroups[activeGroup.Name] = activeGroup
inventory.Hosts[host.Name] = host
if activeGroup.Name != "ungrouped" {
delete(host.DirectGroups, "ungrouped")
}
}
}
if activeState == childrenState {
parsed, err := shlex.Split(line)
if err != nil {
return err
}
groupName := parsed[0]
newGroup := inventory.getOrCreateGroup(groupName)
newGroup.DirectParents[activeGroup.Name] = activeGroup
inventory.Groups[line] = newGroup
}
if activeState == varsState {
k, v, err := splitKV(line)
if err != nil {
return err
}
activeGroup.InventoryVars[k] = v
}
}
inventory.Groups[activeGroup.Name] = activeGroup
return nil
}
// getHosts parses given "host" line from inventory
func (inventory *InventoryData) getHosts(line string, group *Group) (map[string]*Host, error) {
parts, err := shlex.Split(line)
if err != nil {
return nil, err
}
hostpattern, port, err := getHostPort(parts[0])
if err != nil {
return nil, err
}
hostnames, err := expandHostPattern(hostpattern)
if err != nil {
return nil, err
}
result := make(map[string]*Host, len(hostnames))
for _, hostname := range hostnames {
params := parts[1:]
vars := make(map[string]string, len(params))
for _, param := range params {
k, v, err := splitKV(param)
if err != nil {
return nil, err
}
vars[k] = v
}
host := inventory.getOrCreateHost(hostname)
host.Port = port
host.DirectGroups[group.Name] = group
addValues(host.InventoryVars, vars)
result[host.Name] = host
}
return result, nil
}
// splitKV splits `key=value` into two string: key and value
func splitKV(kv string) (string, string, error) {
keyval := strings.SplitN(kv, "=", 2)
if len(keyval) == 1 {
return "", "", fmt.Errorf("bad key=value pair supplied: %s", kv)
}
return strings.TrimSpace(keyval[0]), strings.TrimSpace(keyval[1]), nil
}
// getHostPort splits string like `host-[a:b]-c:22` into `host-[a:b]-c` and `22`
func getHostPort(str string) (string, int, error) {
port := 22
parts := strings.Split(str, ":")
if len(parts) == 1 {
return str, port, nil
}
lastPart := parts[len(parts)-1]
if strings.Contains(lastPart, "]") {
// We are in expand pattern, so no port were specified
return str, port, nil
}
port, err := strconv.Atoi(lastPart)
return strings.Join(parts[:len(parts)-1], ":"), port, err
}
// expandHostPattern turns `host-[a:b]-c` into a flat list of hosts
func expandHostPattern(hostpattern string) ([]string, error) {
lbrac := strings.Replace(hostpattern, "[", "|", 1)
rbrac := strings.Replace(lbrac, "]", "|", 1)
parts := strings.Split(rbrac, "|")
if len(parts) == 1 {
// No pattern detected
return []string{hostpattern}, nil
}
if len(parts) != 3 {
return nil, fmt.Errorf("wrong host pattern: %s", hostpattern)
}
head, nrange, tail := parts[0], parts[1], parts[2]
bounds := strings.Split(nrange, ":")
if len(bounds) < 2 || len(bounds) > 3 {
return nil, fmt.Errorf("wrong host pattern: %s", hostpattern)
}
var begin, end []rune
var step = 1
if len(bounds) == 3 {
step, _ = strconv.Atoi(bounds[2])
}
end = []rune(bounds[1])
if bounds[0] == "" {
if isRunesNumber(end) {
format := fmt.Sprintf("%%0%dd", len(end))
begin = []rune(fmt.Sprintf(format, 0))
} else {
return nil, fmt.Errorf("skipping range start in not allowed with alphabetical range: %s", hostpattern)
}
} else {
begin = []rune(bounds[0])
}
var chars []int
isNumberRange := false
if isRunesNumber(begin) && isRunesNumber(end) {
chars = makeRange(runesToInt(begin), runesToInt(end), step)
isNumberRange = true
} else if !isRunesNumber(begin) && !isRunesNumber(end) && len(begin) == 1 && len(end) == 1 {
dict := append(makeRange('a', 'z', 1), makeRange('A', 'Z', 1)...)
chars = makeRange(
find(dict, int(begin[0])),
find(dict, int(end[0])),
step,
)
for i, c := range chars {
chars[i] = dict[c]
}
}
if len(chars) == 0 {
return nil, fmt.Errorf("bad range specified: %s", nrange)
}
var hosts []string
var format string
if isNumberRange {
format = fmt.Sprintf("%%s%%0%dd%%s", len(begin))
} else {
format = "%s%c%s"
}
for _, c := range chars {
hosts = append(hosts, fmt.Sprintf(format, head, c, tail))
}
var result []string
for _, hostpattern := range hosts {
newHosts, err := expandHostPattern(hostpattern)
if err != nil {
return nil, err
}
result = append(result, newHosts...)
}
return result, nil
}
func isRunesNumber(runes []rune) bool {
for _, rune := range runes {
if rune < '0' || rune > '9' {
return false
}
}
return true
}
// runesToInt turn runes into corresponding number, ex. '7' -> 7
// should be called only on "number" runes! (see `isRunesNumber` function)
func runesToInt(runes []rune) int {
result := 0
for i, rune := range runes {
result += int((rune - '0')) * int(math.Pow10(len(runes)-1-i))
}
return result
}
func makeRange(start, end, step int) []int {
s := make([]int, 0, 1+(end-start)/step)
for start <= end {
s = append(s, start)
start += step
}
return s
}
func find(a []int, x int) int {
for i, n := range a {
if x == n {
return i
}
}
return len(a)
}