forked from cockroachdb/cockroach
-
Notifications
You must be signed in to change notification settings - Fork 0
/
localcluster.go
636 lines (574 loc) · 16.7 KB
/
localcluster.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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
// Copyright 2015 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
// Author: Peter Mattis (peter@cockroachlabs.com)
package cluster
import (
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/cockroachdb/cockroach/security"
"github.com/cockroachdb/cockroach/util"
"github.com/cockroachdb/cockroach/util/log"
"github.com/samalba/dockerclient"
)
const (
builderImage = "cockroachdb/builder"
dockerspyImage = "cockroachdb/docker-spy"
domain = "local"
cockroachPort = 26257
pgPort = 15432
)
var (
cockroachTCP = fmt.Sprintf("%d/tcp", cockroachPort)
pgTCP = fmt.Sprintf("%d/tcp", pgPort)
)
var cockroachImage = flag.String("i", builderImage, "the docker image to run")
var cockroachBinary = flag.String("b", defaultBinary(), "the binary to run (if image == "+builderImage+")")
var cockroachEntry = flag.String("e", "", "the entry point for the image")
var waitOnStop = flag.Bool("w", false, "wait for the user to interrupt before tearing down the cluster")
var pwd = filepath.Clean(os.ExpandEnv("${PWD}"))
// keyLen is the length (in bits) of the generated CA and node certs.
const keyLen = 1024
func prettyJSON(v interface{}) string {
pretty, err := json.MarshalIndent(v, "", " ")
if err != nil {
panic(err)
}
return string(pretty)
}
func defaultBinary() string {
gopath := filepath.SplitList(os.Getenv("GOPATH"))
if len(gopath) == 0 {
return ""
}
return gopath[0] + "/bin/linux_amd64/cockroach"
}
func exists(path string) bool {
if _, err := os.Stat(path); os.IsNotExist(err) {
return false
}
return true
}
func nodeStr(i int) string {
return fmt.Sprintf("roach%d.%s", i, domain)
}
func dataStr(node, store int) string {
return fmt.Sprintf("/data%d.%d", node, store)
}
// The various event types.
const (
eventDie = "die"
)
// Event for a node containing a node index and the type of event.
type Event struct {
NodeIndex int
Status string
}
// LocalCluster manages a local cockroach cluster running on docker. The
// cluster is composed of a "dns" container which automatically registers dns
// entries for the cockroach nodes, a "volumes" container which manages the
// persistent volumes used for certs and node data and N cockroach nodes.
type LocalCluster struct {
client dockerclient.Client
stopper chan struct{}
mu sync.Mutex // Protects the fields below
dns *Container
vols *Container
numLocal int
numStores int
Nodes []*Container
events chan Event
expectedEvents chan Event
CertsDir string
monitorStopper chan struct{}
logDir string
keepLogs bool
ForceLogging bool // Forces logging to disk on a per test basis
}
// CreateLocal creates a new local cockroach cluster. The stopper is used to
// gracefully shutdown the channel (e.g. when a signal arrives). The cluster
// must be started before being used.
func CreateLocal(numLocal, numStores int, logDir string, stopper chan struct{}) *LocalCluster {
select {
case <-stopper:
// The stopper was already closed, exit early.
os.Exit(1)
default:
}
if *cockroachImage == builderImage && !exists(*cockroachBinary) {
log.Fatalf("\"%s\": does not exist", *cockroachBinary)
}
return &LocalCluster{
client: NewDockerClient(),
stopper: stopper,
numLocal: numLocal,
numStores: numStores,
// TODO(tschottdorf): deadlocks will occur if these channels fill up.
events: make(chan Event, 1000),
expectedEvents: make(chan Event, 1000),
logDir: logDir,
}
}
func (l *LocalCluster) expectEvent(c *Container, msgs ...string) {
for index, ctr := range l.Nodes {
if c.ID != ctr.ID {
continue
}
for _, status := range msgs {
l.expectedEvents <- Event{NodeIndex: index, Status: status}
}
break
}
}
// stopOnPanic is invoked as a deferred function in Start in order to attempt
// to tear down the cluster if a panic occurs while starting it. If the panic
// was initiated by the stopper being closed (which panicOnStop notices) then
// the process is exited with a failure code.
func (l *LocalCluster) stopOnPanic() {
if r := recover(); r != nil {
l.stop()
if r != l {
panic(r)
}
os.Exit(1)
}
}
// panicOnStop tests whether the stopper channel has been closed and panics if
// it has. This allows polling for whether to stop and avoids nasty locking
// complications with trying to call Stop at arbitrary points such as in the
// middle of creating a container.
func (l *LocalCluster) panicOnStop() {
if l.stopper == nil {
panic(l)
}
select {
case <-l.stopper:
l.stopper = nil
panic(l)
default:
}
}
func (l *LocalCluster) runDockerSpy() {
l.panicOnStop()
create := func() (*Container, error) {
return createContainer(l, dockerclient.ContainerConfig{
Image: dockerspyImage,
Cmd: []string{"--dns-domain=" + domain},
})
}
c, err := create()
if err == dockerclient.ErrImageNotFound {
log.Infof("pulling %s", dockerspyImage)
err = l.client.PullImage(dockerspyImage, nil)
if err == nil {
c, err = create()
}
}
if err != nil {
panic(err)
}
maybePanic(c.Start([]string{"/var/run/docker.sock:/var/run/docker.sock"}, nil, nil))
c.Name = "docker-spy"
l.dns = c
if ci, err := c.Inspect(); err != nil {
log.Error(err)
} else {
log.Infof("started %s: %s", c.Name, ci.NetworkSettings.IPAddress)
}
}
// create the volumes container that keeps all of the volumes used by
// the cluster.
func (l *LocalCluster) initCluster() {
log.Infof("initializing cluster")
l.panicOnStop()
vols := map[string]struct{}{}
for i := 0; i < l.numLocal; i++ {
for j := 0; j < l.numStores; j++ {
vols[dataStr(i, j)] = struct{}{}
}
}
create := func() (*Container, error) {
var entrypoint []string
if *cockroachImage == builderImage {
entrypoint = append(entrypoint, "/"+filepath.Base(*cockroachBinary))
} else if *cockroachEntry != "" {
entrypoint = append(entrypoint, *cockroachEntry)
}
return createContainer(l, dockerclient.ContainerConfig{
Image: *cockroachImage,
Volumes: vols,
Entrypoint: entrypoint,
Cmd: []string{"init", "--stores=ssd=" + dataStr(0, 0)},
})
}
c, err := create()
if err == dockerclient.ErrImageNotFound && *cockroachImage == builderImage {
log.Infof("pulling %s", *cockroachImage)
err = l.client.PullImage(*cockroachImage, nil)
if err == nil {
c, err = create()
}
}
if err != nil {
panic(err)
}
// Create the temporary certs directory in the current working
// directory. Boot2docker's handling of binding local directories
// into the container is very confusing. If the directory being
// bound has a parent directory that exists in the boot2docker VM
// then that directory is bound into the container. In particular,
// that means that binds of /tmp and /var will be problematic.
l.CertsDir, err = ioutil.TempDir(pwd, ".localcluster.certs.")
if err != nil {
panic(err)
}
binds := []string{
l.CertsDir + ":/certs",
filepath.Join(pwd, "..") + ":/go/src/github.com/cockroachdb/cockroach",
}
if l.logDir != "" {
l.keepLogs = true
if !filepath.IsAbs(l.logDir) {
l.logDir = filepath.Join(pwd, l.logDir)
}
binds = append(binds, l.logDir+":/logs")
// If we don't make sure the directory exists, Docker will and then we
// may run into ownership issues (think Docker running as root, but us
// running as a regular Joe as it happens on CircleCI).
if err := os.MkdirAll(l.logDir, 0777); err != nil {
log.Fatal(err)
}
} else if l.ForceLogging {
l.logDir, err = ioutil.TempDir(pwd, ".localcluster.logs.")
if err != nil {
panic(err)
}
binds = append(binds, l.logDir+":/logs")
}
if *cockroachImage == builderImage {
path, err := filepath.Abs(*cockroachBinary)
if err != nil {
panic(err)
}
binds = append(binds, path+":/"+filepath.Base(*cockroachBinary))
}
maybePanic(c.Start(binds, nil, nil))
maybePanic(c.Wait())
l.vols = c
l.vols.Name = "volumes"
}
func (l *LocalCluster) createRoach(i int, cmd ...string) *Container {
l.panicOnStop()
var hostname string
if i >= 0 {
hostname = fmt.Sprintf("roach%d", i)
}
var entrypoint []string
if *cockroachImage == builderImage {
entrypoint = append(entrypoint, "/"+filepath.Base(*cockroachBinary))
} else if *cockroachEntry != "" {
entrypoint = append(entrypoint, *cockroachEntry)
}
c, err := createContainer(l, dockerclient.ContainerConfig{
Hostname: hostname,
Domainname: domain,
Image: *cockroachImage,
ExposedPorts: map[string]struct{}{
cockroachTCP: {},
pgTCP: {},
},
Entrypoint: entrypoint,
Cmd: cmd,
Labels: map[string]string{
// Allow for `docker ps --filter label=Hostname=roach0` or `--filter label=Roach`.
"Hostname": hostname,
"Roach": "",
},
})
if err != nil {
panic(err)
}
return c
}
func (l *LocalCluster) createCACert() {
log.Infof("creating ca (%dbit) in: %s", keyLen, l.CertsDir)
maybePanic(security.RunCreateCACert(l.CertsDir, keyLen))
}
func (l *LocalCluster) createNodeCerts() {
log.Infof("creating node (%dbit) certs in: %s", keyLen, l.CertsDir)
nodes := []string{dockerIP().String()}
for i := 0; i < l.numLocal; i++ {
nodes = append(nodes, nodeStr(i))
}
maybePanic(security.RunCreateNodeCert(l.CertsDir, keyLen, nodes))
}
func (l *LocalCluster) startNode(i int) *Container {
gossipNodes := []string{}
for j := 0; j < l.numLocal; j++ {
gossipNodes = append(gossipNodes, fmt.Sprintf("%s:%d", nodeStr(j), cockroachPort))
}
var stores = "ssd=" + dataStr(i, 0)
for j := 1; j < l.numStores; j++ {
stores += ",ssd=" + dataStr(i, j)
}
cmd := []string{
"start",
"--stores=" + stores,
"--certs=/certs",
"--addr=" + fmt.Sprintf("%s:%d", nodeStr(i), cockroachPort),
"--gossip=" + strings.Join(gossipNodes, ","),
"--scan-max-idle-time=200ms", // set low to speed up tests
}
var locallogDir string
if len(l.logDir) > 0 {
dockerlogDir := "/logs/" + nodeStr(i)
locallogDir = filepath.Join(l.logDir, nodeStr(i))
if err := os.MkdirAll(locallogDir, 0777); err != nil {
log.Fatal(err)
}
cmd = append(
cmd,
"--log-dir="+dockerlogDir,
"--logtostderr=false",
"--alsologtostderr=true")
}
c := l.createRoach(i, cmd...)
maybePanic(c.Start(nil, l.dns, l.vols))
c.Name = nodeStr(i)
uri := fmt.Sprintf("https://%s", c.Addr(""))
// Infof doesn't take positional parameters, hence the Sprintf.
log.Infof(fmt.Sprintf(`*** started %[1]s ***
ui: %[2]s
trace: %[2]s/debug/requests
logs: %[3]s/cockroach.INFO
certs: %[4]s
pprof: docker exec -it %[5]s /bin/bash -c 'go tool pprof /cockroach <(wget --no-check-certificate -qO- https://$(hostname):26257/debug/pprof/heap)'`,
c.Name, uri, locallogDir, l.CertsDir, c.ID[:5]))
return c
}
func (l *LocalCluster) processEvent(e dockerclient.EventOrError, monitorStopper chan struct{}) bool {
l.mu.Lock()
defer l.mu.Unlock()
if e.Error != nil {
log.Errorf("monitoring error: %s", e.Error)
l.events <- Event{NodeIndex: -1, Status: eventDie}
return false
}
switch e.Status {
case "pull":
return false
}
for i, n := range l.Nodes {
if n != nil && n.ID == e.Id {
if log.V(1) {
log.Errorf("node=%d status=%s", i, e.Status)
}
l.events <- Event{NodeIndex: i, Status: e.Status}
return true
}
}
// TODO(pmattis): When we add the ability to start/stop/restart nodes we'll
// need to keep around a map of old node container ids in order to ignore
// events on those containers.
// An event on any other container is unexpected. Die.
select {
case <-l.stopper:
case <-monitorStopper:
default:
// There is a very tiny race here: the signal handler might be closing the
// stopper simultaneously.
log.Errorf("stopping due to unexpected event: %+v", e)
if r, err := l.client.ContainerLogs(e.Id, &dockerclient.LogOptions{
Stdout: true,
Stderr: true,
}); err == nil {
if _, err := io.Copy(os.Stderr, r); err != nil {
log.Infof("error listing logs: %s", err)
}
r.Close()
}
close(l.stopper)
}
return false
}
func (l *LocalCluster) monitor(monitorStopper chan struct{}) {
// MonitorEvents will (as of Docker 1.7) block until the first event is
// received.
ch, err := l.client.MonitorEvents(nil, l.monitorStopper)
if err != nil {
panic(err)
}
for e := range ch {
if !l.processEvent(e, monitorStopper) {
break
}
}
}
// Start starts the cluster.
func (l *LocalCluster) Start() {
defer l.stopOnPanic()
l.mu.Lock()
defer l.mu.Unlock()
l.runDockerSpy()
l.initCluster()
l.createCACert()
l.createNodeCerts()
l.monitorStopper = make(chan struct{})
go l.monitor(l.monitorStopper)
l.Nodes = make([]*Container, l.numLocal)
for i := range l.Nodes {
l.Nodes[i] = l.startNode(i)
}
}
// Assert drains the Events channel and compares the actual events with those
// expected to have been generated by the operations performed on the nodes in
// the cluster (restart, kill, ...). In the event of a mismatch, the passed
// Tester receives a fatal error.
// Currently, the only events generated (and asserted against) are "die" and
// "restart", to maximize compatibility across different versions of Docker.
func (l *LocalCluster) Assert(t util.Tester) {
const almostZero = 50 * time.Millisecond
filter := func(ch chan Event, wait time.Duration) *Event {
for {
select {
case act := <-ch:
if act.Status != "die" && act.Status != "restart" {
continue
}
return &act
case <-time.After(wait):
}
break
}
return nil
}
var events []Event
for {
exp := filter(l.expectedEvents, almostZero)
if exp == nil {
break
}
act := filter(l.events, time.Second)
if act == nil || *exp != *act {
t.Fatalf("expected event %v, got %v (after %v)", exp, act, events)
}
events = append(events, *exp)
}
if cur := filter(l.events, almostZero); cur != nil {
t.Fatalf("unexpected extra event %v (after %v)", cur, events)
}
if log.V(2) {
log.Infof("asserted %v", events)
}
}
// AssertAndStop calls Assert and then stops the cluster. It is safe to stop
// the cluster multiple times.
func (l *LocalCluster) AssertAndStop(t util.Tester) {
defer l.stop()
l.Assert(t)
}
// stop stops the cluster.
func (l *LocalCluster) stop() {
if *waitOnStop {
log.Infof("waiting for interrupt")
select {
case <-l.stopper:
}
}
log.Infof("stopping")
l.mu.Lock()
defer l.mu.Unlock()
if l.monitorStopper != nil {
close(l.monitorStopper)
l.monitorStopper = nil
}
if l.dns != nil {
maybePanic(l.dns.Kill())
maybePanic(l.dns.Remove())
l.dns = nil
}
if l.vols != nil {
maybePanic(l.vols.Kill())
maybePanic(l.vols.Remove())
l.vols = nil
}
if l.CertsDir != "" {
_ = os.RemoveAll(l.CertsDir)
l.CertsDir = ""
}
for i, n := range l.Nodes {
ci, err := n.Inspect()
crashed := err != nil || (!ci.State.Running && ci.State.ExitCode != 0)
maybePanic(n.Kill())
if len(l.logDir) > 0 {
// TODO(bdarnell): make these filenames more consistent with
// structured logs?
file := filepath.Join(l.logDir, nodeStr(i),
fmt.Sprintf("stderr.%s.log", strings.Replace(
time.Now().Format(time.RFC3339), ":", "_", -1)))
w, err := os.Create(file)
maybePanic(err)
defer w.Close()
maybePanic(n.Logs(w))
if crashed {
log.Infof("node %d: stderr at %s", i, file)
}
} else if crashed {
log.Warningf("node %d died: %s", i, ci.State)
}
maybePanic(n.Remove())
}
l.Nodes = nil
// Removing the log files must happen after shutting down the nodes or
// there might be a panic when it tries to log that it is killing the node.
if !l.keepLogs {
_ = os.RemoveAll(l.logDir)
l.logDir = ""
}
}
// ConnString creates a connections string.
func (l *LocalCluster) ConnString(i int) string {
return "rpcs://" + security.NodeUser + "@" +
l.Nodes[i].Addr("").String() +
"?certs=" + l.CertsDir
}
// PGAddr returns the Postgres address for the given node.
func (l *LocalCluster) PGAddr(i int) *net.TCPAddr {
return l.Nodes[i].PGAddr()
}
// NumNodes returns the number of nodes in the cluster.
func (l *LocalCluster) NumNodes() int {
return len(l.Nodes)
}
// Kill kills the i-th node.
func (l *LocalCluster) Kill(i int) error {
return l.Nodes[i].Kill()
}
// Restart restarts the given node. If the node isn't running, this starts it.
func (l *LocalCluster) Restart(i int) error {
return l.Nodes[i].Restart(5)
}
// URL returns the base url.
func (l *LocalCluster) URL(i int) string {
return "https://" + l.Nodes[i].Addr("26257/tcp").String()
}