add tests

This commit is contained in:
Abel Luck 2023-11-06 09:01:18 +01:00
parent 604d2b3385
commit 12f55ad721
2 changed files with 133 additions and 13 deletions

View file

@ -70,7 +70,7 @@ def group_by_type(input_list):
return result
def tailscale_labels(device) -> Dict[str, str]:
def tailscale_labels(tailnet, device) -> Dict[str, str]:
return {
"__meta_tailscale_device_client_version": device["clientVersion"],
"__meta_tailscale_device_hostname": device["hostname"],
@ -78,7 +78,7 @@ def tailscale_labels(device) -> Dict[str, str]:
"__meta_tailscale_device_id": device["id"],
"__meta_tailscale_device_name": device["name"],
"__meta_tailscale_device_os": device["os"],
"__meta_tailscale_tailnet": settings.tailnet,
"__meta_tailscale_tailnet": tailnet,
}
@ -90,13 +90,12 @@ async def matrix_node_sd(device) -> Dict:
return group_by_type(data)
def matrix_workers_to_sd(device, workers) -> List:
def matrix_workers_to_sd(tailnet, device, workers) -> List:
if len(workers) == 0:
return []
ipv4 = ipv4_only(device["addresses"])[0]
target_groups = []
for worker_type, workers in workers.items():
targets = []
for worker in workers:
port = worker["metrics_port"]
worker_name = worker.get("name", "WORKER_NO_NAME")
@ -105,11 +104,10 @@ def matrix_workers_to_sd(device, workers) -> List:
f"Error parsing worker {worker_name} on host={device['hostname']}. Port is invalid port={port}"
)
continue
targets.append(f"{ipv4}:{port}")
target_groups.append(
{
"targets": targets,
"labels": tailscale_labels(device)
"targets": [f"{ipv4}:{port}"],
"labels": tailscale_labels(tailnet, device)
| {
"__meta_matrix_worker_type": worker_type,
"__meta_matrix_worker_name": worker_name,
@ -119,7 +117,7 @@ def matrix_workers_to_sd(device, workers) -> List:
return target_groups
async def matrix_sd(devices) -> List:
async def matrix_sd(tailnet, devices) -> List:
sd = []
for device in devices:
if "tag:matrix" not in device["tags"]:
@ -132,17 +130,17 @@ async def matrix_sd(devices) -> List:
exc_info=e,
)
workers = {}
targets = matrix_workers_to_sd(device, workers)
targets = matrix_workers_to_sd(tailnet, device, workers)
if targets:
sd.append(targets)
return []
def plain_devices_sd(devices) -> List:
def plain_devices_sd(tailnet, devices) -> List:
sd = []
for device in devices:
targets = ipv4_only(device["addresses"])
labels = tailscale_labels(device)
labels = tailscale_labels(tailnet, device)
sd.append({"labels": labels, "targets": targets})
return sd
@ -153,8 +151,8 @@ async def poll_sd():
while True:
try:
devices = await tailscale_devices()
device_targets = plain_devices_sd(devices)
matrix_targets = await matrix_sd(devices)
device_targets = plain_devices_sd(settings.tailnet, devices)
matrix_targets = await matrix_sd(settings.tailnet, devices)
CACHE_SD = matrix_targets + device_targets
await asyncio.sleep(settings.interval)
except Exception as e: