forked from iron-io/ironcli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommands.go
493 lines (417 loc) · 10.8 KB
/
commands.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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
package main
// Contains each command and its configuration
// TODO(reed): fix: empty schedule payload not working ?
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"os"
"strings"
"time"
"github.com/iron-io/iron_go/config"
"github.com/iron-io/iron_go/worker"
)
// TODO(reed): default flags for everybody
//--config CONFIG config file
// The idea is:
// parse flags -- if help, Usage() && quit
// -> validate arguments, configure command
// -> configure client
// -> run command
//
// if anything goes wrong, peace
type Command interface {
Flags(...string) error // parse subcommand specific flags
Args() error // validate arguments
Config() error // configure env variables
Usage() func() // custom command help TODO(reed): all local now?
Run() // cmd specific
}
// A command is the base for all commands implementing the Command interface.
type command struct {
wrkr worker.Worker
flags *WorkerFlags
hud_URL_str string
token *string
projectID *string
}
// All Commands will do similar configuration
func (bc *command) Config() error {
bc.wrkr.Settings = config.ConfigWithEnv("iron_worker", *envFlag)
if *projectIDFlag != "" {
bc.wrkr.Settings.ProjectId = *projectIDFlag
}
if *tokenFlag != "" {
bc.wrkr.Settings.Token = *tokenFlag
}
if bc.wrkr.Settings.ProjectId == "" {
return errors.New("did not find project id in any config files or env variables")
}
if bc.wrkr.Settings.Token == "" {
return errors.New("did not find token in any config files or env variables")
}
bc.hud_URL_str = `Check https://hud.iron.io/tq/projects/` + bc.wrkr.Settings.ProjectId + "/"
fmt.Println(LINES, `Configuring client`)
pName, err := projectName(bc.wrkr.Settings)
if err != nil {
return err
}
fmt.Printf(`%s Project '%s' with id='%s'`, BLANKS, pName, bc.wrkr.Settings.ProjectId)
fmt.Println()
return nil
}
func projectName(config config.Settings) (string, error) {
// get project name -- go api won't play ball
resp, err := http.Get(fmt.Sprintf("%s://%s:%d/%s/projects/%s?oauth=%s",
config.Scheme, config.Host, config.Port,
config.ApiVersion, config.ProjectId, config.Token))
if err != nil {
return "", err
}
var reply struct {
Name string `json:"name"`
}
err = json.NewDecoder(resp.Body).Decode(&reply)
return reply.Name, err
}
type UploadCmd struct {
command
name *string
config *string
configFile *string
stack *string // deprecated
maxConc *int
retries *int
retriesDelay *int
zip *string
codes worker.Code // for fields, not code
cmd string
}
type QueueCmd struct {
command
// flags
payload *string
payloadFile *string
priority *int
timeout *int
delay *int
wait *bool
cluster *string
// payload
task worker.Task
}
type SchedCmd struct {
command
payload *string
payloadFile *string
priority *int
timeout *int
delay *int
maxConc *int
runEvery *int
runTimes *int
endAt *string // time.RubyTime
startAt *string // time.RubyTime
sched worker.Schedule
}
type StatusCmd struct {
command
taskID string
}
type LogCmd struct {
command
taskID string
}
func (s *SchedCmd) Flags(args ...string) error {
s.flags = NewWorkerFlagSet(s.Usage())
s.payload = s.flags.payload()
s.payloadFile = s.flags.payloadFile()
s.priority = s.flags.priority()
s.timeout = s.flags.timeout()
s.delay = s.flags.delay()
s.maxConc = s.flags.maxConc()
s.runEvery = s.flags.runEvery()
s.runTimes = s.flags.runTimes()
s.endAt = s.flags.endAt()
s.startAt = s.flags.startAt()
err := s.flags.Parse(args)
if err != nil {
return err
}
return s.flags.validateAllFlags()
}
func (s *SchedCmd) Args() error {
if s.flags.NArg() != 1 {
return errors.New("error: schedule takes one argument, a code name")
}
delay := time.Duration(*s.delay) * time.Second
s.sched = worker.Schedule{
CodeName: s.flags.Arg(0),
Delay: &delay,
Priority: s.priority,
RunTimes: s.runTimes,
}
payload := *s.payload
if *s.payloadFile != "" {
pload, err := ioutil.ReadFile(*s.payloadFile)
if err != nil {
return err
}
payload = string(pload)
}
if payload != "" {
s.sched.Payload = payload
}
if *s.endAt != "" {
t, _ := time.Parse(time.RubyDate, *s.endAt) // checked in validateFlags()
s.sched.EndAt = &t
}
if *s.startAt != "" {
t, _ := time.Parse(time.RubyDate, *s.startAt)
s.sched.StartAt = &t
}
if *s.maxConc > 0 {
s.sched.MaxConcurrency = s.maxConc
}
if *s.runEvery > 0 {
s.sched.RunEvery = s.runEvery
}
return nil
}
func (s *SchedCmd) Usage() func() {
return func() {
fmt.Fprintln(os.Stderr, `usage: iron_worker schedule [OPTIONS] CODE_PACKAGE_NAME`)
s.flags.PrintDefaults()
}
}
func (s *SchedCmd) Run() {
fmt.Println(LINES, "Scheduling task '"+s.sched.CodeName+"'")
ids, err := s.wrkr.Schedule(s.sched)
if err != nil {
fmt.Println(BLANKS, err)
return
}
id := ids[0]
fmt.Printf("%s Scheduled task with id='%s'\n", BLANKS, id)
fmt.Println(BLANKS, s.hud_URL_str+"scheduled_jobs/"+id+INFO)
}
func (q *QueueCmd) Flags(args ...string) error {
q.flags = NewWorkerFlagSet(q.Usage())
q.payload = q.flags.payload()
q.payloadFile = q.flags.payloadFile()
q.priority = q.flags.priority()
q.timeout = q.flags.timeout()
q.delay = q.flags.delay()
q.wait = q.flags.wait()
q.cluster = q.flags.cluster()
err := q.flags.Parse(args)
if err != nil {
return err
}
return q.flags.validateAllFlags()
}
// Takes 1 arg for worker name
func (q *QueueCmd) Args() error {
if q.flags.NArg() != 1 {
return errors.New("error: queue takes one argument, a code name")
}
payload := *q.payload
if *q.payloadFile != "" {
pload, err := ioutil.ReadFile(*q.payloadFile)
if err != nil {
return err
}
payload = string(pload)
}
delay := time.Duration(*q.delay) * time.Second
timeout := time.Duration(*q.timeout) * time.Second
q.task = worker.Task{
CodeName: q.flags.Arg(0),
Payload: payload,
Priority: *q.priority,
Timeout: &timeout,
Delay: &delay,
Cluster: *q.cluster,
}
return nil
}
func (q *QueueCmd) Usage() func() {
return func() {
fmt.Fprintln(os.Stderr, `usage: iron_worker queue [OPTIONS] CODE_PACKAGE_NAME`)
q.flags.PrintDefaults()
}
}
func (q *QueueCmd) Run() {
fmt.Println(LINES, "Queueing task '"+q.task.CodeName+"'")
ids, err := q.wrkr.TaskQueue(q.task)
if err != nil {
fmt.Println(BLANKS, err)
return
}
id := ids[0]
fmt.Printf("%s Queued task with id='%s'\n", BLANKS, id)
fmt.Println(BLANKS, q.hud_URL_str+"jobs/"+id+INFO)
if *q.wait {
fmt.Println(LINES, "Waiting for task", id)
out := q.wrkr.WaitForTaskLog(id)
log := <-out
fmt.Println(LINES, "Done")
fmt.Println(LINES, "Printing Log:")
fmt.Printf("%s", string(log))
}
}
func (s *StatusCmd) Flags(args ...string) error {
s.flags = NewWorkerFlagSet(s.Usage())
err := s.flags.Parse(args)
if err != nil {
return err
}
return s.flags.validateAllFlags()
}
// Takes one parameter, the task_id to acquire status of
func (s *StatusCmd) Args() error {
if s.flags.NArg() != 1 {
return errors.New("error: status takes one argument, a task_id")
}
s.taskID = s.flags.Arg(0)
return nil
}
func (s *StatusCmd) Usage() func() {
return func() {
fmt.Fprintln(os.Stderr, `usage: iron_worker status [OPTIONS] task_id`)
s.flags.PrintDefaults()
}
}
func (s *StatusCmd) Run() {
fmt.Println(LINES, `Getting status of task with id='`+s.taskID+`'`)
taskInfo, err := s.wrkr.TaskInfo(s.taskID)
if err != nil {
fmt.Println(err)
}
fmt.Println(BLANKS, taskInfo.Status)
}
func (l *LogCmd) Flags(args ...string) error {
l.flags = NewWorkerFlagSet(l.Usage())
err := l.flags.Parse(args)
if err != nil {
return err
}
return l.flags.validateAllFlags()
}
// Takes one parameter, the task_id to log
func (l *LogCmd) Args() error {
if l.flags.NArg() < 1 {
return errors.New("error: log takes one argument, a task_id")
}
l.taskID = l.flags.Arg(0)
return nil
}
func (l *LogCmd) Usage() func() {
return func() {
fmt.Fprintln(os.Stderr, `usage: iron_worker log [OPTIONS] task_id`)
l.flags.PrintDefaults()
}
}
func (l *LogCmd) Run() {
fmt.Println(LINES, "Getting log for task with id='"+l.taskID+"'")
out, err := l.wrkr.TaskLog(l.taskID)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(out))
}
func (u *UploadCmd) Flags(args ...string) error {
u.flags = NewWorkerFlagSet(u.Usage())
u.name = u.flags.name()
u.stack = u.flags.stack()
u.maxConc = u.flags.maxConc()
u.retries = u.flags.retries()
u.retriesDelay = u.flags.retriesDelay()
u.config = u.flags.config()
u.configFile = u.flags.configFile()
u.zip = u.flags.zip()
err := u.flags.Parse(args)
if err != nil {
return err
}
return u.flags.validateAllFlags()
}
// `iron worker upload [--zip [ZIPFILE]] [IMAGE] [[COMMAND]...]`
//
// old deprecated: `iron worker upload [ZIPFILE] [COMMAND]`
func (u *UploadCmd) Args() error {
if u.flags.NArg() < 1 {
return errors.New("upload takes at least one argument, the name of the image to use.")
}
u.codes.Command = strings.TrimSpace(strings.Join(u.flags.Args()[1:], " "))
if *u.stack != "" {
// deprecated
u.codes.Stack = *u.stack
*u.zip = u.flags.Arg(0)
} else {
u.codes.Image = u.flags.Arg(0)
// command also optional, filled in above
// zip filled in from flag, optional
}
if *u.name == "" {
return errors.New("must specify -name for your worker")
} else {
u.codes.Name = *u.name
}
if *u.zip != "" {
if u.codes.Command == "" { // must have command if using zip
return errors.New("uploading a zip file requires a command, see -help")
}
// make sure it exists and it's a zip
if !strings.HasSuffix(*u.zip, ".zip") {
return errors.New("file extension must be .zip, got: " + *u.zip)
}
if _, err := os.Stat(*u.zip); err != nil {
return err
}
}
if *u.maxConc > 0 {
u.codes.MaxConcurrency = *u.maxConc
}
if *u.retries > 0 {
u.codes.Retries = *u.retries
}
if *u.retriesDelay > 0 {
u.codes.RetriesDelay = time.Duration(*u.retriesDelay) * time.Second
}
if *u.config != "" {
u.codes.Config = *u.config
}
if *u.configFile != "" {
pload, err := ioutil.ReadFile(*u.configFile)
if err != nil {
return err
}
u.codes.Config = string(pload)
}
return nil
}
func (u *UploadCmd) Usage() func() {
return func() {
fmt.Fprintln(os.Stderr, `usage: iron_worker upload -name myworker [OPTIONS] worker.zip command...`)
fmt.Fprintln(os.Stderr)
fmt.Fprintln(os.Stderr, `or`)
fmt.Fprintln(os.Stderr)
fmt.Fprintln(os.Stderr, `usage: iron_worker upload -name myworker [-zip my.zip] [OPTIONS] some/image [command...]`)
u.flags.PrintDefaults()
}
}
func (u *UploadCmd) Run() {
fmt.Println(LINES, `Uploading worker '`+u.codes.Name+`'`)
id, err := pushCodes(*u.zip, &u.wrkr, u.codes)
if err != nil {
fmt.Println(err)
return
}
id = string(id)
fmt.Println(BLANKS, `Uploaded code package with id='`+id+`'`)
fmt.Println(BLANKS, u.hud_URL_str+"code/"+id+INFO)
}