Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Error "Service Access is denied" in service collector useApi #1036

Merged
merged 1 commit into from
Aug 22, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 23 additions & 9 deletions collector/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package collector
import (
"fmt"
"strings"
"syscall"

"github.com/StackExchange/wmi"
"github.com/prometheus-community/windows_exporter/log"
Expand Down Expand Up @@ -234,30 +235,43 @@ func (c *serviceCollector) collectAPI(ch chan<- prometheus.Metric) error {
}
defer svcmgrConnection.Disconnect() //nolint:errcheck

// List All Services from the Services Manager
// List All Services from the Services Manager.
serviceList, err := svcmgrConnection.ListServices()
if err != nil {
return err
}

// Iterate through the Services List
// Iterate through the Services List.
for _, service := range serviceList {
// Retrieve handle for each service
serviceHandle, err := svcmgrConnection.OpenService(service)
// Get UTF16 service name.
serviceName, err := syscall.UTF16PtrFromString(service)
if err != nil {
log.Warnf("Service %s get name error: %#v", service, err)
continue
}
defer serviceHandle.Close()

// Get Service Configuration
serviceConfig, err := serviceHandle.Config()
// Open connection for service handler.
serviceHandle, err := windows.OpenService(svcmgrConnection.Handle, serviceName, windows.GENERIC_READ)
if err != nil {
log.Warnf("Open service %s error: %#v", service, err)
continue
}

// Get Service Current Status
serviceStatus, err := serviceHandle.Query()
// 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
}

Expand Down