forked from dynport/urknall
/
build.go
364 lines (316 loc) · 9.79 KB
/
build.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
package urknall
import (
"bytes"
"fmt"
"path/filepath"
"strings"
"time"
constants "github.com/megamsys/libgo/utils/obc"
"github.com/megamsys/libgo/pairs"
"github.com/megamsys/libgo/events"
"github.com/megamsys/libgo/events/alerts"
"github.com/megamsys/urknall/pubsub"
"github.com/megamsys/urknall/target"
)
const (
RUNNING = "running"
FINISHED = "finished"
STARTING = "starting"
COMPLETED = "completed"
)
var status constants.Status
// A shortcut creating and running a build from the given target and template.
func Run(target Target, tpl Template,inputs map[string]string) (e error) {
return (&Build{
Target: target,
Template: tpl,
Inputs: inputs}).Run()
}
// A shortcut creating and runnign a build from the given target and template
// with the DryRun flag set to true. This is quite helpful to actually see
// which commands would be exeucted in the current setting, without actually
// doing anything.
func DryRun(target Target, tpl Template) (e error) {
return (&Build{Target: target, Template: tpl}).DryRun()
}
// A build is the glue between a target and template.
type Build struct {
Target // Where to run the build.
Template // What to actually build.
Env []string // Environment variables in the form `KEY=VALUE`.
Inputs map[string]string // Inputs for OBC like email and status
}
// This will render the build's template into a package and run all its tasks.
func (b *Build) Run() error {
pkg, e := b.prepareBuild()
if e != nil {
return e
}
m := message(pubsub.MessageTasksProvision, b.hostname(), "")
m.Publish("started")
templateName := strings.Split(pkg.tasks[0].name,".")[0]
status = constants.Status(strings.Join([]string{templateName,RUNNING},"."))
_ = eventNotify(b.Inputs,b.hostname())
for _, task := range pkg.tasks {
if e = b.buildTask(task); e != nil {
m.PublishError(e)
return e
}
}
m.Publish(FINISHED)
status = constants.Status(strings.Join([]string{templateName,FINISHED},"."))
_ = eventNotify(b.Inputs,b.hostname())
return nil
}
func (b *Build) DryRun() error {
pkg, e := b.prepareBuild()
if e != nil {
return e
}
for _, task := range pkg.tasks {
for _, command := range task.commands {
m := message(pubsub.MessageTasksProvisionTask, b.hostname(), task.name)
m.TaskChecksum = command.Checksum()
m.Message = command.LogMsg()
switch {
case command.cached:
m.ExecStatus = pubsub.StatusCached
m.Publish("finished")
default:
m.ExecStatus = pubsub.StatusExecStart
m.Publish("executed")
}
}
}
return nil
}
func (build *Build) prepareBuild() (*packageImpl, error) {
pkg, e := renderTemplate(build.Template)
if e != nil {
return nil, e
}
if e = build.prepareTarget(); e != nil {
return nil, e
}
ct, e := build.buildChecksumTree()
if e != nil {
return nil, fmt.Errorf("error building checksum tree: %s", e.Error())
}
for _, task := range pkg.tasks {
if e = build.prepareTask(task, ct); e != nil {
return nil, e
}
}
return pkg, nil
}
func (build *Build) prepareTarget() error {
if build.User() == "" {
return fmt.Errorf("User not set")
}
rawCmd := fmt.Sprintf(`{ grep "^%s:" /etc/group | grep %s; } && [ -d %[3]s ] && [ -f %[3]s/.v2 ]`,
ukGROUP, build.User(), ukCACHEDIR)
cmd, e := build.prepareInternalCommand(rawCmd)
if e != nil {
return e
}
if e := cmd.Run(); e != nil {
// If user is missing the group, create group (if necessary), add user and restart ssh connection.
cmds := []string{
fmt.Sprintf(`{ grep -e '^%[1]s:' /etc/group > /dev/null || { groupadd %[1]s; }; }`, ukGROUP),
fmt.Sprintf(`{ [ -d %[1]s ] || { mkdir -p -m 2775 %[1]s && chgrp %[2]s %[1]s; }; }`, ukCACHEDIR, ukGROUP),
fmt.Sprintf("usermod -a -G %s %s", ukGROUP, build.User()),
fmt.Sprintf(`[ -f %[1]s/.v2 ] || { export DATE=$(date "+%%Y%%m%%d_%%H%%M%%S") && ls %[1]s | while read dir; do ls -t %[1]s/$dir/*.done | tac > %[1]s/$dir/$DATE.run; done && touch %[1]s/.v2; } `, ukCACHEDIR),
}
cmd, e = build.prepareInternalCommand(strings.Join(cmds, " && "))
if e != nil {
return e
}
out := &bytes.Buffer{}
err := &bytes.Buffer{}
cmd.SetStderr(err)
cmd.SetStdout(out)
if e := cmd.Run(); e != nil {
return fmt.Errorf("failed to initiate user %q for provisioning: %s, out=%q err=%q", build.User(), e, out.String(), err.String())
}
return build.Reset()
}
return nil
}
func (build *Build) prepareTask(tsk *task, ct checksumTree) (e error) {
cacheKey := tsk.name
if cacheKey == "" {
return fmt.Errorf("CacheKey must not be empty")
}
checksumDir := fmt.Sprintf(ukCACHEDIR+"/%s", tsk.name)
var found bool
var checksumList []string
if checksumList, found = ct[cacheKey]; !found {
// Create checksum dir and set group bit (all new files will inherit the directory's group). This allows for
// different users (being part of that group) to create, modify and delete the contained checksum and log files.
createChecksumDirCmd := fmt.Sprintf("mkdir -m2775 -p %s", checksumDir)
cmd, e := build.prepareInternalCommand(createChecksumDirCmd)
if e != nil {
return e
}
err := &bytes.Buffer{}
cmd.SetStderr(err)
if e := cmd.Run(); e != nil {
return fmt.Errorf(err.String() + ": " + e.Error())
}
}
// find commands that need not be executed
for i, cmd := range tsk.commands {
checksum, e := commandChecksum(cmd.command)
if e != nil {
return e
}
switch {
case len(checksumList) <= i || checksum != checksumList[i]:
return nil
default:
cmd.cached = true
}
}
return nil
}
func (build *Build) buildTask(tsk *task) (e error) {
checksumDir := fmt.Sprintf(ukCACHEDIR+"/%s", tsk.name)
tsk.started = time.Now()
for _, cmd := range tsk.commands {
checksum := cmd.Checksum()
m := message(pubsub.MessageTasksProvisionTask, build.hostname(), tsk.name)
m.TaskChecksum = checksum
m.Message = cmd.LogMsg()
var cmdErr error
switch {
case cmd.cached:
m.ExecStatus = pubsub.StatusCached
default:
m.ExecStatus = pubsub.StatusExecStart
m.Publish("started")
status = constants.Status(strings.Join([]string{tsk.name ,STARTING},"."))
_ = eventNotify(build.Inputs,build.hostname())
r := &commandRunner{
build: build,
command: cmd.command,
dir: checksumDir,
taskName: tsk.name,
}
cmdErr = r.run()
if cmdErr == nil {
status = constants.Status(strings.Join([]string{tsk.name,COMPLETED},"."))
_ = eventNotify(build.Inputs,build.hostname())
}
m.Error = cmdErr
m.ExecStatus = pubsub.StatusExecFinished
}
m.Publish("finished")
err := build.addCmdToTaskLog(tsk, checksumDir, checksum, cmdErr)
switch {
case cmdErr != nil:
return cmdErr
case err != nil:
return err
}
}
return nil
}
func eventNotify(inputs map[string]string,host string) error {
var email,hostid string
for k,v := range inputs {
switch k {
case constants.USERMAIL:
email = v
case constants.HOST_ID:
hostid = v
}
}
mi := make(map[string]string)
js := make(pairs.JsonPairs, 0)
m := make(map[string][]string, 2)
m["status"] = []string{status.String()}
m["description"] = []string{status.Description(host)}
js.NukeAndSet(m) //just nuke the matching output key:
mi[constants.HOST_IP] = host
mi[constants.HOST_ID] = hostid
mi[constants.ACCOUNT_ID] = email
mi[constants.EVENT_TYPE] = status.Event_type()
newEvent := events.NewMulti(
[]*events.Event{
&events.Event{
AccountsId: email,
EventAction: alerts.STATUS,
EventType: constants.EventUser,
EventData: alerts.EventData{M: mi, D: js.ToString()},
Timestamp: time.Now().Local(),
},
})
return newEvent.Write()
}
// addCmdToTaskLog will manage the log of run commands in a file. This file gets append the path to a file
// for each command, that contains the executed script. The filename contains either ".done" or ".failed" as
// suffix, depending on the err given (nil or not).
func (build *Build) addCmdToTaskLog(tsk *task, checksumDir, checksum string, err error) (e error) {
prefix := checksumDir + "/" + checksum
sourceFile := prefix + ".sh"
targetFile := prefix + ".done"
if err != nil {
logError(err)
targetFile = prefix + ".failed"
}
rawCmd := fmt.Sprintf("{ [ -f %[1]s ] || mv %[2]s %[1]s; } && echo %[1]s >> %[3]s/%[4]s.run",
targetFile, sourceFile, checksumDir, tsk.started.Format("20060102_150405"))
c, e := build.prepareInternalCommand(rawCmd)
if e != nil {
return e
}
return c.Run()
}
type checksumTree map[string][]string
func (build *Build) buildChecksumTree() (ct checksumTree, e error) {
ct = checksumTree{}
rawCmd := fmt.Sprintf(
`[ -d %[1]s ] && { ls %[1]s | while read dir; do ls -t %[1]s/$dir/*.run | head -n1 | xargs cat; done; }`,
ukCACHEDIR)
cmd, e := build.prepareInternalCommand(rawCmd)
if e != nil {
return nil, e
}
out := &bytes.Buffer{}
err := &bytes.Buffer{}
cmd.SetStdout(out)
cmd.SetStderr(err)
if e := cmd.Run(); e != nil {
return nil, fmt.Errorf("%s: out=%s err=%s", e.Error(), out.String(), err.String())
}
for _, line := range strings.Split(out.String(), "\n") {
line = strings.TrimSpace(line)
if line == "" || !strings.HasSuffix(line, ".done") {
continue
}
pkgname := filepath.Dir(strings.TrimPrefix(line, ukCACHEDIR+"/"))
checksum := strings.TrimSuffix(filepath.Base(line), ".done")
if len(checksum) != 64 {
return nil, fmt.Errorf("invalid checksum %q found for package %q", checksum, pkgname)
}
ct[pkgname] = append(ct[pkgname], checksum)
}
return ct, nil
}
func (build *Build) prepareCommand(rawCmd string) (target.ExecCommand, error) {
var sudo string
if build.User() != "root" {
sudo = "sudo "
}
return build.Command(sudo + rawCmd)
}
func (build *Build) prepareInternalCommand(rawCmd string) (target.ExecCommand, error) {
rawCmd = fmt.Sprintf("sh -x -e <<\"EOC\"\n%s\nEOC\n", rawCmd)
return build.prepareCommand(rawCmd)
}
func (build *Build) hostname() string {
if s, ok := build.Target.(fmt.Stringer); ok {
return s.String()
}
return "MISSING"
}