diff --git a/scripts/nomad_orphan_services.py b/scripts/nomad_orphan_services.py index 75a43ad..9eb7f10 100755 --- a/scripts/nomad_orphan_services.py +++ b/scripts/nomad_orphan_services.py @@ -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)