ruff: Fix RUF004 exit() is only available in the interpreter.

‘exit’ is pulled in for the interactive interpreter as a side effect
of the site module; this can be disabled with python -S and shouldn’t
be relied on.

Also, use the NoReturn type where appropriate.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
This commit is contained in:
Anders Kaseorg 2022-12-03 23:47:12 -08:00 committed by Tim Abbott
parent c850a006d9
commit f3f5dfb5aa
12 changed files with 31 additions and 26 deletions

View File

@ -54,4 +54,4 @@ if __name__ == "__main__":
ret, result = nagios_from_file(RESULTS_FILE, **extra_args)
print(result)
exit(ret)
sys.exit(ret)

View File

@ -14,6 +14,7 @@ import random
import sys
import time
import traceback
from typing import Any, Dict, List, NoReturn, Optional
sys.path.append(".")
sys.path.append("/home/zulip/deployments/current")
@ -21,8 +22,6 @@ from scripts.lib.setup_path import setup_path
setup_path()
from typing import Any, Dict, List, Optional
import django
import zulip
@ -78,7 +77,7 @@ states = {
}
def report(state: str, timestamp: Any = None, msg: Optional[str] = None) -> None:
def report(state: str, timestamp: Any = None, msg: Optional[str] = None) -> NoReturn:
now = int(time.time())
if msg is None:
msg = f"send time was {timestamp}"
@ -87,7 +86,7 @@ def report(state: str, timestamp: Any = None, msg: Optional[str] = None) -> None
f.write(f"{now}|{states[state]}|{state}|{msg}\n")
os.rename(state_file_path + ".tmp", state_file_path)
print(f"{state}: {msg}")
exit(states[state])
sys.exit(states[state])
def send_zulip(sender: zulip.Client, message: Dict[str, Any]) -> None:

View File

@ -9,6 +9,7 @@ This can only use stdlib modules from python.
import configparser
import re
import subprocess
import sys
from typing import Dict, List
@ -63,7 +64,7 @@ def run_sql_query(query: str) -> List[List[str]]:
return [x.split("\0") for x in output.split("\n")]
except subprocess.CalledProcessError as e:
report("CRITICAL", f"psql failed: {str(e)}: {e.output}")
exit(MAXSTATE)
sys.exit(MAXSTATE)
def loc_to_abs_offset(loc_str: str) -> int:
@ -142,4 +143,4 @@ else:
else:
report("OK", msg)
exit(MAXSTATE)
sys.exit(MAXSTATE)

View File

