fix(cmd): return non-zero exit status on config load, TUI, and service startup failures

- Route pre-configuration startup logs to stderr and return exit status 1 from a deferred-safe run helper when config loading, store bootstrap, or TUI execution fails.
- Propagate synchronous proxy service build and runtime errors from StartServiceWithPluginHost to stderr and exit status 1 while preserving exit status 0 on graceful context cancellation.
- Add subprocess and unit regression tests covering missing config, malformed YAML, TUI failures, occupied ports, and interrupt shutdown.

Closes: #7459
Co-authored-by: Dylan <1990016@gmail.com>
Co-authored-by: lzt404 <2596933790@qq.com>
This commit is contained in:
Luis Pater
2026-11-12 03:23:19 +08:00
parent c3a6c7416c
commit f93d5cba95
4 changed files with 350 additions and 38 deletions

View File

@@ -72,6 +72,20 @@ func shouldEnableExampleAPIKeySafeMode(cfg *config.Config, commandMode, tuiMode,
// It parses command-line flags, loads configuration, and starts the appropriate
// service based on the provided flags (login, codex-login, or server mode).
func main() {
os.Exit(run())
}
func logStartupErrorf(format string, args ...any) {
if log.StandardLogger().Out != os.Stderr {
_, _ = fmt.Fprintf(os.Stderr, format+"\n", args...)
}
log.Errorf(format, args...)
}
// run finishes deferred cleanup before main applies the process exit status.
func run() (exitStatus int) {
log.SetOutput(os.Stderr)
if len(os.Args) > 1 && os.Args[1] == "discover" {
discoverFlags := flag.NewFlagSet("discover", flag.ExitOnError)
timeoutSec := discoverFlags.Int("timeout", 3, "Discovery timeout in seconds")
@@ -94,7 +108,7 @@ func main() {
Include: include,
Exclude: exclude,
})
os.Exit(code)
return code
}
// For legacy --discover-json flag or JSON requests, keep stdout clean
@@ -214,7 +228,7 @@ func main() {
Include: include,
Exclude: exclude,
})
os.Exit(code)
return code
}
// Core application variables.
@@ -251,7 +265,7 @@ func main() {
wd, err := os.Getwd()
if err != nil {
log.Errorf("failed to get working directory: %v", err)
return
return 1
}
// Load environment variables from .env if present.
@@ -349,7 +363,7 @@ func main() {
cancelHome()
if errHomeCfg != nil {
log.Errorf("invalid -home-jwt: %v", errHomeCfg)
return
return 1
}
if homeDisableClusterDiscovery {
homeCfg.DisableClusterDiscovery = true
@@ -366,13 +380,13 @@ func main() {
cancelHomeConfig()
if errGetConfig != nil {
log.Errorf("failed to fetch config from home: %v", errGetConfig)
return
return 1
}
parsed, errParseConfig := config.ParseConfigBytes(raw)
if errParseConfig != nil {
log.Errorf("failed to parse config payload from home: %v", errParseConfig)
return
return 1
}
if parsed == nil {
parsed = &config.Config{}
@@ -429,7 +443,7 @@ func main() {
}
}
if errHomePlugins != nil {
return
return 1
}
cfg = parsed
@@ -459,14 +473,14 @@ func main() {
cancel()
if err != nil {
log.Errorf("failed to initialize postgres token store: %v", err)
return
return 1
}
examplePath := filepath.Join(wd, "config.example.yaml")
ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second)
if errBootstrap := pgStoreInst.Bootstrap(ctx, examplePath); errBootstrap != nil {
cancel()
log.Errorf("failed to bootstrap postgres-backed config: %v", errBootstrap)
return
return 1
}
cancel()
configFilePath = pgStoreInst.ConfigPath()
@@ -490,7 +504,7 @@ func main() {
parsed, errParse := url.Parse(resolvedEndpoint)
if errParse != nil {
log.Errorf("failed to parse object store endpoint %q: %v", objectStoreEndpoint, errParse)
return
return 1
}
switch strings.ToLower(parsed.Scheme) {
case "http":
@@ -499,11 +513,11 @@ func main() {
useSSL = true
default:
log.Errorf("unsupported object store scheme %q (only http and https are allowed)", parsed.Scheme)
return
return 1
}
if parsed.Host == "" {
log.Errorf("object store endpoint %q is missing host information", objectStoreEndpoint)
return
return 1
}
resolvedEndpoint = parsed.Host
if parsed.Path != "" && parsed.Path != "/" {
@@ -523,14 +537,14 @@ func main() {
objectStoreInst, err = store.NewObjectTokenStore(objCfg)
if err != nil {
log.Errorf("failed to initialize object token store: %v", err)
return
return 1
}
examplePath := filepath.Join(wd, "config.example.yaml")
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
if errBootstrap := objectStoreInst.Bootstrap(ctx, examplePath); errBootstrap != nil {
cancel()
log.Errorf("failed to bootstrap object-backed config: %v", errBootstrap)
return
return 1
}
cancel()
configFilePath = objectStoreInst.ConfigPath()
@@ -556,7 +570,7 @@ func main() {
gitStoreInst.SetBaseDir(authDir)
if errRepo := gitStoreInst.EnsureRepository(); errRepo != nil {
log.Errorf("failed to prepare git token store: %v", errRepo)
return
return 1
}
configFilePath = gitStoreInst.ConfigPath()
if configFilePath == "" {
@@ -566,20 +580,20 @@ func main() {
examplePath := filepath.Join(wd, "config.example.yaml")
if _, errExample := os.Stat(examplePath); errExample != nil {
log.Errorf("failed to find template config file: %v", errExample)
return
return 1
}
if errCopy := misc.CopyConfigTemplate(examplePath, configFilePath); errCopy != nil {
log.Errorf("failed to bootstrap git-backed config: %v", errCopy)
return
return 1
}
if errCommit := persistSeededConfig(context.Background(), configFilePath, gitStoreInst.PersistConfig); errCommit != nil {
log.Errorf("failed to commit initial git-backed config: %v", errCommit)
return
return 1
}
log.Infof("git-backed config initialized from template: %s", configFilePath)
} else if statErr != nil {
log.Errorf("failed to inspect git-backed config: %v", statErr)
return
return 1
}
cfg, err = config.LoadConfigOptional(configFilePath, isCloudDeploy)
if err == nil {
@@ -593,14 +607,14 @@ func main() {
wd, err = os.Getwd()
if err != nil {
log.Errorf("failed to get working directory: %v", err)
return
return 1
}
configFilePath = filepath.Join(wd, "config.yaml")
cfg, err = config.LoadConfigOptional(configFilePath, isCloudDeploy)
}
if err != nil {
log.Errorf("failed to load config: %v", err)
return
return 1
}
if cfg == nil {
cfg = &config.Config{}
@@ -637,7 +651,7 @@ func main() {
if err = logging.ConfigureLogOutput(cfg); err != nil {
log.Errorf("failed to configure log output: %v", err)
return
return 1
}
log.Infof("CLIProxyAPI Version: %s, Commit: %s, BuiltAt: %s", buildinfo.Version, buildinfo.Commit, buildinfo.BuildDate)
@@ -646,8 +660,8 @@ func main() {
util.SetLogLevel(cfg)
if resolvedAuthDir, errResolveAuthDir := util.ResolveAuthDir(cfg.AuthDir); errResolveAuthDir != nil {
log.Errorf("failed to resolve auth directory: %v", errResolveAuthDir)
return
logStartupErrorf("failed to resolve auth directory: %v", errResolveAuthDir)
return 1
} else {
cfg.AuthDir = resolvedAuthDir
}
@@ -690,13 +704,13 @@ func main() {
errHomePluginLoad := homeplugins.MarkLoadResults(&homePluginSyncReport, pluginHost)
errReportPlugins := home.ReportPluginStatus(context.Background(), homeClient, cfg.Home.NodeID, homePluginSyncReport)
if errHomePluginLoad != nil {
log.Errorf("failed to load home plugins: %v", errHomePluginLoad)
logStartupErrorf("failed to load home plugins: %v", errHomePluginLoad)
}
if errReportPlugins != nil {
log.Warnf("failed to report home plugin load status: %v", errReportPlugins)
}
if errHomePluginLoad != nil {
return
return 1
}
}
if homeClient != nil {
@@ -707,10 +721,7 @@ func main() {
}
if pluginHost.HasTriggeredCommandLineFlags() {
if exitCode, handled := pluginHost.ExecuteCommandLine(context.Background(), os.Args[0], os.Args[1:], configFilePath, flag.CommandLine); handled {
if exitCode != 0 {
os.Exit(exitCode)
}
return
return exitCode
}
}
@@ -749,7 +760,7 @@ func main() {
if isCloudDeploy && !configFileExists {
// No config file available, just wait for shutdown
cmd.WaitForCloudDeploy()
return
return 0
}
if localModel && (!tuiMode || standalone) {
log.Info("Local model mode: using embedded catalogs unless an explicit catalog source is configured")
@@ -795,11 +806,23 @@ func main() {
ready := false
backoff := 100 * time.Millisecond
for i := 0; i < 30; i++ {
select {
case <-done:
i = 30
default:
}
if i >= 30 {
break
}
if _, errGetConfig := client.GetConfig(); errGetConfig == nil {
ready = true
break
}
time.Sleep(backoff)
select {
case <-done:
i = 30
case <-time.After(backoff):
}
if backoff < time.Second {
backoff = time.Duration(float64(backoff) * 1.5)
}
@@ -810,24 +833,30 @@ func main() {
cancel()
<-done
fmt.Fprintf(os.Stderr, "TUI error: embedded server is not ready\n")
return
return 1
}
var errTUI error
if errRun := tui.Run(cfg.Port, password, hook, origStdout); errRun != nil {
restoreIO()
fmt.Fprintf(os.Stderr, "TUI error: %v\n", errRun)
errTUI = errRun
} else {
restoreIO()
}
cancel()
<-done
if errTUI != nil {
return 1
}
} else {
// Default TUI mode: pure management client.
// The proxy server must already be running (locally or remotely).
baseURL := resolveManagementBaseURL(managementBaseURL, cfg)
if errRun := tui.RunWithBaseURL(baseURL, password, nil, os.Stdout); errRun != nil {
fmt.Fprintf(os.Stderr, "TUI error: %v\n", errRun)
return 1
}
}
} else {
@@ -835,9 +864,15 @@ func main() {
managementasset.StartAutoUpdater(context.Background(), configFilePath)
misc.StartAntigravityVersionUpdater(context.Background())
registry.SetLocalModelCatalogs(localModel)
cmd.StartServiceWithPluginHost(cfg, configFilePath, password, pluginHost, serverOptions...)
if errStart := cmd.StartServiceWithPluginHost(cfg, configFilePath, password, pluginHost, serverOptions...); errStart != nil {
if log.StandardLogger().Out != os.Stderr {
_, _ = fmt.Fprintf(os.Stderr, "proxy service error: %v\n", errStart)
}
return 1
}
}
}
return 0
}
// resolveManagementBaseURL determines the management API base URL for TUI client mode.

View File

@@ -0,0 +1,256 @@
package main
import (
"bytes"
"context"
"flag"
"fmt"
"net"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"testing"
"time"
)
const serverExitHelperEnv = "CLIPROXY_TEST_SERVER_EXIT_HELPER"
func TestServerExitHelper(t *testing.T) {
if os.Getenv(serverExitHelperEnv) != "1" {
return
}
for index, arg := range os.Args {
if arg == "--" {
os.Args = append([]string{os.Args[0]}, os.Args[index+1:]...)
flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
main()
return
}
}
t.Fatal("missing server arguments")
}
func newServerExitCommand(t *testing.T, dir string, args ...string) (*exec.Cmd, *bytes.Buffer, *bytes.Buffer) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
t.Cleanup(cancel)
cmdArgs := append([]string{"-test.run=^TestServerExitHelper$", "--"}, args...)
command := exec.CommandContext(ctx, os.Args[0], cmdArgs...)
command.Dir = dir
// Isolate from host store environment variables and prevent external network calls.
command.Env = append(os.Environ(),
serverExitHelperEnv+"=1",
"HOME_JWT=", "home_jwt=",
"PGSTORE_DSN=", "pgstore_dsn=",
"GITSTORE_GIT_URL=", "gitstore_git_url=",
"OBJECTSTORE_ENDPOINT=", "objectstore_endpoint=",
"DEPLOY=", "WRITABLE_PATH=", "writable_path=",
"HTTP_PROXY=http://127.0.0.1:1", "HTTPS_PROXY=http://127.0.0.1:1",
"NO_PROXY=127.0.0.1,localhost",
)
stdout := &bytes.Buffer{}
stderr := &bytes.Buffer{}
command.Stdout = stdout
command.Stderr = stderr
return command, stdout, stderr
}
func writeTestServerConfig(t *testing.T, dir string, port int) string {
t.Helper()
configPath := filepath.Join(dir, "config.yaml")
content := fmt.Sprintf(
"config-version: 8\nserver:\n host: 127.0.0.1\n port: %d\nmanagement:\n secret-key: \"$2a$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy\"\n disable-control-panel: true\noauth:\n auth-dir: %q\naccess:\n api-keys: [test-server-exit-key]\n",
port,
filepath.Join(dir, "auths"),
)
if errWrite := os.WriteFile(configPath, []byte(content), 0o600); errWrite != nil {
t.Fatal(errWrite)
}
return configPath
}
func TestMissingConfigExitsWithFailure(t *testing.T) {
dir := t.TempDir()
missingPath := filepath.Join(dir, "missing.yaml")
command, stdout, stderr := newServerExitCommand(t, dir, "--config", missingPath)
errRun := command.Run()
if command.ProcessState == nil || command.ProcessState.ExitCode() != 1 {
t.Fatalf("expected exit code 1 for missing config, got err=%v exit=%d\nstdout:\n%s\nstderr:\n%s",
errRun, command.ProcessState.ExitCode(), stdout.String(), stderr.String())
}
if !strings.Contains(stderr.String(), "failed to load config") {
t.Fatalf("expected config load error on stderr, got:\nstdout:\n%s\nstderr:\n%s", stdout.String(), stderr.String())
}
if strings.Contains(stdout.String(), "failed to load config") {
t.Fatalf("did not expect config load error on stdout, got:\nstdout:\n%s\nstderr:\n%s", stdout.String(), stderr.String())
}
}
func TestMalformedConfigExitsWithFailure(t *testing.T) {
dir := t.TempDir()
invalidPath := filepath.Join(dir, "invalid.yaml")
if errWrite := os.WriteFile(invalidPath, []byte("routing: [\n"), 0o600); errWrite != nil {
t.Fatal(errWrite)
}
command, stdout, stderr := newServerExitCommand(t, dir, "--config", invalidPath)
errRun := command.Run()
if command.ProcessState == nil || command.ProcessState.ExitCode() != 1 {
t.Fatalf("expected exit code 1 for malformed config, got err=%v exit=%d\nstdout:\n%s\nstderr:\n%s",
errRun, command.ProcessState.ExitCode(), stdout.String(), stderr.String())
}
if !strings.Contains(stderr.String(), "failed to load config") {
t.Fatalf("expected config load error on stderr, got:\nstdout:\n%s\nstderr:\n%s", stdout.String(), stderr.String())
}
if strings.Contains(stdout.String(), "failed to load config") || strings.Contains(stdout.String(), "failed to parse plugin bootstrap config") {
t.Fatalf("did not expect config error/warn diagnostics on stdout, got:\nstdout:\n%s\nstderr:\n%s", stdout.String(), stderr.String())
}
}
func TestTUIClientFailureExitsWithFailure(t *testing.T) {
dir := t.TempDir()
configPath := writeTestServerConfig(t, dir, 18317)
command, stdout, stderr := newServerExitCommand(t, dir, "--config", configPath, "--tui")
errRun := command.Run()
if command.ProcessState == nil || command.ProcessState.ExitCode() != 1 {
t.Fatalf("expected exit code 1 for TUI failure, got err=%v exit=%d\nstdout:\n%s\nstderr:\n%s",
errRun, command.ProcessState.ExitCode(), stdout.String(), stderr.String())
}
if !strings.Contains(stderr.String(), "TUI error:") {
t.Fatalf("expected TUI error on stderr, got:\nstdout:\n%s\nstderr:\n%s", stdout.String(), stderr.String())
}
}
func TestTUIStandaloneEmbeddedServerNotReadyExitsWithFailure(t *testing.T) {
listener, errListen := net.Listen("tcp", "127.0.0.1:0")
if errListen != nil {
t.Fatal(errListen)
}
t.Cleanup(func() {
_ = listener.Close()
})
go func() {
for {
conn, errAccept := listener.Accept()
if errAccept != nil {
return
}
_ = conn.Close()
}
}()
dir := t.TempDir()
configPath := writeTestServerConfig(t, dir, listener.Addr().(*net.TCPAddr).Port)
command, stdout, stderr := newServerExitCommand(t, dir, "--config", configPath, "--tui", "--standalone", "--local-model")
errRun := command.Run()
if command.ProcessState == nil || command.ProcessState.ExitCode() != 1 {
t.Fatalf("expected exit code 1 when standalone embedded server is not ready, got err=%v exit=%d\nstdout:\n%s\nstderr:\n%s",
errRun, command.ProcessState.ExitCode(), stdout.String(), stderr.String())
}
if !strings.Contains(stderr.String(), "TUI error: embedded server is not ready") {
t.Fatalf("expected embedded server not ready error on stderr, got:\nstdout:\n%s\nstderr:\n%s", stdout.String(), stderr.String())
}
}
func TestTUIStandaloneFailureExitsWithFailure(t *testing.T) {
listener, errListen := net.Listen("tcp", "127.0.0.1:0")
if errListen != nil {
t.Fatal(errListen)
}
port := listener.Addr().(*net.TCPAddr).Port
if errClose := listener.Close(); errClose != nil {
t.Fatal(errClose)
}
dir := t.TempDir()
configPath := writeTestServerConfig(t, dir, port)
command, stdout, stderr := newServerExitCommand(t, dir, "--config", configPath, "--tui", "--standalone", "--local-model")
errRun := command.Run()
if command.ProcessState == nil || command.ProcessState.ExitCode() != 1 {
t.Fatalf("expected exit code 1 for standalone TUI failure, got err=%v exit=%d\nstdout:\n%s\nstderr:\n%s",
errRun, command.ProcessState.ExitCode(), stdout.String(), stderr.String())
}
if !strings.Contains(stderr.String(), "TUI error:") {
t.Fatalf("expected TUI error on stderr, got:\nstdout:\n%s\nstderr:\n%s", stdout.String(), stderr.String())
}
}
func TestServerOccupiedPortExitsWithFailure(t *testing.T) {
listener, errListen := net.Listen("tcp", "127.0.0.1:0")
if errListen != nil {
t.Fatal(errListen)
}
t.Cleanup(func() {
_ = listener.Close()
})
dir := t.TempDir()
configPath := writeTestServerConfig(t, dir, listener.Addr().(*net.TCPAddr).Port)
command, stdout, stderr := newServerExitCommand(t, dir, "--config", configPath, "--local-model")
errRun := command.Run()
if command.ProcessState == nil || command.ProcessState.ExitCode() != 1 {
t.Fatalf("expected exit code 1 for occupied port, got err=%v exit=%d\nstdout:\n%s\nstderr:\n%s",
errRun, command.ProcessState.ExitCode(), stdout.String(), stderr.String())
}
if !strings.Contains(stderr.String(), "failed to start HTTP server") {
t.Fatalf("expected HTTP bind failure on stderr, got:\nstdout:\n%s\nstderr:\n%s", stdout.String(), stderr.String())
}
}
func TestServerInterruptExitsSuccessfully(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("os.Interrupt cannot be sent to a process on Windows")
}
listener, errListen := net.Listen("tcp", "127.0.0.1:0")
if errListen != nil {
t.Fatal(errListen)
}
port := listener.Addr().(*net.TCPAddr).Port
if errClose := listener.Close(); errClose != nil {
t.Fatal(errClose)
}
dir := t.TempDir()
configPath := writeTestServerConfig(t, dir, port)
command, stdout, stderr := newServerExitCommand(t, dir, "--config", configPath, "--local-model")
if errStart := command.Start(); errStart != nil {
t.Fatal(errStart)
}
t.Cleanup(func() {
_ = command.Process.Kill()
})
done := make(chan error, 1)
go func() {
done <- command.Wait()
}()
deadline := time.NewTimer(10 * time.Second)
defer deadline.Stop()
ticker := time.NewTicker(10 * time.Millisecond)
defer ticker.Stop()
for {
connection, errDial := net.DialTimeout("tcp", net.JoinHostPort("127.0.0.1", strconv.Itoa(port)), 100*time.Millisecond)
if errDial == nil {
_ = connection.Close()
break
}
select {
case errWait := <-done:
t.Fatalf("server exited before listening: %v\nstdout:\n%s\nstderr:\n%s", errWait, stdout.String(), stderr.String())
case <-deadline.C:
t.Fatal("server did not start listening")
case <-ticker.C:
}
}
if errSignal := command.Process.Signal(os.Interrupt); errSignal != nil {
t.Fatal(errSignal)
}
if errWait := <-done; errWait != nil {
t.Fatalf("expected a successful interrupt shutdown, got %v\nstdout:\n%s\nstderr:\n%s", errWait, stdout.String(), stderr.String())
}
}

View File

@@ -25,12 +25,13 @@ import (
// - cfg: The application configuration
// - configPath: The path to the configuration file
// - localPassword: Optional password accepted for local management requests
func StartService(cfg *config.Config, configPath string, localPassword string) {
StartServiceWithPluginHost(cfg, configPath, localPassword, nil)
func StartService(cfg *config.Config, configPath string, localPassword string) error {
return StartServiceWithPluginHost(cfg, configPath, localPassword, nil)
}
// StartServiceWithPluginHost builds and runs the proxy service with a shared plugin host.
func StartServiceWithPluginHost(cfg *config.Config, configPath string, localPassword string, host *pluginhost.Host, serverOptions ...api.ServerOption) {
// Startup and runtime failures are returned after cleanup; cancellation is a normal shutdown.
func StartServiceWithPluginHost(cfg *config.Config, configPath string, localPassword string, host *pluginhost.Host, serverOptions ...api.ServerOption) error {
builder := cliproxy.NewBuilder().
WithConfig(cfg).
WithConfigPath(configPath).
@@ -58,13 +59,15 @@ func StartServiceWithPluginHost(cfg *config.Config, configPath string, localPass
service, err := builder.Build()
if err != nil {
log.Errorf("failed to build proxy service: %v", err)
return
return err
}
err = service.Run(runCtx)
if err != nil && !errors.Is(err, context.Canceled) {
log.Errorf("proxy service exited with error: %v", err)
return err
}
return nil
}
// StartServiceBackground starts the proxy service in a background goroutine

18
internal/cmd/run_test.go Normal file
View File

@@ -0,0 +1,18 @@
package cmd
import (
"strings"
"testing"
)
func TestStartServiceReturnsBuildError(t *testing.T) {
if errStart := StartService(nil, "", ""); errStart == nil || !strings.Contains(errStart.Error(), "configuration is required") {
t.Fatalf("expected missing configuration error, got %v", errStart)
}
}
func TestStartServiceWithPluginHostReturnsBuildError(t *testing.T) {
if errStart := StartServiceWithPluginHost(nil, "", "", nil); errStart == nil || !strings.Contains(errStart.Error(), "configuration is required") {
t.Fatalf("expected missing configuration error, got %v", errStart)
}
}