From 8bae1abe2035de746d2f83de2cb018266dc10e4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan-Otto=20Kr=C3=B6pke?= Date: Thu, 24 Apr 2025 10:57:58 +0200 Subject: [PATCH] fix: Support running as Windows Service within containers [0.30.x] (#2009) --- cmd/windows_exporter/0_service.go | 2 +- internal/collector/service/service.go | 19 +++++++++---------- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/cmd/windows_exporter/0_service.go b/cmd/windows_exporter/0_service.go index 9707a29b..3dc8203f 100644 --- a/cmd/windows_exporter/0_service.go +++ b/cmd/windows_exporter/0_service.go @@ -38,7 +38,7 @@ var ( 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{}) + serviceManagerFinishedCh = make(chan struct{}, 1) ) // IsService variable declaration allows initiating time-sensitive components like registering the Windows service diff --git a/internal/collector/service/service.go b/internal/collector/service/service.go index 94a147fb..5416e3a8 100644 --- a/internal/collector/service/service.go +++ b/internal/collector/service/service.go @@ -420,15 +420,6 @@ func (c *Collector) getProcessStartTime(pid uint32) (uint64, error) { return 0, fmt.Errorf("failed to open process %w", err) } - defer func(handle windows.Handle) { - err := windows.CloseHandle(handle) - if err != nil { - c.logger.Warn("failed to close process handle", - slog.Any("err", err), - ) - } - }(handle) - var ( creation windows.Filetime exit windows.Filetime @@ -437,6 +428,14 @@ func (c *Collector) getProcessStartTime(pid uint32) (uint64, error) { ) err = windows.GetProcessTimes(handle, &creation, &exit, &krn, &user) + + if err := windows.CloseHandle(handle); err != nil { + c.logger.LogAttrs(context.Background(), slog.LevelWarn, "failed to close process handle", + slog.Any("err", err), + slog.Uint64("pid", uint64(pid)), + ) + } + if err != nil { return 0, fmt.Errorf("failed to get process times %w", err) } @@ -477,7 +476,7 @@ func (c *Collector) getServiceConfig(service *mgr.Service) (mgr.Config, error) { *buf = make([]byte, bytesNeeded) } - c.serviceConfigPoolBytes.Put(buf) + defer c.serviceConfigPoolBytes.Put(buf) return mgr.Config{ BinaryPathName: windows.UTF16PtrToString(serviceConfig.BinaryPathName),