Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
migrations: Degrade gracefully with missing remote dictionaries.
Alex Vandiver1f3aed14a5ed
diff --git a/docs/production/deployment.md b/docs/production/deployment.mdindex 15c52a48c75..1d1c56dbe09 100644--- a/docs/production/deployment.md+++ b/docs/production/deployment.md@@ -87,12 +87,6 @@ as well as those mentioned in thedefault database user will be `zulip`. This setting can only be seton the first install.-- `--postgresql-missing-dictionaries`: Set `postgresql.missing_dictionaries`- ([docs][missing-dicts]) in the Zulip settings, which omits some configuration- needed for full-text indexing. This should be used with [cloud managed- databases like RDS][postgresql]. This option conflicts with- `--no-overwrite-settings`.-- `--no-init-db`: This option instructs the installer to not do anydatabase initialization. This should be used when you already have aZulip database.diff --git a/docs/production/postgresql.md b/docs/production/postgresql.mdindex 29b800ec3a9..c92da50ad13 100644--- a/docs/production/postgresql.md+++ b/docs/production/postgresql.md@@ -36,8 +36,7 @@ arguments:```bash./zulip-server-*/scripts/setup/install --certbot \--email=YOUR_EMAIL --hostname=YOUR_HOSTNAME \- --puppet-classes=zulip::profile::standalone_nodb,zulip::process_fts_updates \- --postgresql-missing-dictionaries+ --puppet-classes=zulip::profile::standalone_nodb,zulip::process_fts_updates```#### Step 2: Create the PostgreSQL databasediff --git a/scripts/lib/install b/scripts/lib/installindex 998395d4f8c..5c513bc6a3b 100755--- a/scripts/lib/install+++ b/scripts/lib/install@@ -32,9 +32,6 @@ Options:Sets the PostgreSQL database user.--postgresql-version=17Sets the version of PostgreSQL that will be installed.- --postgresql-missing-dictionaries- Set postgresql.missing_dictionaries, which alters the initial database. Use with- cloud managed databases like RDS. Conflicts with --no-overwrite-settings.--no-init-dbDoes not do any database initialization; use when you already have a Zulip@@ -91,7 +88,7 @@ EOF# Shell option parsing. Over time, we'll want to move some of the# environment variables below into this self-documenting system.-args="$(getopt -o '' --long help,hostname:,email:,certbot,self-signed-cert,cacert:,postgresql-database-name:,postgresql-database-user:,postgresql-version:,postgresql-missing-dictionaries,no-init-db,puppet-classes:,no-overwrite-settings,no-dist-upgrade,push-notifications,no-push-notifications,no-submit-usage-statistics,agree-to-terms-of-service -n "$0" -- "$@")"+args="$(getopt -o '' --long help,hostname:,email:,certbot,self-signed-cert,cacert:,postgresql-database-name:,postgresql-database-user:,postgresql-version:,no-init-db,puppet-classes:,no-overwrite-settings,no-dist-upgrade,push-notifications,no-push-notifications,no-submit-usage-statistics,agree-to-terms-of-service -n "$0" -- "$@")"eval "set -- $args"while true; do@@ -135,10 +132,6 @@ while true; doshiftshift;;- --postgresql-missing-dictionaries)- POSTGRESQL_MISSING_DICTIONARIES=1- shift- ;;--no-init-db)NO_INIT_DB=1shift@@ -215,14 +208,6 @@ if [ -n "$SELF_SIGNED_CERT" ] && [ -n "$USE_CERTBOT" ]; thenexit 1fi-if [ -n "$POSTGRESQL_MISSING_DICTIONARIES" ] && [ -n "$NO_OVERWRITE_SETTINGS" ]; then- set +x- echo "error: --postgresql-missing-dictionaries and --no-overwrite-settings are incompatible" >&2- echo >&2- usage >&2- exit 1-fi-if [ -z "$EXTERNAL_HOST" ] || [ -z "$ZULIP_ADMINISTRATOR" ]; thenif [ -n "$USE_CERTBOT" ] || [ -z "$NO_INIT_DB" ]; thenusage >&2@@ -561,10 +546,6 @@ deploy_type = productionversion = $POSTGRESQL_VERSIONEOF- if [ -n "$POSTGRESQL_MISSING_DICTIONARIES" ]; then- crudini --set /etc/zulip/zulip.conf postgresql missing_dictionaries true- fi-"$ZULIP_PATH"/scripts/zulip-puppet-apply --noop \--write-catalog-summary \--classfile=/var/lib/puppet/classes.txtdiff --git a/zerver/migrations/0001_initial.py b/zerver/migrations/0001_initial.pyindex 45e99d5557c..d35880f958a 100644--- a/zerver/migrations/0001_initial.py+++ b/zerver/migrations/0001_initial.py@@ -1,5 +1,7 @@# Generated by Django 5.0.7 on 2024-08-13 21:48+import logging+import bitfield.modelsimport django.contrib.auth.modelsimport django.contrib.postgres.indexes@@ -9,11 +11,72 @@ import django.db.models.deletionimport django.db.models.functions.textimport django.utils.timezonefrom django.conf import settings-from django.db import migrations, models+from django.db import connection, migrations, models+from django.db.backends.base.schema import BaseDatabaseSchemaEditor+from django.db.migrations.state import StateApps+from django.db.utils import InternalErrorfrom zerver.models.streams import generate_email_token_for_stream+def set_up_fts_indexes(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor) -> None:+ # Duplicated in 0001_squashed_0569.py+ with connection.cursor() as cursor:+ try:+ cursor.execute(+ """+ CREATE TEXT SEARCH DICTIONARY english_us_hunspell+ (template = ispell, DictFile = en_us, AffFile = en_us, StopWords = zulip_english);+ CREATE TEXT SEARCH CONFIGURATION zulip.english_us_search (COPY=pg_catalog.english);+ ALTER TEXT SEARCH CONFIGURATION zulip.english_us_search+ ALTER MAPPING FOR asciiword, asciihword, hword_asciipart, word, hword, hword_part+ WITH english_us_hunspell, english_stem;+ """+ )+ except InternalError as e:+ # If we have a remote PostgreSQL server, and we get an+ # error about the tsearch_data paths, assume that we're+ # running with a hosted PostgreSQL which we can't install+ # our stemming/stopword dictionaries in; warn and carry+ # on. For local PostgreSQL hosts, this is unexpected and+ # we raise the error.+ if (+ settings.REMOTE_POSTGRES_HOST != ""+ and e.__cause__+ and "/tsearch_data/" in str(e.__cause__)+ ):+ logging.warning(+ "Remote PostgreSQL server %s is not configured with Zulip's improved stemming dictionaries; search quality will be degraded.",+ settings.REMOTE_POSTGRES_HOST,+ )+ cursor.execute(+ """+ CREATE TEXT SEARCH CONFIGURATION zulip.english_us_search (COPY=pg_catalog.english);+ """+ )+ else:+ raise+ cursor.execute(+ """+ CREATE FUNCTION escape_html(text) RETURNS text IMMUTABLE LANGUAGE 'sql' AS $$+ SELECT replace(replace(replace(replace(replace($1, '&', '&'), '<', '<'),+ '>', '>'), '"', '"'), '''', ''');+ $$ ;++ CREATE TABLE fts_update_log (id SERIAL PRIMARY KEY, message_id INTEGER NOT NULL);+ CREATE FUNCTION do_notify_fts_update_log() RETURNS trigger LANGUAGE plpgsql AS+ $$ BEGIN NOTIFY fts_update_log; RETURN NEW; END $$;+ CREATE TRIGGER fts_update_log_notify AFTER INSERT ON fts_update_log+ FOR EACH STATEMENT EXECUTE PROCEDURE do_notify_fts_update_log();+ CREATE FUNCTION append_to_fts_update_log() RETURNS trigger LANGUAGE plpgsql AS+ $$ BEGIN INSERT INTO fts_update_log (message_id) VALUES (NEW.id); RETURN NEW; END $$;+ CREATE TRIGGER zerver_message_update_search_tsvector_async+ BEFORE INSERT OR UPDATE OF subject, rendered_content ON zerver_message+ FOR EACH ROW EXECUTE PROCEDURE append_to_fts_update_log();+ """+ )++class Migration(migrations.Migration):initial = True@@ -21,39 +84,6 @@ class Migration(migrations.Migration):("auth", "0001_initial"),]- if settings.POSTGRESQL_MISSING_DICTIONARIES:- fts_sql = """-CREATE TEXT SEARCH CONFIGURATION zulip.english_us_search (COPY=pg_catalog.english);-"""- else:- fts_sql = """-CREATE TEXT SEARCH DICTIONARY english_us_hunspell- (template = ispell, DictFile = en_us, AffFile = en_us, StopWords = zulip_english);-CREATE TEXT SEARCH CONFIGURATION zulip.english_us_search (COPY=pg_catalog.english);-ALTER TEXT SEARCH CONFIGURATION zulip.english_us_search- ALTER MAPPING FOR asciiword, asciihword, hword_asciipart, word, hword, hword_part- WITH english_us_hunspell, english_stem;-"""-- fts_sql += """--CREATE FUNCTION escape_html(text) RETURNS text IMMUTABLE LANGUAGE 'sql' AS $$- SELECT replace(replace(replace(replace(replace($1, '&', '&'), '<', '<'),- '>', '>'), '"', '"'), '''', ''');-$$ ;--CREATE TABLE fts_update_log (id SERIAL PRIMARY KEY, message_id INTEGER NOT NULL);-CREATE FUNCTION do_notify_fts_update_log() RETURNS trigger LANGUAGE plpgsql AS- $$ BEGIN NOTIFY fts_update_log; RETURN NEW; END $$;-CREATE TRIGGER fts_update_log_notify AFTER INSERT ON fts_update_log- FOR EACH STATEMENT EXECUTE PROCEDURE do_notify_fts_update_log();-CREATE FUNCTION append_to_fts_update_log() RETURNS trigger LANGUAGE plpgsql AS- $$ BEGIN INSERT INTO fts_update_log (message_id) VALUES (NEW.id); RETURN NEW; END $$;-CREATE TRIGGER zerver_message_update_search_tsvector_async- BEFORE INSERT OR UPDATE OF subject, rendered_content ON zerver_message- FOR EACH ROW EXECUTE PROCEDURE append_to_fts_update_log();-"""-operations = [migrations.CreateModel(name="Recipient",@@ -766,8 +796,5 @@ CREATE TRIGGER zerver_message_update_search_tsvector_asyncto="zerver.stream",),),- # Set up full-text search indexes.- migrations.RunSQL(- sql=fts_sql,- ),+ migrations.RunPython(set_up_fts_indexes),]diff --git a/zerver/migrations/0001_squashed_0569.py b/zerver/migrations/0001_squashed_0569.pyindex e6c0575c868..2b846b3c07c 100644--- a/zerver/migrations/0001_squashed_0569.py+++ b/zerver/migrations/0001_squashed_0569.py@@ -1,6 +1,7 @@# Generated by Django 5.0.7 on 2024-08-17 01:15import datetime+import loggingimport uuidfrom enum import IntEnum@@ -14,7 +15,10 @@ import django.db.models.deletionimport django.db.models.functions.textimport django.utils.timezonefrom django.conf import settings-from django.db import migrations, models+from django.db import connection, migrations, models+from django.db.backends.base.schema import BaseDatabaseSchemaEditor+from django.db.migrations.state import StateApps+from django.db.utils import InternalErrorimport zerver.lib.utilsimport zerver.models.linkifiers@@ -53,40 +57,62 @@ class LegacyInviteToRealmPolicyEnum(IntEnum):NOBODY = 6-def get_fts_sql() -> str:- if settings.POSTGRESQL_MISSING_DICTIONARIES:- fts_sql = """-CREATE TEXT SEARCH CONFIGURATION zulip.english_us_search (COPY=pg_catalog.english);-"""- else:- fts_sql = """-CREATE TEXT SEARCH DICTIONARY english_us_hunspell- (template = ispell, DictFile = en_us, AffFile = en_us, StopWords = zulip_english);-CREATE TEXT SEARCH CONFIGURATION zulip.english_us_search (COPY=pg_catalog.english);-ALTER TEXT SEARCH CONFIGURATION zulip.english_us_search- ALTER MAPPING FOR asciiword, asciihword, hword_asciipart, word, hword, hword_part- WITH english_us_hunspell, english_stem;-"""-- fts_sql += """--CREATE FUNCTION escape_html(text) RETURNS text IMMUTABLE LANGUAGE 'sql' AS $$- SELECT replace(replace(replace(replace(replace($1, '&', '&'), '<', '<'),- '>', '>'), '"', '"'), '''', ''');-$$ ;+def set_up_fts_indexes(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor) -> None:+ # Duplicated in 0001_initial.py+ with connection.cursor() as cursor:+ try:+ cursor.execute(+ """+ CREATE TEXT SEARCH DICTIONARY english_us_hunspell+ (template = ispell, DictFile = en_us, AffFile = en_us, StopWords = zulip_english);+ CREATE TEXT SEARCH CONFIGURATION zulip.english_us_search (COPY=pg_catalog.english);+ ALTER TEXT SEARCH CONFIGURATION zulip.english_us_search+ ALTER MAPPING FOR asciiword, asciihword, hword_asciipart, word, hword, hword_part+ WITH english_us_hunspell, english_stem;+ """+ )+ except InternalError as e:+ # If we have a remote PostgreSQL server, and we get an+ # error about the tsearch_data paths, assume that we're+ # running with a hosted PostgreSQL which we can't install+ # our stemming/stopword dictionaries in; warn and carry+ # on. For local PostgreSQL hosts, this is unexpected and+ # we raise the error.+ if (+ settings.REMOTE_POSTGRES_HOST != ""+ and e.__cause__+ and "/tsearch_data/" in str(e.__cause__)+ ):+ logging.warning(+ "Remote PostgreSQL server %s is not configured with Zulip's improved stemming dictionaries; search quality will be degraded.",+ settings.REMOTE_POSTGRES_HOST,+ )+ cursor.execute(+ """+ CREATE TEXT SEARCH CONFIGURATION zulip.english_us_search (COPY=pg_catalog.english);+ """+ )+ else:+ raise+ cursor.execute(+ """+ CREATE FUNCTION escape_html(text) RETURNS text IMMUTABLE LANGUAGE 'sql' AS $$+ SELECT replace(replace(replace(replace(replace($1, '&', '&'), '<', '<'),+ '>', '>'), '"', '"'), '''', ''');+ $$ ;-CREATE TABLE fts_update_log (id BIGSERIAL PRIMARY KEY, message_id INTEGER NOT NULL);-CREATE FUNCTION do_notify_fts_update_log() RETURNS trigger LANGUAGE plpgsql AS- $$ BEGIN NOTIFY fts_update_log; RETURN NEW; END $$;-CREATE TRIGGER fts_update_log_notify AFTER INSERT ON fts_update_log- FOR EACH STATEMENT EXECUTE PROCEDURE do_notify_fts_update_log();-CREATE FUNCTION append_to_fts_update_log() RETURNS trigger LANGUAGE plpgsql AS- $$ BEGIN INSERT INTO fts_update_log (message_id) VALUES (NEW.id); RETURN NEW; END $$;-CREATE TRIGGER zerver_message_update_search_tsvector_async- BEFORE INSERT OR UPDATE OF subject, rendered_content ON zerver_message- FOR EACH ROW EXECUTE PROCEDURE append_to_fts_update_log();-"""- return fts_sql+ CREATE TABLE fts_update_log (id SERIAL PRIMARY KEY, message_id INTEGER NOT NULL);+ CREATE FUNCTION do_notify_fts_update_log() RETURNS trigger LANGUAGE plpgsql AS+ $$ BEGIN NOTIFY fts_update_log; RETURN NEW; END $$;+ CREATE TRIGGER fts_update_log_notify AFTER INSERT ON fts_update_log+ FOR EACH STATEMENT EXECUTE PROCEDURE do_notify_fts_update_log();+ CREATE FUNCTION append_to_fts_update_log() RETURNS trigger LANGUAGE plpgsql AS+ $$ BEGIN INSERT INTO fts_update_log (message_id) VALUES (NEW.id); RETURN NEW; END $$;+ CREATE TRIGGER zerver_message_update_search_tsvector_async+ BEFORE INSERT OR UPDATE OF subject, rendered_content ON zerver_message+ FOR EACH ROW EXECUTE PROCEDURE append_to_fts_update_log();+ """+ )class Migration(migrations.Migration):@@ -3442,8 +3468,5 @@ class Migration(migrations.Migration):CREATE UNIQUE INDEX zerver_stream_realm_id_name_uniq ON zerver_stream (realm_id, upper(name::text));"""),- # Set up full-text search indexes.- migrations.RunSQL(- sql=get_fts_sql(),- ),+ migrations.RunPython(set_up_fts_indexes),]diff --git a/zproject/computed_settings.py b/zproject/computed_settings.pyindex 3752e63a473..bb8ce6b02d8 100644--- a/zproject/computed_settings.py+++ b/zproject/computed_settings.py@@ -396,7 +396,6 @@ elif (PASSWORD=get_secret("postgres_password"),HOST="localhost",)-POSTGRESQL_MISSING_DICTIONARIES = get_config("postgresql", "missing_dictionaries", False)DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"