Skip to content

Commit 0d641dd

Browse files
authored
Merge pull request #3589 from ntnn/dont-panic-outside-of-kcp
Fix sdk/testing panicking when used outside of a kcp clone
2 parents e3a81bc + e11860f commit 0d641dd

File tree

10 files changed

+72
-41
lines changed

10 files changed

+72
-41
lines changed

cmd/sharded-test-server/cache.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ func startCacheServer(ctx context.Context, logDirPath, workingDir, hostIP string
5252
)
5353
cacheWorkingDir := filepath.Join(workingDir, ".kcp-cache")
5454
cachePort := 8012
55-
commandLine := kcptestingserver.Command("cache-server", "cache")
55+
workdir, commandLine := kcptestingserver.Command("cache-server", "cache")
5656
commandLine = append(
5757
commandLine,
5858
fmt.Sprintf("--root-directory=%s", cacheWorkingDir),
@@ -64,6 +64,7 @@ func startCacheServer(ctx context.Context, logDirPath, workingDir, hostIP string
6464
)
6565
fmt.Fprintf(out, "running: %v\n", strings.Join(commandLine, " "))
6666
cmd := exec.CommandContext(ctx, commandLine[0], commandLine[1:]...) //nolint:gosec
67+
cmd.Dir = workdir
6768

6869
logFilePath := filepath.Join(".kcp-cache", "kcp.log")
6970
if logDirPath != "" {

cmd/sharded-test-server/frontproxy.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,8 @@ func startFrontProxy(
131131
}
132132

133133
// run front-proxy command
134-
commandLine := append(kcptestingserver.Command("kcp-front-proxy", "front-proxy"),
134+
workdir, commandLine := kcptestingserver.Command("kcp-front-proxy", "front-proxy")
135+
commandLine = append(commandLine,
135136
"--bind-address="+hostIP,
136137
fmt.Sprintf("--mapping-file=%s", filepath.Join(workDirPath, ".kcp-front-proxy", "mapping.yaml")),
137138
fmt.Sprintf("--root-directory=%s", filepath.Join(workDirPath, ".kcp-front-proxy")),
@@ -147,6 +148,7 @@ func startFrontProxy(
147148
fmt.Fprintf(out, "running: %v\n", strings.Join(commandLine, " "))
148149

149150
cmd := exec.CommandContext(ctx, commandLine[0], commandLine[1:]...) //nolint:gosec
151+
cmd.Dir = workdir
150152

151153
logFilePath := filepath.Join(workDirPath, ".kcp-front-proxy", "proxy.log")
152154
if logDirPath != "" {

cmd/sharded-test-server/virtual.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,7 @@ func (v *VirtualWorkspace) start(ctx context.Context) error {
188188
auditFilePath = filepath.Join(v.logDirPath, fmt.Sprintf("kcp-virtual-workspaces-%d-audit.log", v.index))
189189
}
190190

191-
commandLine := kcptestingserver.Command("virtual-workspaces", strings.ToLower(prefix))
191+
workdir, commandLine := kcptestingserver.Command("virtual-workspaces", strings.ToLower(prefix))
192192
commandLine = append(commandLine, v.args...)
193193
commandLine = append(
194194
commandLine,
@@ -202,6 +202,7 @@ func (v *VirtualWorkspace) start(ctx context.Context) error {
202202
fmt.Fprintf(out, "running: %v\n", strings.Join(commandLine, " "))
203203

204204
cmd := exec.CommandContext(ctx, commandLine[0], commandLine[1:]...) //nolint:gosec
205+
cmd.Dir = workdir
205206

206207
if err := os.MkdirAll(filepath.Dir(logFilePath), 0755); err != nil {
207208
return err

cmd/test-server/kcp/shard.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -94,8 +94,7 @@ func (s *Shard) Start(ctx context.Context, quiet bool) error {
9494
}
9595

9696
// setup command
97-
var commandLine []string
98-
commandLine = append(commandLine, kcptestingserver.StartKcpCommand(s.name)...)
97+
workdir, commandLine := kcptestingserver.StartKcpCommand(s.name)
9998
commandLine = append(commandLine, s.args...)
10099
commandLine = append(commandLine,
101100
"--root-directory", s.runtimeDir,
@@ -114,6 +113,7 @@ func (s *Shard) Start(ctx context.Context, quiet bool) error {
114113
fmt.Fprintf(out, "running: %v\n", strings.Join(commandLine, " "))
115114

116115
cmd := exec.CommandContext(ctx, commandLine[0], commandLine[1:]...) //nolint:gosec
116+
cmd.Dir = workdir
117117
if err := os.MkdirAll(filepath.Dir(s.logFilePath), 0755); err != nil {
118118
return err
119119
}

sdk/testing/helpers/repo.go

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ import (
2424
)
2525

2626
// RepositoryDir returns the absolute path of kcp-dev/kcp repository on disk.
27-
func RepositoryDir() string {
27+
func RepositoryDir() (string, error) {
2828
// Caller(0) returns the path to the calling test file rather than the path to this framework file. That
2929
// precludes assuming how many directories are between the file and the repo root. It's therefore necessary
3030
// to search in the hierarchy for an indication of a path that looks like the repo root.
@@ -35,18 +35,23 @@ func RepositoryDir() string {
3535
if _, err := os.Stat(filepath.Join(currentDir, ".git")); err == nil {
3636
break
3737
} else if errors.Is(err, os.ErrNotExist) {
38+
preDir := currentDir
3839
currentDir, err = filepath.Abs(filepath.Join(currentDir, ".."))
3940
if err != nil {
40-
panic(err)
41+
return "", err
42+
}
43+
if preDir == currentDir {
44+
return "", errors.New("could not find kcp repository root")
4145
}
4246
} else {
43-
panic(err)
47+
return "", err
4448
}
4549
}
46-
return currentDir
50+
return currentDir, nil
4751
}
4852

4953
// RepositoryBinDir returns the absolute path of <repo-dir>/bin. That's where `make build` produces our binaries.
50-
func RepositoryBinDir() string {
51-
return filepath.Join(RepositoryDir(), "bin")
54+
func RepositoryBinDir() (string, error) {
55+
repoDir, err := RepositoryDir()
56+
return filepath.Join(repoDir, "bin"), err
5257
}

sdk/testing/server/fixture.go

Lines changed: 31 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -191,42 +191,43 @@ func newKcpServer(t TestingT, cfg Config) (*kcpServer, error) {
191191
return s, nil
192192
}
193193

194-
// StartKcpCommand returns the string tokens required to start kcp in
195-
// the currently configured mode (direct or via `go run`).
196-
func StartKcpCommand(identity string) []string {
197-
command := Command("kcp", identity)
198-
return append(command, "start")
194+
// StartKcpCommand returns the work dir and string tokens required to
195+
// start kcp in the currently configured mode (direct or via `go run`).
196+
func StartKcpCommand(identity string) (string, []string) {
197+
workdir, command := Command("kcp", identity)
198+
return workdir, append(command, "start")
199199
}
200200

201-
// Command returns the string tokens required to start
202-
// the given executable in the currently configured mode (direct or
203-
// via `go run`).
204-
func Command(executableName, identity string) []string {
205-
if env.RunDelveEnvSet() {
206-
cmdPath := filepath.Join(kcptestinghelpers.RepositoryDir(), "cmd", executableName)
207-
return []string{"dlv", "debug", "--api-version=2", "--headless", fmt.Sprintf("--listen=unix:dlv-%s.sock", identity), cmdPath, "--"}
201+
// Command returns the work dir and string tokens required to start the
202+
// given executable in the currently configured mode (direct or via `go
203+
// run`).
204+
func Command(executableName, identity string) (string, []string) {
205+
if env.NoGoRunEnvSet() {
206+
return "", []string{executableName}
208207
}
209208

210-
// are we inside of the kcp repository?
211-
repo := kcptestinghelpers.RepositoryDir()
212-
wd, err := os.Getwd()
209+
// Check if this is a clone of the kcp repository. If not return the
210+
// executable as is, expecting the user to have it in PATH.
211+
repo, err := kcptestinghelpers.RepositoryDir()
213212
if err != nil {
214-
panic(err)
213+
return "", []string{executableName}
215214
}
216-
inKcp := strings.HasPrefix(wd, repo+"/")
217215

218-
binary := executableName
219-
if binDir := os.Getenv(kcpBinariesDirEnvDir); binDir == "" && inKcp {
220-
binary = filepath.Join(kcptestinghelpers.RepositoryBinDir(), executableName)
221-
} else if binDir != "" {
222-
binary = filepath.Join(binDir, executableName)
216+
cmdDir := filepath.Join("cmd", executableName)
217+
fullPath := filepath.Join(repo, cmdDir)
218+
cmdDir = "./" + cmdDir
219+
220+
if _, err := os.Stat(fullPath); os.IsNotExist(err) {
221+
// The command dir (e.g. $repo/cmd/kcp) does not exist, default
222+
// to the executable name and expect it to be in PATH.
223+
return "", []string{executableName}
223224
}
224225

225-
if env.NoGoRunEnvSet() || !inKcp {
226-
return []string{binary}
226+
if env.RunDelveEnvSet() {
227+
return repo, []string{"dlv", "debug", "--api-version=2", "--headless", fmt.Sprintf("--listen=unix:dlv-%s.sock", identity), cmdDir, "--"}
227228
}
228229

229-
return []string{"go", "run", filepath.Join(repo, "cmd", executableName)}
230+
return repo, []string{"go", "run", cmdDir}
230231
}
231232

232233
// Run runs the kcp server while the parent context is active. This call is not blocking,
@@ -301,13 +302,17 @@ func runExternal(ctx context.Context, t TestingT, cfg Config) (<-chan struct{},
301302
return nil, fmt.Errorf("failed to build kcp args: %w", err)
302303
}
303304

304-
commandLine := append(StartKcpCommand("KCP"), args...)
305+
workdir, commandLine := StartKcpCommand("KCP")
306+
commandLine = append(commandLine, args...)
305307

306308
t.Logf("running: %v", strings.Join(commandLine, " "))
307309

308310
// NOTE: do not use exec.CommandContext here. That method issues a SIGKILL when the context is done, and we
309311
// want to issue SIGTERM instead, to give the server a chance to shut down cleanly.
310312
cmd := exec.Command(commandLine[0], commandLine[1:]...) //nolint:gosec // G204: This is a test utility with controlled inputs
313+
if workdir != "" {
314+
cmd.Dir = workdir
315+
}
311316

312317
// Create a new process group for the child/forked process (which is either 'go run ...' or just 'kcp
313318
// ...'). This is necessary so the SIGTERM we send to terminate the kcp server works even with the

sdk/testing/server/metrics.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,9 @@ func scrapeMetricsForServer(t TestingT, srv RunningServer) {
7474

7575
ctx, cancel := context.WithTimeout(context.Background(), wait.ForeverTestTimeout)
7676
defer cancel()
77-
require.NoError(t, ScrapeMetrics(ctx, srv.RootShardSystemMasterBaseConfig(t), promUrl, kcptestinghelpers.RepositoryDir(), jobName, filepath.Join(srv.CADirectory(), "apiserver.crt"), labels))
77+
repoDir, err := kcptestinghelpers.RepositoryDir()
78+
require.NoError(t, err)
79+
require.NoError(t, ScrapeMetrics(ctx, srv.RootShardSystemMasterBaseConfig(t), promUrl, repoDir, jobName, filepath.Join(srv.CADirectory(), "apiserver.crt"), labels))
7880
}
7981

8082
func ScrapeMetrics(ctx context.Context, cfg *rest.Config, promUrl, promCfgDir, jobName, caFile string, labels map[string]string) error {

test/e2e/framework/flags.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,11 @@ func complete() {
4141
panic(errors.New("only one of --use-default-kcp-server and --kcp-kubeconfig should be set"))
4242
}
4343
if testConfig.useDefaultKCPServer {
44-
testConfig.kcpKubeconfig = filepath.Join(kcptestinghelpers.RepositoryDir(), ".kcp", "admin.kubeconfig")
44+
repo, err := kcptestinghelpers.RepositoryDir()
45+
if err != nil {
46+
panic(err)
47+
}
48+
testConfig.kcpKubeconfig = filepath.Join(repo, ".kcp", "admin.kubeconfig")
4549
}
4650
if len(testConfig.kcpKubeconfig) > 0 && len(testConfig.shardKubeconfigs) == 0 {
4751
testConfig.shardKubeconfigs = map[string]string{corev1alpha1.RootShard: testConfig.kcpKubeconfig}

test/e2e/framework/kcp.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,16 @@ import (
2525
)
2626

2727
// DefaultTokenAuthFile returns the default auth tokens file.
28-
var DefaultTokenAuthFile = filepath.Join(kcptestinghelpers.RepositoryDir(), "test", "e2e", "framework", "auth-tokens.csv")
28+
var DefaultTokenAuthFile string
2929

3030
func init() {
31+
repo, err := kcptestinghelpers.RepositoryDir()
32+
if err != nil {
33+
panic(err)
34+
}
35+
36+
DefaultTokenAuthFile = filepath.Join(repo, "test", "e2e", "framework", "auth-tokens.csv")
37+
3138
var args []string
3239
args = append(args, "--token-auth-file", DefaultTokenAuthFile) //nolint:gocritic // no.
3340
args = append(args, "--feature-gates=WorkspaceMounts=true,CacheAPIs=true,WorkspaceAuthentication=true")

test/e2e/framework/kubectl.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,11 @@ func KcpCliPluginCommand() []string {
4040
if env.NoGoRunEnvSet() {
4141
return []string{"kubectl", "kcp"}
4242
} else {
43-
cmdPath := filepath.Join(kcptestinghelpers.RepositoryDir(), "cmd", "kubectl-kcp")
43+
repo, err := kcptestinghelpers.RepositoryDir()
44+
if err != nil {
45+
panic(err)
46+
}
47+
cmdPath := filepath.Join(repo, "cmd", "kubectl-kcp")
4448
return []string{"go", "run", cmdPath}
4549
}
4650
}

0 commit comments

Comments
 (0)