Skip to content
Merged
Show file tree
Hide file tree
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
49 changes: 47 additions & 2 deletions docs/collector.os.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,28 @@ None
| `windows_os_hostname` | Labelled system hostname information as provided by ComputerSystem.DNSHostName and ComputerSystem.Domain | gauge | `hostname`, `domain`, `fqdn` |
| `windows_os_info` | Contains full product name & version in labels. Note that the `major_version` for Windows 11 is "10"; a build number greater than 22000 represents Windows 11. | gauge | `product`, `version`, `major_version`, `minor_version`, `build_number`, `revision`, `installation_type` |
| `windows_os_install_time_timestamp_seconds` | Unix timestamp of OS installation time | gauge | None |
| `windows_os_reboot_required` | 1 if Windows has recorded that a reboot is required for the reason in the label, 0 otherwise | gauge | `reason` |

### Reboot required reasons

`windows_os_reboot_required` reads the registry locations that Windows uses to
record a pending reboot, one series per `reason`:

| `reason` | Set when |
|----------|----------|
| `component_servicing` | The key `HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending` exists: an update, feature or role change waits for a reboot. |
| `windows_update` | The key `HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired` exists: Windows Update installed updates that need a reboot. |
| `file_rename` | The value `PendingFileRenameOperations` or `PendingFileRenameOperations2` of `HKLM\SYSTEM\CurrentControlSet\Control\Session Manager` lists files to replace or delete at the next boot. Installers and antivirus software set it often, so it alone is a weak signal. |
| `computer_rename` | The computer name under `HKLM\SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName` differs from the active one: the host was renamed. |

The list is not exhaustive: other software, for example a pending domain join
or a Configuration Manager client, can wait for a reboot without setting these
locations, so `0` for every reason does not rule out a pending reboot.

A reason whose registry location the exporter's account may not read is left
out, and a warning is logged once. Any other read error leaves the reason out
and fails the collector's scrape
(`windows_exporter_collector_success{collector="os"}`).

### Example metric

