/
daemon.go
299 lines (249 loc) · 6.21 KB
/
daemon.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
package cmd
import (
"context"
"fmt"
"log"
"os"
"os/signal"
"path"
"runtime"
"syscall"
"time"
"github.com/kardianos/osext"
"github.com/natefinch/lumberjack"
"github.com/nightlyone/lockfile"
"github.com/urfave/cli"
"github.com/manifoldco/torus-cli/api"
"github.com/manifoldco/torus-cli/config"
"github.com/manifoldco/torus-cli/errs"
"github.com/manifoldco/torus-cli/daemon"
)
func init() {
daemon := cli.Command{
Name: "daemon",
Usage: "Manage the session daemon",
Category: "SYSTEM",
Subcommands: []cli.Command{
{
Name: "status",
Usage: "Display daemon status",
Action: daemonStatus,
},
{
Name: "start",
Usage: "Start the session daemon",
Flags: []cli.Flag{
cli.BoolFlag{
Name: "foreground",
Usage: "Run the Daemon in the foreground",
},
cli.BoolFlag{
Name: "daemonize",
Usage: "Run as a background session daemon",
Hidden: true, // not displayed in help; used internally
},
cli.BoolFlag{
Name: "no-permission-check",
Usage: "Skip Torus root dir permission checks",
Hidden: true, // Just for system daemon use
},
},
Action: func(ctx *cli.Context) error {
if ctx.Bool("foreground") {
return startDaemon(ctx)
}
return spawnDaemonCmd()
},
},
{
Name: "stop",
Usage: "Stop the session daemon",
Action: stopDaemonCmd,
},
},
}
Cmds = append(Cmds, daemon)
}
func daemonStatus(ctx *cli.Context) error {
cfg, err := config.LoadConfig()
if err != nil {
return err
}
proc, err := findDaemon(cfg)
if err != nil {
return err
}
if proc == nil {
fmt.Println("Daemon is not running.")
return nil
}
client := api.NewClient(cfg)
v, err := client.Version.GetDaemon(context.Background())
if err != nil {
return errs.NewErrorExitError("Error communicating with the daemon", err)
}
fmt.Printf("Daemon is running. pid: %d version: v%s\n", proc.Pid, v.Version)
return nil
}
func spawnDaemonCmd() error {
cfg, err := config.LoadConfig()
if err != nil {
return err
}
proc, err := findDaemon(cfg)
if err != nil {
return err
}
if proc != nil {
fmt.Println("Daemon is already running.")
return nil
}
err = spawnDaemon()
if err != nil {
return err
}
fmt.Println("Daemon started.")
return nil
}
func spawnDaemon() error {
executable, err := osext.Executable()
if err != nil {
return errs.NewErrorExitError("Unable to find executable.", err)
}
cmd := daemonCommand(executable)
// Clone the current env, removing email and password if they exist.
// no need to keep those hanging around in a long lived-process!
cmd.Env = filterEnv()
err = cmd.Start()
if err != nil {
return errs.NewErrorExitError("Unable to start daemon", err)
}
return nil
}
func startDaemon(ctx *cli.Context) error {
noPermissionCheck := ctx.Bool("no-permission-check")
torusRoot, err := config.CreateTorusRoot(!noPermissionCheck)
if err != nil {
return errs.NewErrorExitError("Failed to initialize Torus root dir.", err)
}
if ctx.Bool("daemonize") {
log.SetOutput(&lumberjack.Logger{
Filename: path.Join(torusRoot, "daemon.log"),
MaxSize: 10, // megabytes
MaxBackups: 3,
MaxAge: 28, // days
})
} else {
// re-enable logging, as by default its silenced for foreground use.
log.SetOutput(os.Stdout)
}
cfg, err := config.NewConfig(torusRoot)
if err != nil {
return errs.NewErrorExitError("Failed to load config.", err)
}
daemon, err := daemon.New(cfg, noPermissionCheck)
if err != nil {
return errs.NewErrorExitError("Failed to create daemon.", err)
}
go watch(daemon)
defer daemon.Shutdown()
log.Printf("v%s of the Daemon is now listening on %s", cfg.Version, daemon.Addr())
err = daemon.Run()
if err != nil {
log.Printf("Error while running daemon.\n%s", err)
}
return err
}
func watch(daemon *daemon.Daemon) {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
s := <-c
log.Printf("Caught a signal: %s", s)
shutdown(daemon)
}
func shutdown(daemon *daemon.Daemon) {
err := daemon.Shutdown()
if err != nil {
log.Printf("Did not shutdown cleanly.\n%s", err)
}
if r := recover(); r != nil {
log.Printf("Failed shutting down; caught panic.\n%v", r)
panic(r)
}
}
func stopDaemonCmd(ctx *cli.Context) error {
cfg, err := config.LoadConfig()
if err != nil {
return err
}
proc, err := findDaemon(cfg)
if err != nil {
return err
}
if proc == nil {
fmt.Println("Daemon is not running.")
return nil
}
graceful, err := stopDaemon(proc)
if err != nil {
return err
}
if graceful {
fmt.Println("Daemon stopped gracefully.")
} else {
fmt.Println("Daemon stopped forcefully.")
}
return nil
}
// stopDaemon stops the daemon process. It returns a bool indicating if the
// shutdown was graceful.
func stopDaemon(proc *os.Process) (bool, error) {
err := proc.Signal(syscall.Signal(syscall.SIGTERM))
if err == nil { // no need to wait for the SIGTERM if the signal failed
increment := 50 * time.Millisecond
for d := increment; d < 3*time.Second; d += increment {
time.Sleep(d)
if _, err := findProcess(proc.Pid); err != nil {
return true, nil
}
}
}
err = proc.Kill()
if err != nil {
return false, errs.NewErrorExitError("Could not stop daemon.", err)
}
return false, nil
}
// findDaemon returns an os.Process for a running daemon, or nil if it is not
// running. It returns an error if the pid file location is invalid in the
// config, or there was an error reading the pid file.
func findDaemon(cfg *config.Config) (*os.Process, error) {
lock, err := lockfile.New(cfg.PidPath)
if err != nil {
return nil, err
}
proc, err := lock.GetOwner()
if err != nil {
// happy path cases. the pid doesn't exist, or it contains garbage,
// or the previous owner is gone.
if os.IsNotExist(err) || err == lockfile.ErrInvalidPid || err == lockfile.ErrDeadOwner {
return nil, nil
}
return nil, err
}
return proc, nil
}
func findProcess(pid int) (*os.Process, error) {
proc, err := os.FindProcess(pid)
if err != nil {
return nil, err
}
// On unix, findprocess does not error. So we have to check for the process.
if runtime.GOOS != "windows" {
err = proc.Signal(syscall.Signal(0))
if err != nil {
return nil, err
}
}
return proc, nil
}