2020-06-11 00:54:34 +02:00
|
|
|
import json
|
|
|
|
import os
|
2022-09-01 01:11:27 +02:00
|
|
|
import re
|
2022-09-22 22:09:34 +02:00
|
|
|
from typing import Dict, List, Pattern, Tuple, Union
|
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
|
|
|
|
2022-09-22 22:09:34 +02:00
|
|
|
shard_map: Dict[str, Union[int, List[int]]] = {}
|
|
|
|
shard_regexes: List[Tuple[Pattern[str], Union[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
|
|
|
|
2022-09-22 22:09:34 +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
|
|
|
|
2022-09-22 22:09:34 +02:00
|
|
|
def get_user_id_tornado_port(realm_ports: List[int], user_id: int) -> int:
|
|
|
|
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}"
|