/
engine.go
152 lines (124 loc) · 2.73 KB
/
engine.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
package internal
import (
"fmt"
"strings"
"sync"
)
type Engine struct {
inventory *MainInventory
playbook *PlayBook
maxConcurrent int
wg *sync.WaitGroup
sshService ssher
}
func NewEngine(playbookPath string, hostPath string) *Engine {
var (
inventory *MainInventory
pb *PlayBook
)
if hostPath != "" {
opts := InventoryPathOptions(hostPath)
inventory = NewInventory(opts)
} else {
inventory = NewInventory()
}
pb = NewPlaybook(playbookPath)
return &Engine{
inventory: inventory,
playbook: pb,
maxConcurrent: 10,
wg: &sync.WaitGroup{},
sshService: NewSSHService(),
}
}
func (e *Engine) Run() {
for i := range e.playbook.Plays {
respObj := e.prepareTasks(i)
switch e.playbook.Plays[i].Strategy {
case "free":
e.FreeStrategy(respObj)
default:
e.LinearStrategy(respObj)
}
}
}
func (e *Engine) LinearStrategy(respObj PlayDoc) {
opts := []ExecOutput{}
for k := 0; k < len(respObj.hosts)/e.maxConcurrent; k += e.maxConcurrent {
start, end := k*e.maxConcurrent, ((k + 1) * e.maxConcurrent)
if end > len(respObj.hosts) {
end = len(respObj.hosts)
}
for _, t := range respObj.tasks {
e.wg.Add(len(respObj.hosts))
for _, h := range respObj.hosts[start:end] {
h := h
t := t
if !e.sameOS(t, h) {
continue
}
go func() {
defer e.wg.Done()
for _, c := range t.cmds {
res, err := e.sshService.execute(h, c)
if err != nil {
continue
}
if strings.Trim(res.Err, " ") != "" && !t.skip_errors {
break
}
opts = append(opts, res)
}
}()
}
}
}
e.wg.Wait()
fmt.Println(opts)
}
func (e *Engine) FreeStrategy(respObj PlayDoc) {
e.wg.Add(len(respObj.hosts))
opts := []ExecOutput{}
for _, h := range respObj.hosts {
h := h
go func() {
defer e.wg.Done()
for _, t := range respObj.tasks {
h := h
if !e.sameOS(t, h) {
continue
}
for _, c := range t.cmds {
res, err := e.sshService.execute(h, c)
fmt.Println("Response is ", res)
if err != nil {
continue
}
if strings.Trim(res.Err, " ") != "" && !t.skip_errors {
break
}
opts = append(opts, res)
}
}
}()
}
e.wg.Wait()
fmt.Println(opts)
}
func (e *Engine) sameOS(t *Task, h string) bool {
if t.os != "any" && t.os != strings.ToLower(e.sshService.getOS(h)) {
return false
}
return true
}
func (e *Engine) prepareTasks(i int) PlayDoc {
respObj := e.playbook.Generate(i)
if e.playbook.Plays[i].Serial > 0 {
e.maxConcurrent = e.playbook.Plays[i].Serial
}
for _, h := range respObj.hosts {
obj := e.inventory.inv.All.Hosts[h]
e.sshService.add(h, obj.SshHost, obj.SshUser, obj.SshPass, "", obj.SshPort)
}
return respObj
}