50 lines
2.1 KiB
Python
50 lines
2.1 KiB
Python
"""CPU-only Docker HTTP probe that also works with a remote Docker daemon."""
|
|
import json
|
|
import subprocess
|
|
import uuid
|
|
|
|
|
|
# Official Python 3.11.17 slim OCI index, including Linux amd64 and arm64.
|
|
# Python belongs to this disposable test helper, never the serving image.
|
|
PROBE_IMAGE = 'python@sha256:0dd364ba7e10242f07755449e3a3d0e35f9efd987952737b90def6709ab0c5ce'
|
|
ISOLATION = ['--read-only', '--user', '65532:65532', '--cap-drop', 'ALL',
|
|
'--security-opt', 'no-new-privileges', '-e', 'CUDA_VISIBLE_DEVICES=',
|
|
'-e', 'NVIDIA_VISIBLE_DEVICES=void']
|
|
PROBE = '''import json,sys,urllib.error,urllib.request
|
|
route,payload=sys.argv[1:]
|
|
body=None if payload == 'null' else json.dumps(json.loads(payload)).encode()
|
|
request=urllib.request.Request('http://127.0.0.1:8081'+route,data=body,
|
|
headers={'Content-Type':'application/json'})
|
|
opener=urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
|
try:
|
|
response=opener.open(request,timeout=5)
|
|
except urllib.error.HTTPError as error:
|
|
response=error
|
|
with response:
|
|
print(json.dumps({'status':response.status,'body':json.load(response)}))
|
|
'''
|
|
|
|
|
|
def docker(*args, check=True, timeout=30):
|
|
return subprocess.run(['docker', *map(str, args)], check=check,
|
|
capture_output=True, text=True, timeout=timeout)
|
|
|
|
|
|
def prepare_probe():
|
|
if docker('image', 'inspect', PROBE_IMAGE, check=False).returncode:
|
|
docker('pull', PROBE_IMAGE, timeout=120)
|
|
identity = docker('image', 'inspect', '--format', '{{.Id}}', PROBE_IMAGE).stdout.strip()
|
|
print(f'Isolated HTTP probe: {PROBE_IMAGE}, local image {identity}', flush=True)
|
|
|
|
|
|
def request(container, route, body=None):
|
|
name = 'strata-http-probe-' + uuid.uuid4().hex
|
|
try:
|
|
result = docker('run', '--rm', '--name', name, *ISOLATION,
|
|
'--network', f'container:{container}', '--entrypoint', 'python3',
|
|
PROBE_IMAGE, '-c', PROBE, route, json.dumps(body))
|
|
decoded = json.loads(result.stdout)
|
|
return decoded['status'], decoded['body']
|
|
finally:
|
|
docker('rm', '-f', name, check=False)
|