fix: slow stop if run as service (#1870)

Signed-off-by: Jan-Otto Kröpke <mail@jkroepke.de>
This commit is contained in:
Jan-Otto Kröpke
2025-02-07 22:26:09 +01:00
committed by GitHub
parent a20e1854d1
commit 1b2958a7cc
6 changed files with 60 additions and 59 deletions

View File

@@ -33,6 +33,9 @@ var (
// stopCh is a channel to send a signal to the service manager that the service is stopping.
stopCh = make(chan struct{})
// serviceManagerFinishedCh is a channel to send a signal to the main function that the service manager has stopped the service.
serviceManagerFinishedCh = make(chan struct{})
)
// IsService variable declaration allows initiating time-sensitive components like registering the Windows service
@@ -49,30 +52,31 @@ var (
//
//nolint:gochecknoglobals
var IsService = func() bool {
defer func() {
go func() {
err := svc.Run(serviceName, &windowsExporterService{})
if err == nil {
return
}
_ = logToEventToLog(windows.EVENTLOG_ERROR_TYPE, fmt.Sprintf("failed to start service: %v", err))
}()
}()
var err error
isService, err := svc.IsWindowsService()
if err != nil {
_ = logToEventToLog(windows.EVENTLOG_ERROR_TYPE, fmt.Sprintf("failed to detect service: %v", err))
//nolint:gosec
_ = os.WriteFile("C:\\Program Files\\windows_exporter\\start-service.error.log", []byte(fmt.Sprintf("failed to detect service: %v", err)), 0o644)
exitCodeCh <- 1
return false
}
if !isService {
return false
}
defer func() {
go func() {
err := svc.Run(serviceName, &windowsExporterService{})
if err != nil {
_ = logToEventToLog(windows.EVENTLOG_ERROR_TYPE, fmt.Sprintf("failed to start service: %v", err))
}
serviceManagerFinishedCh <- struct{}{}
}()
}()
if err := logToEventToLog(windows.EVENTLOG_INFORMATION_TYPE, "attempting to start exporter service"); err != nil {
//nolint:gosec
_ = os.WriteFile("C:\\Program Files\\windows_exporter\\start-service.error.log", []byte(fmt.Sprintf("failed sent log to event log: %v", err)), 0o644)

View File

@@ -57,7 +57,7 @@ func main() {
exitCodeCh <- exitCode
// Wait for the service control manager to signal that we are done.
<-stopCh
<-serviceManagerFinishedCh
}
func run() int {