Skip to content

feat(localdns): add localDNS metrics exporter#7917

Open
saewoni wants to merge 87 commits intomainfrom
sakwa/add_localdns_metrics__systemd
Open

feat(localdns): add localDNS metrics exporter#7917
saewoni wants to merge 87 commits intomainfrom
sakwa/add_localdns_metrics__systemd

Conversation

@saewoni
Copy link
Copy Markdown
Contributor

@saewoni saewoni commented Feb 20, 2026

Adds CPU and memory metrics for localdns.service using systemd accounting and socket activation for efficient, zero-overhead monitoring.

Also exports IP addresses configured for forward plugins for kubedns and vnetdns overrides.

Implementation:

  • localdns_exporter.sh: Reads pre-generated .prom files written by localdns.sh (avoids D-Bus permission issues under DynamicUser)
  • localdns-exporter.socket: Socket activation on port 9353 with MaxConnections=10
  • localdns-exporter@.service: Instantiated service per connection, security hardened (DynamicUser=yes, ProtectSystem=strict,
  • NoNewPrivileges=yes)
  • localdns.sh: Generates resource metrics on each watchdog tick (~6s) and forward IP metrics on corefile update
  • Integrated into all VHD builders (Ubuntu, Mariner, Flatcar, ACL, all arches)
  • Backward compatible: CSE skips setup on older VHDs via node label gating (kubernetes.azure.com/localdns-exporter)

Metrics exposed:

  • localdns_service_status (gauge) — CoreDNS process liveness
  • localdns_cpu_usage_seconds_total (counter)
  • localdns_memory_usage_bytes (gauge)
  • localdns_metrics_last_update_timestamp_seconds (gauge) — staleness detection
  • localdns_vnetdns_forward_info (gauge) — VnetDNS forward IP with block and status labels
  • localdns_kubedns_forward_info (gauge) — KubeDNS forward IP with block and status labels

Test coverage:

  • ShellSpec unit tests for exporter HTTP routing, export_resource_metrics, and forward IP prom generation
  • E2e validation script covering socket activation, metrics format, security hardening, and node label gating
  • VHD content test validates exporter files present with correct permissions

What this PR does / why we need it:

Which issue(s) this PR fixes:

Fixes #

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adds a lightweight Prometheus-compatible metrics exporter for the localdns.service using systemd socket activation. The exporter exposes CPU and memory metrics on port 9353 with zero overhead when not being scraped, making it suitable for production monitoring.

Changes:

  • Added localdns_exporter.sh bash script that queries systemd accounting metrics and formats them as Prometheus metrics
  • Added systemd socket (localdns-exporter.socket) and service (localdns-exporter@.service) units for on-demand activation
  • Integrated the exporter into all Linux VHD builds (Ubuntu, Mariner, Flatcar, ARM64/x64)
  • Added VHD content validation tests and a standalone test script

Reviewed changes

Copilot reviewed 15 out of 15 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
parts/linux/cloud-init/artifacts/localdns_exporter.sh Bash script that scrapes systemd metrics (CPUUsageNSec, MemoryCurrent) and outputs Prometheus-formatted HTTP response
parts/linux/cloud-init/artifacts/localdns-exporter@.service Systemd template service for per-connection worker instances with security hardening
parts/linux/cloud-init/artifacts/localdns-exporter.socket Systemd socket unit listening on port 9353 with Accept=yes for on-demand activation
vhdbuilder/packer/vhd-image-builder-*.json Added file provisioners to copy exporter artifacts to all Linux VHD variants
vhdbuilder/packer/packer_source.sh Added file copying logic and systemctl enable command for the socket
vhdbuilder/packer/imagecustomizer/azlosguard/azlosguard.yml Added exporter files to OSGuard VHD build but missing socket enablement
vhdbuilder/packer/test/linux-vhd-content-test.sh Added validation for exporter files and permissions
e2e/test-localdns-exporter.sh Standalone test script for manual validation

@saewoni saewoni changed the title feat(localdns): add systemd-based Prometheus metrics exporter feat(localdns): add systemd-based Prometheus-format metrics exporter Feb 20, 2026
Copilot AI review requested due to automatic review settings February 20, 2026 22:15
@saewoni saewoni force-pushed the sakwa/add_localdns_metrics__systemd branch from 223b0c3 to 83fc4e2 Compare February 20, 2026 22:21
jingwenw15 and others added 14 commits April 2, 2026 11:11
…porterSocket

On old VHDs without the localdns-exporter.socket unit, the function was
creating a stale drop-in directory, calling get_primary_nic_ip, and
running daemon-reload before the guard skipped the enable step. Move the
guard to the top so the function is a clean no-op when the unit is missing.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Rename localdns_memory_usage_mb to localdns_memory_usage_bytes per
Prometheus base-unit naming convention. Expose raw bytes from systemd
MemoryCurrent instead of dividing by 1048576. This must ship before
the metric name becomes permanent in production dashboards.

