-
Notifications
You must be signed in to change notification settings - Fork 0
/
daemon_test.go
117 lines (102 loc) · 2.1 KB
/
daemon_test.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
package containerd
import (
"context"
"io"
"os/exec"
"sync"
"syscall"
"github.com/pkg/errors"
)
type daemon struct {
sync.Mutex
addr string
cmd *exec.Cmd
}
func (d *daemon) start(name, address string, args []string, stdout, stderr io.Writer) error {
d.Lock()
defer d.Unlock()
if d.cmd != nil {
return errors.New("daemon is already running")
}
args = append(args, []string{"--address", address}...)
cmd := exec.Command(name, args...)
cmd.Stdout = stdout
cmd.Stderr = stderr
if err := cmd.Start(); err != nil {
cmd.Wait()
return errors.Wrap(err, "failed to start daemon")
}
d.addr = address
d.cmd = cmd
return nil
}
func (d *daemon) waitForStart(ctx context.Context) (*Client, error) {
var (
client *Client
serving bool
err error
)
client, err = New(address)
if err != nil {
return nil, err
}
serving, err = client.IsServing(ctx)
if !serving {
client.Close()
if err == nil {
err = errors.New("connection was successful but service is not available")
}
return nil, err
}
return client, err
}
func (d *daemon) Stop() error {
d.Lock()
defer d.Unlock()
if d.cmd == nil {
return errors.New("daemon is not running")
}
return d.cmd.Process.Signal(syscall.SIGTERM)
}
func (d *daemon) Kill() error {
d.Lock()
defer d.Unlock()
if d.cmd == nil {
return errors.New("daemon is not running")
}
return d.cmd.Process.Kill()
}
func (d *daemon) Wait() error {
d.Lock()
defer d.Unlock()
if d.cmd == nil {
return errors.New("daemon is not running")
}
err := d.cmd.Wait()
d.cmd = nil
return err
}
func (d *daemon) Restart(stopCb func()) error {
d.Lock()
defer d.Unlock()
if d.cmd == nil {
return errors.New("daemon is not running")
}
var err error
if err = d.cmd.Process.Signal(syscall.SIGTERM); err != nil {
return errors.Wrap(err, "failed to signal daemon")
}
d.cmd.Wait()
if stopCb != nil {
stopCb()
}
cmd := exec.Command(d.cmd.Path, d.cmd.Args[1:]...)
cmd.Stdout = d.cmd.Stdout
cmd.Stderr = d.cmd.Stderr
if err := cmd.Start(); err != nil {
cmd.Wait()
return errors.Wrap(err, "failed to start new daemon instance")
}
d.cmd = cmd
return nil
}