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
|
// Copyright 2016 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.
// Package testserver provides helpers to run a cockroach binary within tests.
// It automatically downloads the latest cockroach binary for your platform
// (Linux-amd64 and Darwin-amd64 only for now), or attempts to run "cockroach"
// from your PATH.
//
// A normal invocation is (check err every time):
// ts, err := testserver.NewTestServer()
// err = ts.Start()
// defer ts.Stop()
// url := ts.PGURL()
//
// To use, run as follows:
// import "github.com/cockroachdb/cockroach-go/testserver"
// import "testing"
// import "time"
//
// func TestRunServer(t *testing.T) {
// ts, err := testserver.NewTestServer()
// if err != nil {
// t.Fatal(err)
// }
// err := ts.Start()
// if err != nil {
// t.Fatal(err)
// }
// defer ts.Stop()
//
// url := ts.PGURL()
// if url == nil {
// t.Fatalf("url not found")
// }
// t.Logf("URL: %s", url.String())
//
// db, err := sql.Open("postgres", url.String())
// if err != nil {
// t.Fatal(err)
// }
// }
package testserver
import (
"bytes"
"database/sql"
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"net/url"
"os"
"os/exec"
"os/user"
"path/filepath"
"strings"
"sync"
"syscall"
"testing"
"time"
// Import postgres driver.
_ "github.com/lib/pq"
)
var customBinary = flag.String("cockroach-binary", "", "Use specified cockroach binary")
const (
stateNew = 1 + iota
stateRunning
stateStopped
stateFailed
)
// TestServer is a helper to run a real cockroach node.
type TestServer struct {
mu sync.RWMutex
state int
baseDir string
pgURL struct {
set chan struct{}
u *url.URL
}
cmd *exec.Cmd
args []string
stdout string
stderr string
stdoutBuf logWriter
stderrBuf logWriter
listeningURLFile string
}
// NewDBForTest creates a new CockroachDB TestServer instance and
// opens a SQL database connection to it. Returns a sql *DB instance a
// shutdown function. The caller is responsible for executing the
// returned shutdown function on exit.
func NewDBForTest(t *testing.T) (*sql.DB, func()) {
return NewDBForTestWithDatabase(t, "")
}
// NewDBForTestWithDatabase creates a new CockroachDB TestServer
// instance and opens a SQL database connection to it. If database is
// specified, the returned connection will explicitly connect to
// it. Returns a sql *DB instance a shutdown function. The caller is
// responsible for executing the returned shutdown function on exit.
func NewDBForTestWithDatabase(t *testing.T, database string) (*sql.DB, func()) {
ts, err := NewTestServer()
if err != nil {
t.Fatal(err)
}
err = ts.Start()
if err != nil {
t.Fatal(err)
}
url := ts.PGURL()
if url == nil {
t.Fatalf("url not found")
}
if len(database) > 0 {
url.Path = database
}
db, err := sql.Open("postgres", url.String())
if err != nil {
t.Fatal(err)
}
if err := ts.WaitForInit(db); err != nil {
t.Fatal(err)
}
return db, func() {
_ = db.Close()
ts.Stop()
}
}
// NewTestServer creates a new TestServer, but does not start it.
// The cockroach binary for your OS and ARCH is downloaded automatically.
// If the download fails, we attempt just call "cockroach", hoping it is
// found in your path.
func NewTestServer() (*TestServer, error) {
var cockroachBinary string
var err error
if len(*customBinary) > 0 {
cockroachBinary = *customBinary
log.Printf("Using custom cockroach binary: %s", cockroachBinary)
} else if cockroachBinary, err = downloadLatestBinary(); err != nil {
log.Printf("Failed to fetch latest binary: %s, attempting to use cockroach binary from your PATH", err)
cockroachBinary = "cockroach"
} else {
log.Printf("Using automatically-downloaded binary: %s", cockroachBinary)
}
// Force "/tmp/" so avoid OSX's really long temp directory names
// which get us over the socket filename length limit.
baseDir, err := ioutil.TempDir("/tmp", "cockroach-testserver")
if err != nil {
return nil, fmt.Errorf("could not create temp directory: %s", err)
}
logDir := filepath.Join(baseDir, "logs")
if err := os.MkdirAll(logDir, 0755); err != nil {
return nil, fmt.Errorf("could not create logs directory: %s: %s", logDir, err)
}
listeningURLFile := filepath.Join(baseDir, "listen-url")
args := []string{
cockroachBinary,
"start",
"--logtostderr",
"--insecure",
"--host=localhost",
"--port=0",
"--http-port=0",
"--store=" + baseDir,
"--listening-url-file=" + listeningURLFile,
}
ts := &TestServer{
state: stateNew,
baseDir: baseDir,
args: args,
stdout: filepath.Join(logDir, "cockroach.stdout"),
stderr: filepath.Join(logDir, "cockroach.stderr"),
listeningURLFile: listeningURLFile,
}
ts.pgURL.set = make(chan struct{})
return ts, nil
}
// Stdout returns the entire contents of the process' stdout.
func (ts *TestServer) Stdout() string {
return ts.stdoutBuf.String()
}
// Stderr returns the entire contents of the process' stderr.
func (ts *TestServer) Stderr() string {
return ts.stderrBuf.String()
}
// PGURL returns the postgres connection URL to reach the started
// cockroach node.
//
// It blocks until the network URL is determined and does not timeout,
// relying instead on test timeouts.
func (ts *TestServer) PGURL() *url.URL {
<-ts.pgURL.set
return ts.pgURL.u
}
func (ts *TestServer) setPGURL(u *url.URL) {
ts.pgURL.u = u
close(ts.pgURL.set)
}
// WaitForInit retries until a connection is successfully established.
func (ts *TestServer) WaitForInit(db *sql.DB) error {
var err error
for i := 0; i < 50; i++ {
if _, err = db.Query("SHOW DATABASES"); err == nil {
return err
}
log.Printf("WaitForInit: %v", err)
time.Sleep(time.Millisecond * 100)
}
return err
}
func (ts *TestServer) pollListeningURLFile() error {
var data []byte
for {
ts.mu.Lock()
state := ts.state
ts.mu.Unlock()
if state != stateRunning {
return fmt.Errorf("server stopped or crashed before listening URL file was available")
}
var err error
data, err = ioutil.ReadFile(ts.listeningURLFile)
if err == nil {
break
} else if !os.IsNotExist(err) {
return fmt.Errorf("unexpected error while reading listening URL file: %v", err)
}
time.Sleep(100 * time.Millisecond)
}
u, err := url.Parse(string(bytes.TrimSpace(data)))
if err != nil {
return fmt.Errorf("failed to parse SQL URL: %v", err)
}
ts.setPGURL(u)
return nil
}
// Start runs the process, returning an error on any problems,
// including being unable to start, but not unexpected failure.
// It should only be called once in the lifetime of a TestServer object.
func (ts *TestServer) Start() error {
ts.mu.Lock()
if ts.state != stateNew {
ts.mu.Unlock()
return errors.New("Start() can only be called once")
}
ts.state = stateRunning
ts.mu.Unlock()
ts.cmd = exec.Command(ts.args[0], ts.args[1:]...)
ts.cmd.Env = []string{"COCKROACH_MAX_OFFSET=1ns"}
if len(ts.stdout) > 0 {
wr, err := newFileLogWriter(ts.stdout)
if err != nil {
return fmt.Errorf("unable to open file %s: %s", ts.stdout, err)
}
ts.stdoutBuf = wr
}
ts.cmd.Stdout = ts.stdoutBuf
if len(ts.stderr) > 0 {
wr, err := newFileLogWriter(ts.stderr)
if err != nil {
return fmt.Errorf("unable to open file %s: %s", ts.stderr, err)
}
ts.stderrBuf = wr
}
ts.cmd.Stderr = ts.stderrBuf
for k, v := range defaultEnv() {
ts.cmd.Env = append(ts.cmd.Env, k+"="+v)
}
err := ts.cmd.Start()
if ts.cmd.Process != nil {
log.Printf("process %d started: %s", ts.cmd.Process.Pid, strings.Join(ts.args, " "))
}
if err != nil {
log.Print(err.Error())
if err := ts.stdoutBuf.Close(); err != nil {
log.Printf("failed to close stdout: %s", err)
}
if err := ts.stderrBuf.Close(); err != nil {
log.Printf("failed to close stderr: %s", err)
}
ts.mu.Lock()
ts.state = stateFailed
ts.mu.Unlock()
return fmt.Errorf("failure starting process: %s", err)
}
go func() {
err := ts.cmd.Wait()
if err := ts.stdoutBuf.Close(); err != nil {
log.Printf("failed to close stdout: %s", err)
}
if err := ts.stderrBuf.Close(); err != nil {
log.Printf("failed to close stderr: %s", err)
}
ps := ts.cmd.ProcessState
sy := ps.Sys().(syscall.WaitStatus)
log.Printf("Process %d exited with status %d: %v", ps.Pid(), sy.ExitStatus(), err)
log.Print(ps.String())
ts.mu.Lock()
if sy.ExitStatus() == 0 {
ts.state = stateStopped
} else {
ts.state = stateFailed
}
ts.mu.Unlock()
}()
go func() {
if err := ts.pollListeningURLFile(); err != nil {
log.Printf("%v", err)
close(ts.pgURL.set)
ts.Stop()
}
}()
return nil
}
// Stop kills the process if it is still running and cleans its directory.
// It should only be called once in the lifetime of a TestServer object.
// Logs fatal if the process has already failed.
func (ts *TestServer) Stop() {
ts.mu.RLock()
defer ts.mu.RUnlock()
if ts.state == stateNew {
log.Fatal("Stop() called, but Start() was never called")
}
if ts.state == stateFailed {
log.Fatalf("Stop() called, but process exited unexpectedly. Stdout:\n%s\nStderr:\n%s\n",
ts.Stdout(), ts.Stderr())
return
}
if ts.state != stateStopped {
// Only call kill if not running. It could have exited properly.
_ = ts.cmd.Process.Kill()
}
// Only cleanup on intentional stops.
_ = os.RemoveAll(ts.baseDir)
}
type logWriter interface {
Write(p []byte) (n int, err error)
String() string
Len() int64
Close() error
}
type fileLogWriter struct {
filename string
file *os.File
}
func newFileLogWriter(file string) (*fileLogWriter, error) {
f, err := os.Create(file)
if err != nil {
return nil, err
}
return &fileLogWriter{
filename: file,
file: f,
}, nil
}
func (w fileLogWriter) Close() error {
return w.file.Close()
}
func (w fileLogWriter) Write(p []byte) (n int, err error) {
return w.file.Write(p)
}
func (w fileLogWriter) String() string {
b, err := ioutil.ReadFile(w.filename)
if err == nil {
return string(b)
}
return ""
}
func (w fileLogWriter) Len() int64 {
s, err := os.Stat(w.filename)
if err == nil {
return s.Size()
}
return 0
}
func defaultEnv() map[string]string {
vars := map[string]string{}
u, err := user.Current()
if err == nil {
if _, ok := vars["USER"]; !ok {
vars["USER"] = u.Username
}
if _, ok := vars["UID"]; !ok {
vars["UID"] = u.Uid
}
if _, ok := vars["GID"]; !ok {
vars["GID"] = u.Gid
}
if _, ok := vars["HOME"]; !ok {
vars["HOME"] = u.HomeDir
}
}
if _, ok := vars["PATH"]; !ok {
vars["PATH"] = os.Getenv("PATH")
}
return vars
}
|