Skip to content

Live metrics via PaaS API — building a polling dashboard outside the UI

The dashboard's pretty charts hide what you actually need: a queryable, scriptable metrics surface. Build a polling dashboard against the PaaS API that lives next to your other observability tooling.

You inherit an environment running on a managed PaaS. The platform UI has perfectly serviceable charts — CPU per node, memory per node, network per node — but they live in a browser tab nobody keeps open, they don’t alert, and they don’t sit next to the metrics from the rest of your stack. The first time the platform charts and your application metrics disagree about whether the box is hot, you find out the dashboard is a sales artifact, not an observability tool. You need the same numbers in Prometheus.

What’s happening

Every managed PaaS exposes per-node resource counters: CPU usage, memory used vs. limit, disk IO, network throughput, container restarts. The dashboard reads these from the same place the API does. The dashboard refreshes at a fixed interval (often 30s or 60s) and that’s it — no retention, no derived metrics, no alerts on the slope of memory growth. The API gives you the raw counters at a granularity of one minute or finer and lets you pull them into whatever you already trust. The catch is that the metrics endpoints are pay-per-call: each poll counts against the same token quota as log reads, and a naive 10-second poll across 12 nodes will eat the quota in the middle of business hours. The right pattern is a single collector process that polls at a sane cadence, normalizes the response into Prometheus exposition format, and exposes itself as a scrape target — so your Grafana sees PaaS metrics next to everything else.

How to verify

Confirm the metrics endpoint works against a single node. Get the node ID list (see accessing container logs for token setup) and pull stats:

export PAAS_API="https://app.cloud.example.com/1.0"
export PAAS_TOKEN="paste-token-here"
export PAAS_ENVNAME="prod-api"

NODE_ID=184372

curl -sS "${PAAS_API}/statistic/system/rest/getstats" \
  -d "session=${PAAS_TOKEN}" \
  -d "envName=${PAAS_ENVNAME}" \
  -d "nodeid=${NODE_ID}" \
  -d "duration=300" \
  -d "interval=60" \
  | jq '.array[0] | {time, cpu, mem, net_ext_in, net_ext_out, disk_iops}'

You should see something like:

{
  "time": 1714838400,
  "cpu": 38.4,
  "mem": 612434232,
  "net_ext_in": 12838,
  "net_ext_out": 48211,
  "disk_iops": 47
}

CPU is a percentage of allocated cloudlets, mem is bytes used. If you don’t see these fields, check result — value 4 typically means the node has no statistics agent installed (a stack template issue, not an API problem).

The fix

A 70-line Python collector that exposes itself on :9183/metrics for Prometheus to scrape. Save as /opt/paas-exporter/exporter.py:

#!/usr/bin/env python3
"""Prometheus exporter for managed PaaS per-node statistics."""
import os, sys, time, threading
import requests
from http.server import BaseHTTPRequestHandler, HTTPServer

PAAS_API = os.environ["PAAS_API"]
PAAS_TOKEN = os.environ["PAAS_TOKEN"]
PAAS_ENVNAME = os.environ["PAAS_ENVNAME"]
POLL_SECONDS = int(os.environ.get("POLL_SECONDS", "60"))

STATE = {"text": "# starting up\n", "last_ok": 0}

def list_nodes():
    r = requests.post(
        f"{PAAS_API}/environment/control/rest/getenvinfo",
        data={"session": PAAS_TOKEN, "envName": PAAS_ENVNAME},
        timeout=15,
    )
    r.raise_for_status()
    return [
        {"id": n["id"], "name": n.get("name", "unknown"),
         "type": n.get("nodeType", "unknown")}
        for n in r.json().get("nodes", [])
    ]

def get_stats(node_id):
    r = requests.post(
        f"{PAAS_API}/statistic/system/rest/getstats",
        data={"session": PAAS_TOKEN, "envName": PAAS_ENVNAME,
              "nodeid": node_id, "duration": 120, "interval": 60},
        timeout=20,
    )
    r.raise_for_status()
    arr = r.json().get("array", [])
    return arr[-1] if arr else None

