-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun.go
114 lines (93 loc) · 2.18 KB
/
run.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
package ctrl
import (
"flag"
"fmt"
"github.com/afajl/ctrl/config"
"github.com/afajl/ctrl/log"
"github.com/afajl/ctrl/queue"
"github.com/afajl/ctrl/host"
"os"
)
var (
listCmds = flag.Bool("l", false, "list commands")
configfile = flag.String("c", "", "config file")
)
type Run struct {
Config *config.Config
Queue *queue.Queue
Hosts []*host.Host
Cmds []*RoutedCmd
Log, Out *log.WriteLogger
loggers *log.RunLogs
}
func NewRun() *Run {
run := &Run{}
run.Queue = queue.NewQueue()
return run
}
// Wrap a cmd to create a QueuedCmd
func makeQueuedCmd(cmd Cmd, ctrl Ctrl) queue.QueuedCmd {
return func() error {
return cmd(ctrl)
}
}
func getConfig() *config.Config {
if err := config.Init(*configfile); err != nil {
exit_usage("could not load config: ", err)
}
conf := config.StartConfig
if len(conf.Hosts) == 0 {
exit_usage("no hosts specified")
}
return conf
}
func Start(routes *Routes) {
flag.Usage = usage
flag.Parse()
if *listCmds {
routes.Print()
os.Exit(0)
}
run := NewRun()
conf := getConfig()
run.loggers = log.NewRunLogs(conf.Logdir, os.Args[1:], conf.Verbose, !conf.DontLog)
run.Log = run.loggers.GetRunLog()
run.Out = run.loggers.GetRunOut()
var err error
if run.Hosts, err = host.FromStrings(conf.Hosts); err != nil {
exit_usage(err)
}
if run.Cmds, err = routes.Parse(flag.Args()); err != nil {
exit_usage(err)
}
if err := run.Run(); err != nil {
run.Fail(err)
}
}
func (run *Run) Run() error {
for _, cmd := range run.Cmds {
run.QueueCmd(cmd.GetCmd(), run.Hosts...)
}
return run.Queue.Run()
}
func (run *Run) QueueCmd(cmd Cmd, hosts ...*host.Host) {
for _, host := range hosts {
ctrl := NewCtrl(run).ForHost(*host)
ctrl.log = run.loggers.GetHostLog(host.Name)
ctrl.out = run.loggers.GetHostOut(host.Name)
qcmd := makeQueuedCmd(cmd, ctrl)
run.Queue.Add(qcmd)
}
}
func (run *Run) Fail(a ...interface{}) {
run.Out.Fatalln(append([]interface{}{"run stopped:"}, a...)...)
}
func usage() {
fmt.Fprintf(os.Stderr, "\nUsage: %s [OPTION]... COMMANDS...\n", os.Args[0])
flag.PrintDefaults()
}
func exit_usage(args ...interface{}) {
fmt.Fprintf(os.Stderr, "\nERROR: %s\n\n", fmt.Sprint(args...))
usage()
os.Exit(1)
}