mirror of
https://github.com/gadgethd/ukmesh.git
synced 2026-12-06 19:24:41 +00:00
99 lines
3.8 KiB
Python
99 lines
3.8 KiB
Python
"""Stream resident service lifecycle evidence from the local Docker Engine."""
|
|
|
|
from contextlib import contextmanager
|
|
from http.client import HTTPConnection
|
|
import json
|
|
import os
|
|
import socket
|
|
import threading
|
|
import time
|
|
from urllib.parse import urlencode
|
|
|
|
from common import DOCKER_SOCKET
|
|
|
|
|
|
ACTIONS = ('oom', 'die', 'restart', 'start')
|
|
MAX_EVENT_BYTES = 64 * 1024
|
|
|
|
|
|
class DockerEventConnection(HTTPConnection):
|
|
def __init__(self, socket_path):
|
|
super().__init__('localhost', timeout=5)
|
|
self.socket_path = socket_path
|
|
|
|
def connect(self):
|
|
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
self.sock.settimeout(self.timeout)
|
|
self.sock.connect(self.socket_path)
|
|
|
|
|
|
def record_events(response, output, required):
|
|
while line := response.readline(MAX_EVENT_BYTES + 1):
|
|
if len(line) > MAX_EVENT_BYTES or not line.endswith(b'\n'):
|
|
raise ValueError('invalid Docker event framing')
|
|
message = json.loads(line)
|
|
if message['Type'] != 'container' or message['Action'] not in ACTIONS:
|
|
continue
|
|
attributes = message['Actor']['Attributes']
|
|
name = attributes['name']
|
|
if name not in required:
|
|
continue
|
|
timestamp = message['timeNano']
|
|
exit_code = attributes.get('exitCode', '')
|
|
if type(timestamp) is not int or timestamp <= 0 or not isinstance(exit_code, str):
|
|
raise ValueError('invalid Docker lifecycle fields')
|
|
exit_code = exit_code if exit_code.isascii() and exit_code.isdecimal() else ''
|
|
output.write(f"{timestamp}\t{name}\t{message['Action']}\t{exit_code}\n")
|
|
|
|
|
|
@contextmanager
|
|
def lifecycle_events(run, required, *, socket_path=DOCKER_SOCKET):
|
|
# A fresh cgroup cannot report its predecessor's exits. Subscribe before
|
|
# sampling and keep the feed open through the final sample.
|
|
filters = {'type': ['container'], 'container': sorted(required), 'event': ACTIONS}
|
|
query = urlencode({'since': int(time.time()), 'filters': json.dumps(filters)})
|
|
with open(run / 'container-lifecycle.tsv', 'x', buffering=1, encoding='utf-8', opener=private_file) as output:
|
|
connection = DockerEventConnection(socket_path)
|
|
try:
|
|
connection.request('GET', '/events?' + query)
|
|
response = connection.getresponse()
|
|
with response:
|
|
if response.status != 200 or connection.sock is None:
|
|
raise RuntimeError('Docker lifecycle subscription could not be established')
|
|
transport = connection.sock
|
|
transport.settimeout(None)
|
|
stopping = threading.Event()
|
|
ended_early = threading.Event()
|
|
|
|
def collect():
|
|
try:
|
|
record_events(response, output, required)
|
|
except Exception:
|
|
# A half-read event at intentional shutdown is expected.
|
|
pass
|
|
finally:
|
|
if not stopping.is_set():
|
|
ended_early.set()
|
|
|
|
worker = threading.Thread(target=collect, name='docker-lifecycle', daemon=True)
|
|
worker.start()
|
|
try:
|
|
yield
|
|
finally:
|
|
stopping.set()
|
|
try:
|
|
transport.shutdown(socket.SHUT_RDWR)
|
|
except OSError:
|
|
pass
|
|
worker.join(timeout=5)
|
|
if worker.is_alive():
|
|
raise RuntimeError('Docker lifecycle subscription did not stop')
|
|
if ended_early.is_set():
|
|
raise RuntimeError('container lifecycle subscription ended early')
|
|
finally:
|
|
connection.close()
|
|
|
|
|
|
def private_file(path, flags):
|
|
return os.open(path, flags, 0o600)
|