Helper scripts
This commit is contained in:
60
scripts/rotate-eve.py
Normal file
60
scripts/rotate-eve.py
Normal file
@@ -0,0 +1,60 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Rename EVE and ask Suricata to reopen it; invoked each minute by a timer.
|
||||
|
||||
Normal bound: seven 64-MiB/hour segments plus bytes written between timer
|
||||
runs. The tmpfs itself is the hard capacity limit. Not copytruncate.
|
||||
"""
|
||||
import argparse
|
||||
import fcntl
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
|
||||
def rotate(path, max_bytes=64*1024*1024, max_age=3600, keep=6, reopen=None, now=None):
|
||||
now = time.time() if now is None else now
|
||||
try:
|
||||
st = path.stat()
|
||||
except FileNotFoundError:
|
||||
return False
|
||||
# Both mtime and ctime change on writes. Keep an independent age clock.
|
||||
clock = path.with_name('.' + path.name + '.rotation-clock')
|
||||
try:
|
||||
last = float(clock.read_text())
|
||||
except (FileNotFoundError, ValueError):
|
||||
last = now
|
||||
clock.write_text(str(now))
|
||||
if st.st_size < max_bytes and now-last < max_age:
|
||||
return False
|
||||
dst = path.with_name(path.name + '.leaf-' + str(time.time_ns()).zfill(20))
|
||||
path.rename(dst)
|
||||
try:
|
||||
reopen()
|
||||
except BaseException:
|
||||
if not path.exists():
|
||||
dst.rename(path)
|
||||
raise
|
||||
clock.write_text(str(now))
|
||||
for f in sorted(path.parent.glob(path.name + '.leaf-*'))[:-keep] if keep else path.parent.glob(path.name + '.leaf-*'):
|
||||
f.unlink()
|
||||
return True
|
||||
|
||||
|
||||
def main():
|
||||
ap=argparse.ArgumentParser(description=__doc__)
|
||||
ap.add_argument('--path', type=Path, default=Path('/var/log/suricata-leaf/eve.json'))
|
||||
a=ap.parse_args()
|
||||
# Type=simple is active before Suricata installs signal handlers. Never
|
||||
# signal a just-started engine, including manual timer/service triggers.
|
||||
started = subprocess.run(['systemctl','show','--property=ActiveEnterTimestampMonotonic',
|
||||
'--value','suricata-leaf.service'],
|
||||
check=True,capture_output=True,text=True).stdout.strip()
|
||||
if not started or int(started) == 0 or time.monotonic() - int(started)/1e6 < 60:
|
||||
return
|
||||
with open('/run/leaf-eve-rotation.lock', 'a') as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
rotate(a.path, reopen=lambda: subprocess.run(
|
||||
['systemctl','kill','--kill-whom=main','--signal=HUP','suricata-leaf.service'], check=True))
|
||||
|
||||
if __name__ == '__main__': main()
|
||||
Reference in New Issue
Block a user