Skip to content
This repository was archived by the owner on Apr 26, 2024. It is now read-only.

Commit 71ade09

Browse files
committed
Allow background tasks to be run on a separate worker.
1 parent 4f3096d commit 71ade09

21 files changed

+82
-35
lines changed

changelog.d/8369.feature

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Allow running background tasks in a separate worker process.

synapse/app/generic_worker.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -885,6 +885,7 @@ def start(config_options):
885885
# For backwards compatibility let any of the old app names.
886886
assert config.worker_app in (
887887
"synapse.app.appservice",
888+
"synapse.app.background_worker",
888889
"synapse.app.client_reader",
889890
"synapse.app.event_creator",
890891
"synapse.app.federation_reader",
@@ -961,6 +962,22 @@ def start(config_options):
961962
# For other worker types we force this to off.
962963
config.worker.send_federation = False
963964

965+
if config.worker_app == "synapse.app.background_worker":
966+
if config.worker.run_background_tasks:
967+
sys.stderr.write(
968+
"\nThe run_background_tasks must be disabled in the main synapse process"
969+
"\nbefore they can be run in a separate worker."
970+
"\nPlease add ``run_background_tasks: false`` to the main config"
971+
"\n"
972+
)
973+
sys.exit(1)
974+
975+
# Force the background tasks to start since they will be disabled in the main config
976+
config.worker.run_background_tasks = True
977+
else:
978+
# For other worker types we force this to off.
979+
config.worker.run_background_tasks = False
980+
964981
synapse.events.USE_FROZEN_DICTS = config.use_frozen_dicts
965982

966983
hs = GenericWorkerServer(

synapse/app/homeserver.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -620,16 +620,18 @@ def generate_user_daily_visit_stats():
620620
# Rather than update on per session basis, batch up the requests.
621621
# If you increase the loop period, the accuracy of user_daily_visits
622622
# table will decrease
623-
clock.looping_call(generate_user_daily_visit_stats, 5 * 60 * 1000)
623+
if hs.config.run_background_tasks:
624+
clock.looping_call(generate_user_daily_visit_stats, 5 * 60 * 1000)
624625

625626
# monthly active user limiting functionality
626627
def reap_monthly_active_users():
627628
return run_as_background_process(
628629
"reap_monthly_active_users", hs.get_datastore().reap_monthly_active_users
629630
)
630631

631-
clock.looping_call(reap_monthly_active_users, 1000 * 60 * 60)
632-
reap_monthly_active_users()
632+
if hs.config.run_background_tasks:
633+
clock.looping_call(reap_monthly_active_users, 1000 * 60 * 60)
634+
reap_monthly_active_users()
633635

634636
async def generate_monthly_active_users():
635637
current_mau_count = 0
@@ -656,11 +658,13 @@ def start_generate_monthly_active_users():
656658
)
657659

658660
start_generate_monthly_active_users()
659-
if hs.config.limit_usage_by_mau or hs.config.mau_stats_only:
661+
if hs.config.run_background_tasks and (
662+
hs.config.limit_usage_by_mau or hs.config.mau_stats_only
663+
):
660664
clock.looping_call(start_generate_monthly_active_users, 5 * 60 * 1000)
661665
# End of monthly active user settings
662666

663-
if hs.config.report_stats:
667+
if hs.config.run_background_tasks and hs.config.report_stats:
664668
logger.info("Scheduling stats reporting for 3 hour intervals")
665669
clock.looping_call(start_phone_stats_home, 3 * 60 * 60 * 1000)
666670

synapse/config/workers.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,16 @@ def read_config(self, config, **kwargs):
132132

133133
self.events_shard_config = ShardedWorkerHandlingConfig(self.writers.events)
134134

135+
# Whether this worker should run background tasks or not.
136+
#
137+
# As a note for developers, the background tasks guarded by this should
138+
# be able to run on only a single instance (meaning that they don't
139+
# depend on any in-memory state of a particular worker).
140+
#
141+
# Effort is not made to ensure only a single instance of these tasks is
142+
# running.
143+
self.run_background_tasks = config.get("run_background_tasks", True)
144+
135145
def generate_config_section(self, config_dir_path, server_name, **kwargs):
136146
return """\
137147
## Workers ##

synapse/handlers/account_validity.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ def __init__(self, hs):
4242
if (
4343
self._account_validity.enabled
4444
and self._account_validity.renew_by_email_enabled
45+
and hs.config.run_background_tasks
4546
):
4647
# Don't do email-specific configuration if renewal by email is disabled.
4748
self._template_html = self.config.account_validity_template_html

synapse/handlers/auth.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,7 @@ def __init__(self, hs):
203203
self._clock = self.hs.get_clock()
204204

205205
# Expire old UI auth sessions after a period of time.
206-
if hs.config.worker_app is None:
206+
if hs.config.run_background_tasks:
207207
self._clock.looping_call(
208208
run_as_background_process,
209209
5 * 60 * 1000,

synapse/handlers/deactivate_account.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def __init__(self, hs):
4242

4343
# Start the user parter loop so it can resume parting users from rooms where
4444
# it left off (if it has work left to do).
45-
if hs.config.worker_app is None:
45+
if hs.config.run_background_tasks:
4646
hs.get_reactor().callWhenRunning(self._start_user_parting)
4747

4848
self._account_validity_enabled = hs.config.account_validity.enabled

synapse/handlers/device.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -522,12 +522,13 @@ def __init__(self, hs, device_handler):
522522

523523
# Attempt to resync out of sync device lists every 30s.
524524
self._resync_retry_in_progress = False
525-
self.clock.looping_call(
526-
run_as_background_process,
527-
30 * 1000,
528-
func=self._maybe_retry_device_resync,
529-
desc="_maybe_retry_device_resync",
530-
)
525+
if hs.config.run_background_tasks:
526+
self.clock.looping_call(
527+
run_as_background_process,
528+
30 * 1000,
529+
func=self._maybe_retry_device_resync,
530+
desc="_maybe_retry_device_resync",
531+
)
531532

532533
@trace
533534
async def incoming_device_list_update(self, origin, edu_content):

synapse/handlers/message.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -413,7 +413,7 @@ def __init__(self, hs: "HomeServer"):
413413
self._consent_uri_builder = ConsentURIBuilder(self.config)
414414

415415
if (
416-
not self.config.worker_app
416+
self.config.run_background_tasks
417417
and self.config.cleanup_extremities_with_dummy_events
418418
):
419419
self.clock.looping_call(

synapse/handlers/pagination.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ def __init__(self, hs: "HomeServer"):
9292
self._retention_allowed_lifetime_min = hs.config.retention_allowed_lifetime_min
9393
self._retention_allowed_lifetime_max = hs.config.retention_allowed_lifetime_max
9494

95-
if hs.config.retention_enabled:
95+
if hs.config.run_background_tasks and hs.config.retention_enabled:
9696
# Run the purge jobs described in the configuration file.
9797
for job in hs.config.retention_purge_jobs:
9898
logger.info("Setting up purge job with config: %s", job)

synapse/handlers/profile.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -371,11 +371,10 @@ class MasterProfileHandler(BaseProfileHandler):
371371
def __init__(self, hs):
372372
super().__init__(hs)
373373

374-
assert hs.config.worker_app is None
375-
376-
self.clock.looping_call(
377-
self._start_update_remote_profile_cache, self.PROFILE_UPDATE_MS
378-
)
374+
if hs.config.run_background_tasks:
375+
self.clock.looping_call(
376+
self._start_update_remote_profile_cache, self.PROFILE_UPDATE_MS
377+
)
379378

380379
def _start_update_remote_profile_cache(self):
381380
return run_as_background_process(

synapse/handlers/stats.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ def __init__(self, hs):
4949
# Guard to ensure we only process deltas one at a time
5050
self._is_processing = False
5151

52-
if hs.config.stats_enabled:
52+
if self.stats_enabled and hs.config.run_background_tasks:
5353
self.notifier.add_replication_callback(self.notify_new_event)
5454

5555
# We kick this off so that we don't have to wait for a change before

synapse/storage/databases/main/censor_events.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,10 @@ def _censor_redactions():
4040
"_censor_redactions", self._censor_redactions
4141
)
4242

43-
if self.hs.config.redaction_retention_period is not None:
43+
if (
44+
self.hs.config.run_background_tasks
45+
and self.hs.config.redaction_retention_period is not None
46+
):
4447
hs.get_clock().looping_call(_censor_redactions, 5 * 60 * 1000)
4548

4649
async def _censor_redactions(self):

synapse/storage/databases/main/client_ips.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -372,7 +372,7 @@ def __init__(self, database: DatabasePool, db_conn, hs):
372372
"before", "shutdown", self._update_client_ips_batch
373373
)
374374

375-
if self.user_ips_max_age:
375+
if hs.config.run_background_tasks and self.user_ips_max_age:
376376
self._clock.looping_call(self._prune_old_user_ips, 5 * 1000)
377377

378378
async def insert_client_ip(

synapse/storage/databases/main/devices.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -834,7 +834,10 @@ def __init__(self, database: DatabasePool, db_conn, hs):
834834
name="device_id_exists", keylen=2, max_entries=10000
835835
)
836836

837-
self._clock.looping_call(self._prune_old_outbound_device_pokes, 60 * 60 * 1000)
837+
if hs.config.run_background_tasks:
838+
self._clock.looping_call(
839+
self._prune_old_outbound_device_pokes, 60 * 60 * 1000
840+
)
838841

839842
async def store_device(
840843
self, user_id: str, device_id: str, initial_device_display_name: str

synapse/storage/databases/main/event_federation.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -606,9 +606,10 @@ def __init__(self, database: DatabasePool, db_conn, hs):
606606
self.EVENT_AUTH_STATE_ONLY, self._background_delete_non_state_event_auth
607607
)
608608

609-
hs.get_clock().looping_call(
610-
self._delete_old_forward_extrem_cache, 60 * 60 * 1000
611-
)
609+
if hs.config.run_background_tasks:
610+
hs.get_clock().looping_call(
611+
self._delete_old_forward_extrem_cache, 60 * 60 * 1000
612+
)
612613

613614
def _delete_old_forward_extrem_cache(self):
614615
def _delete_old_forward_extrem_cache_txn(txn):

synapse/storage/databases/main/event_push_actions.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -679,9 +679,10 @@ def __init__(self, database: DatabasePool, db_conn, hs):
679679
)
680680

681681
self._doing_notif_rotation = False
682-
self._rotate_notif_loop = self._clock.looping_call(
683-
self._start_rotate_notifs, 30 * 60 * 1000
684-
)
682+
if hs.config.run_background_tasks:
683+
self._rotate_notif_loop = self._clock.looping_call(
684+
self._start_rotate_notifs, 30 * 60 * 1000
685+
)
685686

686687
async def get_push_actions_for_user(
687688
self, user_id, before=None, limit=50, only_highlight=False
@@ -741,7 +742,7 @@ def _remove_old_push_actions_before_txn(
741742
users can still get a list of recent highlights.
742743
743744
Args:
744-
txn: The transcation
745+
txn: The transaction
745746
room_id: Room ID to delete from
746747
user_id: user ID to delete for
747748
stream_ordering: The lowest stream ordering which will

synapse/storage/databases/main/metrics.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,8 @@ def read_forward_extremities():
5252
"read_forward_extremities", self._read_forward_extremities
5353
)
5454

55-
hs.get_clock().looping_call(read_forward_extremities, 60 * 60 * 1000)
55+
if hs.config.run_background_tasks:
56+
hs.get_clock().looping_call(read_forward_extremities, 60 * 60 * 1000)
5657

5758
async def _read_forward_extremities(self):
5859
def fetch(txn):

synapse/storage/databases/main/registration.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -914,7 +914,8 @@ def start_cull():
914914
self.cull_expired_threepid_validation_tokens,
915915
)
916916

917-
hs.get_clock().looping_call(start_cull, THIRTY_MINUTES_IN_MS)
917+
if hs.config.run_background_tasks:
918+
hs.get_clock().looping_call(start_cull, THIRTY_MINUTES_IN_MS)
918919

919920
async def add_access_token_to_user(
920921
self,

synapse/storage/databases/main/roommember.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,10 @@ def __init__(self, database: DatabasePool, db_conn, hs):
6969
self._check_safe_current_state_events_membership_updated_txn(txn)
7070
txn.close()
7171

72-
if self.hs.config.metrics_flags.known_servers:
72+
if (
73+
self.hs.config.run_background_tasks
74+
and self.hs.config.metrics_flags.known_servers
75+
):
7376
self._known_servers_count = 1
7477
self.hs.get_clock().looping_call(
7578
run_as_background_process,

synapse/storage/databases/main/transactions.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,8 @@ class TransactionStore(SQLBaseStore):
5050
def __init__(self, database: DatabasePool, db_conn, hs):
5151
super().__init__(database, db_conn, hs)
5252

53-
self._clock.looping_call(self._start_cleanup_transactions, 30 * 60 * 1000)
53+
if hs.config.run_background_tasks:
54+
self._clock.looping_call(self._start_cleanup_transactions, 30 * 60 * 1000)
5455

5556
self._destination_retry_cache = ExpiringCache(
5657
cache_name="get_destination_retry_timings",

0 commit comments

Comments
 (0)