Skip to content

Commit ae92af3

Browse files
committed
testserver: expose BasedirOverride to allow deeper testing of NoFileCleanup
`BasedirOverride` allows user to set testserver base-dir (as opposed to using a random-dir generated by testserver lib. This helps test `NoFileCleanup` better as preserved store-dir's state can now be asserted upon after original testserver's teardown.
1 parent 0276345 commit ae92af3

File tree

4 files changed

+61
-19
lines changed

4 files changed

+61
-19
lines changed

testserver/tenant.go

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ func (ts *testServerImpl) NewTenantServer(proxy bool) (TestServer, error) {
9393
}
9494

9595
secureFlag := "--insecure"
96-
certsDir := filepath.Join(ts.baseDir, "certs")
96+
certsDir := filepath.Join(ts.BaseDir(), "certs")
9797
if ts.serverArgs.secure {
9898
secureFlag = "--certs-dir=" + certsDir
9999
// Create tenant client certificate.
@@ -235,16 +235,15 @@ func (ts *testServerImpl) NewTenantServer(proxy bool) (TestServer, error) {
235235
// TODO(asubiotto): Specify listeningURLFile once we support dynamic
236236
// ports.
237237
listeningURLFile: "",
238-
stdout: filepath.Join(ts.baseDir, logsDirName, fmt.Sprintf("cockroach.tenant.%d.stdout", tenantID)),
239-
stderr: filepath.Join(ts.baseDir, logsDirName, fmt.Sprintf("cockroach.tenant.%d.stderr", tenantID)),
238+
stdout: filepath.Join(ts.BaseDir(), logsDirName, fmt.Sprintf("cockroach.tenant.%d.stdout", tenantID)),
239+
stderr: filepath.Join(ts.BaseDir(), logsDirName, fmt.Sprintf("cockroach.tenant.%d.stderr", tenantID)),
240240
},
241241
}
242242

243243
tenant := &testServerImpl{
244244
serverArgs: ts.serverArgs,
245245
version: ts.version,
246246
serverState: stateNew,
247-
baseDir: ts.baseDir,
248247
nodes: nodes,
249248
}
250249

testserver/testserver.go

Lines changed: 28 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,6 @@ type testServerImpl struct {
152152
version *version.Version
153153
serverArgs testServerArgs
154154
serverState int
155-
baseDir string
156155
pgURL []pgURLChan
157156
initCmd *exec.Cmd
158157
initCmdArgs []string
@@ -241,6 +240,7 @@ type testServerArgs struct {
241240
localityFlags []string
242241
cockroachLogsDir string
243242
noFileCleanup bool // do not clean files at `Stop`
243+
baseDir string
244244
}
245245

246246
// CockroachBinaryPathOpt is a TestServer option that can be passed to
@@ -283,6 +283,15 @@ func NoFileCleanup() TestServerOpt {
283283
}
284284
}
285285

286+
// BasedirOverride is a TestServer option that can be passed to NewTestServer
287+
// to use a given path as testserver base-dir (as opposed to creating a
288+
// temporary one on the fly, which is the default behavior).
289+
func BasedirOverride(baseDirPath string) TestServerOpt {
290+
return func(args *testServerArgs) {
291+
args.baseDir = baseDirPath
292+
}
293+
}
294+
286295
// SetStoreMemSizeOpt is a TestServer option that can be passed to NewTestServer
287296
// to set the proportion of available memory that is allocated
288297
// to the test server.
@@ -437,20 +446,26 @@ var errStoppedInMiddle = errors.New("download stopped in middle")
437446
// If the download fails, we attempt just call "cockroach", hoping it is
438447
// found in your path.
439448
func NewTestServer(opts ...TestServerOpt) (TestServer, error) {
440-
baseDir, err := os.MkdirTemp("", "cockroach-testserver")
441-
if err != nil {
442-
return nil, fmt.Errorf("%s: could not create temp directory: %w", testserverMessagePrefix, err)
443-
}
444-
445449
serverArgs := &testServerArgs{numNodes: 1}
446450
serverArgs.storeMemSize = defaultStoreMemSize
447451
serverArgs.initTimeoutSeconds = defaultInitTimeout
448452
serverArgs.pollListenURLTimeoutSeconds = defaultPollListenURLTimeout
449453
serverArgs.listenAddrHost = defaultListenAddrHost
450-
serverArgs.cockroachLogsDir = baseDir
451454
for _, applyOptToArgs := range opts {
452455
applyOptToArgs(serverArgs)
453456
}
457+
var err error
458+
if serverArgs.baseDir == "" {
459+
baseDir, err := os.MkdirTemp("", "cockroach-testserver")
460+
if err != nil {
461+
return nil, fmt.Errorf("%s: could not create temp directory: %w", testserverMessagePrefix, err)
462+
}
463+
serverArgs.baseDir = baseDir
464+
if serverArgs.cockroachLogsDir == "" {
465+
serverArgs.cockroachLogsDir = baseDir
466+
}
467+
}
468+
454469
log.Printf("cockroach logs directory: %s", serverArgs.cockroachLogsDir)
455470

456471
if serverArgs.cockroachBinary != "" {
@@ -496,7 +511,7 @@ func NewTestServer(opts ...TestServerOpt) (TestServer, error) {
496511
}
497512

498513
mkDir := func(name string) (string, error) {
499-
path := filepath.Join(baseDir, name)
514+
path := filepath.Join(serverArgs.baseDir, name)
500515
if err := os.MkdirAll(path, 0755); err != nil {
501516
return "", fmt.Errorf("%s: could not create %s directory: %s: %w",
502517
testserverMessagePrefix, name, path, err)
@@ -638,7 +653,6 @@ func NewTestServer(opts ...TestServerOpt) (TestServer, error) {
638653
serverArgs: *serverArgs,
639654
version: v,
640655
serverState: stateNew,
641-
baseDir: baseDir,
642656
initCmdArgs: initArgs,
643657
curTenantID: firstTenantID,
644658
nodes: nodes,
@@ -686,7 +700,7 @@ func (ts *testServerImpl) StderrForNode(i int) string {
686700

687701
// BaseDir returns directory StoreOnDiskOpt writes to if used.
688702
func (ts *testServerImpl) BaseDir() string {
689-
return ts.baseDir
703+
return ts.serverArgs.baseDir
690704
}
691705

692706
// PGURL returns the postgres connection URL to reach the started
@@ -887,7 +901,7 @@ func (ts *testServerImpl) Stop() {
887901
}
888902
ts.mu.RLock()
889903

890-
nodeDir := filepath.Join(ts.baseDir, strconv.Itoa(i))
904+
nodeDir := filepath.Join(ts.BaseDir(), strconv.Itoa(i))
891905
if ts.serverArgs.noFileCleanup {
892906
log.Printf("%s: skipping file cleanup of node-dir %s", testserverMessagePrefix, nodeDir)
893907
} else if err := os.RemoveAll(nodeDir); err != nil {
@@ -903,9 +917,9 @@ func (ts *testServerImpl) Stop() {
903917

904918
// Only cleanup on intentional stops.
905919
if ts.serverArgs.noFileCleanup {
906-
log.Printf("%s: skipping file cleanup of base-dir %s", testserverMessagePrefix, ts.baseDir)
920+
log.Printf("%s: skipping file cleanup of base-dir %s", testserverMessagePrefix, ts.BaseDir())
907921
} else {
908-
_ = os.RemoveAll(ts.baseDir)
922+
_ = os.RemoveAll(ts.BaseDir())
909923
}
910924
}
911925

@@ -922,7 +936,7 @@ func (ts *testServerImpl) CockroachInit() error {
922936
// Set the working directory of the cockroach process to our temp folder.
923937
// This stops cockroach from polluting the project directory with _dump
924938
// folders.
925-
ts.initCmd.Dir = ts.baseDir
939+
ts.initCmd.Dir = ts.serverArgs.baseDir
926940

927941
err := ts.initCmd.Start()
928942
if ts.initCmd.Process != nil {

testserver/testserver_test.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,35 @@ func TestRunServer(t *testing.T) {
254254
}
255255
}
256256

257+
func TestBaseDirIsPreservedWhenNoFileCleanupRequested(t *testing.T) {
258+
ts, err := testserver.NewTestServer(
259+
testserver.NoFileCleanup(),
260+
testserver.StoreOnDiskOpt())
261+
require.NoError(t, err)
262+
baseDir := ts.BaseDir()
263+
264+
db, err := sql.Open("postgres", ts.PGURL().String())
265+
require.NoError(t, err)
266+
267+
_, err = db.Exec("create table store_preservation_test(id int primary key)")
268+
require.NoError(t, err)
269+
_, err = db.Exec("insert into store_preservation_test(id) values (123456789)")
270+
require.NoError(t, err)
271+
ts.Stop()
272+
273+
newTs, err := testserver.NewTestServer(
274+
testserver.BasedirOverride(baseDir),
275+
testserver.StoreOnDiskOpt())
276+
require.NoError(t, err)
277+
defer newTs.Stop()
278+
db, err = sql.Open("postgres", newTs.PGURL().String())
279+
require.NoError(t, err)
280+
row := db.QueryRow("select id from store_preservation_test")
281+
retrivedIntVal := 0
282+
require.NoError(t, row.Scan(&retrivedIntVal))
283+
require.Equal(t, 123456789, retrivedIntVal)
284+
}
285+
257286
func TestCockroachBinaryPathOpt(t *testing.T) {
258287
crdbBinary := "doesnotexist"
259288
_, err := testserver.NewTestServer(testserver.CockroachBinaryPathOpt(crdbBinary))

testserver/testservernode.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ func (ts *testServerImpl) StartNode(i int) error {
102102
// Set the working directory of the cockroach process to our temp folder.
103103
// This stops cockroach from polluting the project directory with _dump
104104
// folders.
105-
currCmd.Dir = ts.baseDir
105+
currCmd.Dir = ts.BaseDir()
106106

107107
if len(ts.nodes[i].stdout) > 0 {
108108
wr, err := newFileLogWriter(ts.nodes[i].stdout)

0 commit comments

Comments
 (0)