Fix Service Access is denied in collector useApi

Signed-off-by: Alvaro Cabanas <albanas@gmail.com>
Signed-off-by: alvarocabanas <acabanas@newrelic.com>
This commit is contained in:
alvarocabanas 2022-07-29 10:49:32 +02:00
parent c5ec339750
commit c9e28c4c00
No known key found for this signature in database
GPG Key ID: EC23B4C391771AD1
1 changed files with 27 additions and 13 deletions

View File

@ -6,6 +6,7 @@ package collector
import ( import (
"fmt" "fmt"
"strings" "strings"
"syscall"
"github.com/StackExchange/wmi" "github.com/StackExchange/wmi"
"github.com/prometheus-community/windows_exporter/log" "github.com/prometheus-community/windows_exporter/log"
@ -234,30 +235,43 @@ func (c *serviceCollector) collectAPI(ch chan<- prometheus.Metric) error {
} }
defer svcmgrConnection.Disconnect() //nolint:errcheck defer svcmgrConnection.Disconnect() //nolint:errcheck
// List All Services from the Services Manager // List All Services from the Services Manager.
serviceList, err := svcmgrConnection.ListServices() serviceList, err := svcmgrConnection.ListServices()
if err != nil { if err != nil {
return err return err
} }
// Iterate through the Services List // Iterate through the Services List.
for _, service := range serviceList { for _, service := range serviceList {
// Retrieve handle for each service // Get UTF16 service name.
serviceHandle, err := svcmgrConnection.OpenService(service) serviceName, err := syscall.UTF16PtrFromString(service)
if err != nil {
continue
}
defer serviceHandle.Close()
// Get Service Configuration
serviceConfig, err := serviceHandle.Config()
if err != nil { if err != nil {
log.Warnf("Service %s get name error: %#v", service, err)
continue continue
} }
// Get Service Current Status // Open connection for service handler.
serviceStatus, err := serviceHandle.Query() serviceHandle, err := windows.OpenService(svcmgrConnection.Handle, serviceName, windows.GENERIC_READ)
if err != nil { if err != nil {
log.Warnf("Open service %s error: %#v", service, err)
continue
}
// Create handle for each service.
serviceManager := &mgr.Service{Name: service, Handle: serviceHandle}
defer serviceManager.Close()
// Get Service Configuration.
serviceConfig, err := serviceManager.Config()
if err != nil {
log.Warnf("Get ervice %s config error: %#v", service, err)
continue
}
// Get Service Current Status.
serviceStatus, err := serviceManager.Query()
if err != nil {
log.Warnf("Get service %s status error: %#v", service, err)
continue continue
} }