@ -1,6 +1,7 @@
#!/usr/bin/env python3
import subprocess
import sys
from datetime import datetime, timedelta, timezone
import dateutil.parser
@ -15,7 +16,7 @@ states = {
def report(state: str, msg: str) -> None:
print(f"{state}: {msg}")
exit(states[state])
sys.exit(states[state])
if (

View File

@ -190,7 +190,7 @@ if options.nagios_check:
if num > 5:
state = "CRITICAL"
print(f"{state}: {num} rows in fts_update_log table")
exit(states[state])
sys.exit(states[state])
conn = None

View File

@ -9,8 +9,9 @@ mirrors when they receive the messages sent every minute by
/etc/cron.d/test_zephyr_personal_mirrors
"""
import os
import sys
import time
from typing import Dict
from typing import Dict, NoReturn
RESULTS_DIR: str = "/home/zulip/mirror_status"
@ -22,9 +23,9 @@ states: Dict[str, int] = {
}
def report(state: str, output: str) -> None:
def report(state: str, output: str) -> NoReturn:
print(f"{state}\n{output}")
exit(states[state])
sys.exit(states[state])
output = ""

View File

@ -9,6 +9,7 @@ Django ORM.
import datetime
import os
import sys
from typing import NoReturn
sys.path.append("/home/zulip/deployments/current")
from scripts.lib.setup_path import setup_path
@ -39,7 +40,7 @@ state_file_path = "/var/lib/nagios_state/check_user_zephyr_mirror_liveness"
now = timezone_now()
def report(state: str, short_msg: str, too_old: AbstractSet[Any] = set()) -> None:
def report(state: str, short_msg: str, too_old: AbstractSet[Any] = set()) -> NoReturn:
too_old_data = ""
if too_old:
too_old_data = "\nLast call to get_message for recently out of date mirrors:\n" + "\n".join(
@ -54,7 +55,7 @@ def report(state: str, short_msg: str, too_old: AbstractSet[Any] = set()) -> Non
f.write(f"{int(now.timestamp())}|{states[state]}|{state}|{short_msg}{too_old_data}")
os.rename(state_file_path + ".tmp", state_file_path)
print(f"{state}: {short_msg}{too_old_data}")
exit(states[state])
sys.exit(states[state])
all_users = UserActivity.objects.filter(

View File

@ -10,8 +10,9 @@ run out of cron.
See puppet/zulip_ops/files/cron.d/zephyr-mirror for the crontab details.
"""
import os
import sys
import time
from typing import Dict
from typing import Dict, NoReturn
RESULTS_FILE = "/var/lib/nagios_state/check-mirroring-results"
@ -23,13 +24,13 @@ states: Dict[str, int] = {
}
def report(state: str, data: str, last_check: float) -> None:
def report(state: str, data: str, last_check: float) -> NoReturn:
print(
"{}: Last test run completed at {}\n{}".format(
state, time.strftime("%Y-%m-%d %H:%M %Z", time.gmtime(last_check)), data
)
)
exit(states[state])
sys.exit(states[state])
with open(RESULTS_FILE) as f:

View File

@ -48,6 +48,7 @@ import posix
import ssl
import sys
from configparser import RawConfigParser
from typing import NoReturn
from urllib.error import HTTPError
from urllib.parse import urlencode, urljoin, urlparse
from urllib.request import Request, urlopen
@ -94,15 +95,15 @@ options = parser.parse_args()
MAX_ALLOWED_PAYLOAD = 25 * 1024 * 1024
def process_response_error(e: HTTPError) -> None:
def process_response_error(e: HTTPError) -> NoReturn:
if e.code == 400:
response_content = e.read()
response_data = json.loads(response_content)
print(response_data["msg"])
exit(posix.EX_NOUSER)
sys.exit(posix.EX_NOUSER)
else:
print("4.4.2 Connection dropped: Internal server error.")
exit(1)
sys.exit(1)
def send_email_mirror(
@ -115,12 +116,12 @@ def send_email_mirror(
) -> None:
if not rcpt_to:
print("5.1.1 Bad destination mailbox address: No missed message email address.")
exit(posix.EX_NOUSER)
sys.exit(posix.EX_NOUSER)
msg_bytes = sys.stdin.buffer.read(MAX_ALLOWED_PAYLOAD + 1)
if len(msg_bytes) > MAX_ALLOWED_PAYLOAD:
# We're not at EOF, reject large mail.
print("5.3.4 Message too big for system: Max size is 25MiB")
exit(posix.EX_DATAERR)
sys.exit(posix.EX_DATAERR)
secrets_file = RawConfigParser()
secrets_file.read("/etc/zulip/zulip-secrets.conf")
@ -128,7 +129,7 @@ def send_email_mirror(
shared_secret = secrets_file.get("secrets", "shared_secret")
if test:
exit(0)
return
if not urlparse(host).scheme:
config_file = get_config_file()

View File

@ -25,7 +25,7 @@ class Command(ZulipBaseCommand):
if realm.deactivated:
print("The realm", options["realm_id"], "is already deactivated.")
exit(0)
return
print("Deactivating", options["realm_id"])
do_deactivate_realm(realm, acting_user=None)

View File

@ -16,7 +16,7 @@ class Command(ZulipBaseCommand):
assert realm is not None # Should be ensured by parser
if not realm.deactivated:
print("Realm", options["realm_id"], "is already active.")
exit(0)
return
print("Reactivating", options["realm_id"])
do_reactivate_realm(realm)
print("Done!")

View File

@ -16,7 +16,7 @@ class Command(ZulipBaseCommand):
assert realm is not None # Should be ensured by parser
if not realm.deactivated:
print("Realm", options["realm_id"], "is active. Please deactivate the Realm the first.")
exit(0)
return
print("Scrubbing", options["realm_id"])
do_scrub_realm(realm, acting_user=None)
print("Done!")