Add a read-only check for orphaned service script

This commit is contained in:
IamTheFij 2023-08-28 13:54:06 -07:00
parent 08f92f8ba5
commit 50447b9a7d
1 changed files with 20 additions and 2 deletions

View File

@ -1,4 +1,5 @@
#! /usr/bin/env python3
from argparse import ArgumentParser
from os import environ
from typing import Any
from typing import cast
@ -31,6 +32,14 @@ def nomad_req(
return response.text
exit_code = 0
parser = ArgumentParser(
description="Checks for orphaned services and optional deletes them.",
)
parser.add_argument("-d", "--delete", action="store_true", help="Delete orphan services")
args = parser.parse_args()
for namespace in nomad_req("services"):
namespace = cast(dict[str, Any], namespace)
for service in namespace["Services"]:
@ -40,13 +49,22 @@ for namespace in nomad_req("services"):
service_id = service_instance["ID"]
alloc_id = service_instance["AllocID"]
alloc_found = True
try:
alloc = nomad_req("allocation", alloc_id)
continue
except requests.exceptions.HTTPError as e:
if e.response.status_code == 404:
alloc_found = False
print(
f"alloc {alloc_id} not found for {service_name}. Deleting {service_id}"
)
nomad_req("service", service_name, service_id, method="DELETE")
raise e
else:
raise e
if not alloc_found and args.delete:
nomad_req("service", service_name, service_id, method="DELETE")
exit(exit_code)