forked from mtusi2026/mtusi2026lab5
86 lines
2.8 KiB
Python
86 lines
2.8 KiB
Python
"""Whitelisted Docker lifecycle events; never serialize environment or exec args."""
|
|
|
|
import json
|
|
import subprocess
|
|
import threading
|
|
|
|
|
|
class LifecycleEvents:
|
|
def __init__(self, project, path):
|
|
self.closing = False
|
|
self.oom = 0
|
|
self.failed = False
|
|
self.path = path
|
|
self.process = subprocess.Popen(
|
|
[
|
|
"docker",
|
|
"events",
|
|
"--filter",
|
|
"label=com.docker.compose.project=" + project,
|
|
"--format",
|
|
"{{json .}}",
|
|
],
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.DEVNULL,
|
|
text=True,
|
|
)
|
|
self.thread = threading.Thread(target=self.read, daemon=True)
|
|
self.thread.start()
|
|
|
|
def read(self):
|
|
try:
|
|
with self.path.open("x") as output:
|
|
for line in self.process.stdout:
|
|
try:
|
|
event = json.loads(line)
|
|
except json.JSONDecodeError:
|
|
if self.closing:
|
|
break
|
|
raise
|
|
action = event.get("Action", "")
|
|
if event.get("Type") != "container" or action not in (
|
|
"create",
|
|
"start",
|
|
"stop",
|
|
"kill",
|
|
"die",
|
|
"restart",
|
|
"destroy",
|
|
"oom",
|
|
"pause",
|
|
"unpause",
|
|
):
|
|
continue
|
|
actor = event.get("Actor", {})
|
|
attributes = actor.get("Attributes", {})
|
|
value = {
|
|
"time_nano": event.get("timeNano"),
|
|
"action": action,
|
|
"container_id": actor.get("ID"),
|
|
"service": attributes.get("com.docker.compose.service"),
|
|
"exit_code": attributes.get("exitCode"),
|
|
"signal": attributes.get("signal"),
|
|
}
|
|
if action == "oom":
|
|
self.oom += 1
|
|
output.write(json.dumps(value) + "\n")
|
|
output.flush()
|
|
except Exception:
|
|
self.failed = True
|
|
finally:
|
|
if not self.closing:
|
|
self.failed = True
|
|
|
|
def close(self):
|
|
self.closing = True
|
|
if self.process.poll() is None:
|
|
self.process.terminate()
|
|
try:
|
|
self.process.wait(timeout=5)
|
|
except subprocess.TimeoutExpired:
|
|
self.process.kill()
|
|
self.process.wait()
|
|
self.thread.join(timeout=5)
|
|
if self.thread.is_alive():
|
|
self.failed = True
|