def loop():
    while True:
        out = ["# HELP paas_node_cpu_percent CPU usage (%)",
               "# TYPE paas_node_cpu_percent gauge",
               "# HELP paas_node_mem_bytes Memory used (bytes)",
               "# TYPE paas_node_mem_bytes gauge",
               "# HELP paas_node_net_in_bytes Inbound network (bytes/min)",
               "# TYPE paas_node_net_in_bytes gauge",
               "# HELP paas_node_net_out_bytes Outbound network (bytes/min)",
               "# TYPE paas_node_net_out_bytes gauge",
               "# HELP paas_node_disk_iops Disk IOPS",
               "# TYPE paas_node_disk_iops gauge",
               "# HELP paas_scrape_success Scrape success per node",
               "# TYPE paas_scrape_success gauge"]
        try:
            nodes = list_nodes()
        except Exception as e:
            sys.stderr.write(f"list_nodes failed: {e}\n")
            time.sleep(POLL_SECONDS)
            continue

        for n in nodes:
            labels = f'node_id="{n["id"]}",node_name="{n["name"]}",node_type="{n["type"]}"'
            try:
                s = get_stats(n["id"])
                if not s:
                    out.append(f'paas_scrape_success{{{labels}}} 0')
                    continue
                out.append(f'paas_node_cpu_percent{{{labels}}} {s.get("cpu",0)}')
                out.append(f'paas_node_mem_bytes{{{labels}}} {s.get("mem",0)}')
                out.append(f'paas_node_net_in_bytes{{{labels}}} {s.get("net_ext_in",0)}')
                out.append(f'paas_node_net_out_bytes{{{labels}}} {s.get("net_ext_out",0)}')
                out.append(f'paas_node_disk_iops{{{labels}}} {s.get("disk_iops",0)}')
                out.append(f'paas_scrape_success{{{labels}}} 1')
            except Exception as e:
                sys.stderr.write(f"node {n['id']} stats failed: {e}\n")
                out.append(f'paas_scrape_success{{{labels}}} 0')
            # Be polite to the API rate limiter.
            time.sleep(0.4)

        STATE["text"] = "\n".join(out) + "\n"
        STATE["last_ok"] = int(time.time())
        time.sleep(POLL_SECONDS)

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path != "/metrics":
            self.send_response(404); self.end_headers(); return
        body = STATE["text"].encode("utf-8")
        self.send_response(200)
        self.send_header("Content-Type", "text/plain; version=0.0.4")
        self.end_headers()
        self.wfile.write(body)
    def log_message(self, *a): pass

if __name__ == "__main__":
    threading.Thread(target=loop, daemon=True).start()
    HTTPServer(("0.0.0.0", 9183), Handler).serve_forever()

Run it under systemd with the token in EnvironmentFile=:

[Unit]
Description=PaaS metrics exporter
After=network-online.target

[Service]
Type=simple
EnvironmentFile=/etc/paas-exporter/env
ExecStart=/usr/bin/python3 /opt/paas-exporter/exporter.py
Restart=on-failure
User=paas-exporter
LimitNOFILE=4096

[Install]
WantedBy=multi-user.target

Add a Prometheus scrape job:

- job_name: paas-platform
  scrape_interval: 60s
  static_configs:
    - targets: ['paas-exporter.internal:9183']

Two operational notes. First, the API quota is the constraint — at 12 nodes and a 60-second cadence, you’re using roughly 720 calls per hour just for node stats, plus the getenvinfo call. If your token’s window is 1000/hour, you have no headroom for logs or anything else. Either dedicate a token to the exporter or raise the cadence to 120s. Second, alert on paas_scrape_success == 0 — when the platform API throttles you or revokes the token, the exporter quietly returns stale data, and silence is the failure mode you want to catch.

We instrument managed PaaS environments with platform-aware metrics as part of monitoring and support on managed PaaS — scope a metrics rollout if you need it sooner than your team can do it themselves.