-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.go
More file actions
370 lines (306 loc) · 8.2 KB
/
agent.go
File metadata and controls
370 lines (306 loc) · 8.2 KB
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
package storm
import (
"errors"
"fmt"
"os"
"os/exec"
"runtime"
"strings"
)
type Agent struct {
inventory *Inventory
workflow *Workflow
ssh *Ssh
}
type RunArgs struct {
Wf *string
If *string
Wc *WorkflowConfig
Ic *InventoryConfig
Contexts map[string]map[string]any
Callback func(interface{})
StepOutputType int
}
type RunOption func(*RunArgs)
func (a *Agent) AgentWithConfigs(w WorkflowConfig, i InventoryConfig) RunOption {
return func(ra *RunArgs) {
ra.Wc = &w
ra.Ic = &i
}
}
func (a *Agent) AgentWithFiles(w string, i string) RunOption {
return func(ra *RunArgs) {
ra.Wf = &w
ra.If = &i
}
}
func (a *Agent) AgentWithContexts(contexts map[string]map[string]any) RunOption {
return func(ra *RunArgs) {
ra.Contexts = contexts
}
}
func (a *Agent) AgentWithCallback(callback func(interface{}), format int) RunOption {
return func(ra *RunArgs) {
ra.Callback = callback
ra.StepOutputType = format
}
}
func (a *Agent) Run(opts ...RunOption) error {
var wc *WorkflowConfig
var ic *InventoryConfig
args := RunArgs{
StepOutputType: StepOutputTypePlain,
}
for _, opt := range opts {
opt(&args)
}
// effectiveWf tracks the workflow file to copy to remote — it may be a
// rendered temp file when contexts are provided.
var effectiveWf string
if args.Wf != nil && args.If != nil {
effectiveWf = *args.Wf
if len(args.Contexts) > 0 {
raw, err := os.ReadFile(effectiveWf)
if err != nil {
return fmt.Errorf("cannot read workflow file: %w", err)
}
rendered, err := RenderTemplate(string(raw), args.Contexts)
if err != nil {
return fmt.Errorf("template render error: %w", err)
}
tmpFile, err := os.CreateTemp("", "storm-workflow-*.yaml")
if err != nil {
return fmt.Errorf("cannot create temp file: %w", err)
}
defer os.Remove(tmpFile.Name())
if _, err := tmpFile.WriteString(rendered); err != nil {
tmpFile.Close()
return fmt.Errorf("cannot write temp file: %w", err)
}
tmpFile.Close()
effectiveWf = tmpFile.Name()
}
_wc, err := a.workflow.Load(effectiveWf)
if err != nil {
return err
}
wc = _wc
_ic, err := a.inventory.Load(*args.If)
if err != nil {
return err
}
ic = _ic
} else {
wc = args.Wc
ic = args.Ic
}
if wc == nil && ic == nil {
return errors.New("invalid inventory and workflow configurations")
}
callback := func(s string) {
if args.StepOutputType == StepOutputTypePlain {
fmt.Println(s)
} else {
args.Callback(s)
}
}
for _, server := range ic.Servers {
if args.StepOutputType == StepOutputTypePlain {
fmt.Printf("Server: [%s]\n", server.Name)
}
sshClient, err := a.ssh.Authenticate(AuthenticateArgs{
Host: server.Host,
Port: server.Port,
User: server.User,
Password: server.SshPassword,
PrivateSshKey: server.PrivateSshKey,
})
if err != nil {
return errors.Join(err, errors.New("authentication failed"))
}
destinationFilePath := fmt.Sprintf("/home/%s/workflow.yaml", server.User)
err = a.ssh.CopyFile(CopyFileArgs{
Client: sshClient,
From: effectiveWf,
To: destinationFilePath,
Permissions: "0655",
})
if err != nil {
return errors.Join(errors.New("could generate workflow file"), err)
}
_, _, err = a.ssh.ExecuteCommand(ExecuteCommandArgs{
Client: sshClient,
Command: fmt.Sprintf("~/.storm/bin/storm run -f=%d %s", args.StepOutputType, destinationFilePath),
OutputCallback: callback,
ErrorCallback: callback,
})
if err != nil {
return err
}
}
return nil
}
// This is meant for testing locally or in CI
func (a *Agent) InstallDev(ic InventoryConfig) error {
os.Setenv("GOOS", "linux")
os.Setenv("GOARCH", "arm64")
_, err := exec.Command("go", "build", "-o", "storm", "./cmd").Output()
if err != nil {
return errors.Join(errors.New("build failed; could not build storm"), err)
}
defer os.Remove("./storm")
for _, server := range ic.Servers {
fmt.Printf("Server: [%s]\n", server.Name)
sshClient, err := a.ssh.Authenticate(AuthenticateArgs{
Host: server.Host,
Port: server.Port,
User: server.User,
Password: server.SshPassword,
PrivateSshKey: server.PrivateSshKey,
})
if err != nil {
return err
}
fmt.Print("Installing storm on server ... ")
err = a.ssh.CopyTo(sshClient, "./storm", fmt.Sprintf("/home/%s/.storm/bin/storm", server.User))
if err != nil {
fmt.Print(errors.Join(errors.New("ssh can't copy file"), err))
return err
}
_, _, err = a.ssh.ExecuteCommand(ExecuteCommandArgs{
Client: sshClient,
Command: "chmod +x ~/.storm/bin/storm",
OutputCallback: func(s string) {},
ErrorCallback: func(s string) { fmt.Println("> ", s) },
})
if err != nil {
return err
}
fmt.Println("Storm is Ready!")
}
return nil
}
func (a *Agent) InstallProd(ic InventoryConfig) error {
for _, server := range ic.Servers {
fmt.Printf("Server: [%s]\n", server.Name)
sshClient, err := a.ssh.Authenticate(AuthenticateArgs{
Host: server.Host,
Port: server.Port,
User: server.User,
Password: server.SshPassword,
PrivateSshKey: server.PrivateSshKey,
})
if err != nil {
return err
}
platform := strings.Split(runtime.GOOS, "/")[0]
fmt.Println("Installing storm on server ... ")
// TODO: get remote server type
switch platform {
case "windows":
_, _, err := a.ssh.ExecuteCommand(ExecuteCommandArgs{
Client: sshClient,
Command: "powershell -c irm https://raw.githubusercontent.com/Overal-X/storm/main/scripts/install.sh | iex",
OutputCallback: func(s string) {},
ErrorCallback: func(s string) {},
})
if err != nil {
return errors.Join(err, errors.New("build failed; could not install storm"))
}
case "linux", "darwin":
_, _, err := a.ssh.ExecuteCommand(ExecuteCommandArgs{
Client: sshClient,
Command: "curl -fsSL https://raw.githubusercontent.com/Overal-X/storm/main/scripts/install.sh | bash",
OutputCallback: func(s string) { fmt.Println("> ", s) },
ErrorCallback: func(s string) { fmt.Println("> ", s) },
})
if err != nil {
return errors.Join(err, errors.New("build failed; could not install storm"))
}
default:
return errors.New("platform not supported")
}
fmt.Println("Storm is Ready!")
}
return nil
}
type InstallArgs struct {
If string
Ic InventoryConfig
// Installation mode; options are `dev` or `prod`
Mode string
}
func (a *Agent) Install(args InstallArgs) error {
var ic *InventoryConfig = &args.Ic
if args.If != "" {
_ic, err := a.inventory.Load(args.If)
if err != nil {
return err
}
ic = _ic
}
switch args.Mode {
case "dev":
return a.InstallDev(*ic)
case "prod":
return a.InstallProd(*ic)
default:
return errors.New("installation mode not supported")
}
}
type UninstallArgs struct {
If string
Ic InventoryConfig
}
func (a *Agent) Uninstall(args UninstallArgs) error {
var ic *InventoryConfig = &args.Ic
if args.If != "" {
_ic, err := a.inventory.Load(args.If)
if err != nil {
return err
}
ic = _ic
}
for _, server := range ic.Servers {
fmt.Printf("Server: [%s]\n", server.Name)
sshClient, err := a.ssh.Authenticate(AuthenticateArgs{
Host: server.Host,
Port: server.Port,
User: server.User,
Password: server.SshPassword,
PrivateSshKey: server.PrivateSshKey,
})
if err != nil {
return err
}
_, _, err = a.ssh.ExecuteCommand(ExecuteCommandArgs{
Client: sshClient,
Command: "which ~/.storm/bin/storm",
OutputCallback: func(s string) {},
ErrorCallback: func(s string) {},
})
if err != nil {
fmt.Println("Storm is not installed.")
continue
}
fmt.Println("Removing storm from server ... ")
_, _, err = a.ssh.ExecuteCommand(ExecuteCommandArgs{
Client: sshClient,
Command: "rm -rf ~/.storm/",
OutputCallback: func(s string) {},
ErrorCallback: func(s string) {},
})
if err != nil {
return errors.Join(errors.New("cannot remove ~/.storm/"), err)
}
fmt.Println("Storm has been removed (:")
}
return nil
}
func NewAgent() *Agent {
return &Agent{
workflow: NewWorkflow(),
inventory: NewInventory(),
ssh: NewSsh(),
}
}