This repository has been archived by the owner on Sep 2, 2021. It is now read-only.
/
machines.go
476 lines (471 loc) · 14.9 KB
/
machines.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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
package cli
import (
"fmt"
"os"
"path/filepath"
"runtime"
"strconv"
"time"
"github.com/digitalrebar/provision/v4/agent"
"github.com/digitalrebar/provision/v4/models"
"github.com/spf13/cobra"
)
var (
// ActuallyPowerThings is a boolean to use in testing to keep from power off the test machine
ActuallyPowerThings = true
// DefaultStateLoc is the default location to save agent state
DefaultStateLoc string
)
func init() {
if DefaultStateLoc == "" {
switch runtime.GOOS {
case "windows":
DefaultStateLoc = filepath.Join(os.Getenv("SYSTEMROOT"), `/System32/config/systemprofile/AppData/Local/rackn/drp-agent`)
default:
DefaultStateLoc = "/var/lib/drp-agent"
}
}
addRegistrar(registerMachine)
}
func registerMachine(app *cobra.Command) {
op := &ops{
name: "machines",
singleName: "machine",
example: func() models.Model { return &models.Machine{} },
}
op.addCommand(&cobra.Command{
Use: "workflow [id] [workflow]",
Short: fmt.Sprintf("Set the machine's workflow"),
Long: `Helper function to update the machine's workflow.`,
Args: func(c *cobra.Command, args []string) error {
if len(args) != 2 {
return fmt.Errorf("%v requires 2 arguments", c.UseLine())
}
return nil
},
RunE: func(c *cobra.Command, args []string) error {
m, err := op.refOrFill(args[0])
if err != nil {
return generateError(err, "Failed to fetch %v: %v", op.singleName, args[0])
}
clone := models.Clone(m).(*models.Machine)
clone.Workflow = args[1]
req := Session.Req().PatchTo(m, clone)
if force {
req.Params("force", "true")
}
if err := req.Do(&clone); err != nil {
return err
}
return prettyPrint(clone)
},
})
op.addCommand(&cobra.Command{
Use: "stage [id] [stage]",
Short: fmt.Sprintf("Set the machine's stage"),
Long: `Helper function to update the machine's stage.`,
Args: func(c *cobra.Command, args []string) error {
if len(args) != 2 {
return fmt.Errorf("%v requires 2 arguments", c.UseLine())
}
return nil
},
RunE: func(c *cobra.Command, args []string) error {
m, err := op.refOrFill(args[0])
if err != nil {
return generateError(err, "Failed to fetch %v: %v", op.singleName, args[0])
}
clone := models.Clone(m).(*models.Machine)
clone.Stage = args[1]
req := Session.Req().PatchTo(m, clone)
if force {
req.Params("force", "true")
}
if err := req.Do(&clone); err != nil {
return err
}
return prettyPrint(clone)
},
})
op.addCommand(&cobra.Command{
Use: "releaseToPool [id]",
Short: fmt.Sprintf("Release this machine back to the pool"),
Long: `Release this machine back to the pool`,
Args: func(c *cobra.Command, args []string) error {
if len(args) != 1 {
return fmt.Errorf("%v requires 1 arguments", c.UseLine())
}
return nil
},
RunE: func(c *cobra.Command, args []string) error {
mid := args[0]
r := &[]models.PoolResult{}
p := map[string]interface{}{}
if err := Session.Req().Post(p).UrlFor("machines", mid, "releaseToPool").Do(r); err != nil {
return err
}
return prettyPrint(r)
},
})
op.addCommand(&cobra.Command{
Use: "run [id]",
Short: fmt.Sprintf("Mark the machine as runnable"),
Long: `Set the machine's Runnable flag to true`,
Args: func(c *cobra.Command, args []string) error {
if len(args) != 1 {
return fmt.Errorf("%v requires 1 arguments", c.UseLine())
}
return nil
},
RunE: func(c *cobra.Command, args []string) error {
m, err := op.refOrFill(args[0])
if err != nil {
return generateError(err, "Failed to fetch %v: %v", op.singleName, args[0])
}
clone := models.Clone(m).(*models.Machine)
clone.Runnable = true
if err := Session.Req().PatchTo(m, clone).Do(&clone); err != nil {
return err
}
return prettyPrint(clone)
},
})
op.addCommand(&cobra.Command{
Use: "pause [id]",
Short: fmt.Sprintf("Mark the machine as NOT runnable"),
Long: `Set the machine's Runnable flag to false`,
Args: func(c *cobra.Command, args []string) error {
if len(args) != 1 {
return fmt.Errorf("%v requires 1 arguments", c.UseLine())
}
return nil
},
RunE: func(c *cobra.Command, args []string) error {
m, err := op.refOrFill(args[0])
if err != nil {
return generateError(err, "Failed to fetch %v: %v", op.singleName, args[0])
}
clone := models.Clone(m).(*models.Machine)
clone.Runnable = false
if err := Session.Req().PatchTo(m, clone).Do(&clone); err != nil {
return err
}
return prettyPrint(clone)
},
})
jobs := &cobra.Command{
Use: "jobs",
Short: "Access commands for manipulating the current job",
}
jobs.AddCommand(&cobra.Command{
Use: "create [id]",
Short: "Create a job for the current task on machine [id]",
Args: func(c *cobra.Command, args []string) error {
if len(args) != 1 {
return fmt.Errorf("%v requires 1 argument", c.UseLine())
}
return nil
},
RunE: func(c *cobra.Command, args []string) error {
id := args[0]
m, err := op.refOrFill(id)
if err != nil {
return generateError(err, "Failed to fetch %v: %v", op.singleName, id)
}
machine := m.(*models.Machine)
job := &models.Job{}
j2 := &models.Job{}
job.Machine = machine.Uuid
if err := Session.Req().Post(job).UrlFor("jobs").Do(j2); err != nil {
return generateError(err, "Failed to create job for %v: %v", op.singleName, id)
}
return prettyPrint(j2)
},
})
jobs.AddCommand(&cobra.Command{
Use: "current [id]",
Short: "Get the current job on machine [id]",
Args: func(c *cobra.Command, args []string) error {
if len(args) != 1 {
return fmt.Errorf("%v requires 1 argument", c.UseLine())
}
return nil
},
RunE: func(c *cobra.Command, args []string) error {
id := args[0]
m, err := op.refOrFill(id)
if err != nil {
return generateError(err, "Failed to fetch %v: %v", op.singleName, id)
}
machine := m.(*models.Machine)
if machine.CurrentJob == nil || len(machine.CurrentJob) == 0 {
return fmt.Errorf("No current job on machine %v", m.Key())
}
job := &models.Job{}
if err := Session.Req().UrlFor("jobs", machine.CurrentJob.String()).Do(job); err != nil {
return generateError(err, "Failed to fetch current job for %v: %v", op.singleName, id)
}
return prettyPrint(job)
},
})
jobs.AddCommand(&cobra.Command{
Use: "state [id] to [state]",
Short: "Set the current job on machine [id] to [state]",
Args: func(c *cobra.Command, args []string) error {
if len(args) != 3 {
return fmt.Errorf("%v requires 2 arguments", c.UseLine())
}
return nil
},
RunE: func(c *cobra.Command, args []string) error {
id := args[0]
state := args[2]
m, err := op.refOrFill(id)
if err != nil {
return generateError(err, "Failed to fetch %v: %v", op.singleName, id)
}
machine := m.(*models.Machine)
if machine.CurrentJob == nil || len(machine.CurrentJob) == 0 {
return fmt.Errorf("No current job on machine %v", m.Key())
}
job := &models.Job{}
if err := Session.Req().UrlFor("jobs", machine.CurrentJob.String()).Do(job); err != nil {
return generateError(err, "Failed to fetch current job for %v: %v", op.singleName, id)
}
j2 := models.Clone(job).(*models.Job)
j2.State = state
j3, err := Session.PatchTo(job, j2)
if err != nil {
return generateError(err, "Failed to mark job %s as %s", job.Uuid, state)
}
return prettyPrint(j3)
},
})
op.addCommand(jobs)
op.addCommand(&cobra.Command{
Use: "currentlog [id]",
Short: "Get the log for the most recent job run on the machine",
Args: func(c *cobra.Command, args []string) error {
if len(args) != 1 {
return fmt.Errorf("%v requires 1 argument", c.UseLine())
}
return nil
},
RunE: func(c *cobra.Command, args []string) error {
m, err := op.refOrFill(args[0])
if err != nil {
return generateError(err, "Failed to fetch %v: %v", op.singleName, args[0])
}
return Session.Req().UrlFor("jobs", m.(*models.Machine).CurrentJob.String(), "log").Do(os.Stdout)
},
})
op.addCommand(&cobra.Command{
Use: "deletejobs [id]",
Short: "Delete all jobs associated with machine",
Args: func(c *cobra.Command, args []string) error {
if len(args) != 1 {
return fmt.Errorf("%v requires 1 argument", c.UseLine())
}
return nil
},
RunE: func(c *cobra.Command, args []string) error {
m, err := op.refOrFill(args[0])
if err != nil {
return generateError(err, "Failed to fetch %v: %v", op.singleName, args[0])
}
jobs := []*models.Job{}
if err := Session.Req().Filter("jobs",
"Machine", "Eq", m.Key(),
"sort", "StartTime",
"reverse").Do(&jobs); err != nil {
return generateError(err, "Failed to fetch jobs for %s: %v", op.singleName, args[0])
}
for _, job := range jobs {
if _, err := Session.DeleteModel("jobs", job.Key()); err != nil {
return generateError(err, "Failed to delete Job %s", job.Key())
}
fmt.Printf("Deleted Job %s", job.Key())
}
return nil
},
})
tasks := &cobra.Command{
Use: "tasks",
Short: "Access task manipulation for machines",
}
tasks.AddCommand(&cobra.Command{
Use: "add [id] [at [offset]] [task...]",
Short: "Add tasks to the task list for [id]",
Long: `You may omit "at [offset]" to indicate that the task should be appended to the
end of the task list. Otherwise, [offset] 0 indicates that the tasks
should be inserted immediately after the current task. Negative numbers
are not accepted.`,
Args: func(c *cobra.Command, args []string) error {
if len(args) < 2 {
return fmt.Errorf("%v requires at least an id and one task", c.UseLine())
}
if args[1] == "at" {
if len(args) < 4 {
return fmt.Errorf("%v requires at least 3 arguments when specifying an offset", c.UseLine())
}
if _, err := strconv.Atoi(args[2]); err != nil {
return fmt.Errorf("%v: %s is not a number", c.UseLine(), args[2])
}
}
return nil
},
RunE: func(c *cobra.Command, args []string) error {
id := args[0]
var offset = -1
var tasks []string
if args[1] == "at" {
offset, _ = strconv.Atoi(args[2])
tasks = args[3:]
} else {
tasks = args[1:]
}
obj, err := op.refOrFill(id)
if err != nil {
return err
}
m := models.Clone(obj).(*models.Machine)
if err := m.AddTasks(offset, tasks...); err != nil {
generateError(err, "Cannot add tasks")
}
if err := Session.Req().PatchTo(obj, m).Do(&m); err != nil {
return err
}
return prettyPrint(m)
},
})
tasks.AddCommand(&cobra.Command{
Use: "del [task...]",
Short: "Remove tasks from the mutable part of the task list",
Long: `Each entry in [task...] will remove at most one instance of it from the
machine task list. If you want to remove more than one, you need to
pass in more than one task.`,
Args: func(c *cobra.Command, args []string) error {
if len(args) < 2 {
return fmt.Errorf("%v requires at least an id and one task", c.UseLine())
}
return nil
},
RunE: func(c *cobra.Command, args []string) error {
id := args[0]
tasks := args[1:]
obj, err := op.refOrFill(id)
if err != nil {
return err
}
m := models.Clone(obj).(*models.Machine)
m.DelTasks(tasks...)
if err := Session.Req().PatchTo(obj, m).Do(&m); err != nil {
return err
}
return prettyPrint(m)
},
})
op.addCommand(tasks)
var exitOnFailure = false
var oneShot = false
var skipPower = false
var runStateLoc string
var runContext string
processJobs := &cobra.Command{
Use: "processjobs [id]",
Short: "For the given machine, process pending jobs until done.",
Long: `
For the provided machine, identified by UUID, process the task list on
that machine until an error occurs or all jobs are complete. Upon
completion, optionally wait for additional jobs as specified by
the stage runner wait flag.
`,
Args: func(c *cobra.Command, args []string) error {
if len(args) > 1 {
return fmt.Errorf("%v requires 1 argument", c.UseLine())
}
return nil
},
RunE: func(c *cobra.Command, args []string) error {
uuid := os.Getenv("RS_UUID")
if len(args) == 1 {
uuid = args[0]
}
m := &models.Machine{}
if err := Session.FillModel(m, uuid); err != nil {
return err
}
if runStateLoc == "" {
runStateLoc = DefaultStateLoc
}
if runStateLoc != "" {
if err := os.MkdirAll(runStateLoc, 0700); err != nil {
return fmt.Errorf("Unable to create state directory %s: %v", runStateLoc, err)
}
}
if runContext == "" {
runContext = os.Getenv("RS_CONTEXT")
}
agt, err := agent.New(Session, m, oneShot, exitOnFailure, ActuallyPowerThings && !skipPower, os.Stdout)
if err != nil {
return err
}
if oneShot {
agt = agt.Timeout(time.Second)
}
return agt.StateLoc(runStateLoc).Context(runContext).Run()
},
}
processJobs.Flags().BoolVar(&exitOnFailure, "exit-on-failure", false, "Exit on failure of a task")
processJobs.Flags().BoolVar(&oneShot, "oneshot", false, "Do not wait for additional tasks to appear")
processJobs.Flags().BoolVar(&skipPower, "skip-power", false, "Skip any power cycle actions")
processJobs.Flags().StringVar(&runStateLoc, "state-dir", "", "Location to save agent runtime state")
processJobs.Flags().StringVar(&runContext, "context", "", "Execution context this agent should pay attention to jobs in")
// Flag deprecated due to standardizing on all hyphenated form for persistent flags.
processJobs.Flags().BoolVar(&skipPower, "skipPower", false, "Skip any power cycle actions")
processJobs.Flags().StringVar(&runStateLoc, "stateDir", "", "Location to save agent runtime state")
processJobs.Flags().MarkHidden("skipPower")
processJobs.Flags().MarkHidden("stateDir")
processJobs.Flags().MarkDeprecated("skipPower", "please use --skip-power")
processJobs.Flags().MarkDeprecated("stateDir", "please use --state-dir")
op.addCommand(processJobs)
var tokenDuration = ""
tokenFetch := &cobra.Command{
Hidden: true,
Use: "token [id]",
Short: "Fetch a machine Token",
Long: "Fetch an authentication token for a Machine that has the same access rights the runner uses.",
Args: func(c *cobra.Command, args []string) error {
if len(args) > 1 {
return fmt.Errorf("%v requires 1 argument", c.UseLine())
}
return nil
},
RunE: func(c *cobra.Command, args []string) error {
res := &models.UserToken{}
if err := Session.Req().UrlFor("machines", args[0], "token").Params("ttl", tokenDuration).Do(&res); err != nil {
return err
}
return prettyPrint(res)
},
}
op.addCommand(&cobra.Command{
Use: "whoami",
Short: "Figure out what machine UUID most closely matches the current system",
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, args []string) error {
whoami := &models.Whoami{}
if err := whoami.Fill(); err != nil {
return err
}
if err := Session.Req().Post(whoami).UrlFor("whoami").Do(&whoami); err != nil {
return err
}
return prettyPrint(whoami)
},
})
tokenFetch.Flags().StringVar(&tokenDuration, "ttl", "1h", "The time that the retrieved token should be valid.")
op.addCommand(tokenFetch)
op.addCommand(inspectCommands())
op.command(app)
}