MCPcopy Create free account
hub / github.com/PerpetualSoftware/pad / startBackgroundServer

Function startBackgroundServer

internal/cli/server.go:96–147  ·  view source on GitHub ↗
(cfg *config.Config)

Source from the content-addressed store, hash-verified

94}
95
96func startBackgroundServer(cfg *config.Config) error {
97 // Start server as background process
98 exePath, err := os.Executable()
99 if err != nil {
100 return fmt.Errorf("find executable: %w", err)
101 }
102
103 cmd := serverStartCommand(exePath)
104 setSysProcAttr(cmd)
105
106 // Redirect stdout/stderr to log file
107 logFile, err := os.OpenFile(cfg.LogFile(), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
108 if err != nil {
109 return fmt.Errorf("open log file: %w", err)
110 }
111 cmd.Stdout = logFile
112 cmd.Stderr = logFile
113
114 if err := cmd.Start(); err != nil {
115 logFile.Close()
116 return fmt.Errorf("start server: %w", err)
117 }
118
119 // The PID file is deliberately NOT written here (BUG-2965).
120 // The child claims it AFTER it binds the port, so the file always names the
121 // process that actually owns the address. Writing it from the parent, at
122 // spawn time, records a process that may never bind — and when the port is
123 // held by an existing server that is briefly unhealthy, that write
124 // overwrites the running server's own entry with a pid that is about to
125 // exit, leaving a healthy server unaddressable by `pad server stop`. The
126 // health wait below is what tells us the child got there.
127
128 // Release the process so it doesn't become a zombie
129 cmd.Process.Release()
130 logFile.Close()
131
132 // Wait for server to become healthy
133 for i := 0; i < 30; i++ {
134 time.Sleep(100 * time.Millisecond)
135 if serverResponds(cfg.Host, cfg.Port) {
136 return nil
137 }
138 }
139
140 // The child binds before it migrates (TASK-3620), so a held port after
141 // three seconds is a server still starting: wait for it as EnsureServer
142 // does, rather than fail a call whose server is about to serve.
143 if portHeld(cfg.Host, cfg.Port) {
144 return awaitServing(cfg)
145 }
146 return fmt.Errorf("server failed to start within 3 seconds. Check %s for errors", cfg.LogFile())
147}
148
149// StopServer stops the server this CLI's config points at — or explains why it
150// will not, which is the harder half.

Callers

nothing calls this directly

Calls 9

serverStartCommandFunction · 0.85
serverRespondsFunction · 0.85
portHeldFunction · 0.85
awaitServingFunction · 0.85
LogFileMethod · 0.80
StartMethod · 0.80
ReleaseMethod · 0.80
setSysProcAttrFunction · 0.70
CloseMethod · 0.65

Tested by

no test coverage detected