Metric exporter for Pinecrypt Gateway
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
3.0 KiB

#!/usr/bin/env python
import aiohttp
import asyncio
import os
import re
from collections import Counter
from sanic import Sanic, response, exceptions
app = Sanic("exporter")
PREFIX = "pinecrypt_gateway_"
raise ValueError("No PROMETHEUS_BEARER_TOKEN specified")
async def wrap(i):
metrics_seen = set()
async for name, tp, value, labels in i:
if name not in metrics_seen:
yield "# TYPE %s %s" % (PREFIX + name, tp)
yield "%s%s %d" % (
PREFIX + name,
("{%s}" % ",".join(["%s=\"%s\"" % j for j in labels.items()]) if labels else ""),
async def exporter_stats():
# Export number of open file handles
yield "exporter_file_descriptors", "gauge", len(os.listdir("/proc/self/fd")), {}
async def openvpn_stats(port, service):
last_seen = Counter()
# Export OpenVPN status
reader, writer = await asyncio.open_connection("", port)
writer.write(b"status 2\n")
await writer.drain()
while True:
line = await reader.readline()
values = line.decode("ascii").strip().split(",")
header = values[0]
if header == "END":
elif header == "CLIENT_LIST":
_, cn, remote, _, _, rxbytes, txbytes, _, since, _, cid, pid, cipher = values
labels = {"cn": cn, "service": service}
yield "client_connected_since", "gauge", int(since), labels
labels["cipher"] = cipher
yield "client_rx_bytes", "counter", int(rxbytes), labels
yield "client_tx_bytes", "counter", int(txbytes), labels
elif header == "ROUTING_TABLE":
_, addr, cn, remote, _, last_ref = values
last_seen[cn] = max(last_seen[cn], int(last_ref))
await writer.wait_closed()
for key, value in last_seen.items():
yield "client_last_seen", "gauge", value, {"cn": key, "service": service}
async def view_export(request):
if request.token != PROMETHEUS_BEARER_TOKEN:
raise exceptions.Forbidden("Invalid bearer token")
async def streaming_fn(response):
for i in exporter_stats(), openvpn_stats(7505, "openvpn-udp"), openvpn_stats(7506, "openvpn-tcp"):
async for line in wrap(i):
await response.write(line + "\n")
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=5)) as session:
for port in (4001, 5001, 8001, 9001):
async with session.get("" % port) as upstream_response:
async for line in upstream_response.content:
if not re.match("(# (HELP|TYPE) )?(pinecrypt|goredns)_", line.decode("ascii")):
await response.write(line)
return, content_type="text/plain")