Files
cscs-portal/project_notify.py
2026-10-15 10:32:25 +02:00

249 lines
9.5 KiB
Python
Executable File

#!/usr/bin/env python3
"""Preview and individually approve low-NH-usage emails to CSCS PIs."""
from __future__ import annotations
import argparse
from datetime import date
import getpass
import os
import sys
from cscs_portal import CSCSClient
from cscs_portal.project import current_quarter, parse_quarter, quarter_label, quarter_offset
from cscs_portal.notifications import (
DEFAULT_TEMPLATE,
SHARED_PROJECTS,
SMTPSettings,
load_template,
load_notification_template,
resolve_mail_headers,
resolve_smtp_settings,
preview_message,
project_info_for_notification,
render_message,
send_message,
summarize_nh,
)
def percent_threshold(raw: str) -> float:
import math
try:
value = float(raw)
except ValueError as exc:
raise argparse.ArgumentTypeError("threshold must be a percentage from 0 to 100") from exc
if not math.isfinite(value) or value < 0 or value > 100:
raise argparse.ArgumentTypeError("threshold must be a percentage from 0 to 100")
return value
def positive_int(raw: str) -> int:
try:
value = int(raw)
except ValueError as exc:
raise argparse.ArgumentTypeError("must be a positive integer") from exc
if value <= 0:
raise argparse.ArgumentTypeError("must be a positive integer")
return value
def parse_args(argv=None):
year, q = current_quarter()
parser = argparse.ArgumentParser(
description="Compose one email per project below an NH usage threshold. "
"Only send after an explicit per-project confirmation."
)
parser.add_argument("projects", nargs="+", metavar="PROJECT", help="Project name or UUID")
parser.add_argument("--quarter", help=f"Quarter YYYY-QN (default: {quarter_label(year, q)})")
parser.add_argument(
"--threshold", type=percent_threshold, default=50.0, metavar="PERCENT",
help="Select projects with NH usage strictly below this value (default: 50)",
)
parser.add_argument(
"--deputy-pi", action="store_true", help="Add Deputy PI email(s) to the To header"
)
parser.add_argument(
"--template", default=str(DEFAULT_TEMPLATE), metavar="YAML",
help="Email subject and body YAML file",
)
parser.add_argument("--dry-run", action="store_true", help="Print previews; never send")
parser.add_argument(
"--include-shared-projects", action="store_true",
help="Also contact the PSI shared pool projects psi/psigpu (skipped by default)",
)
parser.add_argument(
"--allow-historical-send", action="store_true",
help="Allow actual sending for an earlier quarter (normally preview-only)",
)
parser.add_argument(
"--from-address", metavar="EMAIL", default=None,
help="Sender (CLI overrides system environment and YAML defaults)",
)
parser.add_argument(
"--cc-address", metavar="EMAIL", default=None,
help="CC address (default: system environment, YAML, then admin list)",
)
parser.add_argument(
"--reply-to", metavar="EMAIL", default=None,
help="Optional Reply-To address",
)
parser.add_argument("--smtp-host", default=None, metavar="HOST")
parser.add_argument(
"--smtp-port", type=positive_int, default=None, metavar="PORT",
help="Uses system variable, YAML, or transport default (587/465/25)",
)
parser.add_argument(
"--smtp-security", choices=("starttls", "ssl", "none"),
default=None,
help="Transport protection; 'none' is permitted for localhost only",
)
parser.add_argument("--smtp-user", default=None)
parser.add_argument(
"--login-timeout", type=positive_int, default=28800, metavar="SECONDS",
help="Interactive Chromium login timeout (default: 28800)",
)
return parser.parse_args(argv)
def _smtp_settings(args) -> SMTPSettings:
"""Resolve system/CLI/template options only after a user approves send."""
template = args._notification_template
password = os.getenv("PSI_SMTP_PASSWORD") or os.getenv("SMTP_PASSWORD")
# Only ask for a password when the selected SMTP account needs one.
username = (
args.smtp_user or os.getenv("PSI_SMTP_USER") or os.getenv("SMTP_USER")
or template.smtp.get("username")
)
if username and not password:
# Catch invalid host/sender/TLS settings before prompting for a secret.
resolve_smtp_settings(args, template, password="__validation_only__")
password = getpass.getpass(f"SMTP password for {username}: ")
return resolve_smtp_settings(args, template, password=password)
def _open_client(timeout: int):
# Existing package versions vary: the recent CLI supports configurable
# Chromium timeouts, while the original October 12 upload did not.
import inspect
if "login_timeout" in inspect.signature(CSCSClient).parameters:
return CSCSClient(login_timeout=timeout)
if timeout != 28800:
print(
"WARNING: installed CSCSClient does not support --login-timeout; "
"using its existing default.", file=sys.stderr,
)
return CSCSClient()
def main(argv=None, *, input_fn=input, smtp_send=send_message):
args = parse_args(argv)
if args.quarter:
try:
year, quarter = parse_quarter(args.quarter)
except argparse.ArgumentTypeError as exc:
print(f"ERROR: {exc}", file=sys.stderr)
return 2
else:
year, quarter = current_quarter()
try:
quarter_offset(year, quarter)
except RuntimeError as exc:
print(f"ERROR: {exc}", file=sys.stderr)
return 2
quarter_name = quarter_label(year, quarter)
historical = (year, quarter) != current_quarter()
if historical and not args.allow_historical_send:
print(
f"NOTE: {quarter_name} is in the past. Previews only: sending disabled "
"unless --allow-historical-send is specified."
)
template = load_notification_template(args.template)
subject, body = template.subject, template.body
args._notification_template = template
try:
mail_headers = resolve_mail_headers(args, template)
except ValueError as exc:
print(f"ERROR: invalid mail configuration: {exc}", file=sys.stderr)
return 2
counts = {"eligible": 0, "sent": 0, "declined": 0, "errors": 0, "skipped": 0}
smtp_config = None
with _open_client(args.login_timeout) as client:
for selector in args.projects:
try:
info = project_info_for_notification(client, selector, year, quarter)
name = info.get("name") or selector
if not args.include_shared_projects and name.lower() in SHARED_PROJECTS:
print(f"SKIP {name}: shared allocation pool")
counts["skipped"] += 1
continue
usage = summarize_nh(info)
if not usage:
print(f"SKIP {name}: no usable NH allocation/usage (or allocated NH = 0)")
counts["skipped"] += 1
continue
if usage.percent >= args.threshold:
print(f"SKIP {name}: {usage.percent:.2f}% >= {args.threshold:.2f}%")
counts["skipped"] += 1
continue
if info.get("team_status") != "ok":
print(f"SKIP {name}: current project team unavailable")
counts["skipped"] += 1
continue
if not any(person.get("email") for person in (info.get("team") or {}).get("PI", [])):
print(f"SKIP {name}: no PI email address available")
counts["skipped"] += 1
continue
message = render_message(
info, usage, subject, body, as_of=date.today(),
with_deputies=args.deputy_pi,
sender=mail_headers.sender,
cc=mail_headers.cc,
reply_to=mail_headers.reply_to,
)
except Exception as exc:
print(f"ERROR {selector}: {exc}", file=sys.stderr)
counts["errors"] += 1
continue
counts["eligible"] += 1
preview_message(
message, project_name=name, percent=usage.percent,
threshold=args.threshold,
)
if args.dry_run or (historical and not args.allow_historical_send):
print(f"DRY RUN - not sent: {name}")
continue
try:
reply = input_fn("Send this email? [y/N] ").strip().lower()
except (EOFError, KeyboardInterrupt):
print("\nStopping without sending the pending email.")
break
if reply not in ("y", "yes"):
print(f"DECLINED: {name}")
counts["declined"] += 1
continue
try:
if smtp_config is None:
smtp_config = _smtp_settings(args)
smtp_send(message, smtp_config)
except Exception as exc:
print(f"SEND FAILED {name}: {exc}", file=sys.stderr)
counts["errors"] += 1
continue
counts["sent"] += 1
print(f"SENT: {name} -> {message['To']}")
print(
f"\nSummary: eligible={counts['eligible']}, sent={counts['sent']}, "
f"declined={counts['declined']}, skipped={counts['skipped']}, "
f"errors={counts['errors']}"
)
return 1 if counts["errors"] else 0
if __name__ == "__main__":
sys.exit(main())