#!/usr/bin/python3
#
# systemd/journalctl show timestamps in a container that come from
# the monotonic system clock, which is not namesapced. This means
# that the output is not terribly useful for determining boot time
# of a container.
#
# /proc/uptime in lxd shows a timestamp relative to the start of
# the container.
#
# So, we can figure out at what monontonic time this container
# started by subtracting the value in /proc/uptime from time.monotonic()
#
# Then, we can filter the output of journalctl --output=short-monotonic
# and adjust the timestamps to get information useful in a container.
# It works in a non-container also because uptime and monotonic will
# be close-enough that we throw away numbers < 1.
#
# Usage for this tool is simple:
# lxd-journalctl [journalctl [arguments]]
#
import subprocess
import sys
import time
with open("/proc/uptime") as fp:
uptime_s, _idle = fp.read().split()
mono = time.monotonic()
delta = mono - float(uptime_s)
if delta < 1:
delta = 0
print("delta is %03f" % (mono - float(uptime_s)))
out = subprocess.check_output(
['journalctl', '--no-pager', '--output=short-monotonic'] + sys.argv[1:])
for line in out.splitlines():
if line.startswith(b'['):
end_time = line.index(b']')
fmt = b"[%%%df]" % (end_time - 2)
ts = float(line[1:end_time])
line = fmt % (ts - delta) + line[end_time+1:]
sys.stdout.buffer.write(line + b'\n')