Expand All @@ -32,10 +54,33 @@ windows_os_info{build_number="19045",installation_type="Client",major_version="1
# HELP windows_os_install_time_timestamp_seconds Unix timestamp of OS installation time
# TYPE windows_os_install_time_timestamp_seconds gauge
windows_os_install_time_timestamp_seconds 1.6725312e+09
# HELP windows_os_reboot_required 1 if Windows has recorded that a reboot is required for the reason in the label, 0 otherwise
# TYPE windows_os_reboot_required gauge
windows_os_reboot_required{reason="component_servicing"} 0
windows_os_reboot_required{reason="computer_rename"} 0
windows_os_reboot_required{reason="file_rename"} 1
windows_os_reboot_required{reason="windows_update"} 0
```

## Useful queries
_This collector does not yet have useful query examples, we would appreciate your help adding them!_

Hosts that wait for a reboot after updates or a role change:

```promql
max by (instance) (windows_os_reboot_required{reason=~"component_servicing|windows_update|computer_rename"}) == 1
```

## Alerting examples
_This collector does not yet have alerting examples, we would appreciate your help adding them!_

**prometheus.rules**

```yaml
- alert: WindowsRebootRequired
expr: max by (instance) (windows_os_reboot_required{reason=~"component_servicing|windows_update|computer_rename"}) == 1
for: 24h
labels:
severity: info
annotations:
summary: "Reboot required on {{ $labels.instance }}"
description: "{{ $labels.instance }} has waited more than 24 hours for a reboot to finish installing updates or configuration changes."
```
170 changes: 166 additions & 4 deletions internal/collector/os/os.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"github.com/prometheus-community/windows_exporter/internal/osversion"
"github.com/prometheus-community/windows_exporter/internal/types"
"github.com/prometheus/client_golang/prometheus"
"golang.org/x/sys/windows"
"golang.org/x/sys/windows/registry"
)

Expand All @@ -33,12 +34,18 @@ var ConfigDefaults = Config{}
// A Collector is a Prometheus Collector for OS metrics.
type Collector struct {
config Config
logger *slog.Logger

installTimeTimestamp float64

hostname *prometheus.Desc
osInformation *prometheus.Desc
installTime *prometheus.Desc
// rebootRequiredDenied records the reasons whose registry location the
// exporter can't read, so that the warning is logged once.
rebootRequiredDenied map[string]bool

hostname *prometheus.Desc
osInformation *prometheus.Desc
installTime *prometheus.Desc
rebootRequired *prometheus.Desc
}

func New(config *Config) *Collector {
Expand All @@ -65,7 +72,10 @@ func (c *Collector) Close() error {
return nil
}

func (c *Collector) Build(_ *slog.Logger, _ *mi.Session) error {
func (c *Collector) Build(logger *slog.Logger, _ *mi.Session) error {
c.logger = logger.With(slog.String("collector", Name))
c.rebootRequiredDenied = make(map[string]bool)

if err := sysinfoapi.Load(); err != nil {
return err
}
Expand Down Expand Up @@ -122,6 +132,13 @@ func (c *Collector) Build(_ *slog.Logger, _ *mi.Session) error {
nil,
)

c.rebootRequired = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "reboot_required"),
"1 if Windows has recorded that a reboot is required for the reason in the label, 0 otherwise",
[]string{"reason"},
nil,
)

return nil
}

Expand All @@ -146,9 +163,154 @@ func (c *Collector) Collect(ch chan<- prometheus.Metric, _ time.Duration) error
errs = append(errs, fmt.Errorf("failed to collect hostname metrics: %w", err))
}

if err := c.collectRebootRequired(ch); err != nil {
errs = append(errs, fmt.Errorf("failed to collect reboot required metrics: %w", err))
}

return errors.Join(errs...)
}

func (c *Collector) collectRebootRequired(ch chan<- prometheus.Metric) error {
// The registry locations that Windows components use to record a
// pending reboot, by the value of the reason label.
checks := []struct {
reason string
check func() (bool, error)
}{
{"component_servicing", func() (bool, error) {
return registryKeyExists(`SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending`)
}},
{"windows_update", func() (bool, error) {
return registryKeyExists(`SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired`)
}},
{"file_rename", pendingFileRenameOperations},
{"computer_rename", pendingComputerRename},
}

errs := make([]error, 0)

for _, check := range checks {
required, err := check.check()
if errors.Is(err, windows.ERROR_ACCESS_DENIED) {
// The account of the exporter can't read this location. Leave
// the reason out instead of failing every scrape.
if !c.rebootRequiredDenied[check.reason] {
c.rebootRequiredDenied[check.reason] = true

c.logger.Warn("can't read reboot required reason, leaving it out",
slog.String("reason", check.reason),
slog.Any("err", err),
)
}

continue
} else if err != nil {
errs = append(errs, fmt.Errorf("%s: %w", check.reason, err))

continue
}

value := 0.0
if required {
value = 1.0
}

ch <- prometheus.MustNewConstMetric(
c.rebootRequired,
prometheus.GaugeValue,
value,
check.reason,
)
}

return errors.Join(errs...)
}

// registryKeyExists reports whether the key below HKEY_LOCAL_MACHINE exists.
func registryKeyExists(path string) (bool, error) {
key, err := registry.OpenKey(registry.LOCAL_MACHINE, path, registry.QUERY_VALUE)
if errors.Is(err, registry.ErrNotExist) {
return false, nil
} else if err != nil {
return false, fmt.Errorf("failed to open registry key %q: %w", path, err)
}

_ = key.Close()

return true, nil
}

// pendingFileRenameOperations reports whether the session manager has file
// rename or delete operations queued for the next boot.
func pendingFileRenameOperations() (bool, error) {
const path = `SYSTEM\CurrentControlSet\Control\Session Manager`

key, err := registry.OpenKey(registry.LOCAL_MACHINE, path, registry.QUERY_VALUE)
if err != nil {
return false, fmt.Errorf("failed to open registry key %q: %w", path, err)
}

defer func(key registry.Key) {
_ = key.Close()
}(key)

for _, name := range []string{"PendingFileRenameOperations", "PendingFileRenameOperations2"} {
operations, _, err := key.GetStringsValue(name)
switch {
case errors.Is(err, registry.ErrNotExist):
continue
case errors.Is(err, registry.ErrUnexpectedType):
// Windows expects REG_MULTI_SZ. Count a value that another tool
// wrote with a different type as pending, like a non-empty list.
return true, nil
case err != nil:
return false, fmt.Errorf("failed to read registry value %q: %w", name, err)
}

for _, operation := range operations {
if operation != "" {
return true, nil
}
}
}

return false, nil
}

// pendingComputerRename reports whether the computer name that takes effect
// at the next boot differs from the active one.
func pendingComputerRename() (bool, error) {
active, err := registryStringValue(`SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName`, "ComputerName")
if err != nil {
return false, err
}

pending, err := registryStringValue(`SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName`, "ComputerName")
if err != nil {
return false, err
}

return !strings.EqualFold(active, pending), nil
}

func registryStringValue(path, name string) (string, error) {
key, err := registry.OpenKey(registry.LOCAL_MACHINE, path, registry.QUERY_VALUE)
if err != nil {
return "", fmt.Errorf("failed to open registry key %q: %w", path, err)
}

defer func(key registry.Key) {
_ = key.Close()
}(key)

value, _, err := key.GetStringValue(name)
if err != nil {
return "", fmt.Errorf("failed to read registry value %q: %w", name, err)
}

return value, nil
}

func (c *Collector) collectHostname(ch chan<- prometheus.Metric) error {
hostname, err := sysinfoapi.GetComputerName(sysinfoapi.ComputerNameDNSHostname)
if err != nil {
Expand Down
25 changes: 25 additions & 0 deletions internal/collector/os/os_internal_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// SPDX-License-Identifier: MIT
//
// Copyright The Prometheus Authors

//go:build windows

package os

import (
"testing"

"github.com/stretchr/testify/require"
)

func TestRegistryKeyExists(t *testing.T) {
t.Parallel()

exists, err := registryKeyExists(`SOFTWARE\Microsoft`)
require.NoError(t, err)
require.True(t, exists)

exists, err = registryKeyExists(`SOFTWARE\Microsoft\windows_exporter\does not exist`)
require.NoError(t, err)
require.False(t, exists)
}
20 changes: 19 additions & 1 deletion internal/collector/os/os_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,30 @@ import (

"github.com/prometheus-community/windows_exporter/internal/collector/os"
"github.com/prometheus-community/windows_exporter/internal/utils/testutils"
dto "github.com/prometheus/client_model/go"
"github.com/stretchr/testify/require"
)

func BenchmarkCollector(b *testing.B) {
testutils.FuncBenchmarkCollector(b, os.Name, os.NewWithFlags)
}

func TestCollector(t *testing.T) {
testutils.TestCollector(t, os.New, nil)
families := testutils.TestCollector(t, os.New, nil)

family := families["windows_os_reboot_required"]
require.NotNil(t, family)
require.Equal(t, dto.MetricType_GAUGE, family.GetType())

reasons := make([]string, 0, len(family.GetMetric()))

for _, metric := range family.GetMetric() {
require.Len(t, metric.GetLabel(), 1)
require.Equal(t, "reason", metric.GetLabel()[0].GetName())
require.Contains(t, []float64{0, 1}, metric.GetGauge().GetValue())

reasons = append(reasons, metric.GetLabel()[0].GetValue())
}

require.ElementsMatch(t, []string{"component_servicing", "computer_rename", "file_rename", "windows_update"}, reasons)
}
1 change: 1 addition & 0 deletions internal/metriccontract/metrics_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ var ignoredReferences = map[string]string{
"windows_rules": "a rule file of the mixin tests",
"windows_alerts": "an alert file of the mixin tests",
"windows_hyperv_datastore": "the prefix of the datastore metrics in docs/collector.hyperv.md",
"windows_update": "a reason label value of windows_os_reboot_required",
}

func TestMetricReferences(t *testing.T) {
Expand Down
2 changes: 2 additions & 0 deletions tools/e2e-output.txt
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,8 @@ windows_exporter_collector_timeout{collector="udp"} 0
# TYPE windows_os_info gauge
# HELP windows_os_install_time_timestamp_seconds Unix timestamp of OS installation time
# TYPE windows_os_install_time_timestamp_seconds gauge
# HELP windows_os_reboot_required 1 if Windows has recorded that a reboot is required for the reason in the label, 0 otherwise
# TYPE windows_os_reboot_required gauge
# HELP windows_pagefile_free_bytes Number of bytes that can be mapped into the operating system paging files without causing any other pages to be swapped out
# TYPE windows_pagefile_free_bytes gauge
# HELP windows_pagefile_limit_bytes Current size of the paging file in bytes
Expand Down
Loading