Increase CPU precision from %.4f to %.9f to preserve nanosecond
source precision from CPUUsageNSec, avoiding step-function artifacts
in rate() calculations at low CPU usage.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…st filter

Add Connection: close header to HTTP responses in localdns_exporter.sh
for HTTP/1.1 compliance (message framing without Content-Length).

Add localdns_metrics_last_update_timestamp_seconds gauge to detect
stale .prom data when the watchdog stops updating. Consumers can alert
on: time() - localdns_metrics_last_update_timestamp_seconds > 120.

Fix run-localdns-test.sh to actually pass the test name argument as
-run flag to go test. Previously the filter was silently ignored.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add MaxConnections=10 to localdns-exporter.socket to prevent unbounded
process spawning from port scans or misbehaving scrapers. Excess
connections are refused with TCP RST; Prometheus retries next interval.

Widen RestrictAddressFamilies to AF_UNIX AF_INET AF_INET6 in the
service unit. Socket activation passes an AF_INET fd as stdin/stdout;
current systemd exempts inherited fds from seccomp filtering, but this
is an implementation detail not a guarantee. Adding AF_INET/AF_INET6
future-proofs against stricter seccomp enforcement in newer systemd.

Pass LOCALDNS_SCRIPT_PATH via Environment= in the service unit so the
exporter derives .prom file paths from the same source as localdns.sh,
eliminating silent divergence if the path ever changes.

Update e2e test to validate the new RestrictAddressFamilies allowlist.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Remove run-localdns-test.sh which was unused by any code in the repo.
Localdns tests can be run via standard TAGS_TO_RUN filtering instead.

Tighten ss port grep from ':9353' to ':9353[[:space:]]' to prevent
false substring matches against ports like 93539.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…ile parser

- Switch from systemctlEnableAndStartNoBlock to systemctlEnableAndStart
  for the exporter socket unit. Socket units activate in <10ms so
  blocking is fine and ensures the socket is active before adding the
  kubelet node label.

- Fix stale comment in localdns-exporter@.service that said "reads
  systemd properties" when the exporter only reads .prom files.

- Simplify corefile parser: store full zone:port from $1 instead of
  stripping :53 and re-appending it. Same metric output, port now
  comes from one source (the corefile) instead of being hardcoded
  in two places.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
… status check

Move localdns-exporter socket setup after ensureKubelet to avoid adding
latency to kubelet startup. The kubelet node label (which must be set
before kubelet starts) is split out and added separately before
ensureKubelet (~0ms variable append).

Additional PR feedback fixes:
- Replace systemctl is-active with kill -0 $COREDNS_PID for accurate
  service status (systemctl always returns "active" from within the service)
- Combine two systemctl show calls into one to reduce D-Bus overhead
- Add read -t 5 timeout in exporter to prevent indefinite blocking
- Use systemctlEnableAndStartNoBlock since post-kubelet ordering removes
  the need to wait for socket activation
- Update HELP comments to reflect kill -0 based status check

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Update shellspec tests to reflect code changes:
- Remove enableLocalDNS exporter tests (moved to configureLocalDNSExporterSocket)
- Add block= label to forward IP metric assertions in localdns_spec
- Fix missing status assertions to include block="none"

Fix OSGuard imagecustomizer config: localdns.sh was placed at
/opt/azure/containers/localdns.sh but localdns.service ExecStart
expects /opt/azure/containers/localdns/localdns.sh.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…k to test fixtures

Replace nc (netcat) with bash /dev/tcp for holding open a TCP connection
in e2e validation — nc may not be installed on all AKS distros.

Add the production health-check server block (bind 169.254.10.10
169.254.10.11, whoami, no forward) to all corefile test fixtures so
the parser is tested against the real corefile structure and regressions
from the health-check block are caught.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…e comments

Only add the localdns-exporter kubelet node label if the exporter socket
unit exists on the VHD. This prevents old VHDs (without exporter files)
from advertising exporter=enabled when no exporter is available to scrape.

Also fix stale comments in enableLocalDNS and configureLocalDNSExporterSocket
to accurately describe the current boot sequence and guard purpose.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Flatcar compiles bash without --enable-net-redirections, so /dev/tcp
is not available. Revert to nc (available on all AKS VHD distros)
for holding the TCP connection open during security inspection.
Use `sleep 120 | nc` to keep stdin open and prevent nc from closing.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
The e2e validation script now checks if localdns-exporter.socket exists
on the VHD before running. Older VHDs built from main don't have the
exporter units — exit 0 gracefully instead of hard-failing. If the unit
IS installed, all checks still run and any failure is a real bug.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add three unit tests covering the branching logic in export_resource_metrics:
- Active status when COREDNS_PID is alive (CPU/memory conversion verified)
- Inactive status when COREDNS_PID is empty
- Defaults to zero when systemctl returns [not set] values

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
… validation gating

