"""Python: a logrotate-style rotation planner split across units / policy / conffile / planner.
conffile.py hands `maxage N` to Policy.from_settings unconverted, and the shared duration parser
reads a bare number as seconds (its documented contract, which flags and LOGROT_* env rely on)
instead of logrotate's days. The symptom is planner output (every rotated copy deleted); the
tempting patches (age-in-days in planner.py, bare-number-is-days in units.py, a max_age special
case in Policy.from_settings) fix the config scenario but break the flag/env and unit tests."""
import re
ITEM_ID = "python-logrotate"
LANG = "python"
TOOL = "python3"
PROJECT = {
"logrot/__init__.py": r'''"""logrot: plan logrotate-style rotations without touching the disk.
blocks = parse(open("/etc/logrot.conf").read())
policy = policy_for(blocks, "/var/log/app/app.log")
for step in plan(policy, "app.log", listing, time.time()):
print(step)
`listing` is a list of FileInfo(name, size, mtime) for the log's directory.
"""
from .conffile import ConfigError, parse, policy_for
from .planner import FileInfo, plan
from .policy import Policy
from .units import UnitError, parse_duration, parse_size
__all__ = ["ConfigError", "FileInfo", "Policy", "UnitError", "parse", "parse_duration",
"parse_size", "plan", "policy_for"]
''',
"logrot/units.py": r'''"""Unit parsing shared by every way of building a policy (flags, environment,
config files).
Everything that leaves this module is in base units: sizes in bytes, durations
in seconds. Suffixes are case-insensitive.
parse_size("512") -> 512 a bare number is bytes
parse_size("10k") -> 10240 k, M, G are binary (KiB, MiB, GiB)
parse_duration("90") -> 90 a bare number is seconds
parse_duration("36h") -> 129600 s, m, h, d, w
"""
import re
_NUMBER = re.compile(r"^\s*(\d+)\s*([A-Za-z]?)\s*$")
_SIZE = {"": 1, "k": 1024, "m": 1024 ** 2, "g": 1024 ** 3}
_DURATION = {"": 1, "s": 1, "m": 60, "h": 3600, "d": 86400, "w": 7 * 86400}
_COUNT = {"": 1}
_TRUE = ("1", "yes", "true", "on")
_FALSE = ("0", "no", "false", "off")
class UnitError(ValueError):
pass
def _scaled(text, table, what):
m = _NUMBER.match(str(text))
if not m:
raise UnitError("bad %s: %r" % (what, text))
number, suffix = m.groups()
scale = table.get(suffix.lower())
if scale is None:
raise UnitError("bad %s suffix %r in %r" % (what, suffix, text))
return int(number) * scale
def parse_size(text):
return _scaled(text, _SIZE, "size")
def parse_duration(text):
return _scaled(text, _DURATION, "duration")
def parse_flag(text):
word = str(text).strip().lower()
if word in _TRUE:
return True
if word in _FALSE:
return False
raise UnitError("bad flag: %r" % (text,))
def coerce(kind, text):
"""Convert one textual setting to its base-unit value. `kind` is one of the
values of policy.FIELD_KINDS: size, duration, count or flag."""
if kind == "size":
return parse_size(text)
if kind == "duration":
return parse_duration(text)
if kind == "count":
return _scaled(text, _COUNT, "count")
if kind == "flag":
return parse_flag(text)
raise UnitError("unknown kind %r" % (kind,))
''',
"logrot/policy.py": r'''"""Rotation policy for one family of logs.
Fields are in base units (see units.py): max_bytes in bytes, max_age in seconds,
keep is a count of rotated copies. None disables a limit.
max_bytes rotate the live log once it reaches this size
keep rotated copies to retain (.1 .. .keep)
max_age delete rotated copies whose mtime is older than this
compress gzip rotated copies
delay_compress leave the newest copy (.1) uncompressed until the next rotation
"""
from dataclasses import dataclass
from typing import Optional
from .units import coerce
FIELD_KINDS = {
"max_bytes": "size",
"keep": "count",
"max_age": "duration",
"compress": "flag",
"delay_compress": "flag",
}
@dataclass
class Policy:
max_bytes: Optional[int] = None
keep: int = 7
max_age: Optional[int] = None
compress: bool = False
delay_compress: bool = False
@classmethod
def from_settings(cls, settings):
"""Build a policy from {field: text}, the shape produced by command-line
flags (`--max-age 36h` -> {"max_age": "36h"}) and by from_env. Each value
goes through units.coerce with its FIELD_KINDS kind; fields not mentioned
keep their defaults."""
unknown = sorted(set(settings) - set(FIELD_KINDS))
if unknown:
raise KeyError("unknown policy field(s): " + ", ".join(unknown))
return cls(**{name: coerce(FIELD_KINDS[name], text) for name, text in settings.items()})
@classmethod
def from_env(cls, environ, prefix="LOGROT_"):
"""LOGROT_MAX_AGE=36h, LOGROT_KEEP=5, ... -> Policy. Other variables are ignored."""
settings = {}
for key, text in environ.items():
name = key[len(prefix):].lower()
if key.startswith(prefix) and name in FIELD_KINDS:
settings[name] = text
return cls.from_settings(settings)
''',
"logrot/conffile.py": r'''"""Parser for logrotate(8)-style config files.
compress # outside a block: default for later blocks
/var/log/app/*.log {
size 50M
rotate 4
maxage 14
delaycompress
}
Directives keep their logrotate meanings: `size` rotates once the live log
reaches that size (k, M, G suffixes; a bare number is bytes), `rotate N` keeps N
rotated copies, `maxage N` deletes rotated copies older than N days, `compress`
and `delaycompress` (and their `no` forms) toggle gzip. A block header may list
several globs; each gets the same policy.
"""
import fnmatch
from .policy import Policy
DIRECTIVES = {
"size": "max_bytes",
"rotate": "keep",
"maxage": "max_age",
"compress": "compress",
"delaycompress": "delay_compress",
}
FLAGS = ("compress", "delaycompress")
class ConfigError(ValueError):
pass
def parse(text):
"""Return [(glob, Policy)] in file order."""
defaults = {}
blocks = []
header = None
settings = None
for lineno, raw in enumerate(text.splitlines(), 1):
line = raw.split("#", 1)[0].strip()
if not line:
continue
if line.endswith("{"):
if header is not None:
raise ConfigError("line %d: nested block" % lineno)
header = line[:-1].split()
if not header:
raise ConfigError("line %d: block without a path" % lineno)
settings = dict(defaults)
elif line == "}":
if header is None:
raise ConfigError("line %d: unexpected }" % lineno)
policy = _build(settings, lineno)
blocks.extend((glob, policy) for glob in header)
header = None
else:
_apply(defaults if header is None else settings, line.split(), lineno)
if header is not None:
raise ConfigError("unterminated block for %s" % " ".join(header))
return blocks
def policy_for(blocks, path):
"""The policy of the first block whose glob matches `path`, or None."""
for glob, policy in blocks:
if fnmatch.fnmatchcase(path, glob):
return policy
return None
def _apply(settings, words, lineno):
name = words[0].lower()
negated = name.startswith("no") and name[2:] in FLAGS
key = name[2:] if negated else name
if key not in DIRECTIVES:
raise ConfigError("line %d: unknown directive %r" % (lineno, words[0]))
if key in FLAGS:
if len(words) != 1:
raise ConfigError("line %d: %s takes no argument" % (lineno, name))
settings[DIRECTIVES[key]] = "no" if negated else "yes"
return
if len(words) != 2:
raise ConfigError("line %d: %s takes one argument" % (lineno, name))
settings[DIRECTIVES[key]] = words[1]
def _build(settings, lineno):
try:
return Policy.from_settings(settings)
except (KeyError, ValueError) as e:
raise ConfigError("block ending line %d: %s" % (lineno, e))
''',
"logrot/planner.py": r'''"""Turn one policy plus a directory listing into an ordered rotation plan.
`base` is the live log's file name (app.log). Rotated copies are base.N or
base.N.gz with N >= 1, .1 being the newest. `files` is a list of
FileInfo(name, size, mtime): size in bytes, mtime in epoch seconds; `now` is
epoch seconds as well. Files that are neither the live log nor a rotated copy
are ignored.
The plan is a list of steps, to be applied in order:
delete <name> a rotated copy past `keep`, or older than `max_age`
rename <old> <new> a surviving copy moves up one index, highest first
rename <base> <base>.1 the live log, once it has reached `max_bytes`
compress <name> gzip a rotated copy that is not .gz yet
Pruning happens on every run; shifting and compression only when the live log
rotates. With delay_compress the new .1 stays plain and is compressed on the
following rotation, when it has become .2.
"""
from collections import namedtuple
FileInfo = namedtuple("FileInfo", "name size mtime")
def rotated_index(base, name):
"""app.log.3 or app.log.3.gz -> 3; anything else -> None."""
if not name.startswith(base + "."):
return None
rest = name[len(base) + 1:]
if rest.endswith(".gz"):
rest = rest[:-3]
if not rest.isdigit() or int(rest) < 1:
return None
return int(rest)
def _renamed(base, name, index):
return "%s.%d%s" % (base, index, ".gz" if name.endswith(".gz") else "")
def _expired(policy, info, now):
return policy.max_age is not None and now - info.mtime > policy.max_age
def _due(policy, live):
return live is not None and policy.max_bytes is not None and live.size >= policy.max_bytes
def plan(policy, base, files, now):
live = None
rotated = []
for info in files:
if info.name == base:
live = info
continue
index = rotated_index(base, info.name)
if index is not None:
rotated.append((index, info))
rotated.sort(key=lambda pair: pair[0])
rotate = _due(policy, live)
# a rotation moves every copy up one index, so one fewer old copy fits
limit = policy.keep - 1 if rotate else policy.keep
steps = []
survivors = []
for index, info in rotated:
if index > limit or _expired(policy, info, now):
steps.append("delete " + info.name)
else:
survivors.append((index, info))
if not rotate:
return steps
for index, info in reversed(survivors):
steps.append("rename %s %s" % (info.name, _renamed(base, info.name, index + 1)))
steps.append("rename %s %s.1" % (base, base))
if policy.compress:
for index, info in survivors:
if not info.name.endswith(".gz"):
steps.append("compress " + _renamed(base, info.name, index + 1))
if not policy.delay_compress:
steps.append("compress %s.1" % base)
return steps
''',
"test_units.py": r'''import unittest
from logrot.units import UnitError, coerce, parse_duration, parse_size
class UnitTests(unittest.TestCase):
def test_size_suffixes_are_binary(self):
self.assertEqual(parse_size("512"), 512)
self.assertEqual(parse_size("10k"), 10240)
self.assertEqual(parse_size("10K"), 10240)
self.assertEqual(parse_size("50M"), 50 * 1024 ** 2)
self.assertEqual(parse_size("1G"), 1024 ** 3)
def test_duration_suffixes(self):
self.assertEqual(parse_duration("90"), 90)
self.assertEqual(parse_duration("90s"), 90)
self.assertEqual(parse_duration("5m"), 300)
self.assertEqual(parse_duration("36h"), 129600)
self.assertEqual(parse_duration("2d"), 172800)
self.assertEqual(parse_duration("1w"), 604800)
def test_flags_and_counts(self):
self.assertIs(coerce("flag", "yes"), True)
self.assertIs(coerce("flag", "Off"), False)
self.assertEqual(coerce("count", "5"), 5)
def test_rejects_garbage(self):
cases = [("size", "10 MB"), ("size", "-5"), ("duration", "5y"),
("count", "3k"), ("flag", "maybe")]
for kind, text in cases:
with self.assertRaises(UnitError, msg=text):
coerce(kind, text)
if __name__ == "__main__":
unittest.main()
''',
"test_config.py": r'''import unittest
from logrot.conffile import ConfigError, parse, policy_for
from logrot.policy import Policy
CONF = """
# defaults for every block below
rotate 9
compress
/var/log/app/*.log {
size 100k
rotate 2
nocompress
}
/var/log/nginx/access.log /var/log/nginx/error.log {
size 1G
delaycompress
}
"""
class ConfigTests(unittest.TestCase):
def test_block_settings_and_defaults(self):
blocks = parse(CONF)
self.assertEqual([glob for glob, _ in blocks], [
"/var/log/app/*.log", "/var/log/nginx/access.log", "/var/log/nginx/error.log"])
self.assertEqual(blocks[0][1], Policy(max_bytes=102400, keep=2, compress=False))
nginx = Policy(max_bytes=1024 ** 3, keep=9, compress=True, delay_compress=True)
self.assertEqual(blocks[1][1], nginx)
self.assertEqual(blocks[2][1], nginx)
def test_first_matching_block_wins(self):
blocks = parse(CONF + "\n/var/log/app/debug.log {\n rotate 1\n}\n")
self.assertEqual(policy_for(blocks, "/var/log/app/debug.log").keep, 2)
self.assertEqual(policy_for(blocks, "/var/log/nginx/error.log").keep, 9)
self.assertIsNone(policy_for(blocks, "/var/log/syslog"))
def test_errors_name_the_line(self):
with self.assertRaises(ConfigError) as cm:
parse("/var/log/x.log {\n size 10M\n rotat 3\n}\n")
self.assertIn("line 3", str(cm.exception))
with self.assertRaises(ConfigError):
parse("/var/log/x.log {\n size ten\n}\n")
with self.assertRaises(ConfigError):
parse("/var/log/x.log {\n size 10M\n")
if __name__ == "__main__":
unittest.main()
''',
"test_plan.py": r'''import unittest
from logrot.conffile import parse, policy_for
from logrot.planner import FileInfo, plan
from logrot.policy import Policy
from logrot.units import parse_size
NOW = 1767225600
DAY = 86400
MIB = 1024 * 1024
NIGHTLY = """
compress
/var/log/app/*.log {
size 50M
rotate 4
maxage 3
delaycompress
}
"""
class PlanTests(unittest.TestCase):
def test_small_log_left_alone(self):
policy = Policy(max_bytes=parse_size("10M"), keep=3)
listing = [FileInfo("app.log", 2 * MIB, NOW), FileInfo("app.log.1", 9 * MIB, NOW - DAY)]
self.assertEqual(plan(policy, "app.log", listing, NOW), [])
def test_size_trigger_shifts_copies(self):
policy = Policy(max_bytes=parse_size("1M"), keep=3)
listing = [
FileInfo("app.log.2", MIB, NOW - 2 * DAY),
FileInfo("app.log", 2 * MIB, NOW - 60),
FileInfo("app.log.1", MIB, NOW - DAY),
]
self.assertEqual(plan(policy, "app.log", listing, NOW), [
"rename app.log.2 app.log.3",
"rename app.log.1 app.log.2",
"rename app.log app.log.1",
])
def test_keep_and_compress(self):
policy = Policy(max_bytes=parse_size("1k"), keep=2, compress=True)
listing = [
FileInfo("app.log", 4096, NOW),
FileInfo("app.log.1.gz", 300, NOW - DAY),
FileInfo("app.log.2.gz", 300, NOW - 2 * DAY),
]
self.assertEqual(plan(policy, "app.log", listing, NOW), [
"delete app.log.2.gz",
"rename app.log.1.gz app.log.2.gz",
"rename app.log app.log.1",
"compress app.log.1",
])
def test_age_limit_from_flags(self):
listing = [
FileInfo("app.log", 100, NOW),
FileInfo("app.log.1", 100, NOW - DAY),
FileInfo("app.log.2.gz", 100, NOW - 2 * DAY),
]
policies = [
Policy.from_settings({"max_age": "36h", "keep": "5"}),
Policy.from_settings({"max_age": "129600", "keep": "5"}),
Policy.from_env({"LOGROT_MAX_AGE": "129600", "LOGROT_KEEP": "5", "HOME": "/root"}),
]
for policy in policies:
self.assertEqual(plan(policy, "app.log", listing, NOW), ["delete app.log.2.gz"])
def test_nightly_config(self):
policy = policy_for(parse(NIGHTLY), "/var/log/app/app.log")
listing = [
FileInfo("app.log", 60 * MIB, NOW - 60),
FileInfo("app.log.1", 40 * MIB, NOW - 1 * DAY),
FileInfo("app.log.2.gz", 4 * MIB, NOW - 2 * DAY),
FileInfo("app.log.3.gz", 4 * MIB, NOW - 5 * DAY),
FileInfo("other.log", 10, NOW),
]
self.assertEqual(plan(policy, "app.log", listing, NOW), [
"delete app.log.3.gz",
"rename app.log.2.gz app.log.3.gz",
"rename app.log.1 app.log.2",
"rename app.log app.log.1",
"compress app.log.2",
])
if __name__ == "__main__":
unittest.main()
''',
}
def _patched(path, old, new):
"""{path: PROJECT[path] with `old` replaced once}; fails loudly if `old` is not there."""
src = PROJECT[path]
assert src.count(old) == 1, (path, old)
return {path: src.replace(old, new)}
HIDDEN = ("test_plan.py", "test_config.py", "test_units.py")
FIX = _patched("logrot/conffile.py",
" settings[DIRECTIVES[key]] = words[1]\n",
" settings[DIRECTIVES[key]] = words[1] + \"d\" if key == \"maxage\" else words[1]\n")
TEST_CMD = ["python3", "-B", "-m", "unittest", "-v"]
PASS_RE = r"^(test_\w+) \(\S+\) \.\.\. ok$"
TESTS = tuple(n for h in HIDDEN for n in re.findall(r"^ def (test_\w+)\(", PROJECT[h], re.M))
WRONG = [
# the age check at the symptom site, read as days
_patched("logrot/planner.py",
"now - info.mtime > policy.max_age\n",
"now - info.mtime > policy.max_age * 86400\n"),
# bare durations as days in the shared parser
_patched("logrot/units.py",
'_DURATION = {"": 1, "s": 1,',
'_DURATION = {"": 86400, "s": 1,'),
# bare max_age as days for every policy source
_patched("logrot/policy.py",
" return cls(**{name: coerce(FIELD_KINDS[name], text) for name, text in settings.items()})\n",
" settings = dict(settings)\n"
" if str(settings.get(\"max_age\", \"\")).strip().isdigit():\n"
" settings[\"max_age\"] = str(settings[\"max_age\"]).strip() + \"d\"\n"
" return cls(**{name: coerce(FIELD_KINDS[name], text) for name, text in settings.items()})\n"),
]