Skip to content

Commit

Permalink
system: refactor collector (#1730)
Browse files Browse the repository at this point in the history
Signed-off-by: Jan-Otto Kröpke <[email protected]>
  • Loading branch information
jkroepke authored Nov 13, 2024
1 parent f332361 commit 31bcf42
Show file tree
Hide file tree
Showing 9 changed files with 138 additions and 125 deletions.
12 changes: 6 additions & 6 deletions exporter.go
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,12 @@ func run() int {

logger.Debug("Logging has Started")

if v, ok := os.LookupEnv("WINDOWS_EXPORTER_PERF_COUNTERS_ENGINE"); ok && v == "pdh" || *togglePDH == "pdh" {
logger.Info("Using performance data helper from PHD.dll for performance counter collection. This is in experimental state.")

toggle.PHDEnabled = true
}

if *printCollectors {
printCollectorsToStdout()

Expand Down Expand Up @@ -221,12 +227,6 @@ func run() int {

logger.Info("Enabled collectors: " + strings.Join(enabledCollectorList, ", "))

if v, ok := os.LookupEnv("WINDOWS_EXPORTER_PERF_COUNTERS_ENGINE"); ok && v == "pdh" || *togglePDH == "pdh" {
logger.Info("Using performance data helper from PHD.dll for performance counter collection. This is in experimental state.")

toggle.PHDEnabled = true
}

mux := http.NewServeMux()
mux.Handle("GET /health", httphandler.NewHealthHandler())
mux.Handle("GET /version", httphandler.NewVersionHandler())
Expand Down
2 changes: 1 addition & 1 deletion internal/collector/cpu/cpu.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ func (c *Collector) Build(_ *slog.Logger, _ *mi.Session) error {

var err error

c.perfDataCollector, err = perfdata.NewCollector(perfdata.V1, "Processor Information", perfdata.AllInstances, counters)
c.perfDataCollector, err = perfdata.NewCollector(perfdata.V2, "Processor Information", perfdata.AllInstances, counters)
if err != nil {
return fmt.Errorf("failed to create Processor Information collector: %w", err)
}
Expand Down
11 changes: 11 additions & 0 deletions internal/collector/system/const.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package system

const (
ContextSwitchesPersec = "Context Switches/sec"
ExceptionDispatchesPersec = "Exception Dispatches/sec"
ProcessorQueueLength = "Processor Queue Length"
SystemCallsPersec = "System Calls/sec"
SystemUpTime = "System Up Time"
Processes = "Processes"
Threads = "Threads"
)
78 changes: 40 additions & 38 deletions internal/collector/system/system.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@ package system

import (
"errors"
"fmt"
"log/slog"

"github.com/alecthomas/kingpin/v2"
"github.com/prometheus-community/windows_exporter/internal/mi"
v1 "github.com/prometheus-community/windows_exporter/internal/perfdata/v1"
"github.com/prometheus-community/windows_exporter/internal/perfdata"
"github.com/prometheus-community/windows_exporter/internal/perfdata/perftypes"
"github.com/prometheus-community/windows_exporter/internal/types"
"github.com/prometheus/client_golang/prometheus"
)
Expand All @@ -23,6 +25,8 @@ var ConfigDefaults = Config{}
type Collector struct {
config Config

perfDataCollector perfdata.Collector

contextSwitchesTotal *prometheus.Desc
exceptionDispatchesTotal *prometheus.Desc
processorQueueLength *prometheus.Desc
Expand Down Expand Up @@ -54,14 +58,31 @@ func (c *Collector) GetName() string {
}

func (c *Collector) GetPerfCounter(_ *slog.Logger) ([]string, error) {
return []string{"System"}, nil
return []string{}, nil
}

func (c *Collector) Close(_ *slog.Logger) error {
return nil
}

func (c *Collector) Build(_ *slog.Logger, _ *mi.Session) error {
counters := []string{
ContextSwitchesPersec,
ExceptionDispatchesPersec,
ProcessorQueueLength,
SystemCallsPersec,
SystemUpTime,
Processes,
Threads,
}

var err error

c.perfDataCollector, err = perfdata.NewCollector(perfdata.V2, "System", nil, counters)
if err != nil {
return fmt.Errorf("failed to create System collector: %w", err)
}

c.contextSwitchesTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "context_switches_total"),
"Total number of context switches (WMI source: PerfOS_System.ContextSwitchesPersec)",
Expand Down Expand Up @@ -117,78 +138,59 @@ func (c *Collector) Build(_ *slog.Logger, _ *mi.Session) error {

// Collect sends the metric values for each metric
// to the provided prometheus Metric channel.
func (c *Collector) Collect(ctx *types.ScrapeContext, logger *slog.Logger, ch chan<- prometheus.Metric) error {
logger = logger.With(slog.String("collector", Name))
if err := c.collect(ctx, logger, ch); err != nil {
logger.Error("failed collecting system metrics",
slog.Any("err", err),
)

return err
func (c *Collector) Collect(_ *types.ScrapeContext, _ *slog.Logger, ch chan<- prometheus.Metric) error {
if err := c.collect(ch); err != nil {
return fmt.Errorf("failed collecting system metrics: %w", err)
}

return nil
}

// Win32_PerfRawData_PerfOS_System docs:
// - https://web.archive.org/web/20050830140516/http://msdn.microsoft.com/library/en-us/wmisdk/wmi/win32_perfrawdata_perfos_system.asp
type system struct {
ContextSwitchesPersec float64 `perflib:"Context Switches/sec"`
ExceptionDispatchesPersec float64 `perflib:"Exception Dispatches/sec"`
ProcessorQueueLength float64 `perflib:"Processor Queue Length"`
SystemCallsPersec float64 `perflib:"System Calls/sec"`
SystemUpTime float64 `perflib:"System Up Time"`
Processes float64 `perflib:"Processes"`
Threads float64 `perflib:"Threads"`
}

func (c *Collector) collect(ctx *types.ScrapeContext, logger *slog.Logger, ch chan<- prometheus.Metric) error {
logger = logger.With(slog.String("collector", Name))

var dst []system

if err := v1.UnmarshalObject(ctx.PerfObjects["System"], &dst, logger); err != nil {
return err
func (c *Collector) collect(ch chan<- prometheus.Metric) error {
perfData, err := c.perfDataCollector.Collect()
if err != nil {
return fmt.Errorf("failed to collect System metrics: %w", err)
}

if len(dst) == 0 {
return errors.New("no data returned from Performance Counter")
data, ok := perfData[perftypes.EmptyInstance]
if !ok {
return errors.New("query for System returned empty result set")
}

ch <- prometheus.MustNewConstMetric(
c.contextSwitchesTotal,
prometheus.CounterValue,
dst[0].ContextSwitchesPersec,
data[ContextSwitchesPersec].FirstValue,
)
ch <- prometheus.MustNewConstMetric(
c.exceptionDispatchesTotal,
prometheus.CounterValue,
dst[0].ExceptionDispatchesPersec,
data[ExceptionDispatchesPersec].FirstValue,
)
ch <- prometheus.MustNewConstMetric(
c.processorQueueLength,
prometheus.GaugeValue,
dst[0].ProcessorQueueLength,
data[ProcessorQueueLength].FirstValue,
)
ch <- prometheus.MustNewConstMetric(
c.processes,
prometheus.GaugeValue,
dst[0].Processes,
data[Processes].FirstValue,
)
ch <- prometheus.MustNewConstMetric(
c.systemCallsTotal,
prometheus.CounterValue,
dst[0].SystemCallsPersec,
data[SystemCallsPersec].FirstValue,
)
ch <- prometheus.MustNewConstMetric(
c.systemUpTime,
prometheus.GaugeValue,
dst[0].SystemUpTime,
data[SystemUpTime].FirstValue,
)
ch <- prometheus.MustNewConstMetric(
c.threads,
prometheus.GaugeValue,
dst[0].Threads,
data[Threads].FirstValue,
)

// Windows has no defined limit, and is based off available resources. This currently isn't calculated by WMI and is set to default value.
Expand Down
36 changes: 18 additions & 18 deletions internal/collector/terminal_services/const.go
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
package terminal_services

const (
HandleCount = "Handle Count"
PageFaultsPersec = "Page Faults/sec"
PageFileBytes = "Page File Bytes"
PageFileBytesPeak = "Page File Bytes Peak"
PercentPrivilegedTime = "% Privileged Time"
PercentProcessorTime = "% Processor Time"
PercentUserTime = "% User Time"
PoolNonpagedBytes = "Pool Nonpaged Bytes"
PoolPagedBytes = "Pool Paged Bytes"
PrivateBytes = "Private Bytes"
ThreadCount = "Thread Count"
VirtualBytes = "Virtual Bytes"
VirtualBytesPeak = "Virtual Bytes Peak"
WorkingSet = "Working Set"
WorkingSetPeak = "Working Set Peak"
handleCount = "Handle Count"
pageFaultsPersec = "Page Faults/sec"
pageFileBytes = "Page File Bytes"
pageFileBytesPeak = "Page File Bytes Peak"
percentPrivilegedTime = "% Privileged Time"
percentProcessorTime = "% Processor Time"
percentUserTime = "% User Time"
poolNonpagedBytes = "Pool Nonpaged Bytes"
poolPagedBytes = "Pool Paged Bytes"
privateBytes = "Private Bytes"
threadCount = "Thread Count"
virtualBytes = "Virtual Bytes"
virtualBytesPeak = "Virtual Bytes Peak"
workingSet = "Working Set"
workingSetPeak = "Working Set Peak"

SuccessfulConnections = "Successful Connections"
PendingConnections = "Pending Connections"
FailedConnections = "Failed Connections"
successfulConnections = "Successful Connections"
pendingConnections = "Pending Connections"
failedConnections = "Failed Connections"
)
Loading

0 comments on commit 31bcf42

Please sign in to comment.