The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
fix(service): wait for the collector's process to exit when stopping it on Windows (#1164)
kyle-elliott-asymptote528ea0b23179
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 0835b774..dff66ee8 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -870,13 +870,21 @@ jobs:run: |# /qn is silent, and the verbose log is what makes a custom-action failure diagnosable --# without it msiexec reports only an exit code.+ #+ # /norestart on every msiexec here: a silent msiexec that finds a file it cannot remove or+ # replace schedules the change for the next boot and restarts the machine itself. On a runner+ # that looked like a hang -- the runner vanished mid-step, never uploaded its log, and the job+ # ran out its timeout. With /norestart the same condition returns 3010, which fails the step+ # at once, and the step prints the files the log says were in use.$log = "$env:GITHUB_WORKSPACE\install.log"$p = Start-Process msiexec.exe -Wait -PassThru -ArgumentList @(- '/i', "$env:GITHUB_WORKSPACE\Beacon-0.0.1.msi", '/qn', '/l*v', $log+ '/i', "$env:GITHUB_WORKSPACE\Beacon-0.0.1.msi", '/qn', '/norestart', '/l*v', $log)if ($p.ExitCode -ne 0) {Write-Output "--- install log (tail) ---"Get-Content -LiteralPath $log -Tail 120 | Write-Output+ Write-Output "--- files in use (Info 1903 schedules a reboot to finish) ---"+ Select-String -LiteralPath $log -Pattern 'Info 1903|Note: 1: 2329|in use' | Select-Object -Last 10 | ForEach-Object Linethrow "msiexec /i exited $($p.ExitCode)"}@@ -913,17 +921,18 @@ jobs:$log = "$env:GITHUB_WORKSPACE\upgrade.log"$p = Start-Process msiexec.exe -Wait -PassThru -ArgumentList @(- '/i', "$env:GITHUB_WORKSPACE\Beacon-0.0.2.msi", '/qn', '/l*v', $log+ '/i', "$env:GITHUB_WORKSPACE\Beacon-0.0.2.msi", '/qn', '/norestart', '/l*v', $log)if ($p.ExitCode -ne 0) {Write-Output "--- upgrade log (tail) ---"Get-Content -LiteralPath $log -Tail 150 | Write-Output+ Write-Output "--- files in use (Info 1903 schedules a reboot to finish) ---"+ Select-String -LiteralPath $log -Pattern 'Info 1903|Note: 1: 2329|in use' | Select-Object -Last 10 | ForEach-Object Linethrow "msiexec upgrade exited $($p.ExitCode)"}- # 3010 is "reboot required", which msiexec returns when it could not replace a file in use- # and deferred it. It is not an error code, which is exactly why it has to be checked for:- # the install would report success while still running the old collector.+ # A deferred replacement also leaves "Reboot" in the log. With /norestart it returns 3010 and+ # fails the step above; these lines say which file it was if anything still slips through.if (Select-String -LiteralPath $log -Pattern 'Reboot' -Quiet) {Write-Output "--- reboot mentions in the upgrade log ---"Select-String -LiteralPath $log -Pattern 'Reboot' | Select-Object -First 10 | Write-Output@@ -1005,11 +1014,13 @@ jobs:# The upgraded product is what is installed, so that is what gets removed. Each build gets a# fresh ProductCode, so removing with the 0.0.1 package would not match anything.$p = Start-Process msiexec.exe -Wait -PassThru -ArgumentList @(- '/x', "$env:GITHUB_WORKSPACE\Beacon-0.0.2.msi", '/qn',+ '/x', "$env:GITHUB_WORKSPACE\Beacon-0.0.2.msi", '/qn', '/norestart','/l*v', "$env:GITHUB_WORKSPACE\uninstall.log")if ($p.ExitCode -ne 0) {Get-Content -LiteralPath "$env:GITHUB_WORKSPACE\uninstall.log" -Tail 120 | Write-Output+ Write-Output "--- files in use (Info 1903 schedules a reboot to finish) ---"+ Select-String -LiteralPath "$env:GITHUB_WORKSPACE\uninstall.log" -Pattern 'Info 1903|Note: 1: 2329|in use' | Select-Object -Last 10 | ForEach-Object Linethrow "msiexec /x exited $($p.ExitCode)"}diff --git a/cli/beacon/internal/endpoint/service/windows_scm.go b/cli/beacon/internal/endpoint/service/windows_scm.goindex 3db0d580..bdc67834 100644--- a/cli/beacon/internal/endpoint/service/windows_scm.go+++ b/cli/beacon/internal/endpoint/service/windows_scm.go@@ -166,9 +166,16 @@ func removeService() error {})}-// stopAndWait asks the service to stop and waits for it, so a delete does not race a running-// process. A service that will not stop is reported rather than force-killed: the SCM has no-// equivalent of SIGKILL for a service, and pretending otherwise would hide a wedged collector.+// stopAndWait asks the service to stop and waits until its process has exited, so a delete does+// not race a running process and a caller that then removes or replaces the binary finds it free.+// A service that will not stop is reported rather than force-killed: the SCM has no equivalent of+// SIGKILL for a service, and pretending otherwise would hide a wedged collector.+//+// SERVICE_STOPPED alone is not enough. The collector reports it from inside its service handler,+// and the process still has to return from svc.Run and exit before Windows releases the image. An+// MSI uninstall or upgrade that reaches beacon-otelcol.exe in that window cannot remove it,+// schedules the delete for the next boot, and -- under msiexec /qn without /norestart, which is how+// fleet tooling runs it -- restarts the machine on the spot.func stopAndWait(s *mgr.Service) error {status, err := s.Query()if err != nil {@@ -177,28 +184,69 @@ func stopAndWait(s *mgr.Service) error {if status.State == svc.Stopped {return nil}+ // Opened before the stop request, so the handle is to this service's process and cannot become+ // whatever reuses the PID after it exits. Best effort: without a handle the wait below falls+ // back to the service state alone, which is what it always was.+ process := openServiceProcess(status.ProcessId)+ if process != 0 {+ defer windows.CloseHandle(process)+ }+ deadline := time.Now().Add(serviceStopTimeout)+if _, err := s.Control(svc.Stop); err != nil {- // Already stopped between the query and the control request; that is the outcome we want.+ // Already stopped between the query and the control request; that is the outcome we want,+ // once its process is gone.if errors.Is(err, windows.ERROR_SERVICE_NOT_ACTIVE) {- return nil+ return waitForServiceProcess(process, deadline)}return fmt.Errorf("stop the %s service: %w", WindowsServiceName, err)}- deadline := time.Now().Add(serviceStopTimeout)for time.Now().Before(deadline) {status, err := s.Query()if err != nil {return fmt.Errorf("query the %s service while stopping: %w", WindowsServiceName, err)}if status.State == svc.Stopped {- return nil+ return waitForServiceProcess(process, deadline)}time.Sleep(300 * time.Millisecond)}return fmt.Errorf("the %s service did not stop within %s", WindowsServiceName, serviceStopTimeout)}+// openServiceProcess returns a handle that can wait on the service's process, or 0 when there is no+// process to wait on or it cannot be opened.+func openServiceProcess(pid uint32) windows.Handle {+ if pid == 0 {+ return 0+ }+ h, err := windows.OpenProcess(windows.SYNCHRONIZE, false, pid)+ if err != nil {+ return 0+ }+ return h+}++// waitForServiceProcess waits, until deadline, for the process behind a stopped service to exit.+func waitForServiceProcess(process windows.Handle, deadline time.Time) error {+ if process == 0 {+ return nil+ }+ remaining := time.Until(deadline)+ if remaining < 0 {+ remaining = 0+ }+ event, err := windows.WaitForSingleObject(process, uint32(remaining.Milliseconds()))+ if err != nil {+ return fmt.Errorf("wait for the %s service's process to exit: %w", WindowsServiceName, err)+ }+ if event == uint32(windows.WAIT_TIMEOUT) {+ return fmt.Errorf("the %s service stopped but its process did not exit within %s", WindowsServiceName, serviceStopTimeout)+ }+ return nil+}+func restartService() error {if err := withManager(func(m *mgr.Mgr) error {s, err := m.OpenService(WindowsServiceName)