This repository has been archived by the owner on Mar 13, 2021. It is now read-only.
forked from cloudfoundry/guardian
-
Notifications
You must be signed in to change notification settings - Fork 1
/
runner.go
320 lines (258 loc) · 8.3 KB
/
runner.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
package runner
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"os/exec"
"path"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
"code.cloudfoundry.org/garden/client"
"code.cloudfoundry.org/garden/client/connection"
"code.cloudfoundry.org/lager"
"code.cloudfoundry.org/lager/lagertest"
"github.com/eapache/go-resiliency/retrier"
"github.com/onsi/ginkgo"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/gbytes"
"github.com/tedsuo/ifrit"
"github.com/tedsuo/ifrit/ginkgomon"
)
const MNT_DETACH = 0x2
var DataDir string
var TarBin = os.Getenv("GARDEN_TAR_PATH")
type RunningGarden struct {
client.Client
runner GardenRunner
process ifrit.Process
debugIP string
debugPort int
Pid int
Tmpdir string
DepotDir string
DataDir string
GraphPath string
logger lager.Logger
}
type GardenRunner struct {
*ginkgomon.Runner
Cmd *exec.Cmd
TmpDir string
GraphPath string
ConsoleSockets string
DepotDir string
DebugIp string
DebugPort int
Network, Addr string
}
func init() {
DataDir = os.Getenv("GARDEN_TEST_GRAPHPATH")
if DataDir == "" {
// This must be set outside of the Ginkgo node directory (tmpDir) because
// otherwise the Concourse worker may run into one of the AUFS kernel
// module bugs that cause the VM to become unresponsive.
DataDir = "/tmp/aufs_mount"
}
}
func NewGardenRunner(bin, initBin, nstarBin, dadooBin, grootfsBin, rootfs, tarBin, network, address string, user *syscall.Credential, argv ...string) GardenRunner {
r := GardenRunner{}
r.Network = network
r.Addr = address
r.TmpDir = filepath.Join(
os.TempDir(),
fmt.Sprintf("test-garden-%d", ginkgo.GinkgoParallelNode()),
)
r.GraphPath = filepath.Join(DataDir, fmt.Sprintf("node-%d", ginkgo.GinkgoParallelNode()))
r.DepotDir = filepath.Join(r.TmpDir, "containers")
r.ConsoleSockets = filepath.Join(r.TmpDir, "console-sockets")
MustMountTmpfs(r.GraphPath)
r.Cmd = cmd(r.TmpDir, r.DepotDir, r.GraphPath, r.ConsoleSockets, r.Network, r.Addr, bin, initBin, nstarBin, dadooBin, grootfsBin, tarBin, rootfs, user, argv...)
r.Cmd.Env = append(os.Environ(), fmt.Sprintf("TMPDIR=%s", r.TmpDir))
for i, arg := range r.Cmd.Args {
if arg == "--debug-bind-ip" {
r.DebugIp = r.Cmd.Args[i+1]
}
if arg == "--debug-bind-port" {
r.DebugPort, _ = strconv.Atoi(r.Cmd.Args[i+1])
}
}
r.Runner = ginkgomon.New(ginkgomon.Config{
Name: "guardian",
Command: r.Cmd,
AnsiColorCode: "31m",
StartCheck: "guardian.started",
StartCheckTimeout: 30 * time.Second,
})
return r
}
func Start(bin, initBin, nstarBin, dadooBin, grootfsBin, rootfs, tarBin string, user *syscall.Credential, argv ...string) *RunningGarden {
runner := NewGardenRunner(bin, initBin, nstarBin, dadooBin, grootfsBin, rootfs, tarBin, "unix", fmt.Sprintf("/tmp/garden_%d.sock", GinkgoParallelNode()), user, argv...)
r := &RunningGarden{
runner: runner,
DepotDir: runner.DepotDir,
DataDir: DataDir,
GraphPath: runner.GraphPath,
Tmpdir: runner.TmpDir,
logger: lagertest.NewTestLogger("garden-runner"),
debugIP: runner.DebugIp,
debugPort: runner.DebugPort,
Client: client.New(connection.New(runner.Network, runner.Addr)),
}
r.process = ifrit.Invoke(r.runner)
r.Pid = runner.Cmd.Process.Pid
return r
}
func (r *RunningGarden) Kill() error {
r.process.Signal(syscall.SIGKILL)
select {
case err := <-r.process.Wait():
return err
case <-time.After(time.Second * 10):
r.process.Signal(syscall.SIGKILL)
return errors.New("timed out waiting for garden to shutdown after 10 seconds")
}
}
func (r *RunningGarden) DestroyAndStop() error {
if err := r.DestroyContainers(); err != nil {
return err
}
if err := r.Stop(); err != nil {
return err
}
return nil
}
func (r *RunningGarden) Stop() error {
r.process.Signal(syscall.SIGTERM)
var err error
for i := 0; i < 5; i++ {
select {
case err := <-r.process.Wait():
return err
case <-time.After(time.Second * 5):
r.process.Signal(syscall.SIGTERM)
err = errors.New("timed out waiting for garden to shutdown after 5 seconds")
}
}
r.process.Signal(syscall.SIGKILL)
return err
}
func cmd(tmpdir, depotDir, graphPath, consoleSocketsPath, network, addr, bin, initBin, nstarBin, dadooBin, grootfsBin, tarBin, rootfs string, user *syscall.Credential, argv ...string) *exec.Cmd {
Expect(os.MkdirAll(tmpdir, 0755)).To(Succeed())
Expect(os.MkdirAll(depotDir, 0755)).To(Succeed())
appendDefaultFlag := func(ar []string, key, value string) []string {
for _, a := range argv {
if a == key {
return ar
}
}
if value != "" {
return append(ar, key, value)
} else {
return append(ar, key)
}
}
gardenArgs := make([]string, len(argv))
copy(gardenArgs, argv)
switch network {
case "tcp":
gardenArgs = appendDefaultFlag(gardenArgs, "--bind-ip", strings.Split(addr, ":")[0])
gardenArgs = appendDefaultFlag(gardenArgs, "--bind-port", strings.Split(addr, ":")[1])
case "unix":
gardenArgs = appendDefaultFlag(gardenArgs, "--bind-socket", addr)
}
if rootfs != "" {
gardenArgs = appendDefaultFlag(gardenArgs, "--default-rootfs", rootfs)
}
gardenArgs = appendDefaultFlag(gardenArgs, "--depot", depotDir)
gardenArgs = appendDefaultFlag(gardenArgs, "--graph", graphPath)
gardenArgs = appendDefaultFlag(gardenArgs, "--console-sockets-path", consoleSocketsPath)
gardenArgs = appendDefaultFlag(gardenArgs, "--tag", fmt.Sprintf("%d", GinkgoParallelNode()))
gardenArgs = appendDefaultFlag(gardenArgs, "--network-pool", fmt.Sprintf("10.254.%d.0/22", 4*GinkgoParallelNode()))
gardenArgs = appendDefaultFlag(gardenArgs, "--init-bin", initBin)
gardenArgs = appendDefaultFlag(gardenArgs, "--dadoo-bin", dadooBin)
gardenArgs = appendDefaultFlag(gardenArgs, "--nstar-bin", nstarBin)
gardenArgs = appendDefaultFlag(gardenArgs, "--tar-bin", tarBin)
gardenArgs = appendDefaultFlag(gardenArgs, "--port-pool-start", fmt.Sprintf("%d", GinkgoParallelNode()*7000))
cmd := exec.Command(bin, append([]string{"server"}, gardenArgs...)...)
if user != nil {
cmd.SysProcAttr = &syscall.SysProcAttr{}
cmd.SysProcAttr.Credential = user
uidGid := fmt.Sprintf("%d:%d", user.Uid, user.Gid)
Expect(exec.Command("chown", "-R", uidGid, tmpdir).Run()).To(Succeed())
}
return cmd
}
func (r *RunningGarden) Cleanup() {
// unmount aufs since the docker graph driver leaves this around,
// otherwise the following commands might fail
retry := retrier.New(retrier.ConstantBackoff(200, 500*time.Millisecond), nil)
err := retry.Run(func() error {
if err := os.RemoveAll(path.Join(r.GraphPath, "aufs")); err == nil {
return nil // if we can remove it, it's already unmounted
}
if err := syscall.Unmount(path.Join(r.GraphPath, "aufs"), MNT_DETACH); err != nil {
r.logger.Error("failed-unmount-attempt", err)
return err
}
return nil
})
if err != nil {
r.logger.Error("failed-to-unmount", err)
}
MustUnmountTmpfs(r.GraphPath)
// In the kernel version 3.19.0-51-generic the code bellow results in
// hanging the running VM. We are not deleting the node-X directories. They
// are empty and the next test will re-use them. We will stick with that
// workaround until we can test on a newer kernel that will hopefully not
// have this bug.
//
// if err := os.RemoveAll(r.GraphPath); err != nil {
// r.logger.Error("remove-graph", err)
// }
r.logger.Info("cleanup-tempdirs")
if err := os.RemoveAll(r.Tmpdir); err != nil {
r.logger.Error("cleanup-tempdirs-failed", err, lager.Data{"tmpdir": r.Tmpdir})
} else {
r.logger.Info("tempdirs-removed")
}
}
func (r *RunningGarden) DestroyContainers() error {
containers, err := r.Containers(nil)
if err != nil {
return err
}
for _, container := range containers {
r.Destroy(container.Handle())
}
return nil
}
type debugVars struct {
NumGoRoutines int `json:"numGoRoutines"`
}
func (r *RunningGarden) NumGoroutines() (int, error) {
debugURL := fmt.Sprintf("http://%s:%d/debug/vars", r.debugIP, r.debugPort)
res, err := http.Get(debugURL)
if err != nil {
return 0, err
}
defer res.Body.Close()
decoder := json.NewDecoder(res.Body)
var debugVarsData debugVars
err = decoder.Decode(&debugVarsData)
if err != nil {
return 0, err
}
return debugVarsData.NumGoRoutines, nil
}
func (r *RunningGarden) Buffer() *gbytes.Buffer {
return r.runner.Buffer()
}
func (r *RunningGarden) ExitCode() int {
return r.runner.ExitCode()
}