-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcommand.go
More file actions
114 lines (91 loc) · 2.42 KB
/
Copy pathcommand.go
File metadata and controls
114 lines (91 loc) · 2.42 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
package athena
import (
"context"
"fmt"
"os"
"os/signal"
"time"
cli "github.com/jawher/mow.cli"
rscsrv "github.com/lab259/go-rscsrv"
"github.com/lab259/rlog/v2"
)
type CommandAction func(opt *CommandOptions)
type CommandOptions struct {
BindAddress string
Wait int
Hostname string
IsDryRun bool
}
type commandBuilder struct {
wait int
hostname string
services []rscsrv.Service
}
func NewCommand(services ...rscsrv.Service) *commandBuilder {
hostname, _ := os.Hostname()
return &commandBuilder{
services: services,
wait: 0,
hostname: hostname,
}
}
func (b *commandBuilder) Wait(wait int) *commandBuilder {
b.wait = wait
return b
}
func (b *commandBuilder) Hostname(hostname string) *commandBuilder {
b.hostname = hostname
return b
}
func (b *commandBuilder) Build() cli.CmdInitializer {
serviceStarter := rscsrv.DefaultServiceStarter(b.services...)
return cli.CmdInitializer(func(cmd *cli.Cmd) {
var options CommandOptions
cmd.IntPtr(&options.Wait, cli.IntOpt{
Name: "w wait",
Value: b.wait,
Desc: "Delay in seconds before the initialization",
EnvVar: "WAIT",
})
cmd.StringPtr(&options.Hostname, cli.StringOpt{
Name: "H hostname",
Value: b.hostname,
Desc: "The name of the station running the app instance",
EnvVar: "HOSTNAME",
})
cmd.BoolOptPtr(&options.IsDryRun, "d dry-run", false, "Loads the configuration and check if the dependencies are working (such as database connections)")
cmd.Before = func() {
os.Setenv("HOSTNAME", options.Hostname)
if options.IsDryRun {
rlog.Trace(1, "This is a dry run!")
}
if options.Wait > 0 {
rlog.Infof(" Waiting %d seconds before continue ...", options.Wait)
time.Sleep(time.Duration(options.Wait) * time.Second)
rlog.Info(fmt.Sprintf(" > Waiting %s", "DONE"))
}
if options.IsDryRun {
// TODO(felipemfp): figure out how to use dry run (if it is useful? maybe go thru services and try to .Load and .ApplyConfiguration?)
if options.IsDryRun {
rlog.Trace(1, "Everything looks fine!")
}
os.Exit(0)
}
}
cmd.Action = func() {
var exitCode int
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt)
go func() {
<-signals
serviceStarter.Stop(true)
}()
if err := serviceStarter.Start(); err != context.Canceled {
exitCode = 2
serviceStarter.Stop(true)
}
serviceStarter.Wait()
os.Exit(exitCode)
}
})
}