mirror of
https://github.com/chatmail/relay.git
synced 2026-11-24 13:59:36 +00:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
153a52f30c | ||
|
|
52af5ff427 | ||
|
|
a1a32e8153 | ||
|
|
a873f51d52 | ||
|
|
b57f871c97 |
@@ -1,4 +1,4 @@
|
||||
|
||||
Please refer to
|
||||
[Delta Chat community standards and practices](https://delta.chat/community-standards)
|
||||
[Delta Chat community standards and practices](https://delta.chat/en/community-standards)
|
||||
which also apply for all chatmail developments.
|
||||
|
||||
@@ -29,7 +29,7 @@ jobs:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
persist-credentials: false
|
||||
- name: download filtermail
|
||||
run: curl -L https://github.com/chatmail/filtermail/releases/download/v0.7.10/filtermail-x86_64 -o /usr/local/bin/filtermail && chmod +x /usr/local/bin/filtermail
|
||||
run: curl -L https://github.com/chatmail/filtermail/releases/download/v0.7.7/filtermail-x86_64 -o /usr/local/bin/filtermail && chmod +x /usr/local/bin/filtermail
|
||||
- name: run chatmaild tests
|
||||
working-directory: chatmaild
|
||||
run: pipx run tox
|
||||
|
||||
@@ -8,7 +8,7 @@ name: Trigger Docker build
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
branches: [main, j4n/dovecot-multidist]
|
||||
tags: ['[0-9]+.[0-9]+.[0-9]+']
|
||||
workflow_dispatch:
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ 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]
|
||||
|
||||
@@ -31,7 +31,7 @@ class Config:
|
||||
self.max_user_send_per_minute = int(params.pop("max_user_send_per_minute", 60))
|
||||
self.max_user_send_burst_size = int(params.pop("max_user_send_burst_size", 10))
|
||||
self.max_mailbox_size = params.pop("max_mailbox_size", "500M")
|
||||
self.max_message_size = int(params.pop("max_message_size", 52428800))
|
||||
self.max_message_size = int(params.pop("max_message_size", 31457280))
|
||||
self.delete_mails_after = params.pop("delete_mails_after", "20")
|
||||
self.delete_large_after = params.pop("delete_large_after", "7")
|
||||
self.delete_inactive_users_after = int(
|
||||
|
||||
@@ -5,9 +5,9 @@
|
||||
"sources": [
|
||||
{
|
||||
"sourceId": "gplay",
|
||||
"versionInteger": 761,
|
||||
"versionString": "2.69.0",
|
||||
"downloadUrl": "https://github.com/deltachat/deltachat-android/releases/download/v2.69.0/deltachat-gplay-release-2.69.0.apk"
|
||||
"versionInteger": 759,
|
||||
"versionString": "2.64.0",
|
||||
"downloadUrl": "https://github.com/deltachat/deltachat-android/releases/download/v2.64.0/deltachat-gplay-release-2.64.0.apk"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -99,23 +99,22 @@ def scan_mailbox_messages(mbox):
|
||||
return messages
|
||||
|
||||
|
||||
def expire_to_target(mbox, target_bytes, dry=False):
|
||||
def expire_to_target(mbox, target_bytes):
|
||||
messages = scan_mailbox_messages(mbox)
|
||||
total_size = sum(m.quota_size for m in messages)
|
||||
# Keep recent 24 hours of messages protected from expiry because
|
||||
# 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 = []
|
||||
removed = 0
|
||||
for entry in sorted(messages):
|
||||
if total_size <= target_bytes:
|
||||
break
|
||||
if entry.mtime > undeletable_messages_cutoff:
|
||||
break
|
||||
if not dry:
|
||||
(mbox / entry.path).unlink(missing_ok=True)
|
||||
(mbox / entry.path).unlink(missing_ok=True)
|
||||
total_size -= entry.quota_size
|
||||
removed.append(entry)
|
||||
removed += 1
|
||||
|
||||
return removed
|
||||
|
||||
@@ -124,23 +123,7 @@ def print_info(msg):
|
||||
print(msg, file=sys.stderr)
|
||||
|
||||
|
||||
PROM_HELP = {
|
||||
"storage_bytes": "Mailbox storage in bytes.",
|
||||
"messages_bytes": "Sum of msg bytes >= threshold.",
|
||||
"messages_count": "Number of msgs >= size threshold.",
|
||||
"accounts": "Number of accounts.",
|
||||
"accounts_active": "Non-CI accounts active within N days.",
|
||||
"expire_removed_mailboxes": "Mailboxes removed by the last run.",
|
||||
"expire_removed_files": "Files removed by the last run.",
|
||||
"expire_duration_seconds": "Duration of the last run.",
|
||||
"expire_last_run_timestamp_seconds": "End of the last run.",
|
||||
}
|
||||
|
||||
|
||||
class Expiry:
|
||||
login_days = (1, 10, 30, 40, 80, 100, 150)
|
||||
size_thresholds = (0, 100 * 1024, 512 * 1024, 1 << 20, 2 << 20, 5 << 20, 10 << 20)
|
||||
|
||||
def __init__(self, config, dry, now, verbose):
|
||||
self.config = config
|
||||
self.dry = dry
|
||||
@@ -150,13 +133,7 @@ class Expiry:
|
||||
self.all_mboxes = 0
|
||||
self.del_files = 0
|
||||
self.all_files = 0
|
||||
self.removed_paths = set()
|
||||
self.start = time.time()
|
||||
self.size_messages = self.size_extra = 0
|
||||
self.num_ci_logins = self.num_all_logins = 0
|
||||
self.login_buckets = dict.fromkeys(self.login_days, 0)
|
||||
self.msg_bytes = dict.fromkeys(self.size_thresholds, 0)
|
||||
self.msg_counts = dict.fromkeys(self.size_thresholds, 0)
|
||||
|
||||
def remove_mailbox(self, mboxdir):
|
||||
if self.verbose:
|
||||
@@ -177,7 +154,6 @@ 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):
|
||||
@@ -211,7 +187,6 @@ 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)
|
||||
@@ -227,35 +202,18 @@ class Expiry:
|
||||
target_bytes = (
|
||||
self.config.max_mailbox_size_mb * 1024 * 1024 * QUOTA_CLEANUP_FACTOR
|
||||
)
|
||||
removed = expire_to_target(Path(mbox.basedir), target_bytes, dry=self.dry)
|
||||
removed = expire_to_target(Path(mbox.basedir), target_bytes)
|
||||
if removed:
|
||||
changed = True
|
||||
self.del_files += len(removed)
|
||||
self.removed_paths.update(f"{mbox.basedir}/{e.path}" for e in removed)
|
||||
self.del_files += removed
|
||||
if self.verbose:
|
||||
print_info(
|
||||
f"quota-expire: removed {len(removed)} message(s) from {mboxname}"
|
||||
f"quota-expire: removed {removed} message(s) from {mboxname}"
|
||||
)
|
||||
|
||||
if changed:
|
||||
self.remove_file(f"{mbox.basedir}/maildirsize")
|
||||
|
||||
self.num_all_logins += 1
|
||||
if mboxname.startswith("ci-"):
|
||||
self.num_ci_logins += 1
|
||||
else:
|
||||
for days in self.login_buckets:
|
||||
if mbox.last_login >= self.now - days * 86400:
|
||||
self.login_buckets[days] += 1
|
||||
kept = [m for m in mbox.messages if m.path not in self.removed_paths]
|
||||
for size in self.msg_bytes:
|
||||
for msg in kept:
|
||||
if msg.size >= size:
|
||||
self.msg_bytes[size] += msg.size
|
||||
self.msg_counts[size] += 1
|
||||
self.size_messages += sum(m.size for m in kept)
|
||||
self.size_extra += sum(entry.size for entry in mbox.extrafiles)
|
||||
|
||||
def get_summary(self):
|
||||
return (
|
||||
f"Removed {self.del_mboxes} out of {self.all_mboxes} mailboxes "
|
||||
@@ -263,33 +221,6 @@ class Expiry:
|
||||
f"in {time.time() - self.start:2.2f} seconds"
|
||||
)
|
||||
|
||||
def write_prom(self, path):
|
||||
end = time.time()
|
||||
storage = dict(messages=self.size_messages, extra=self.size_extra)
|
||||
storage["total"] = self.size_messages + self.size_extra
|
||||
accounts = dict(all=self.num_all_logins, ci=self.num_ci_logins)
|
||||
accounts["user"] = accounts["all"] - accounts["ci"]
|
||||
tmp = f"{path}.tmp"
|
||||
with open(tmp, "w") as f:
|
||||
|
||||
def gauge(name, values, label=None):
|
||||
print(f"# HELP chatmail_{name} {PROM_HELP[name]}", file=f)
|
||||
print(f"# TYPE chatmail_{name} gauge", file=f)
|
||||
for key, value in values.items() if label else [(None, values)]:
|
||||
labels = f'{{{label}="{key}"}}' if label else ""
|
||||
print(f"chatmail_{name}{labels} {value}", file=f)
|
||||
|
||||
gauge("storage_bytes", storage, "kind")
|
||||
gauge("messages_bytes", self.msg_bytes, "min_size")
|
||||
gauge("messages_count", self.msg_counts, "min_size")
|
||||
gauge("accounts", accounts, "kind")
|
||||
gauge("accounts_active", self.login_buckets, "days")
|
||||
gauge("expire_removed_mailboxes", self.del_mboxes)
|
||||
gauge("expire_removed_files", self.del_files)
|
||||
gauge("expire_duration_seconds", f"{end - self.start:.2f}")
|
||||
gauge("expire_last_run_timestamp_seconds", f"{end:.0f}")
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
def daily_expire_main(args=None):
|
||||
"""Expire mailboxes and messages according to chatmail config"""
|
||||
@@ -325,11 +256,6 @@ 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)
|
||||
@@ -342,8 +268,6 @@ def daily_expire_main(args=None):
|
||||
for mailbox in iter_mailboxes(str(config.mailboxes_dir), maxnum=maxnum):
|
||||
exp.process_mailbox_stat(mailbox)
|
||||
print(exp.get_summary())
|
||||
if args.prom:
|
||||
exp.write_prom(args.prom)
|
||||
|
||||
|
||||
def quota_expire_main(args=None):
|
||||
@@ -367,7 +291,7 @@ def quota_expire_main(args=None):
|
||||
|
||||
target_bytes = args.target_mb * 1024 * 1024
|
||||
|
||||
removed_count = len(expire_to_target(args.mailbox_path, target_bytes))
|
||||
removed_count = expire_to_target(args.mailbox_path, target_bytes)
|
||||
if removed_count:
|
||||
(args.mailbox_path / "maildirsize").unlink(missing_ok=True)
|
||||
print(
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
"""
|
||||
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
|
||||
|
||||
"""
|
||||
|
||||
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):
|
||||
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)}
|
||||
|
||||
KiB = 1024
|
||||
MiB = 1024 * KiB
|
||||
self.message_size_thresholds = (
|
||||
0,
|
||||
100 * KiB,
|
||||
MiB // 2,
|
||||
1 * MiB,
|
||||
2 * MiB,
|
||||
5 * MiB,
|
||||
10 * MiB,
|
||||
)
|
||||
self.message_buckets = {x: 0 for x in self.message_size_thresholds}
|
||||
self.message_count_buckets = {x: 0 for x in self.message_size_thresholds}
|
||||
|
||||
def process_mailbox_stat(self, mailbox):
|
||||
# categorize login times
|
||||
last_login = mailbox.last_login
|
||||
if last_login:
|
||||
self.num_all_logins += 1
|
||||
if os.path.basename(mailbox.basedir)[:3] == "ci-":
|
||||
self.num_ci_logins += 1
|
||||
else:
|
||||
for days in self.login_buckets:
|
||||
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))
|
||||
fd, tmppath = tempfile.mkstemp(dir=dirpath, suffix=".tmp")
|
||||
try:
|
||||
with os.fdopen(fd, "w") as f:
|
||||
f.write(content)
|
||||
os.chmod(tmppath, 0o644)
|
||||
os.rename(tmppath, filepath)
|
||||
except BaseException:
|
||||
try:
|
||||
os.unlink(tmppath)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
|
||||
def dump_textfile(self, filepath):
|
||||
"""Dump metrics in Prometheus exposition format."""
|
||||
lines = []
|
||||
|
||||
lines.append("# HELP chatmail_storage_bytes Mailbox storage in bytes.")
|
||||
lines.append("# TYPE chatmail_storage_bytes gauge")
|
||||
lines.append(f'chatmail_storage_bytes{{kind="messages"}} {self.size_messages}')
|
||||
lines.append(f'chatmail_storage_bytes{{kind="extra"}} {self.size_extra}')
|
||||
total = self.size_extra + self.size_messages
|
||||
lines.append(f'chatmail_storage_bytes{{kind="total"}} {total}')
|
||||
|
||||
lines.append("# HELP chatmail_messages_bytes Sum of msg bytes >= threshold.")
|
||||
lines.append("# TYPE chatmail_messages_bytes gauge")
|
||||
for minsize, sumsize in self.message_buckets.items():
|
||||
lines.append(f'chatmail_messages_bytes{{min_size="{minsize}"}} {sumsize}')
|
||||
|
||||
lines.append("# HELP chatmail_messages_count Number of msgs >= size threshold.")
|
||||
lines.append("# TYPE chatmail_messages_count gauge")
|
||||
for minsize, count in self.message_count_buckets.items():
|
||||
lines.append(f'chatmail_messages_count{{min_size="{minsize}"}} {count}')
|
||||
|
||||
lines.append("# HELP chatmail_accounts Number of accounts.")
|
||||
lines.append("# TYPE chatmail_accounts gauge")
|
||||
user_logins = self.num_all_logins - self.num_ci_logins
|
||||
lines.append(f'chatmail_accounts{{kind="all"}} {self.num_all_logins}')
|
||||
lines.append(f'chatmail_accounts{{kind="ci"}} {self.num_ci_logins}')
|
||||
lines.append(f'chatmail_accounts{{kind="user"}} {user_logins}')
|
||||
|
||||
lines.append(
|
||||
"# HELP chatmail_accounts_active Non-CI accounts active within N days."
|
||||
)
|
||||
lines.append("# TYPE chatmail_accounts_active gauge")
|
||||
for days, active in self.login_buckets.items():
|
||||
lines.append(f'chatmail_accounts_active{{days="{days}"}} {active}')
|
||||
|
||||
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()
|
||||
@@ -22,7 +22,7 @@ mail_domain = {mail_domain}
|
||||
#max_mailbox_size = 500M
|
||||
|
||||
# maximum message size for an e-mail in bytes
|
||||
#max_message_size = 52428800
|
||||
#max_message_size = 31457280
|
||||
|
||||
# days after which mails are unconditionally deleted
|
||||
#delete_mails_after = 20
|
||||
|
||||
@@ -21,6 +21,7 @@ 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
|
||||
|
||||
@@ -128,29 +129,62 @@ def test_mbox_without_password(mbox1, example_config, capsys):
|
||||
assert not os.path.isdir(mbox_rescan.basedir)
|
||||
|
||||
|
||||
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_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_basic(example_config, mbox1):
|
||||
mboxdir = Path(mbox1.basedir)
|
||||
p1 = _create_message(mboxdir, "cur", 400 * MB, days_old=2, disk_size=10)
|
||||
p2 = _create_message(mboxdir, "cur", 400 * MB, days_old=2, disk_size=10)
|
||||
args = (str(example_config._inipath),)
|
||||
expiry_main(args)
|
||||
assert p1.exists() and p2.exists()
|
||||
assert mboxdir.joinpath("maildirsize").exists()
|
||||
|
||||
|
||||
def test_expiry_cli_old_files(capsys, example_config, mbox1):
|
||||
@@ -228,7 +262,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 len(removed) == 2
|
||||
assert removed == 2
|
||||
msgs = scan_mailbox_messages(tmp_path)
|
||||
assert len(msgs) == 1
|
||||
# the surviving message is the fresh undeletable one
|
||||
|
||||
@@ -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":
|
||||
if fn == "chatmail-expire" or fn == "chatmail-fsreport":
|
||||
# don't auto-start but let the corresponding timer trigger execution
|
||||
enabled = False
|
||||
else:
|
||||
|
||||
@@ -102,6 +102,23 @@ def _install_remote_venv_with_chatmaild(deployer) -> None:
|
||||
dest=remote_dist_file,
|
||||
)
|
||||
|
||||
# Remove venv if its Python major.minor doesn't match the system Python
|
||||
server.shell(
|
||||
name="remove stale chatmaild venv if python version changed",
|
||||
commands=[
|
||||
"\n".join(
|
||||
[
|
||||
r"re='[0-9]+\.[0-9]+'", # major.minor out of 'Python X.Y.Z'
|
||||
'sys_version=$(python3 --version 2>/dev/null | grep -oE "$re")',
|
||||
f'venv_version=$({remote_venv_dir}/bin/python --version 2>/dev/null | grep -oE "$re")',
|
||||
# an empty sys_version means we could not tell: keep the venv
|
||||
f'[ -z "$sys_version" ] || [ "$sys_version" = "$venv_version" ] '
|
||||
f"|| rm -rf {remote_venv_dir}",
|
||||
]
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
pip.virtualenv(
|
||||
name=f"chatmaild virtualenv {remote_venv_dir}",
|
||||
path=remote_venv_dir,
|
||||
@@ -288,18 +305,6 @@ class LegacyRemoveDeployer(Deployer):
|
||||
enabled=False,
|
||||
)
|
||||
|
||||
# chatmail-fsreport was folded into chatmail-expiry
|
||||
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
|
||||
@@ -393,6 +398,8 @@ class ChatmailVenvDeployer(Deployer):
|
||||
"lastlogin",
|
||||
"chatmail-expire",
|
||||
"chatmail-expire.timer",
|
||||
"chatmail-fsreport",
|
||||
"chatmail-fsreport.timer",
|
||||
)
|
||||
|
||||
def install(self):
|
||||
@@ -421,6 +428,12 @@ class ChatmailDeployer(Deployer):
|
||||
src=BytesIO(b'APT::Install-Recommends "false";\n'),
|
||||
dest="/etc/apt/apt.conf.d/00InstallRecommends",
|
||||
)
|
||||
# Pin dovecot-* to priority -1 before any apt operation, apt should
|
||||
# never manage dovecot as our version might be lower than the distro's.
|
||||
self.put_file(
|
||||
src=StringIO("Package: dovecot-*\nPin: version *\nPin-Priority: -1\n"),
|
||||
dest="/etc/apt/preferences.d/pin-dovecot",
|
||||
)
|
||||
apt.update(name="apt update", cache_time=24 * 3600)
|
||||
apt.upgrade(name="upgrade apt packages", auto_remove=True)
|
||||
|
||||
@@ -441,8 +454,6 @@ 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
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import io
|
||||
import urllib.request
|
||||
|
||||
from chatmaild.config import Config
|
||||
from pyinfra import host
|
||||
from pyinfra.facts.deb import DebPackages
|
||||
from pyinfra.facts.server import Arch, Command, Sysctl
|
||||
from pyinfra.operations import apt, files, server
|
||||
from pyinfra.operations import files, server
|
||||
|
||||
from cmdeploy.basedeploy import (
|
||||
Deployer,
|
||||
@@ -16,7 +15,13 @@ from cmdeploy.basedeploy import (
|
||||
)
|
||||
from cmdeploy.pins import DOVECOT_SHA256, DOVECOT_VERSION
|
||||
|
||||
DOVECOT_PACKAGE_VERSION = f"1:{DOVECOT_VERSION}"
|
||||
VERSION_ID_CMD = "grep '^VERSION_ID=' /etc/os-release"
|
||||
|
||||
|
||||
def _stamped_version(deb_release: int) -> str:
|
||||
"""Version as built, including the per-distro suffix stamped by
|
||||
chatmail/dovecot CI into package version and filename."""
|
||||
return f"{DOVECOT_VERSION}+deb{deb_release}u1"
|
||||
|
||||
|
||||
class DovecotDeployer(Deployer):
|
||||
@@ -29,34 +34,30 @@ class DovecotDeployer(Deployer):
|
||||
|
||||
def install(self):
|
||||
arch = host.get_fact(Arch)
|
||||
deb_release = _parse_version_id(host.get_fact(Command, VERSION_ID_CMD))
|
||||
with blocked_service_startup():
|
||||
debs = []
|
||||
for pkg in ("core", "imapd", "lmtpd", "auth-lua"):
|
||||
deb, changed = _download_dovecot_package(pkg, arch)
|
||||
deb, changed = _download_dovecot_package(pkg, arch, deb_release)
|
||||
self.need_restart |= changed
|
||||
if deb:
|
||||
debs.append(deb)
|
||||
if debs:
|
||||
deb_list = " ".join(debs)
|
||||
# First dpkg may fail on missing dependencies (stderr suppressed);
|
||||
# apt-get --fix-broken pulls them in, then dpkg retries cleanly.
|
||||
# apt-get install with local .deb paths resolves depends
|
||||
# against the configured repos (e.g. pulls libwrap0),
|
||||
# The pin file written earlier by ChatmailDeployer prevents apt
|
||||
# from installing a 'wrong' version
|
||||
server.shell(
|
||||
name="Install dovecot packages",
|
||||
commands=[
|
||||
f"dpkg --force-confdef --force-confold -i {deb_list} 2> /dev/null || true",
|
||||
"DEBIAN_FRONTEND=noninteractive apt-get -y --fix-broken install",
|
||||
f"dpkg --force-confdef --force-confold -i {deb_list}",
|
||||
"DEBIAN_FRONTEND=noninteractive apt-get install -y "
|
||||
'-o Dpkg::Options::="--force-confdef" '
|
||||
'-o Dpkg::Options::="--force-confold" '
|
||||
f"--allow-downgrades {deb_list}",
|
||||
],
|
||||
)
|
||||
self.need_restart = True
|
||||
self.put_file(
|
||||
src=io.StringIO(
|
||||
"Package: dovecot-*\n"
|
||||
"Pin: version *\n"
|
||||
"Pin-Priority: -1\n"
|
||||
),
|
||||
dest="/etc/apt/preferences.d/pin-dovecot",
|
||||
)
|
||||
|
||||
def configure(self):
|
||||
configure_remote_units(self, self.config.mail_domain_bare, self.units)
|
||||
@@ -69,7 +70,7 @@ class DovecotDeployer(Deployer):
|
||||
if not self.disable_mail and not self.need_restart:
|
||||
stale = host.get_fact(
|
||||
Command,
|
||||
'pid=$(systemctl show -p MainPID --value dovecot.service 2>/dev/null);'
|
||||
"pid=$(systemctl show -p MainPID --value dovecot.service 2>/dev/null);"
|
||||
' [ "${pid:-0}" != "0" ] && readlink "/proc/$pid/exe" 2>/dev/null | grep -q "(deleted)"'
|
||||
" && echo STALE || true",
|
||||
)
|
||||
@@ -84,6 +85,15 @@ class DovecotDeployer(Deployer):
|
||||
)
|
||||
|
||||
|
||||
def _parse_version_id(version_line: str) -> int:
|
||||
"""Debian major release from an /etc/os-release VERSION_ID line."""
|
||||
_, _, raw = (version_line or "").strip().partition("=")
|
||||
try:
|
||||
return int(raw.strip('"'))
|
||||
except ValueError:
|
||||
raise ValueError(f"cannot determine Debian release from {version_line!r}")
|
||||
|
||||
|
||||
def _pick_url(primary, fallback):
|
||||
try:
|
||||
req = urllib.request.Request(primary, method="HEAD")
|
||||
@@ -93,27 +103,36 @@ def _pick_url(primary, fallback):
|
||||
return fallback
|
||||
|
||||
|
||||
def _download_dovecot_package(package: str, arch: str) -> tuple[str | None, bool]:
|
||||
def _download_dovecot_package(package: str, arch: str, deb_release: int) -> tuple[str | None, bool]:
|
||||
"""Download a dovecot .deb if needed, return (path, changed)."""
|
||||
arch = "amd64" if arch == "x86_64" else arch
|
||||
arch = "arm64" if arch == "aarch64" else arch
|
||||
|
||||
pkg_name = f"dovecot-{package}"
|
||||
sha256 = DOVECOT_SHA256.get((package, arch))
|
||||
if sha256 is None:
|
||||
op = apt.packages(packages=[pkg_name])
|
||||
return None, bool(getattr(op, "changed", False))
|
||||
try:
|
||||
# never fall back to the distro package: it is pinned to -1 and would
|
||||
# in any case be a version we did not build and do not support
|
||||
sha256 = DOVECOT_SHA256[(arch, deb_release, package)]
|
||||
except KeyError:
|
||||
raise ValueError(f"no dovecot build for {pkg_name} on deb{deb_release}/{arch}")
|
||||
|
||||
stamped_version = _stamped_version(deb_release)
|
||||
installed_versions = host.get_fact(DebPackages).get(pkg_name, [])
|
||||
if DOVECOT_PACKAGE_VERSION in installed_versions:
|
||||
if f"1:{stamped_version}" in installed_versions:
|
||||
return None, False
|
||||
|
||||
url_version = DOVECOT_VERSION.replace("+", "%2B")
|
||||
deb_base = f"{pkg_name}_{url_version}_{arch}.deb"
|
||||
primary_url = f"https://download.delta.chat/dovecot/{deb_base}"
|
||||
fallback_url = f"https://github.com/chatmail/dovecot/releases/download/upstream%2F{url_version}/{deb_base}"
|
||||
# Primary URL: flat structure with distro suffix in filename
|
||||
primary_deb = f"{pkg_name}_{stamped_version}_{arch}.deb"
|
||||
primary_url = f"https://download.delta.chat/dovecot/{primary_deb}"
|
||||
# GitHub release files: escaped + in filename; the release tag stays
|
||||
# distro-neutral, both distros ship in one combined release
|
||||
tag_version = DOVECOT_VERSION.replace("+", "%2B")
|
||||
fallback_deb = f"{pkg_name}_{stamped_version.replace('+', '%2B')}_{arch}.deb"
|
||||
fallback_url = (
|
||||
f"https://github.com/chatmail/dovecot/releases/download/upstream%2F{tag_version}/{fallback_deb}"
|
||||
)
|
||||
url = _pick_url(primary_url, fallback_url)
|
||||
deb_filename = f"/root/{deb_base}"
|
||||
deb_filename = f"/root/{primary_deb}"
|
||||
|
||||
files.download(
|
||||
name=f"Download {pkg_name}",
|
||||
@@ -125,6 +144,7 @@ def _download_dovecot_package(package: str, arch: str) -> tuple[str | None, bool
|
||||
|
||||
return deb_filename, True
|
||||
|
||||
|
||||
def _configure_dovecot(deployer, config: Config, debug: bool = False):
|
||||
"""Configures Dovecot IMAP server."""
|
||||
deployer.put_template(
|
||||
|
||||
@@ -56,6 +56,8 @@ mail_server_admin = mailto:{{ config.privacy_mail }}
|
||||
# <https://doc.dovecot.org/2.3/configuration_manual/quota_plugin/>
|
||||
mail_plugins = zlib quota
|
||||
|
||||
imap_capability = +XDELTAPUSH XCHATMAIL
|
||||
|
||||
|
||||
# Authentication for system users.
|
||||
passdb {
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
"""Versions, hashes, and download URLs for pre-built artifacts fetched during deploy."""
|
||||
|
||||
FILTERMAIL_VERSION = "v0.7.10"
|
||||
FILTERMAIL_VERSION = "v0.7.7"
|
||||
FILTERMAIL_ARTIFACTS = {
|
||||
"x86_64": (
|
||||
f"https://github.com/chatmail/filtermail/releases/download/{FILTERMAIL_VERSION}/filtermail-x86_64",
|
||||
"c800e39e37d81c504f48dee2e61c10fcdd679c23e7ab958d6f0e6413c19d2be3",
|
||||
"0691debf501f854f4e6a9dd6516f3a0ef03d95721a9b540309014bfe1a1f52b1",
|
||||
),
|
||||
"aarch64": (
|
||||
f"https://github.com/chatmail/filtermail/releases/download/{FILTERMAIL_VERSION}/filtermail-aarch64",
|
||||
"eaf2a46c7c39e898bb37b82716a0a866cea5bbbc642675c78c259e0f98517ceb",
|
||||
"964f85df8b65b812666113f968cbfdd8da88ce16d218284deb359c1e2400d2da",
|
||||
),
|
||||
"mtail": (
|
||||
f"https://raw.githubusercontent.com/chatmail/filtermail/{FILTERMAIL_VERSION}/contrib/filtermail.mtail",
|
||||
@@ -28,16 +28,25 @@ MTAIL_ARTIFACTS = {
|
||||
),
|
||||
}
|
||||
|
||||
DOVECOT_VERSION = "2.3.21+dfsg1-3"
|
||||
# distro-neutral base version, as committed in chatmail/dovecot debian/changelog
|
||||
DOVECOT_VERSION = "2.3.21+dfsg1-3+chatmail2"
|
||||
DOVECOT_SHA256 = {
|
||||
("core", "amd64"): "dd060706f52a306fa863d874717210b9fe10536c824afe1790eec247ded5b27d",
|
||||
("core", "arm64"): "e7548e8a82929722e973629ecc40fcfa886894cef3db88f23535149e7f730dc9",
|
||||
("imapd", "amd64"): "8d8dc6fc00bbb6cdb25d345844f41ce2f1c53f764b79a838eb2a03103eebfa86",
|
||||
("imapd", "arm64"): "178fa877ddd5df9930e8308b518f4b07df10e759050725f8217a0c1fb3fd707f",
|
||||
("lmtpd", "amd64"): "2f69ba5e35363de50962d42cccbfe4ed8495265044e244007d7ccddad77513ab",
|
||||
("lmtpd", "arm64"): "89f52fb36524f5877a177dff4a713ba771fd3f91f22ed0af7238d495e143b38f",
|
||||
("auth-lua", "amd64"): "d724f37712faba52e177153114af1831e54da555c57c6474c05f96f176176ce4",
|
||||
("auth-lua", "arm64"): "7272768e20de148c35891d99cd60205acbe7e732b056caf0a83e8194d49136e6",
|
||||
("amd64", 12, "auth-lua"): "ef1b8e1db45147a74b48d63125bd61b2cc2f250e1006656ba1c58b9c12f5cde6",
|
||||
("arm64", 12, "auth-lua"): "c1a06ee9374439893e397ba3b0cacf532a733290c184f4f30ea39df8699be329",
|
||||
("amd64", 13, "auth-lua"): "6c0946d2516efcbcaa09a27df9b8ea701861cce270d71941056b3c69831a5ea2",
|
||||
("arm64", 13, "auth-lua"): "5e6c9cfe47f7f3b8aa0d68a3e607161b6abaee1ad696cb1419e997b3099b2985",
|
||||
("amd64", 12, "core"): "ac3977264d9b9a6fcec53fd3f5cdd2a79ca8aa0324de530c07e535008540826e",
|
||||
("arm64", 12, "core"): "21626c9c9b52cbdcf1a17b5c09e3c4043e69aa371bf83cc2fcb3b7ddaecdc109",
|
||||
("amd64", 13, "core"): "47c242ef23c17e700ac19d52d82c9fdb2ebd757d8beb3a7f6781d2de59f87bd0",
|
||||
("arm64", 13, "core"): "c14c53f112c875f698c4cb6e5870c605cd0a9dd98d35a66e94ceb1827f8020a3",
|
||||
("amd64", 12, "imapd"): "92a7ab5fc7dc32886a0c34404f919f1335d397b48c467e0c1ef77e56978f60ea",
|
||||
("arm64", 12, "imapd"): "9369fd566fec4df109ef23debf34ea0417ae85beb29cbe7de619d4d1f31b120c",
|
||||
("amd64", 13, "imapd"): "e38cc1266455f937ed62f971ea859c47e1a99247841ed0ad946963b524cfdbc5",
|
||||
("arm64", 13, "imapd"): "11d97dabf23171b37f8b1335dfdb81d408f8b95391aea6d4066aecc9fde01dfe",
|
||||
("amd64", 12, "lmtpd"): "dc3de473789969f7dd3504ac8783da5e42a446d2d7a305a4e9d7081a6dfe71ab",
|
||||
("arm64", 12, "lmtpd"): "ae2cbd6c5c43f6d8e2172997b055448f4c79238e2f99cd9ab9200a7d9f548908",
|
||||
("amd64", 13, "lmtpd"): "833b243e28c7baff141ecf37456e310f5d836e7944a3b9f2fe5074adf0d6a418",
|
||||
("arm64", 13, "lmtpd"): "55af47a121ba7e23966b20ddaab2dff7feba4b34677864e045e31a702afa180d",
|
||||
}
|
||||
TURN_VERSION = "v0.4"
|
||||
TURN_ARTIFACTS = {
|
||||
|
||||
@@ -5,5 +5,5 @@ After=network.target
|
||||
[Service]
|
||||
Type=oneshot
|
||||
User=vmail
|
||||
ExecStart={execpath} {config_path} -v --remove --prom /var/lib/chatmail/expire.prom
|
||||
ExecStart={execpath} {config_path} -v --remove
|
||||
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
[Unit]
|
||||
Description=chatmail file system storage reporting job
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
User=vmail
|
||||
ExecStart={execpath} {config_path}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
[Unit]
|
||||
Description=Run Daily Chatmail fsreport Job
|
||||
|
||||
[Timer]
|
||||
OnCalendar=*-*-* 08:02:00
|
||||
Persistent=true
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -15,6 +15,13 @@ def test_init(tmp_path, maildomain):
|
||||
assert config.mail_domain_bare == maildomain
|
||||
|
||||
|
||||
def test_capabilities(imap):
|
||||
imap.connect()
|
||||
capas = imap.conn.capabilities
|
||||
assert "XCHATMAIL" in capas
|
||||
assert "XDELTAPUSH" in capas
|
||||
|
||||
|
||||
def test_login_basic_functioning(imap_or_smtp, gencreds, lp):
|
||||
"""Test a) that an initial login creates a user automatically
|
||||
and b) verify we can also login a second time with the same password
|
||||
|
||||
@@ -3,29 +3,40 @@ from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from pyinfra.facts.deb import DebPackages
|
||||
from pyinfra.facts.server import Command
|
||||
|
||||
from cmdeploy.dovecot import deployer as dovecot_deployer
|
||||
|
||||
|
||||
def _fact_name(key):
|
||||
if isinstance(key, tuple):
|
||||
return f"{key[0].__name__}{key[1:]!r}"
|
||||
return key.__name__
|
||||
|
||||
|
||||
def make_host(*fact_pairs):
|
||||
"""Build a mock host; get_fact(cls) dispatches to the provided facts mapping.
|
||||
"""Build a mock host; get_fact() dispatches to the provided facts mapping.
|
||||
|
||||
Args:
|
||||
*fact_pairs: tuples of (fact_class, fact_value) to register
|
||||
*fact_pairs: (fact_class, value) to match any call of that fact, or
|
||||
((fact_class, *args), value) to match one specific call. Needed
|
||||
for Command, which install() and check_restart() invoke with
|
||||
different scripts; a bare Command entry would serve both.
|
||||
|
||||
Returns:
|
||||
SimpleNamespace with get_fact that raises a clear error if an
|
||||
unexpected fact type is requested.
|
||||
unregistered fact is requested.
|
||||
"""
|
||||
facts = dict(fact_pairs)
|
||||
|
||||
def get_fact(cls):
|
||||
if cls not in facts:
|
||||
registered = ", ".join(c.__name__ for c in facts)
|
||||
raise LookupError(
|
||||
f"unexpected get_fact({cls.__name__}); only registered: {registered}"
|
||||
)
|
||||
return facts[cls]
|
||||
def get_fact(cls, *args):
|
||||
for key in ((cls, *args), cls):
|
||||
if key in facts:
|
||||
return facts[key]
|
||||
registered = ", ".join(_fact_name(k) for k in facts)
|
||||
raise LookupError(
|
||||
f"unexpected get_fact({_fact_name((cls, *args))}); only registered: {registered}"
|
||||
)
|
||||
|
||||
return SimpleNamespace(get_fact=get_fact)
|
||||
|
||||
@@ -64,7 +75,9 @@ def track_shell(monkeypatch):
|
||||
|
||||
|
||||
def test_download_dovecot_package_skips_epoch_matched_install(monkeypatch):
|
||||
epoch_version = dovecot_deployer.DOVECOT_PACKAGE_VERSION
|
||||
# what dpkg reports after installing our deb: epoch + the +debNu1 suffix
|
||||
# that chatmail/dovecot CI stamps via dch before building
|
||||
epoch_version = f"1:{dovecot_deployer._stamped_version(12)}"
|
||||
downloads = []
|
||||
monkeypatch.setattr(
|
||||
dovecot_deployer,
|
||||
@@ -82,15 +95,17 @@ def test_download_dovecot_package_skips_epoch_matched_install(monkeypatch):
|
||||
lambda **kwargs: downloads.append(kwargs),
|
||||
)
|
||||
|
||||
deb, changed = dovecot_deployer._download_dovecot_package("core", "amd64")
|
||||
deb, changed = dovecot_deployer._download_dovecot_package("core", "amd64", deb_release=12)
|
||||
|
||||
assert deb is None, f"expected no deb path when version matches, got {deb!r}"
|
||||
assert changed is False, "should not flag changed when version already installed"
|
||||
assert downloads == [], "should not download when version already installed"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("deb_release", [12, 13])
|
||||
@pytest.mark.parametrize("arch", ["amd64", "arm64"])
|
||||
def test_download_dovecot_package_uses_archive_version_for_url_and_filename(
|
||||
monkeypatch,
|
||||
monkeypatch, deb_release, arch
|
||||
):
|
||||
downloads = []
|
||||
monkeypatch.setattr(
|
||||
@@ -109,18 +124,26 @@ def test_download_dovecot_package_uses_archive_version_for_url_and_filename(
|
||||
lambda **kwargs: downloads.append(kwargs),
|
||||
)
|
||||
|
||||
deb, changed = dovecot_deployer._download_dovecot_package("core", "amd64")
|
||||
deb, changed = dovecot_deployer._download_dovecot_package(
|
||||
"core", arch, deb_release=deb_release
|
||||
)
|
||||
|
||||
archive_version = dovecot_deployer.DOVECOT_VERSION.replace("+", "%2B")
|
||||
expected_deb = f"/root/dovecot-core_{archive_version}_amd64.deb"
|
||||
stamped = dovecot_deployer._stamped_version(deb_release)
|
||||
expected_deb = f"/root/dovecot-core_{stamped}_{arch}.deb"
|
||||
|
||||
# Verify the returned path uses archive version, not package version (with epoch)
|
||||
# path uses the stamped version, and deb filenames never carry the epoch
|
||||
assert changed is True, "should flag changed when package not yet installed"
|
||||
assert deb == expected_deb, f"deb path mismatch: {deb!r} != {expected_deb!r}"
|
||||
assert dovecot_deployer.DOVECOT_PACKAGE_VERSION not in deb, (
|
||||
f"deb path should use archive version (no epoch), got {deb!r}"
|
||||
)
|
||||
assert "1:" not in deb, f"deb filename must not contain the epoch, got {deb!r}"
|
||||
assert len(downloads) == 1, "files.download should be called exactly once"
|
||||
# the checksum is the security boundary: verify the right table row is used
|
||||
assert (
|
||||
downloads[0]["sha256sum"]
|
||||
== dovecot_deployer.DOVECOT_SHA256[(arch, deb_release, "core")]
|
||||
), "must pass the sha256 matching (arch, release, package)"
|
||||
assert f"deb{deb_release}u1" in downloads[0]["src"], (
|
||||
f"download URL should carry the deb{deb_release} suffix, got {downloads[0]['src']!r}"
|
||||
)
|
||||
|
||||
|
||||
def test_install_skips_dpkg_path_when_epoch_matched_packages_present(
|
||||
@@ -133,13 +156,14 @@ def test_install_skips_dpkg_path_when_epoch_matched_packages_present(
|
||||
(
|
||||
dovecot_deployer.DebPackages,
|
||||
{
|
||||
"dovecot-core": [dovecot_deployer.DOVECOT_PACKAGE_VERSION],
|
||||
"dovecot-imapd": [dovecot_deployer.DOVECOT_PACKAGE_VERSION],
|
||||
"dovecot-lmtpd": [dovecot_deployer.DOVECOT_PACKAGE_VERSION],
|
||||
"dovecot-auth-lua": [dovecot_deployer.DOVECOT_PACKAGE_VERSION],
|
||||
"dovecot-core": [f"1:{dovecot_deployer._stamped_version(12)}"],
|
||||
"dovecot-imapd": [f"1:{dovecot_deployer._stamped_version(12)}"],
|
||||
"dovecot-lmtpd": [f"1:{dovecot_deployer._stamped_version(12)}"],
|
||||
"dovecot-auth-lua": [f"1:{dovecot_deployer._stamped_version(12)}"],
|
||||
},
|
||||
),
|
||||
(dovecot_deployer.Arch, "x86_64"),
|
||||
((Command, dovecot_deployer.VERSION_ID_CMD), 'VERSION_ID="12"'),
|
||||
),
|
||||
)
|
||||
downloads = []
|
||||
@@ -153,44 +177,26 @@ def test_install_skips_dpkg_path_when_epoch_matched_packages_present(
|
||||
|
||||
assert downloads == [], "should not download when all packages epoch-matched"
|
||||
assert track_shell == [], "should not run dpkg when all packages epoch-matched"
|
||||
assert deployer.need_restart is False, (
|
||||
"need_restart should be False when nothing changed"
|
||||
)
|
||||
assert deployer.need_restart is False, "need_restart should be False when nothing changed"
|
||||
|
||||
|
||||
def test_install_unsupported_arch_falls_back_to_apt(
|
||||
def test_install_unsupported_arch_raises(
|
||||
deployer, patch_blocked, mock_files_put, track_shell, monkeypatch
|
||||
):
|
||||
# For unsupported architectures, all fact lookups return the arch string.
|
||||
monkeypatch.setattr(
|
||||
dovecot_deployer,
|
||||
"host",
|
||||
SimpleNamespace(get_fact=lambda cls: "riscv64"),
|
||||
make_host(
|
||||
(dovecot_deployer.Arch, "riscv64"),
|
||||
((Command, dovecot_deployer.VERSION_ID_CMD), 'VERSION_ID="12"'),
|
||||
),
|
||||
)
|
||||
apt_calls = []
|
||||
|
||||
# Mirrors apt.packages() return value: OperationMeta with .changed property.
|
||||
# Only lmtpd triggers a change to verify |= accumulation of changed flags.
|
||||
def fake_apt(**kwargs):
|
||||
apt_calls.append(kwargs)
|
||||
changed = "lmtpd" in kwargs["packages"][0]
|
||||
return SimpleNamespace(changed=changed)
|
||||
# we never fall back to the pinned distro package
|
||||
with pytest.raises(ValueError, match="no dovecot build for dovecot-core"):
|
||||
deployer.install()
|
||||
|
||||
monkeypatch.setattr(dovecot_deployer.apt, "packages", fake_apt)
|
||||
|
||||
deployer.install()
|
||||
|
||||
actual_pkgs = [c["packages"] for c in apt_calls]
|
||||
assert actual_pkgs == [
|
||||
["dovecot-core"],
|
||||
["dovecot-imapd"],
|
||||
["dovecot-lmtpd"],
|
||||
["dovecot-auth-lua"],
|
||||
], f"expected apt install of core/imapd/lmtpd/auth-lua, got {actual_pkgs}"
|
||||
assert track_shell == [], "should not run dpkg for unsupported arch"
|
||||
assert deployer.need_restart is True, (
|
||||
"need_restart should be True when apt installed a package"
|
||||
)
|
||||
assert track_shell == [], "should not run apt-get for unsupported arch"
|
||||
|
||||
|
||||
def test_install_runs_dpkg_when_packages_need_download(
|
||||
@@ -202,6 +208,7 @@ def test_install_runs_dpkg_when_packages_need_download(
|
||||
make_host(
|
||||
(dovecot_deployer.DebPackages, {}),
|
||||
(dovecot_deployer.Arch, "x86_64"),
|
||||
((Command, dovecot_deployer.VERSION_ID_CMD), 'VERSION_ID="12"'),
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
@@ -217,17 +224,15 @@ def test_install_runs_dpkg_when_packages_need_download(
|
||||
|
||||
deployer.install()
|
||||
|
||||
assert len(track_shell) == 1, (
|
||||
f"expected one server.shell() call for dpkg install, got {len(track_shell)}"
|
||||
)
|
||||
assert len(track_shell) == 1, f"expected one server.shell() call for dpkg install, got {len(track_shell)}"
|
||||
cmds = track_shell[0]["commands"]
|
||||
assert len(cmds) == 3, f"expected 3 dpkg/apt commands, got: {cmds}"
|
||||
assert cmds[0].startswith("dpkg --force-confdef --force-confold -i ")
|
||||
assert "apt-get -y --fix-broken install" in cmds[1]
|
||||
assert cmds[2].startswith("dpkg --force-confdef --force-confold -i ")
|
||||
assert deployer.need_restart is True, (
|
||||
"need_restart should be True after dpkg install"
|
||||
)
|
||||
assert len(cmds) == 1, f"expected single apt-get install command, got: {cmds}"
|
||||
assert "apt-get install -y" in cmds[0]
|
||||
assert '-o Dpkg::Options::="--force-confdef"' in cmds[0]
|
||||
assert '-o Dpkg::Options::="--force-confold"' in cmds[0]
|
||||
assert "--allow-downgrades" in cmds[0]
|
||||
assert ".deb" in cmds[0]
|
||||
assert deployer.need_restart is True, "need_restart should be True after dpkg install"
|
||||
|
||||
|
||||
def test_pick_url_falls_back_on_primary_error(monkeypatch):
|
||||
@@ -236,6 +241,45 @@ def test_pick_url_falls_back_on_primary_error(monkeypatch):
|
||||
|
||||
monkeypatch.setattr(dovecot_deployer.urllib.request, "urlopen", raise_error)
|
||||
result = dovecot_deployer._pick_url("http://primary", "http://fallback")
|
||||
assert result == "http://fallback", (
|
||||
f"should fall back when primary fails, got {result!r}"
|
||||
assert result == "http://fallback", f"should fall back when primary fails, got {result!r}"
|
||||
|
||||
|
||||
def test_install_fails_on_unsupported_debian_version(deployer, patch_blocked, monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
dovecot_deployer,
|
||||
"host",
|
||||
make_host(
|
||||
(dovecot_deployer.Arch, "x86_64"),
|
||||
((Command, dovecot_deployer.VERSION_ID_CMD), 'VERSION_ID="99"'),
|
||||
),
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="no dovecot build for dovecot-core on deb99"):
|
||||
deployer.install()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"version_line", ["", None, "ID=debian"], ids=["empty", "none", "no-version-id"]
|
||||
)
|
||||
def test_parse_version_id_raises_without_version_id(version_line):
|
||||
with pytest.raises(ValueError, match="cannot determine Debian release"):
|
||||
dovecot_deployer._parse_version_id(version_line)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("deb_release", [12, 13])
|
||||
def test_parse_version_id(deb_release):
|
||||
parsed = dovecot_deployer._parse_version_id(f'VERSION_ID="{deb_release}"\n')
|
||||
assert parsed == deb_release
|
||||
|
||||
|
||||
def test_dovecot_sha256_covers_all_packages_per_release():
|
||||
"""Every release in the table needs all four packages on both arches."""
|
||||
table = dovecot_deployer.DOVECOT_SHA256
|
||||
expected = {
|
||||
(arch, pkg)
|
||||
for arch in ("amd64", "arm64")
|
||||
for pkg in ("core", "imapd", "lmtpd", "auth-lua")
|
||||
}
|
||||
for release in {r for _, r, _ in table}:
|
||||
got = {(arch, pkg) for arch, r, pkg in table if r == release}
|
||||
assert got == expected, f"deb{release} incomplete: {sorted(expected - got)}"
|
||||
|
||||
@@ -37,9 +37,6 @@ extlinks = {
|
||||
# Warn about repository links spelled out in full instead of using the roles.
|
||||
extlinks_detect_hardcoded_links = True
|
||||
|
||||
# delta.chat/help picks the reader's language in JavaScript and keeps the anchor.
|
||||
linkcheck_anchors_ignore_for_url = [r"https://delta\.chat/help"]
|
||||
|
||||
|
||||
# -- Options for HTML output -------------------------------------------------
|
||||
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
|
||||
|
||||
+1
-1
@@ -90,4 +90,4 @@ enforce end-to-end encryption on their own.
|
||||
The end-to-end encryption protection includes attached media, user
|
||||
display names, avatars and group names. What is visible to operators is:
|
||||
message date, sender and receiver addresses.
|
||||
Please see the `Delta Chat FAQ on encryption and security <https://delta.chat/help#e2ee>`_ for further info.
|
||||
Please see the `Delta Chat FAQ on encryption and security <https://delta.chat/en/help#e2ee>`_ for further info.
|
||||
|
||||
@@ -97,7 +97,7 @@ short overview of ``chatmaild`` services:
|
||||
to store user-specific relay-side config. On new messages, it
|
||||
:repofile:`passes the user’s push notification token <chatmaild/src/chatmaild/notifier.py>`
|
||||
to
|
||||
`notifications.delta.chat <https://delta.chat/help#instant-delivery>`_
|
||||
`notifications.delta.chat <https://delta.chat/en/help#instant-delivery>`_
|
||||
so the push notifications on the user’s phone can be triggered by
|
||||
Apple/Google/Huawei.
|
||||
|
||||
@@ -105,8 +105,6 @@ 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``.
|
||||
@@ -145,6 +143,7 @@ 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;
|
||||
@@ -167,6 +166,7 @@ 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;
|
||||
|
||||
+1
-1
@@ -35,4 +35,4 @@ you can also **scan this QR code** with Delta Chat:
|
||||
|
||||
🐣 **Choose** your Avatar and Name
|
||||
|
||||
💬 **Start** chatting with any Delta Chat contacts using [QR invite codes](https://delta.chat/help#howtoe2ee)
|
||||
💬 **Start** chatting with any Delta Chat contacts using [QR invite codes](https://delta.chat/en/help#howtoe2ee)
|
||||
|
||||
+2
-2
@@ -10,12 +10,12 @@ for the usage in chats, especially DeltaChat.
|
||||
### Rate and storage limits
|
||||
|
||||
- Un-encrypted messages are blocked to recipients outside
|
||||
{{config.mail_domain}} but setting up contact via [QR invite codes](https://delta.chat/help#howtoe2ee)
|
||||
{{config.mail_domain}} but setting up contact via [QR invite codes](https://delta.chat/en/help#howtoe2ee)
|
||||
allows your messages to pass freely to any outside recipients.
|
||||
|
||||
- You may send up to {{ config.max_user_send_per_minute }} messages per minute.
|
||||
|
||||
- You can store up to [{{ config.max_mailbox_size }} messages on the server](https://delta.chat/help#what-happens-if-i-turn-on-delete-old-messages-from-server).
|
||||
- You can store up to [{{ config.max_mailbox_size }} messages on the server](https://delta.chat/en/help#what-happens-if-i-turn-on-delete-old-messages-from-server).
|
||||
|
||||
- Messages are unconditionally removed latest {{ config.delete_mails_after }} days after arriving on the server.
|
||||
Earlier, if storage may exceed otherwise.
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@
|
||||
Welcome to `{{config.mail_domain}}`, the default chatmail onboarding server for Delta Chat users.
|
||||
It is operated on the side by a small sysops team
|
||||
on a voluntary basis.
|
||||
See [other chatmail servers](https://chatmail.at/relays) for alternative server operators.
|
||||
See [other chatmail servers](https://delta.chat/en/chatmail) for alternative server operators.
|
||||
{% endif %}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user