Turning ZTE C320 ONU inventory into Prometheus metrics
An OLT knows things about your network that no router does: which ONU is registered, on which PON port, with which serial number, in which state, and since when. Almost nobody exports that as metrics. The result is a blind spot that shows up as "customer complains, technician drives to the pole, ONU is LOS" — an hour of work that a single gauge would have predicted.
This is how I turn a ZTE C320's ONU inventory into Prometheus metrics without a vendor NMS, an SNMP MIB marathon, or a per-ONU polling loop that takes ten minutes per scrape.
The problem with per-ONU polling
The naive approach is to ask the OLT about every ONU: state, optical level, last-down-reason. On a shelf with 1,200 ONUs that is 1,200 CLI commands or 1,200 SNMP GETs per cycle. It works on a lab bench and collapses in production: SSH session timeouts, 40-minute poll cycles, and an OLT control plane that starts dropping management traffic while it is busy forwarding customer traffic.
The fix is to poll aggregates and deltas, not everything:
- Per-port state listing — one command per PON port, not per ONU.
- Per-ONU detail only for ONUs that are not in working state.
- Inventory (serial, name, port) once per cycle, cached, diffed against the previous run.
On 16 PON ports that is 16 commands plus a handful of detail queries — a few seconds, not minutes.
What the CLI actually gives you
Command names drift between firmware versions, so verify on your shelf before trusting any script (including this one). The shape of the output is what matters:
ZXAN# show gpon onu state gpon-olt_1/2/3
OnuIndex Admin State OMCC State Phase State Channel
gpon-onu_1/2/3:1 enable enable working 1
gpon-onu_1/2/3:2 enable enable LOS 1
gpon-onu_1/2/3:7 enable disable OffLine 1
Three columns matter: the ONU index (which encodes port and ONU ID), the admin state, and the phase state. Everything else is noise for monitoring purposes.
ZXAN# show gpon onu baseinfo gpon-olt_1/2/3
OnuIndex Name Sn Type Distance
gpon-onu_1/2/3:1 AGIL-RT-0142 ZTEGC0A1B2C3 F601 1240
gpon-onu_1/2/3:2 AGIL-RT-0187 ZTEGC0D4E5F6 F601 2310
The Name field is the leverage point: if you name ONUs by subscriber identifier at provisioning time, then inventory reconciliation becomes a join, not an investigation.
Design: one collector, one textfile
systemd timer (5 min)
│
▼
olt_inventory.py ──SSH (read-only)──▶ ZTE C320
│
├─▶ /var/lib/node_exporter/textfile_collector/olt.prom (metrics)
└─▶ /var/lib/olt-inventory/last.json (cache + diff)
Prometheus never talks to the OLT. It scrapes node_exporter, which publishes whatever the textfile collector drops in a directory. That decoupling means a slow or unreachable OLT never blocks a scrape — it just makes the metrics stale, which is a separate alert.
The collector
Read-only SSH key, no password, no interactive shell. The script keeps a single session per run and never retries inside the same session:
import json, re, subprocess, pathlib, time
OLT = "[email protected]"
KEY = "/etc/olt-inventory/id_ro"
PORTS = [f"gpon-olt_1/{s}/{p}" for s in (1, 2) for p in range(1, 9)]
PROM = pathlib.Path("/var/lib/node_exporter/textfile_collector/olt.prom")
CACHE = pathlib.Path("/var/lib/olt-inventory/last.json")
STATE = {"working": 1} # everything else counts as down
RE_STATE = re.compile(r"^\s*(gpon-onu_[\d/]+:\d+)\s+(\w+)\s+(\w+)\s+(\w+)")
RE_BASE = re.compile(r"^\s*(gpon-onu_[\d/]+:\d+)\s+(\S+)\s+(\S+)\s+(\S+)")
def ssh(cmd: str, timeout: int = 45) -> str:
r = subprocess.run(
["ssh", "-i", KEY, "-o", "BatchMode=yes", "-o", "ConnectTimeout=10", OLT, cmd],
capture_output=True, text=True, timeout=timeout,
)
return r.stdout
def collect():
onus, samples = {}, []
for port in PORTS:
out = ssh(f"show gpon onu state {port}")
for line in out.splitlines():
m = RE_STATE.match(line)
if not m:
continue
idx, admin, omcc, phase = m.groups()
onus[idx] = {"port": port, "admin": admin, "phase": phase, "name": "", "sn": ""}
samples.append((idx, port, 1 if phase in STATE else 0, phase))
base = ssh(f"show gpon onu baseinfo {port}")
for line in base.splitlines():
m = RE_BASE.match(line)
if m and m.group(1) in onus:
onus[m.group(1)]["name"] = m.group(2)
onus[m.group(1)]["sn"] = m.group(3)
return onus, samples
Two practical details that cost me a day each:
- Paging. Long port listings can paginate and silently truncate. Add
| no-more(or disable paging for the account) or you will monitor half your ONUs and never notice. - Timeouts per port. One slow port should not kill the whole run. Wrap each port call in its own try/except, record a failure metric, and keep going.
Inventory as a metric, not a spreadsheet
The numbers worth exposing are counts and drift, not 1,200 individual series. Per port and per state, plus a heartbeat:
def render(onus, errors):
lines = [
"# HELP olt_onu_up ONU phase state (1 = working, 0 = down)",
"# TYPE olt_onu_up gauge",
"# HELP olt_onu_count ONUs registered per PON port",
"# TYPE olt_onu_count gauge",
"# HELP olt_onu_collector_errors Ports that failed this cycle",
"# TYPE olt_onu_collector_errors gauge",
"# HELP olt_onu_last_run_seconds Unix time of last successful collection",
"# TYPE olt_onu_last_run_seconds gauge",
]
per_port, down = {}, []
for idx, port, up, phase in SAMPLES:
per_port[port] = per_port.get(port, 0) + 1
lines.append(f'olt_onu_up{{onu="{idx}",port="{port}",phase="{phase}"}} {up}')
if not up:
down.append(idx)
for port, n in per_port.items():
lines.append(f'olt_onu_count{{port="{port}"}} {n}')
lines.append(f"olt_onu_collector_errors {len(errors)}")
lines.append(f"olt_onu_last_run_seconds {int(time.time())}" if not errors else "")
tmp = PROM.with_suffix(".tmp")
tmp.write_text("\n".join(x for x in lines if x) + "\n")
tmp.replace(PROM)
Writing to a temporary file and renaming it is not a style preference: node_exporter reads the directory on scrape, and a half-written file produces a parse error that silently drops every metric in it.
Alerts that catch real failures
Four rules, each tied to a failure I have actually had:
groups:
- name: olt-inventory
rules:
- alert: OltCollectorStale
expr: time() - olt_onu_last_run_seconds > 900
for: 5m
labels: { severity: warning }
annotations:
summary: "OLT inventory collector has not reported for 15+ minutes"
- alert: OltCollectorPartial
expr: olt_onu_collector_errors > 0
for: 10m
labels: { severity: warning }
- alert: PonPortNearCapacity
expr: olt_onu_count > 58
for: 30m
labels: { severity: info }
annotations:
summary: "PON port {{ $labels.port }} at {{ $value }} ONUs (split 1:64)"
- alert: OnuDownLong
expr: olt_onu_up == 0
for: 30m
labels: { severity: warning }
OltCollectorStale is the rule that keeps the rest honest. Without it, a broken collector looks exactly like a healthy network: no alerts, no data, and everyone assumes it is fine. This is the same failure mode that killed the previous monitoring setup I inherited — processes alive, database empty.
Reconciliation: the metric nobody builds
Once inventory is in Prometheus, compare it with what your billing system thinks exists. Two numbers matter:
- ONUs registered but not in billing — potential theft of service, or a provisioning leak.
- Subscribers in billing but no ONU on the OLT — dead records that inflate customer counts.
I export both as counters from the same collector, joining against a read-only view of the billing database:
import pymysql
def reconcile(onu_names):
db = pymysql.connect(read_default_file="/etc/olt-inventory/billing.cnf",
cursorclass=pymysql.cursors.DictCursor)
with db.cursor() as cur:
cur.execute("SELECT username FROM subscribers WHERE active = 1")
billed = {row["username"] for row in cur}
olt = {n for n in onu_names if n}
return len(olt - billed), len(billed - olt) # orphan_onu, ghost_subscriber
Exposing olt_onu_orphan_total and olt_ghost_subscriber_total turned a quarterly manual audit into a dashboard that updates every five minutes. The first run found 37 ghost subscribers — accounts still being invoiced for hardware that had been removed months earlier.
What broke in production
- Ten-minute collection, then nothing. The OLT's management CPU throttles under CLI load. Fix: 16 targeted commands instead of 1,200, and a five-minute timer instead of one.
- Duplicate serials. A clone ONU registered twice produced two identical inventory rows and confused reconciliation. Fix: alert on
count by (sn) (olt_onu_up) > 1. - ONU rename churn. Provisioning changed names weekly, so labels changed and series churned. Fix: keep the ONU index as the label, expose the name only in the reconciliation join.
- Prometheus staleness. When the collector died, the last value lived for five minutes and then vanished — which is correct, and exactly why the heartbeat alert exists.
Why this is worth the effort
The C320 will tell you which ONU went down, when, and on which port. The only reason most teams find out from a phone call is that nobody asked it in a format their monitoring can read. One script, one systemd timer, and a textfile turn the OLT into a first-class metric source — and the reconciliation numbers turn it into a business check, not just a network one.