Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
checks: Move checkconfig to standard check framework.
Alex Vandiver6c9705a6bb78
diff --git a/docs/subsystems/management-commands.md b/docs/subsystems/management-commands.mdindex f9be106f440..f4560f99f01 100644--- a/docs/subsystems/management-commands.md+++ b/docs/subsystems/management-commands.md@@ -21,7 +21,7 @@ written for a range of purposes:- The actual scripts run by supervisord to run the persistentprocesses in a Zulip server, e.g., `runtornado` and `process_queue`.- For a sysadmin to verify a Zulip server's configuration during- installation, e.g., `checkconfig`, `send_test_email`.+ installation, e.g., `send_test_email`.- As the interface for doing those rare operations that don't have aUI yet, e.g., `deactivate_realm`, `reactivate_realm`,`change_user_email` (for the case where the user doesn't control thediff --git a/scripts/lib/install b/scripts/lib/installindex 72878a13ddf..998395d4f8c 100755--- a/scripts/lib/install+++ b/scripts/lib/install@@ -233,7 +233,7 @@ fiif [ "$EXTERNAL_HOST" = zulip.example.com ] \|| [ "$ZULIP_ADMINISTRATOR" = [email protected] ]; then# These example values are specifically checked for and would fail- # later; see check_config in zerver/lib/management.py.+ # later; see zerver/checks.pyecho 'error: The example hostname and email must be replaced with real values.' >&2echo >&2usage >&2diff --git a/scripts/setup/initialize-database b/scripts/setup/initialize-databaseindex f9a0b01de20..994cdb3120c 100755--- a/scripts/setup/initialize-database+++ b/scripts/setup/initialize-database@@ -33,8 +33,6 @@ set -xTHIS_DIR="$(dirname "$(readlink -f "$0")")"cd "$THIS_DIR/../.."-./manage.py checkconfig-./manage.py migrate --noinput./manage.py createcachetable third_party_api_resultsdiff --git a/zerver/apps.py b/zerver/apps.pyindex 6caf0d46dca..da64f0c63c3 100644--- a/zerver/apps.py+++ b/zerver/apps.py@@ -5,9 +5,12 @@ import django_stubs_extfrom django.apps import AppConfigfrom django.conf import settingsfrom django.core.cache import cache+from django.core.checks import registerfrom django.db.models.signals import post_migratefrom typing_extensions import override+from zerver.checks import check_required_settings+def flush_cache(sender: AppConfig | None, **kwargs: Any) -> None:logging.info("Clearing memcached cache after migrations")@@ -19,6 +22,8 @@ class ZerverConfig(AppConfig):@overridedef ready(self) -> None:+ register(check_required_settings)+if settings.SENTRY_DSN: # nocoveragefrom zproject.config import get_configfrom zproject.sentry import setup_sentrydiff --git a/zerver/checks.py b/zerver/checks.pynew file mode 100644index 00000000000..2e7c702c86b--- /dev/null+++ b/zerver/checks.py@@ -0,0 +1,42 @@+from collections.abc import Iterable, Sequence+from typing import Any++from django.apps.config import AppConfig+from django.conf import settings+from django.core import checks+++def check_required_settings(+ app_configs: Sequence[AppConfig] | None,+ databases: Sequence[str] | None,+ **kwargs: Any,+) -> Iterable[checks.CheckMessage]:+ # These are the settings that we will check that the user has filled in for+ # production deployments before starting the app. It consists of a series+ # of pairs of (setting name, default value that it must be changed from)+ required_settings = [+ ("EXTERNAL_HOST", "zulip.example.com"),+ ("ZULIP_ADMINISTRATOR", "[email protected]"),+ # SECRET_KEY doesn't really need to be here, in+ # that we set it automatically, but just in+ # case, it seems worth having in this list+ ("SECRET_KEY", ""),+ ("AUTHENTICATION_BACKENDS", ()),+ ]+ errors = []+ for setting_name, default in required_settings:+ if (+ hasattr(settings, setting_name)+ and getattr(settings, setting_name) != default+ and getattr(settings, setting_name)+ ):+ continue++ errors.append(+ checks.Error(+ f"You must set {setting_name} in /etc/zulip/settings.py",+ obj=f"settings.{setting_name}",+ id="zulip.E001",+ )+ )+ return errorsdiff --git a/zerver/lib/management.py b/zerver/lib/management.pyindex 8a120193330..0f3d386baf3 100644--- a/zerver/lib/management.py+++ b/zerver/lib/management.py@@ -30,19 +30,6 @@ def is_integer_string(val: str) -> bool:return False-def check_config() -> None:- for setting_name, default in settings.REQUIRED_SETTINGS:- # if required setting is the same as default OR is not found in settings,- # throw error to add/set that setting in config- try:- if getattr(settings, setting_name) != default:- continue- except AttributeError:- pass-- raise CommandError(f"Error: You must set {setting_name} in /etc/zulip/settings.py.")--class HandleMethod(Protocol):def __call__(self, *args: Any, **kwargs: Any) -> None: ...diff --git a/zerver/management/commands/checkconfig.py b/zerver/management/commands/checkconfig.pydeleted file mode 100644index 93ae8f167ff..00000000000--- a/zerver/management/commands/checkconfig.py+++ /dev/null@@ -1,13 +0,0 @@-from typing import Any--from typing_extensions import override--from zerver.lib.management import ZulipBaseCommand, check_config---class Command(ZulipBaseCommand):- help = """Checks /etc/zulip/settings.py for common configuration issues."""-- @override- def handle(self, *args: Any, **options: Any) -> None:- check_config()diff --git a/zerver/management/commands/register_server.py b/zerver/management/commands/register_server.pyindex 5822c07a4dd..0e90aa5f838 100644--- a/zerver/management/commands/register_server.py+++ b/zerver/management/commands/register_server.py@@ -10,7 +10,7 @@ from django.utils.crypto import get_random_stringfrom requests.models import Responsefrom typing_extensions import override-from zerver.lib.management import ZulipBaseCommand, check_config+from zerver.lib.management import ZulipBaseCommandfrom zerver.lib.remote_server import (PushBouncerSession,prepare_for_registration_transfer_challenge,@@ -58,9 +58,6 @@ that registration and saving the updated secret in@overridedef handle(self, *args: Any, **options: Any) -> None:- if not settings.DEVELOPMENT:- check_config()-if not settings.ZULIP_ORG_ID:raise CommandError("Missing zulip_org_id; run scripts/setup/generate_secrets.py to generate."diff --git a/zerver/tests/test_checks.py b/zerver/tests/test_checks.pynew file mode 100644index 00000000000..812dbaac29b--- /dev/null+++ b/zerver/tests/test_checks.py@@ -0,0 +1,38 @@+import os+from contextlib import ExitStack+from typing import Any++from django.core.management import call_command+from django.core.management.base import SystemCheckError+from django.test import override_settings++from zerver.lib.test_classes import ZulipTestCase+++class TestChecks(ZulipTestCase):+ def assert_check_with_error(self, message: str | None, **kwargs: Any) -> None:+ with open(os.devnull, "w") as DEVNULL, override_settings(**kwargs), ExitStack() as stack:+ if message is not None:+ stack.enter_context(self.assertRaisesMessage(SystemCheckError, message))+ call_command("check", stdout=DEVNULL)++ def test_checks_required_setting(self) -> None:+ self.assert_check_with_error(+ "(zulip.E001) You must set ZULIP_ADMINISTRATOR in /etc/zulip/settings.py",+ ZULIP_ADMINISTRATOR="[email protected]",+ )++ self.assert_check_with_error(+ "(zulip.E001) You must set ZULIP_ADMINISTRATOR in /etc/zulip/settings.py",+ ZULIP_ADMINISTRATOR="",+ )++ self.assert_check_with_error(+ "(zulip.E001) You must set ZULIP_ADMINISTRATOR in /etc/zulip/settings.py",+ ZULIP_ADMINISTRATOR=None,+ )++ self.assert_check_with_error(+ None,+ ZULIP_ADMINISTRATOR="[email protected]",+ )diff --git a/zerver/tests/test_management_commands.py b/zerver/tests/test_management_commands.pyindex 9b31fed0646..9cae2ff983b 100644--- a/zerver/tests/test_management_commands.py+++ b/zerver/tests/test_management_commands.py@@ -19,7 +19,7 @@ from typing_extensions import overridefrom confirmation.models import Confirmation, generate_realm_creation_urlfrom zerver.actions.create_user import do_create_userfrom zerver.actions.user_settings import do_change_user_setting-from zerver.lib.management import ZulipBaseCommand, check_config+from zerver.lib.management import ZulipBaseCommandfrom zerver.lib.test_classes import ZulipTestCasefrom zerver.lib.test_helpers import most_recent_message, stdout_suppressedfrom zerver.models import Realm, RealmAuditLog, Recipient, UserProfile@@ -29,17 +29,7 @@ from zerver.models.streams import get_streamfrom zerver.models.users import get_user_profile_by_email-class TestCheckConfig(ZulipTestCase):- def test_check_config(self) -> None:- check_config()- with (- self.settings(REQUIRED_SETTINGS=[("asdf", "not asdf")]),- self.assertRaisesRegex(- CommandError, "Error: You must set asdf in /etc/zulip/settings.py."- ),- ):- check_config()-+class TestWarnNoEmail(ZulipTestCase):@override_settings(WARN_NO_EMAIL=True)def test_check_send_email(self) -> None:with self.assertRaisesRegex(CommandError, "Outgoing email not yet configured, see"):