Move the exporter validation skip logic from a silent `exit 0` in the
bash script to a Go-level node label check. The label
`kubernetes.azure.com/localdns-exporter` is only set by CSE when the
VHD has the exporter socket installed, so it's the right signal.

If the label is absent, the test logs a WARNING (visible in output)
and skips. If the label is present, full validation runs and hard-fails
on any issue. This avoids silently passing when something is broken.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
EnvironmentFile=-/etc/localdns/environment
ExecStart=/opt/azure/containers/localdns/localdns.sh
# Enable resource accounting for metrics collection
CPUAccounting=yes
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what is this for ?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

these enable cgroup accounting for the service so systemd actually tracks cpu time and memory usage. without them systemctl show localdns.service --property=CPUUsageNSec,MemoryCurrent returns [not set], and export_resource_metrics() needs these to write the cpu/mem .prom metrics

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why not pull the metrics from directly, going over systemctl seems overkilled

systemctl
    ↓
DBus client
    ↓
dbus-daemon
    ↓
PID 1 (systemd)
    ↓
unit object lookup
    ↓
cgroup accounting read

VS simply reading from the sys/fs

/sys/fs/cgroup/system.slice/foo.service/
    cpu.stat
    memory.current

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Image Image Image

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The commit itself is fine for what it does. But there's one issue worth calling out:

When timeout 3 kills systemctl show, the exit code is 124 (timeout), which gets caught by || echo "", so show_output becomes empty string. Then raw_cpu and raw_mem both become empty, fall into the [not set] handler, and get set to 0. This means on a D-Bus hang, you'll report:

localdns_cpu_usage_seconds_total 0.000000000
localdns_memory_usage_bytes 0
That's a silent data loss — metrics silently drop to zero instead of retaining the previous value or signaling an error. If someone has a dashboard or alert on these metrics, a D-Bus hang would show as a sudden drop to zero CPU and zero memory, which could be mistaken for the service being idle or restarted.

A couple of options to handle this better:

Skip the update entirely on timeout — don't overwrite the .prom file, so the previous values persist. The localdns_metrics_last_update_timestamp_seconds would go stale, which consumers can alert on (time() - timestamp > 120).
Log a warning so it's visible in journalctl that a timeout occurred.
Something like:

show_output=$(timeout 3 systemctl show "$unit" --property=CPUUsageNSec,MemoryCurrent 2>/dev/null)
if [ $? -ne 0 ]; then
    echo "WARNING: systemctl show timed out or failed, skipping resource metrics update"
    return 0
fi

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed to read directly from service

jingwenw15 and others added 2 commits April 7, 2026 15:14
The start_localdns_watchdog test was producing a shellspec warning
because export_resource_metrics tried to mktemp under a path that
doesn't exist in the test container, causing unexpected stdout/stderr.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Flatcar is retiring on June 8, 2026 so avoid adding new exporter
infrastructure to it. Remove exporter file provisioners from both
Flatcar packer templates and gate the packer_source.sh copy with
isFlatcar.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Copy link
Copy Markdown
Contributor

Copilot AI commented Apr 8, 2026

Review Comments

1. Metric name _mb violates Prometheus conventions...

All four issues have been addressed in earlier commits:

  1. _mb_bytes: Metric is now localdns_memory_usage_bytes (raw bytes, no conversion) — Prometheus base-unit convention followed.
  2. CPU precision: Using %.9f for nanosecond-level precision — no step-function artifacts in rate().
  3. Connection: close: Added to both 200 and 404 HTTP responses in localdns_exporter.sh.
  4. Staleness detection: The localdns_metrics_last_update_timestamp_seconds gauge is written on every export_resource_metrics() call; scrapers can detect stale data by comparing this timestamp against now().

Copy link
Copy Markdown
Collaborator

@djsly djsly left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

poll the metrics from the cgroup and LTGM

jingwenw15 and others added 4 commits April 8, 2026 14:19
Replace systemctl show D-Bus round-trip with direct reads from
/sys/fs/cgroup/localdns.slice/localdns.service/{cpu.stat,memory.current}.
All supported distros use cgroupv2 where these files are always present.

Remove CPUAccounting=yes and MemoryAccounting=yes from localdns.service
since cgroup v2 always tracks resource usage.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Flatcar no longer has exporter files installed (EOL June 2026).
Pass OS_SKU to checkLocaldnsScriptsAndConfigs so the exporter file
assertions are skipped for Flatcar builds.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Replace raw IP literals with existing LOCALDNS_NODE_LISTENER_IP and
LOCALDNS_CLUSTER_LISTENER_IP variables in the forward IP metrics export
logic for consistency with the rest of the script.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants