2020-06-11 00:54:34 +02:00
|
|
|
import json
|
|
|
|
import os
|
2022-09-01 01:11:27 +02:00
|
|
|
import re
|
2024-07-12 02:30:25 +02:00
|
|
|
from re import Pattern
|
2020-06-11 00:54:34 +02:00
|
|
|
|
2018-11-02 23:51:05 +01:00
|
|
|
from django.conf import settings
|
|
|
|
|
2022-09-22 22:09:34 +02:00
|
|
|
from zerver.models import Realm, UserProfile
|
2020-06-11 00:54:34 +02:00
|
|
|
|
2024-07-12 02:30:23 +02:00
|
|
|
shard_map: dict[str, int | list[int]] = {}
|
|
|
|
shard_regexes: list[tuple[Pattern[str], int | list[int]]] = []
|
2018-11-07 02:13:37 +01:00
|
|
|
if os.path.exists("/etc/zulip/sharding.json"):
|
|
|
|
with open("/etc/zulip/sharding.json") as f:
|
2022-09-01 01:11:27 +02:00
|
|
|
data = json.loads(f.read())
|
|
|
|
shard_map = data.get(
|
|
|
|
"shard_map",
|
|
|
|
data, # backwards compatibility
|
|
|
|
)
|
|
|
|
shard_regexes = [
|
2024-06-30 20:29:07 +02:00
|
|
|
(re.compile(regex, re.IGNORECASE), port)
|
|
|
|
for regex, port in data.get("shard_regexes", [])
|
2022-09-01 01:11:27 +02:00
|
|
|
]
|
2018-11-02 23:51:05 +01:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
2024-07-12 02:30:17 +02:00
|
|
|
def get_realm_tornado_ports(realm: Realm) -> list[int]:
|
2022-09-01 01:11:27 +02:00
|
|
|
if realm.host in shard_map:
|
2022-09-22 22:09:34 +02:00
|
|
|
ports = shard_map[realm.host]
|
|
|
|
return [ports] if isinstance(ports, int) else ports
|
2022-09-01 01:11:27 +02:00
|
|
|
|
2022-09-22 22:09:34 +02:00
|
|
|
for regex, ports in shard_regexes:
|
2022-09-01 01:11:27 +02:00
|
|
|
if regex.match(realm.host):
|
2022-09-22 22:09:34 +02:00
|
|
|
return [ports] if isinstance(ports, int) else ports
|
2022-09-01 01:11:27 +02:00
|
|
|
|
2022-09-22 22:09:34 +02:00
|
|
|
return [settings.TORNADO_PORTS[0]]
|
2018-11-02 23:51:05 +01:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
2024-07-12 02:30:17 +02:00
|
|
|
def get_user_id_tornado_port(realm_ports: list[int], user_id: int) -> int:
|
2022-09-22 22:09:34 +02:00
|
|
|
return realm_ports[user_id % len(realm_ports)]
|
|
|
|
|
|
|
|
|
|
|
|
def get_user_tornado_port(user: UserProfile) -> int:
|
|
|
|
return get_user_id_tornado_port(get_realm_tornado_ports(user.realm), user.id)
|
|
|
|
|
|
|
|
|
2023-04-26 02:40:54 +02:00
|
|
|
def get_tornado_url(port: int) -> str:
|
2020-06-13 08:59:37 +02:00
|
|
|
return f"http://127.0.0.1:{port}"
|
2018-11-03 00:06:13 +01:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
2018-11-03 00:06:13 +01:00
|
|
|
def notify_tornado_queue_name(port: int) -> str:
|
|
|
|
if settings.TORNADO_PROCESSES == 1:
|
|
|
|
return "notify_tornado"
|
2020-06-13 08:59:37 +02:00
|
|
|
return f"notify_tornado_port_{port}"
|