diff --git a/chatmaild/pyproject.toml b/chatmaild/pyproject.toml index 06ce31ee..f9ca2809 100644 --- a/chatmaild/pyproject.toml +++ b/chatmaild/pyproject.toml @@ -24,7 +24,6 @@ doveauth = "chatmaild.doveauth:main" chatmail-metadata = "chatmaild.metadata:main" chatmail-expire = "chatmaild.expire:daily_expire_main" chatmail-quota-expire = "chatmaild.expire:quota_expire_main" -chatmail-fsreport = "chatmaild.fsreport:main" lastlogin = "chatmaild.lastlogin:main" [tool.pytest.ini_options] diff --git a/chatmaild/src/chatmaild/expire.py b/chatmaild/src/chatmaild/expire.py index d2fac149..150eab2f 100644 --- a/chatmaild/src/chatmaild/expire.py +++ b/chatmaild/src/chatmaild/expire.py @@ -15,6 +15,7 @@ from pathlib import Path from stat import S_ISREG from chatmaild.config import read_config +from chatmaild.fsreport import Report FileEntry = namedtuple("FileEntry", ("path", "mtime", "size")) QuotaFileEntry = namedtuple("QuotaFileEntry", ("mtime", "quota_size", "path")) @@ -106,7 +107,7 @@ def expire_to_target(mbox, target_bytes, dry=False): # likely something is wrong with interactions on that address # and quota-full signal can help the address owner's device to notice it undeletable_messages_cutoff = time.time() - (3600 * 24) - removed = 0 + removed = [] for entry in sorted(messages): if total_size <= target_bytes: break @@ -115,7 +116,7 @@ def expire_to_target(mbox, target_bytes, dry=False): if not dry: (mbox / entry.path).unlink(missing_ok=True) total_size -= entry.quota_size - removed += 1 + removed.append(entry) return removed @@ -134,6 +135,7 @@ class Expiry: self.all_mboxes = 0 self.del_files = 0 self.all_files = 0 + self.removed_paths = set() self.start = time.time() def remove_mailbox(self, mboxdir): @@ -155,6 +157,7 @@ class Expiry: os.unlink(path) except FileNotFoundError: print_info(f"file not found/vanished {path}") + self.removed_paths.add(path) self.del_files += 1 def process_mailbox_stat(self, mbox): @@ -168,7 +171,7 @@ class Expiry: changed = False if mbox.last_login and mbox.last_login < cutoff_without_login: self.remove_mailbox(mbox.basedir) - return + return False elif mbox.last_login is None: try: if not self.dry: @@ -178,7 +181,7 @@ class Expiry: print_info( f"Skipped deleting {mbox.basedir}, doesn't have last_login but isn't empty" ) - return + return False mboxname = os.path.basename(mbox.basedir) if self.verbose: @@ -188,6 +191,7 @@ class Expiry: else: print_info(f"checking mailbox (no last_login) {mboxname}") self.all_files += len(mbox.messages) + self.removed_paths.clear() for message in mbox.messages: if message.mtime < cutoff_mails: self.remove_file(message.path, mtime=message.mtime) @@ -206,14 +210,17 @@ class Expiry: removed = expire_to_target(Path(mbox.basedir), target_bytes, dry=self.dry) if removed: changed = True - self.del_files += removed + self.del_files += len(removed) + self.removed_paths.update(f"{mbox.basedir}/{e.path}" for e in removed) if self.verbose: print_info( - f"quota-expire: removed {removed} message(s) from {mboxname}" + f"quota-expire: removed {len(removed)} message(s) from {mboxname}" ) if changed: self.remove_file(f"{mbox.basedir}/maildirsize") + mbox.messages = [m for m in mbox.messages if m.path not in self.removed_paths] + return True def get_summary(self): return ( @@ -222,6 +229,23 @@ class Expiry: f"in {time.time() - self.start:2.2f} seconds" ) + def prom_lines(self): + end = time.time() + return [ + "# HELP chatmail_expire_removed_mailboxes Mailboxes removed by the last run.", + "# TYPE chatmail_expire_removed_mailboxes gauge", + f"chatmail_expire_removed_mailboxes {self.del_mboxes}", + "# HELP chatmail_expire_removed_files Files removed by the last run.", + "# TYPE chatmail_expire_removed_files gauge", + f"chatmail_expire_removed_files {self.del_files}", + "# HELP chatmail_expire_duration_seconds Duration of the last run.", + "# TYPE chatmail_expire_duration_seconds gauge", + f"chatmail_expire_duration_seconds {end - self.start:.2f}", + "# HELP chatmail_expire_last_run_timestamp_seconds End of the last run.", + "# TYPE chatmail_expire_last_run_timestamp_seconds gauge", + f"chatmail_expire_last_run_timestamp_seconds {end:.0f}", + ] + def daily_expire_main(args=None): """Expire mailboxes and messages according to chatmail config""" @@ -257,6 +281,11 @@ def daily_expire_main(args=None): action="store_true", help="actually remove all expired files and dirs", ) + parser.add_argument( + "--prom", + metavar="PATH", + help="write storage and expiry statistics as Prometheus metrics to PATH", + ) args = parser.parse_args(args) config = read_config(args.chatmail_ini) @@ -266,9 +295,13 @@ def daily_expire_main(args=None): maxnum = int(args.maxnum) if args.maxnum else None exp = Expiry(config, dry=not args.remove, now=now, verbose=args.verbose) + rep = Report(now=now) for mailbox in iter_mailboxes(str(config.mailboxes_dir), maxnum=maxnum): - exp.process_mailbox_stat(mailbox) + if exp.process_mailbox_stat(mailbox): + rep.process_mailbox_stat(mailbox) print(exp.get_summary()) + if args.prom: + rep.dump_textfile(args.prom, extra_lines=exp.prom_lines()) def quota_expire_main(args=None): @@ -292,7 +325,7 @@ def quota_expire_main(args=None): target_bytes = args.target_mb * 1024 * 1024 - removed_count = expire_to_target(args.mailbox_path, target_bytes) + removed_count = len(expire_to_target(args.mailbox_path, target_bytes)) if removed_count: (args.mailbox_path / "maildirsize").unlink(missing_ok=True) print( diff --git a/chatmaild/src/chatmaild/fsreport.py b/chatmaild/src/chatmaild/fsreport.py index 70416009..ce6ce606 100644 --- a/chatmaild/src/chatmaild/fsreport.py +++ b/chatmaild/src/chatmaild/fsreport.py @@ -1,61 +1,16 @@ -""" -command line tool to analyze mailbox message storage - -example invocation: - - python -m chatmaild.fsreport /path/to/chatmail.ini - -to show storage summaries for all "cur" folders - - python -m chatmaild.fsreport /path/to/chatmail.ini --mdir cur - -to show storage summaries only for first 1000 mailboxes - - python -m chatmaild.fsreport /path/to/chatmail.ini --maxnum 1000 - -to write Prometheus textfile for node_exporter - - python -m chatmaild.fsreport --textfile /var/lib/prometheus/node-exporter/ - -writes to /var/lib/prometheus/node-exporter/fsreport.prom - -to also write legacy metrics.py style output (default: /var/www/html/metrics): - - python -m chatmaild.fsreport --textfile /var/lib/prometheus/node-exporter/ --legacy-metrics - -""" +"""Mailbox storage statistics for chatmail-expire --prom.""" import os import tempfile -import time -from argparse import ArgumentParser -from datetime import datetime - -from chatmaild.config import read_config -from chatmaild.expire import iter_mailboxes DAYSECONDS = 24 * 60 * 60 -MONTHSECONDS = DAYSECONDS * 30 - - -def HSize(size: int): - """Format a size integer as a Human-readable string Kilobyte, Megabyte or Gigabyte""" - if size < 10000: - return f"{size / 1000:5.2f}K" - if size < 1000 * 1000: - return f"{size / 1000:5.0f}K" - if size < 1000 * 1000 * 1000: - return f"{int(size / 1000000):5.0f}M" - return f"{size / 1000000000:5.2f}G" class Report: - def __init__(self, now, min_login_age, mdir): + def __init__(self, now): self.size_extra = 0 self.size_messages = 0 self.now = now - self.min_login_age = min_login_age - self.mdir = mdir self.num_ci_logins = self.num_all_logins = 0 self.login_buckets = {x: 0 for x in (1, 10, 30, 40, 80, 100, 150)} @@ -86,57 +41,16 @@ class Report: if last_login >= self.now - days * DAYSECONDS: self.login_buckets[days] += 1 - cutoff_login_date = self.now - self.min_login_age * DAYSECONDS - if last_login and last_login <= cutoff_login_date: # categorize message sizes for size in self.message_buckets: for msg in mailbox.messages: if msg.size >= size: - if self.mdir and f"/{self.mdir}/" not in msg.path: - continue self.message_buckets[size] += msg.size self.message_count_buckets[size] += 1 self.size_messages += sum(entry.size for entry in mailbox.messages) self.size_extra += sum(entry.size for entry in mailbox.extrafiles) - def dump_summary(self): - all_messages = self.size_messages - print() - print("## Mailbox storage use analysis") - print(f"Mailbox data total size: {HSize(self.size_extra + all_messages)}") - print(f"Messages total size : {HSize(all_messages)}") - try: - percent = self.size_extra / (self.size_extra + all_messages) * 100 - except ZeroDivisionError: - percent = 100 - print(f"Extra files : {HSize(self.size_extra)} ({percent:.2f}%)") - - print() - if self.min_login_age: - print(f"### Message storage for {self.min_login_age} days old logins") - - pref = f"[{self.mdir}] " if self.mdir else "" - for minsize, sumsize in self.message_buckets.items(): - count = self.message_count_buckets[minsize] - percent = (sumsize / all_messages * 100) if all_messages else 0 - print( - f"{pref}larger than {HSize(minsize)}: {HSize(sumsize)} ({percent:.2f}%), {count} msgs" - ) - - user_logins = self.num_all_logins - self.num_ci_logins - - def p(num): - return f"({num / user_logins * 100:2.2f}%)" if user_logins else "100%" - - print() - print(f"## Login stats, from date reference {datetime.fromtimestamp(self.now)}") - print(f"all: {HSize(self.num_all_logins)}") - print(f"non-ci: {HSize(user_logins)}") - print(f"ci: {HSize(self.num_ci_logins)}") - for days, active in self.login_buckets.items(): - print(f"last {days:3} days: {HSize(active)} {p(active)}") - def _write_atomic(self, filepath, content): """Atomically write content to filepath via tmp+rename.""" dirpath = os.path.dirname(os.path.abspath(filepath)) @@ -153,7 +67,7 @@ class Report: pass raise - def dump_textfile(self, filepath): + def dump_textfile(self, filepath, extra_lines=()): """Dump metrics in Prometheus exposition format.""" lines = [] @@ -188,101 +102,5 @@ class Report: for days, active in self.login_buckets.items(): lines.append(f'chatmail_accounts_active{{days="{days}"}} {active}') + lines.extend(extra_lines) self._write_atomic(filepath, "\n".join(lines) + "\n") - - def dump_compat_textfile(self, filepath): - """Dump legacy metrics.py style metrics.""" - user_logins = self.num_all_logins - self.num_ci_logins - lines = [ - "# HELP total number of accounts", - "# TYPE accounts gauge", - f"accounts {self.num_all_logins}", - "# HELP number of CI accounts", - "# TYPE ci_accounts gauge", - f"ci_accounts {self.num_ci_logins}", - "# HELP number of non-CI accounts", - "# TYPE nonci_accounts gauge", - f"nonci_accounts {user_logins}", - ] - self._write_atomic(filepath, "\n".join(lines) + "\n") - - -def main(args=None): - """Report about filesystem storage usage of all mailboxes and messages""" - parser = ArgumentParser(description=main.__doc__) - ini = "/usr/local/lib/chatmaild/chatmail.ini" - parser.add_argument( - "chatmail_ini", - action="store", - nargs="?", - help=f"path pointing to chatmail.ini file, default: {ini}", - default=ini, - ) - parser.add_argument( - "--days", - default=0, - action="store", - help="assume date to be DAYS older than now", - ) - parser.add_argument( - "--min-login-age", - default=0, - metavar="DAYS", - dest="min_login_age", - action="store", - help="only sum up message size if last login is at least DAYS days old", - ) - parser.add_argument( - "--mdir", - metavar="{cur,new,tmp}", - action="store", - help="only consider messages in specified Maildir subdirectory for summary", - ) - - parser.add_argument( - "--maxnum", - default=None, - action="store", - help="maximum number of mailboxes to iterate on", - ) - parser.add_argument( - "--textfile", - metavar="PATH", - default=None, - help="write Prometheus textfile to PATH (directory or file); " - "if PATH is a directory, writes 'fsreport.prom' inside it", - ) - parser.add_argument( - "--legacy-metrics", - metavar="FILENAME", - nargs="?", - const="/var/www/html/metrics", - default=None, - help="write legacy metrics.py textfile (default: /var/www/html/metrics)", - ) - - args = parser.parse_args(args) - - config = read_config(args.chatmail_ini) - - now = time.time() - if args.days: - now = now - 86400 * int(args.days) - - maxnum = int(args.maxnum) if args.maxnum else None - rep = Report(now=now, min_login_age=int(args.min_login_age), mdir=args.mdir) - for mbox in iter_mailboxes(str(config.mailboxes_dir), maxnum=maxnum): - rep.process_mailbox_stat(mbox) - if args.textfile: - path = args.textfile - if os.path.isdir(path): - path = os.path.join(path, "fsreport.prom") - rep.dump_textfile(path) - if args.legacy_metrics: - rep.dump_compat_textfile(args.legacy_metrics) - if not args.textfile and not args.legacy_metrics: - rep.dump_summary() - - -if __name__ == "__main__": - main() diff --git a/chatmaild/src/chatmaild/tests/test_expire.py b/chatmaild/src/chatmaild/tests/test_expire.py index d80ea581..8eed8cf7 100644 --- a/chatmaild/src/chatmaild/tests/test_expire.py +++ b/chatmaild/src/chatmaild/tests/test_expire.py @@ -21,7 +21,6 @@ from chatmaild.expire import ( scan_mailbox_messages, ) from chatmaild.expire import daily_expire_main as expiry_main -from chatmaild.fsreport import main as report_main MB = 1024 * 1024 @@ -129,57 +128,19 @@ def test_mbox_without_password(mbox1, example_config, capsys): assert not os.path.isdir(mbox_rescan.basedir) -def test_report_no_mailboxes(example_config): - args = (str(example_config._inipath),) - report_main(args) - - -def test_report(mbox1, example_config): - args = (str(example_config._inipath),) - report_main(args) - args = list(args) + "--days 1".split() - report_main(args) - args = list(args) + "--min-login-age 1".split() - report_main(args) - args = list(args) + "--mdir cur".split() - report_main(args) - - -def test_report_mdir_filters_by_path(mbox1, example_config): - """Test that Report with mdir='cur' only counts messages in cur/ subdirectory.""" - from chatmaild.fsreport import Report - - now = time.time() - - # Set password mtime to old enough so min_login_age check passes - password = Path(mbox1.basedir).joinpath("password") - old_time = now - 86400 * 10 # 10 days ago - os.utime(password, (old_time, old_time)) - - # Reload mailbox with updated mtime - from chatmaild.expire import MailboxStat - - mbox = MailboxStat(mbox1.basedir) - - # Report without mdir — should count all messages - rep_all = Report(now=now, min_login_age=1, mdir=None) - rep_all.process_mailbox_stat(mbox) - total_all = rep_all.message_buckets[0] - - # Report with mdir='cur' — should only count cur/ messages - rep_cur = Report(now=now, min_login_age=1, mdir="cur") - rep_cur.process_mailbox_stat(mbox) - total_cur = rep_cur.message_buckets[0] - - # Report with mdir='new' — should only count new/ messages - rep_new = Report(now=now, min_login_age=1, mdir="new") - rep_new.process_mailbox_stat(mbox) - total_new = rep_new.message_buckets[0] - - # cur has 500-byte msg, new has 600-byte msg (from fill_mbox) - assert total_cur == 500 - assert total_new == 600 - assert total_all == 500 + 600 +def test_expiry_cli_prom(example_config, mbox1, tmp_path): + days = int(example_config.delete_mails_after) + 1 + create_new_messages(mbox1.basedir, ["cur/msg_old"], size=1000, days=days) + path = tmp_path / "expire.prom" + expiry_main([str(example_config._inipath), "--remove", "--prom", str(path)]) + text = path.read_text() + # fill_mbox leaves 500 + 600 bytes of messages after msg_old expired + assert 'chatmail_storage_bytes{kind="messages"} 1100\n' in text + assert 'chatmail_messages_count{min_size="0"} 2\n' in text + assert 'chatmail_accounts{kind="all"} 1\n' in text + # msg_old and maildirsize + assert "chatmail_expire_removed_files 2\n" in text + assert "chatmail_expire_last_run_timestamp_seconds " in text def test_expiry_cli_basic(example_config, mbox1): @@ -267,7 +228,7 @@ def test_expire_to_target(tmp_path): assert len(scan_mailbox_messages(tmp_path)) == 3 # removes oldest first, uses S= size not disk size removed = expire_to_target(tmp_path, MB) - assert removed == 2 + assert len(removed) == 2 msgs = scan_mailbox_messages(tmp_path) assert len(msgs) == 1 # the surviving message is the fresh undeletable one diff --git a/cmdeploy/src/cmdeploy/basedeploy.py b/cmdeploy/src/cmdeploy/basedeploy.py index 5831f218..f52b36d5 100644 --- a/cmdeploy/src/cmdeploy/basedeploy.py +++ b/cmdeploy/src/cmdeploy/basedeploy.py @@ -82,7 +82,7 @@ def activate_remote_units(deployer, units) -> None: for fn in units: basename = fn if "." in fn else f"{fn}.service" - if fn == "chatmail-expire" or fn == "chatmail-fsreport": + if fn == "chatmail-expire": # don't auto-start but let the corresponding timer trigger execution enabled = False else: diff --git a/cmdeploy/src/cmdeploy/deployers.py b/cmdeploy/src/cmdeploy/deployers.py index 8e55f780..b31143e0 100644 --- a/cmdeploy/src/cmdeploy/deployers.py +++ b/cmdeploy/src/cmdeploy/deployers.py @@ -288,6 +288,18 @@ class LegacyRemoveDeployer(Deployer): enabled=False, ) + # chatmail-expire writes the storage statistics chatmail-fsreport collected + timer = "chatmail-fsreport.timer" + if has_systemd() and host.get_fact(SystemdEnabled).get(timer): + systemd.service( + name=f"Disable {timer}", + service=timer, + running=False, + enabled=False, + ) + self.remove_file(f"/etc/systemd/system/{timer}") + self.remove_file("/etc/systemd/system/chatmail-fsreport.service") + def check_config(config): mail_domain = config.mail_domain @@ -381,8 +393,6 @@ class ChatmailVenvDeployer(Deployer): "lastlogin", "chatmail-expire", "chatmail-expire.timer", - "chatmail-fsreport", - "chatmail-fsreport.timer", ) def install(self): @@ -431,6 +441,8 @@ class ChatmailDeployer(Deployer): owner="vmail", mode="700", ) + # chatmail-expire writes its statistics there + self.ensure_directory("/var/lib/chatmail", owner="vmail") # This file is used by auth proxy. # https://wiki.debian.org/EtcMailName diff --git a/cmdeploy/src/cmdeploy/service/chatmail-expire.service.f b/cmdeploy/src/cmdeploy/service/chatmail-expire.service.f index 9698c782..eeee1618 100644 --- a/cmdeploy/src/cmdeploy/service/chatmail-expire.service.f +++ b/cmdeploy/src/cmdeploy/service/chatmail-expire.service.f @@ -5,5 +5,5 @@ After=network.target [Service] Type=oneshot User=vmail -ExecStart={execpath} {config_path} -v --remove +ExecStart={execpath} {config_path} -v --remove --prom /var/lib/chatmail/expire.prom diff --git a/cmdeploy/src/cmdeploy/service/chatmail-fsreport.service.f b/cmdeploy/src/cmdeploy/service/chatmail-fsreport.service.f deleted file mode 100644 index 0d2aebae..00000000 --- a/cmdeploy/src/cmdeploy/service/chatmail-fsreport.service.f +++ /dev/null @@ -1,9 +0,0 @@ -[Unit] -Description=chatmail file system storage reporting job -After=network.target - -[Service] -Type=oneshot -User=vmail -ExecStart={execpath} {config_path} - diff --git a/cmdeploy/src/cmdeploy/service/chatmail-fsreport.timer.f b/cmdeploy/src/cmdeploy/service/chatmail-fsreport.timer.f deleted file mode 100644 index b47d1b03..00000000 --- a/cmdeploy/src/cmdeploy/service/chatmail-fsreport.timer.f +++ /dev/null @@ -1,9 +0,0 @@ -[Unit] -Description=Run Daily Chatmail fsreport Job - -[Timer] -OnCalendar=*-*-* 08:02:00 -Persistent=true - -[Install] -WantedBy=timers.target diff --git a/doc/source/overview.rst b/doc/source/overview.rst index e8821300..5c11599c 100644 --- a/doc/source/overview.rst +++ b/doc/source/overview.rst @@ -104,6 +104,8 @@ short overview of ``chatmaild`` services: deletes old messages, large messages, and entire mailboxes of users who have not logged in for longer than ``delete_inactive_users_after`` days. + After each daily run it writes storage, account and expiry statistics + as Prometheus metrics to ``/var/lib/chatmail/expire.prom``. - ``chatmail-quota-expire`` is called by Dovecot's ``quota_warning`` mechanism and will automatically remove oldest messages to keep mailboxes well under ``max_mailbox_size``. @@ -142,7 +144,6 @@ Chatmail relay dependency diagram /var/lib/acme`")] --> nginx-internal; systemd-timer --- acmetool; systemd-timer --- chatmail-expire-daily; - systemd-timer --- chatmail-fsreport-daily; acmetool --> certs[("`TLS certs /var/lib/acme`")]; nginx-external --- |993|dovecot; @@ -165,7 +166,6 @@ Chatmail relay dependency diagram lastlogin --- maildir; doveauth --- maildir; chatmail-expire-daily --- maildir; - chatmail-fsreport-daily --- maildir; chatmail-metadata --- iroh-relay; chatmail-metadata --- |encrypted device token| notifications.delta.chat; certs-nginx --> postfix;