52 lines
1.4 KiB
Python
52 lines
1.4 KiB
Python
"""Map a live process alias to a Compose container, then control that container."""
|
|
|
|
import argparse
|
|
import json
|
|
import os
|
|
import subprocess
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
PROBE = """
|
|
import urllib.request
|
|
response = urllib.request.urlopen("http://127.0.0.1:8080/health/live", timeout=3)
|
|
print(response.headers["X-Instance-Id"])
|
|
"""
|
|
|
|
|
|
def docker(*args, capture=True):
|
|
return subprocess.run(
|
|
("docker", *args), cwd=ROOT, capture_output=capture, text=True,
|
|
check=True, timeout=60,
|
|
).stdout
|
|
|
|
|
|
def replicas():
|
|
result = {}
|
|
for container in docker("compose", "ps", "-q", "api").split():
|
|
try:
|
|
alias = docker("exec", container, "python", "-c", PROBE).strip()
|
|
except subprocess.CalledProcessError:
|
|
continue
|
|
if alias and alias not in result:
|
|
result[alias] = container
|
|
return result
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("operation", choices=("list", "stop"))
|
|
args = parser.parse_args()
|
|
mapping = replicas()
|
|
if args.operation == "list":
|
|
print(json.dumps(mapping, indent=2))
|
|
return
|
|
alias = os.environ.get("TARGET_INSTANCE_ID")
|
|
if not alias or alias not in mapping:
|
|
raise SystemExit("TARGET_INSTANCE_ID must match a running API process")
|
|
docker("stop", "--timeout", "10", mapping[alias], capture=False)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|