mirror of
https://github.com/gadgethd/ukmesh.git
synced 2026-12-06 03:14:09 +00:00
98 lines
5.0 KiB
Python
98 lines
5.0 KiB
Python
from concurrent.futures import ThreadPoolExecutor
|
|
from contextlib import contextmanager
|
|
import json
|
|
from pathlib import Path
|
|
import socket
|
|
import tempfile
|
|
import threading
|
|
import time
|
|
import unittest
|
|
from urllib.parse import parse_qs, urlsplit
|
|
|
|
from docker_events import ACTIONS, lifecycle_events
|
|
|
|
|
|
def event(action, *, name='api', kind='container', exit_code=None):
|
|
attributes = {'name': name, 'irrelevant': 'synthetic-label'}
|
|
if exit_code is not None:
|
|
attributes['exitCode'] = exit_code
|
|
return json.dumps({'Type': kind, 'Action': action, 'Actor': {'Attributes': attributes},
|
|
'timeNano': 123456789}).encode() + b'\n'
|
|
|
|
|
|
@contextmanager
|
|
def engine(directory, payloads, *, keep_open=True, accepted=True):
|
|
path = str(directory / 'docker.sock')
|
|
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as listener, ThreadPoolExecutor(1) as pool:
|
|
listener.bind(path)
|
|
listener.listen()
|
|
listener.settimeout(3)
|
|
|
|
def serve():
|
|
connection, _ = listener.accept()
|
|
with connection, connection.makefile('rb') as request:
|
|
connection.settimeout(3)
|
|
target = request.readline().decode().split()[1]
|
|
while request.readline() not in (b'\r\n', b''):
|
|
pass
|
|
if not accepted:
|
|
connection.sendall(b'HTTP/1.1 500 Unavailable\r\nContent-Length: 0\r\n\r\n')
|
|
return target
|
|
response = b'HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n'
|
|
response += b''.join(f'{len(payload):x}\r\n'.encode() + payload + b'\r\n' for payload in payloads)
|
|
# The client can close as soon as an invalid event is available.
|
|
# Send the finite response in one write so the mock has no trailing write to race.
|
|
connection.sendall(response if keep_open else response + b'0\r\n\r\n')
|
|
if keep_open:
|
|
if request.read(1) != b'':
|
|
raise AssertionError('event subscription sent unexpected body data')
|
|
return target
|
|
|
|
exchange = pool.submit(serve)
|
|
yield path, exchange
|
|
exchange.result(timeout=4)
|
|
|
|
|
|
class DockerLifecycleTests(unittest.TestCase):
|
|
def test_selected_events_are_flushed_as_minimal_private_records(self):
|
|
events = [event('start'), event('die', exit_code='137'), event('restart'), event('oom'),
|
|
event('start', name='other'), event('die', kind='network'), event('inspect')]
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
root = Path(directory)
|
|
expected = ['123456789\tapi\tstart\t', '123456789\tapi\tdie\t137',
|
|
'123456789\tapi\trestart\t', '123456789\tapi\toom\t']
|
|
with engine(root, events) as (path, exchange):
|
|
with lifecycle_events(root, {'api', 'broker'}, socket_path=path):
|
|
receipt = root / 'container-lifecycle.tsv'
|
|
deadline = time.monotonic() + 2
|
|
while len(receipt.read_text().splitlines()) < len(expected) and time.monotonic() < deadline:
|
|
time.sleep(.01)
|
|
self.assertEqual(receipt.read_text().splitlines(), expected)
|
|
self.assertEqual(receipt.stat().st_mode & 0o777, 0o600)
|
|
url = urlsplit(exchange.result(timeout=2))
|
|
self.assertEqual(url.path, '/events')
|
|
parameters = parse_qs(url.query)
|
|
self.assertLessEqual(abs(int(parameters['since'][0]) - int(time.time())), 5)
|
|
self.assertEqual(json.loads(parameters['filters'][0]),
|
|
{'container': ['api', 'broker'], 'type': ['container'], 'event': list(ACTIONS)})
|
|
|
|
def test_a_missing_or_invalid_event_stream_fails_qualification(self):
|
|
for payloads in ([], [b'not-json\n'], [b'x' * (64 * 1024 + 1)]):
|
|
with self.subTest(payload_bytes=sum(map(len, payloads))), tempfile.TemporaryDirectory() as directory:
|
|
root = Path(directory)
|
|
with engine(root, payloads, keep_open=False) as (path, _):
|
|
with self.assertRaisesRegex(RuntimeError, 'subscription ended early'):
|
|
with lifecycle_events(root, {'api'}, socket_path=path):
|
|
deadline = time.monotonic() + 2
|
|
while any(t.name == 'docker-lifecycle' for t in threading.enumerate()):
|
|
self.assertLess(time.monotonic(), deadline)
|
|
time.sleep(.01)
|
|
|
|
def test_a_rejected_subscription_fails_before_sampling(self):
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
root = Path(directory)
|
|
with engine(root, [], accepted=False) as (path, _):
|
|
with self.assertRaisesRegex(RuntimeError, 'could not be established'):
|
|
with lifecycle_events(root, {'api'}, socket_path=path):
|
|
self.fail('qualification started without a lifecycle subscription')
|