Debian Codegraph @

testserver/testserver.go

raw symbols SCIP
1 // Copyright 2016 The Cockroach Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12 // implied. See the License for the specific language governing
13 // permissions and limitations under the License.
14
15 // Package testserver provides helpers to run a cockroach binary within tests.
16 // It automatically downloads the latest cockroach binary for your platform
17 // (Linux-amd64 and Darwin-amd64 only for now), or attempts to run "cockroach"
18 // from your PATH.
19 //
20 // A normal invocation is (check err every time):
21 // ts, err := testserver.NewTestServer()
22 // err = ts.Start()
23 // defer ts.Stop()
24 // url := ts.PGURL()
25 //
26 // To use, run as follows:
27 // import "github.com/cockroachdb/cockroach-go/testserver"
28 // import "testing"
29 // import "time"
30 //
31 // func TestRunServer(t *testing.T) {
32 // ts, err := testserver.NewTestServer()
33 // if err != nil {
34 // t.Fatal(err)
35 // }
36 // err := ts.Start()
37 // if err != nil {
38 // t.Fatal(err)
39 // }
40 // defer ts.Stop()
41 //
42 // url := ts.PGURL()
43 // if url == nil {
44 // t.Fatalf("url not found")
45 // }
46 // t.Logf("URL: %s", url.String())
47 //
48 // db, err := sql.Open("postgres", url.String())
49 // if err != nil {
50 // t.Fatal(err)
51 // }
52 // }
53 package testserver
54
55 import (
56 "bytes"
57 "database/sql"
58 "errors"
59 "flag"
60 "fmt"
61 "io/ioutil"
62 "log"
63 "net/url"
64 "os"
65 "os/exec"
66 "os/user"
67 "path/filepath"
68 "strings"
69 "sync"
70 "syscall"
71 "testing"
72 "time"
73
74 // Import postgres driver.
75 _ "github.com/lib/pq"
76 )
77
78 var customBinary = flag.String("cockroach-binary", "", "Use specified cockroach binary")
79
80 const (
81 stateNew = 1 + iota
82 stateRunning
83 stateStopped
84 stateFailed
85 )
86
87 // TestServer is a helper to run a real cockroach node.
88 type TestServer struct {
89 mu sync.RWMutex
90 state int
91 baseDir string
92 pgURL struct {
93 set chan struct{}
94 u *url.URL
95 }
96 cmd *exec.Cmd
97 args []string
98 stdout string
99 stderr string
100 stdoutBuf logWriter
101 stderrBuf logWriter
102 listeningURLFile string
103 }
104
105 // NewDBForTest creates a new CockroachDB TestServer instance and
106 // opens a SQL database connection to it. Returns a sql *DB instance a
107 // shutdown function. The caller is responsible for executing the
108 // returned shutdown function on exit.
109 func NewDBForTest(t *testing.T) (*sql.DB, func()) {
110 return NewDBForTestWithDatabase(t, "")
111 }
112
113 // NewDBForTestWithDatabase creates a new CockroachDB TestServer
114 // instance and opens a SQL database connection to it. If database is
115 // specified, the returned connection will explicitly connect to
116 // it. Returns a sql *DB instance a shutdown function. The caller is
117 // responsible for executing the returned shutdown function on exit.
118 func NewDBForTestWithDatabase(t *testing.T, database string) (*sql.DB, func()) {
119 ts, err := NewTestServer()
120 if err != nil {
121 t.Fatal(err)
122 }
123
124 err = ts.Start()
125 if err != nil {
126 t.Fatal(err)
127 }
128
129 url := ts.PGURL()
130 if url == nil {
131 t.Fatalf("url not found")
132 }
133 if len(database) > 0 {
134 url.Path = database
135 }
136
137 db, err := sql.Open("postgres", url.String())
138 if err != nil {
139 t.Fatal(err)
140 }
141
142 if err := ts.WaitForInit(db); err != nil {
143 t.Fatal(err)
144 }
145
146 return db, func() {
147 _ = db.Close()
148 ts.Stop()
149 }
150 }
151
152 // NewTestServer creates a new TestServer, but does not start it.
153 // The cockroach binary for your OS and ARCH is downloaded automatically.
154 // If the download fails, we attempt just call "cockroach", hoping it is
155 // found in your path.
156 func NewTestServer() (*TestServer, error) {
157 var cockroachBinary string
158 var err error
159 if len(*customBinary) > 0 {
160 cockroachBinary = *customBinary
161 log.Printf("Using custom cockroach binary: %s", cockroachBinary)
162 } else if cockroachBinary, err = downloadLatestBinary(); err != nil {
163 log.Printf("Failed to fetch latest binary: %s, attempting to use cockroach binary from your PATH", err)
164 cockroachBinary = "cockroach"
165 } else {
166 log.Printf("Using automatically-downloaded binary: %s", cockroachBinary)
167 }
168
169 // Force "/tmp/" so avoid OSX's really long temp directory names
170 // which get us over the socket filename length limit.
171 baseDir, err := ioutil.TempDir("/tmp", "cockroach-testserver")
172 if err != nil {
173 return nil, fmt.Errorf("could not create temp directory: %s", err)
174 }
175
176 logDir := filepath.Join(baseDir, "logs")
177 if err := os.MkdirAll(logDir, 0755); err != nil {
178 return nil, fmt.Errorf("could not create logs directory: %s: %s", logDir, err)
179 }
180
181 listeningURLFile := filepath.Join(baseDir, "listen-url")
182
183 args := []string{
184 cockroachBinary,
185 "start",
186 "--logtostderr",
187 "--insecure",
188 "--host=localhost",
189 "--port=0",
190 "--http-port=0",
191 "--store=" + baseDir,
192 "--listening-url-file=" + listeningURLFile,
193 }
194
195 ts := &TestServer{
196 state: stateNew,
197 baseDir: baseDir,
198 args: args,
199 stdout: filepath.Join(logDir, "cockroach.stdout"),
200 stderr: filepath.Join(logDir, "cockroach.stderr"),
201 listeningURLFile: listeningURLFile,
202 }
203 ts.pgURL.set = make(chan struct{})
204 return ts, nil
205 }
206
207 // Stdout returns the entire contents of the process' stdout.
208 func (ts *TestServer) Stdout() string {
209 return ts.stdoutBuf.String()
210 }
211
212 // Stderr returns the entire contents of the process' stderr.
213 func (ts *TestServer) Stderr() string {
214 return ts.stderrBuf.String()
215 }
216
217 // PGURL returns the postgres connection URL to reach the started
218 // cockroach node.
219 //
220 // It blocks until the network URL is determined and does not timeout,
221 // relying instead on test timeouts.
222 func (ts *TestServer) PGURL() *url.URL {
223 <-ts.pgURL.set
224 return ts.pgURL.u
225 }
226
227 func (ts *TestServer) setPGURL(u *url.URL) {
228 ts.pgURL.u = u
229 close(ts.pgURL.set)
230 }
231
232 // WaitForInit retries until a connection is successfully established.
233 func (ts *TestServer) WaitForInit(db *sql.DB) error {
234 var err error
235 for i := 0; i < 50; i++ {
236 if _, err = db.Query("SHOW DATABASES"); err == nil {
237 return err
238 }
239 log.Printf("WaitForInit: %v", err)
240 time.Sleep(time.Millisecond * 100)
241 }
242 return err
243 }
244
245 func (ts *TestServer) pollListeningURLFile() error {
246 var data []byte
247 for {
248 ts.mu.Lock()
249 state := ts.state
250 ts.mu.Unlock()
251 if state != stateRunning {
252 return fmt.Errorf("server stopped or crashed before listening URL file was available")
253 }
254
255 var err error
256 data, err = ioutil.ReadFile(ts.listeningURLFile)
257 if err == nil {
258 break
259 } else if !os.IsNotExist(err) {
260 return fmt.Errorf("unexpected error while reading listening URL file: %v", err)
261 }
262 time.Sleep(100 * time.Millisecond)
263 }
264
265 u, err := url.Parse(string(bytes.TrimSpace(data)))
266 if err != nil {
267 return fmt.Errorf("failed to parse SQL URL: %v", err)
268 }
269 ts.setPGURL(u)
270
271 return nil
272 }
273
274 // Start runs the process, returning an error on any problems,
275 // including being unable to start, but not unexpected failure.
276 // It should only be called once in the lifetime of a TestServer object.
277 func (ts *TestServer) Start() error {
278 ts.mu.Lock()
279 if ts.state != stateNew {
280 ts.mu.Unlock()
281 return errors.New("Start() can only be called once")
282 }
283 ts.state = stateRunning
284 ts.mu.Unlock()
285
286 ts.cmd = exec.Command(ts.args[0], ts.args[1:]...)
287 ts.cmd.Env = []string{"COCKROACH_MAX_OFFSET=1ns"}
288
289 if len(ts.stdout) > 0 {
290 wr, err := newFileLogWriter(ts.stdout)
291 if err != nil {
292 return fmt.Errorf("unable to open file %s: %s", ts.stdout, err)
293 }
294 ts.stdoutBuf = wr
295 }
296 ts.cmd.Stdout = ts.stdoutBuf
297
298 if len(ts.stderr) > 0 {
299 wr, err := newFileLogWriter(ts.stderr)
300 if err != nil {
301 return fmt.Errorf("unable to open file %s: %s", ts.stderr, err)
302 }
303 ts.stderrBuf = wr
304 }
305 ts.cmd.Stderr = ts.stderrBuf
306
307 for k, v := range defaultEnv() {
308 ts.cmd.Env = append(ts.cmd.Env, k+"="+v)
309 }
310
311 err := ts.cmd.Start()
312 if ts.cmd.Process != nil {
313 log.Printf("process %d started: %s", ts.cmd.Process.Pid, strings.Join(ts.args, " "))
314 }
315 if err != nil {
316 log.Print(err.Error())
317 if err := ts.stdoutBuf.Close(); err != nil {
318 log.Printf("failed to close stdout: %s", err)
319 }
320 if err := ts.stderrBuf.Close(); err != nil {
321 log.Printf("failed to close stderr: %s", err)
322 }
323
324 ts.mu.Lock()
325 ts.state = stateFailed
326 ts.mu.Unlock()
327
328 return fmt.Errorf("failure starting process: %s", err)
329 }
330
331 go func() {
332 err := ts.cmd.Wait()
333
334 if err := ts.stdoutBuf.Close(); err != nil {
335 log.Printf("failed to close stdout: %s", err)
336 }
337 if err := ts.stderrBuf.Close(); err != nil {
338 log.Printf("failed to close stderr: %s", err)
339 }
340
341 ps := ts.cmd.ProcessState
342 sy := ps.Sys().(syscall.WaitStatus)
343
344 log.Printf("Process %d exited with status %d: %v", ps.Pid(), sy.ExitStatus(), err)
345 log.Print(ps.String())
346
347 ts.mu.Lock()
348 if sy.ExitStatus() == 0 {
349 ts.state = stateStopped
350 } else {
351 ts.state = stateFailed
352 }
353 ts.mu.Unlock()
354 }()
355
356 go func() {
357 if err := ts.pollListeningURLFile(); err != nil {
358 log.Printf("%v", err)
359 close(ts.pgURL.set)
360 ts.Stop()
361 }
362 }()
363
364 return nil
365 }
366
367 // Stop kills the process if it is still running and cleans its directory.
368 // It should only be called once in the lifetime of a TestServer object.
369 // Logs fatal if the process has already failed.
370 func (ts *TestServer) Stop() {
371 ts.mu.RLock()
372 defer ts.mu.RUnlock()
373
374 if ts.state == stateNew {
375 log.Fatal("Stop() called, but Start() was never called")
376 }
377 if ts.state == stateFailed {
378 log.Fatalf("Stop() called, but process exited unexpectedly. Stdout:\n%s\nStderr:\n%s\n",
379 ts.Stdout(), ts.Stderr())
380 return
381 }
382
383 if ts.state != stateStopped {
384 // Only call kill if not running. It could have exited properly.
385 _ = ts.cmd.Process.Kill()
386 }
387
388 // Only cleanup on intentional stops.
389 _ = os.RemoveAll(ts.baseDir)
390 }
391
392 type logWriter interface {
393 Write(p []byte) (n int, err error)
394 String() string
395 Len() int64
396 Close() error
397 }
398
399 type fileLogWriter struct {
400 filename string
401 file *os.File
402 }
403
404 func newFileLogWriter(file string) (*fileLogWriter, error) {
405 f, err := os.Create(file)
406 if err != nil {
407 return nil, err
408 }
409
410 return &fileLogWriter{
411 filename: file,
412 file: f,
413 }, nil
414 }
415
416 func (w fileLogWriter) Close() error {
417 return w.file.Close()
418 }
419
420 func (w fileLogWriter) Write(p []byte) (n int, err error) {
421 return w.file.Write(p)
422 }
423
424 func (w fileLogWriter) String() string {
425 b, err := ioutil.ReadFile(w.filename)
426 if err == nil {
427 return string(b)
428 }
429 return ""
430 }
431
432 func (w fileLogWriter) Len() int64 {
433 s, err := os.Stat(w.filename)
434 if err == nil {
435 return s.Size()
436 }
437 return 0
438 }
439
440 func defaultEnv() map[string]string {
441 vars := map[string]string{}
442 u, err := user.Current()
443 if err == nil {
444 if _, ok := vars["USER"]; !ok {
445 vars["USER"] = u.Username
446 }
447 if _, ok := vars["UID"]; !ok {
448 vars["UID"] = u.Uid
449 }
450 if _, ok := vars["GID"]; !ok {
451 vars["GID"] = u.Gid
452 }
453 if _, ok := vars["HOME"]; !ok {
454 vars["HOME"] = u.HomeDir
455 }
456 }
457 if _, ok := vars["PATH"]; !ok {
458 vars["PATH"] = os.Getenv("PATH")
459 }
460 return vars
461 }