system: read the boot time from the kernel on every scrape (#2690)

Signed-off-by: Jan-Otto Kröpke <mail@jkroepke.de>
This commit is contained in:
Jan-Otto Kröpke
2026-10-11 20:47:11 +02:00
committed by GitHub
parent 9869fb12d1
commit be5036dfa8
5 changed files with 139 additions and 30 deletions
+2 -2
View File
@@ -1,6 +1,6 @@
# system collector
The system collector exposes metrics about ...
The system collector exposes system-wide metrics of the System performance counter object, such as context switches, system calls, processes and threads, and the system boot time.
|||
-|-
@@ -16,7 +16,7 @@ None
| Name | Description | Type | Labels |
|----------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------|--------|
| `windows_system_boot_time_timestamp` | Unix timestamp of last system boot | gauge | None |
| `windows_system_boot_time_timestamp` | Unix timestamp of last system boot, in whole seconds. Follows clock corrections | gauge | None |
| `windows_system_context_switches_total` | Total number of [context switches](https://en.wikipedia.org/wiki/Context_switch) | counter | None |
| `windows_system_exception_dispatches_total` | Total exceptions dispatched by the system | counter | None |
| `windows_system_processes` | Number of process contexts currently loaded or running on the operating system | gauge | None |
+32 -21
View File
@@ -18,12 +18,13 @@
package system
import (
"errors"
"fmt"
"log/slog"
"time"
"github.com/alecthomas/kingpin/v2"
"github.com/prometheus-community/windows_exporter/internal/headers/kernel32"
"github.com/prometheus-community/windows_exporter/internal/headers/ntdll"
"github.com/prometheus-community/windows_exporter/internal/mi"
"github.com/prometheus-community/windows_exporter/internal/pdh"
"github.com/prometheus-community/windows_exporter/internal/types"
@@ -37,12 +38,10 @@ type Config struct{}
//nolint:gochecknoglobals
var ConfigDefaults = Config{}
// A Collector is a Prometheus Collector for WMI metrics.
// A Collector is a Prometheus Collector for System performance counter metrics.
type Collector struct {
config Config
bootTimeTimestamp float64
perfDataCollector *pdh.Collector[perfDataCounterValues]
perfDataObject []perfDataCounterValues
@@ -85,25 +84,25 @@ func (c *Collector) Close() error {
func (c *Collector) Build(logger *slog.Logger, _ *mi.Session) error {
c.bootTime = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "boot_time_timestamp"),
"Unix timestamp of system boot time",
"Unix timestamp of last system boot. Follows clock corrections.",
nil,
nil,
)
c.contextSwitchesTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "context_switches_total"),
"Total number of context switches (WMI source: PerfOS_System.ContextSwitchesPersec)",
"Total number of context switches",
nil,
nil,
)
c.exceptionDispatchesTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "exception_dispatches_total"),
"Total number of exceptions dispatched (WMI source: PerfOS_System.ExceptionDispatchesPersec)",
"Total number of exceptions dispatched",
nil,
nil,
)
c.processes = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "processes"),
"Current number of processes (WMI source: PerfOS_System.Processes)",
"Current number of processes",
nil,
nil,
)
@@ -116,25 +115,23 @@ func (c *Collector) Build(logger *slog.Logger, _ *mi.Session) error {
c.processorQueueLength = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "processor_queue_length"),
"Length of processor queue (WMI source: PerfOS_System.ProcessorQueueLength)",
"Length of processor queue",
nil,
nil,
)
c.systemCallsTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "system_calls_total"),
"Total number of system calls (WMI source: PerfOS_System.SystemCallsPersec)",
"Total number of system calls",
nil,
nil,
)
c.threads = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "threads"),
"Current number of threads (WMI source: PerfOS_System.Threads)",
"Current number of threads",
nil,
nil,
)
c.bootTimeTimestamp = float64(uint64(time.Now().UnixMilli())-kernel32.GetTickCount64()) / 1000
var err error
c.perfDataCollector, err = pdh.NewCollector[perfDataCounterValues](logger.With(slog.String("collector", Name)), pdh.CounterTypeRaw, "System", nil)
@@ -148,11 +145,14 @@ func (c *Collector) Build(logger *slog.Logger, _ *mi.Session) error {
// Collect sends the metric values for each metric
// to the provided prometheus Metric channel.
func (c *Collector) Collect(ch chan<- prometheus.Metric, _ time.Duration) error {
// The boot time does not depend on the performance counters.
bootTimeErr := c.collectBootTime(ch)
err := c.perfDataCollector.Collect(&c.perfDataObject)
if err != nil {
return fmt.Errorf("failed to collect System metrics: %w", err)
return errors.Join(bootTimeErr, fmt.Errorf("failed to collect System metrics: %w", err))
} else if len(c.perfDataObject) == 0 {
return fmt.Errorf("failed to collect System metrics: %w", types.ErrNoDataUnexpected)
return errors.Join(bootTimeErr, fmt.Errorf("failed to collect System metrics: %w", types.ErrNoDataUnexpected))
}
ch <- prometheus.MustNewConstMetric(
@@ -191,12 +191,6 @@ func (c *Collector) Collect(ch chan<- prometheus.Metric, _ time.Duration) error
c.perfDataObject[0].Threads,
)
ch <- prometheus.MustNewConstMetric(
c.bootTime,
prometheus.GaugeValue,
c.bootTimeTimestamp,
)
// Windows has no defined limit, and is based off available resources. This currently isn't calculated by WMI and is set to default value.
// https://techcommunity.microsoft.com/t5/windows-blog-archive/pushing-the-limits-of-windows-processes-and-threads/ba-p/723824
// https://docs.microsoft.com/en-us/windows/win32/cimwin32prov/win32-operatingsystem
@@ -206,5 +200,22 @@ func (c *Collector) Collect(ch chan<- prometheus.Metric, _ time.Duration) error
float64(4294967295),
)
return bootTimeErr
}
func (c *Collector) collectBootTime(ch chan<- prometheus.Metric) error {
bootTime, err := ntdll.BootTime()
if err != nil {
return fmt.Errorf("failed to get system boot time: %w", err)
}
// Whole seconds keep the value stable when the kernel moves the boot time
// by a sub-second clock correction.
ch <- prometheus.MustNewConstMetric(
c.bootTime,
prometheus.GaugeValue,
float64(bootTime.Unix()),
)
return nil
}
-7
View File
@@ -29,7 +29,6 @@ var (
procGetDynamicTimeZoneInformationSys = modkernel32.NewProc("GetDynamicTimeZoneInformation")
procKernelLocalFileTimeToFileTime = modkernel32.NewProc("LocalFileTimeToFileTime")
procGetTickCount = modkernel32.NewProc("GetTickCount64")
procOpenJobObject = modkernel32.NewProc("OpenJobObjectW")
procIsProcessInJob = modkernel32.NewProc("IsProcessInJob")
)
@@ -81,9 +80,3 @@ func LocalFileTimeToFileTime(localFileTime, utcFileTime *windows.Filetime) uint3
return uint32(ret)
}
func GetTickCount64() uint64 {
ret, _, _ := procGetTickCount.Call()
return uint64(ret)
}
+63
View File
@@ -0,0 +1,63 @@
// SPDX-License-Identifier: Apache-2.0
//
// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build windows
package ntdll
import (
"fmt"
"time"
"unsafe"
"golang.org/x/sys/windows"
)
// SystemTimeOfDayInformation is the SYSTEM_TIMEOFDAY_INFORMATION structure.
// The times are in 100-nanosecond intervals since January 1, 1601 (UTC).
type SystemTimeOfDayInformation struct {
BootTime int64
CurrentTime int64
TimeZoneBias int64
TimeZoneID uint32
Reserved uint32
BootTimeBias uint64
SleepTimeBias uint64
}
// BootTime returns the time the system booted.
//
// The kernel moves the boot time along when the system time is set, so it
// stays correct after a clock correction.
func BootTime() (time.Time, error) {
var info SystemTimeOfDayInformation
err := windows.NtQuerySystemInformation(
windows.SystemTimeOfDayInformation,
unsafe.Pointer(&info),
uint32(unsafe.Sizeof(info)),
nil,
)
if err != nil {
return time.Time{}, fmt.Errorf("NtQuerySystemInformation(SystemTimeOfDayInformation): %w", err)
}
ft := windows.Filetime{
LowDateTime: uint32(info.BootTime),
HighDateTime: uint32(info.BootTime >> 32),
}
return time.Unix(0, ft.Nanoseconds()), nil
}
+42
View File
@@ -0,0 +1,42 @@
// SPDX-License-Identifier: Apache-2.0
//
// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build windows
package ntdll_test
import (
"testing"
"time"
"github.com/prometheus-community/windows_exporter/internal/headers/ntdll"
"github.com/stretchr/testify/require"
)
func TestBootTime(t *testing.T) {
t.Parallel()
bootTime, err := ntdll.BootTime()
require.NoError(t, err)
require.True(t, bootTime.Before(time.Now()), "boot time %s is in the future", bootTime)
require.True(t, bootTime.After(time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)), "boot time %s is too old", bootTime)
// The boot time must not depend on when it is read. Allow for a clock
// correction between the two calls.
again, err := ntdll.BootTime()
require.NoError(t, err)
require.WithinDuration(t, bootTime, again, time.Second)
}