py3: Switch almost all shebang lines to use `python3`.
This causes `upgrade-zulip-from-git`, as well as a no-option run of
`tools/build-release-tarball`, to produce a Zulip install running
Python 3, rather than Python 2. In particular this means that the
virtualenv we create, in which all application code runs, is Python 3.
One shebang line, on `zulip-ec2-configure-interfaces`, explicitly
keeps Python 2, and at least one external ops script, `wal-e`, also
still runs on Python 2. See discussion on the respective previous
commits that made those explicit. There may also be some other
third-party scripts we use, outside of this source tree and running
outside our virtualenv, that still run on Python 2.
2017-08-02 23:15:16 +02:00
|
|
|
|
#!/usr/bin/env python3
|
2017-08-21 19:41:19 +02:00
|
|
|
|
import argparse
|
2020-06-11 00:54:34 +02:00
|
|
|
|
import configparser
|
2019-08-30 00:14:43 +02:00
|
|
|
|
import functools
|
2017-08-19 16:23:30 +02:00
|
|
|
|
import hashlib
|
2020-06-11 00:54:34 +02:00
|
|
|
|
import json
|
2017-08-18 06:36:37 +02:00
|
|
|
|
import logging
|
2013-05-16 18:02:25 +02:00
|
|
|
|
import os
|
2013-11-13 21:54:30 +01:00
|
|
|
|
import pwd
|
2020-07-09 20:31:34 +02:00
|
|
|
|
import random
|
2018-07-18 23:26:44 +02:00
|
|
|
|
import shlex
|
2016-01-10 20:58:11 +01:00
|
|
|
|
import shutil
|
2023-03-09 02:50:11 +01:00
|
|
|
|
import signal
|
2016-04-06 17:15:31 +02:00
|
|
|
|
import subprocess
|
2016-01-10 20:58:11 +01:00
|
|
|
|
import sys
|
|
|
|
|
import time
|
2017-10-18 04:14:06 +02:00
|
|
|
|
import uuid
|
2024-07-12 02:30:32 +02:00
|
|
|
|
import zoneinfo
|
2024-07-12 02:30:25 +02:00
|
|
|
|
from collections.abc import Sequence
|
2023-11-19 19:45:19 +01:00
|
|
|
|
from datetime import datetime, timedelta
|
2024-07-12 02:30:25 +02:00
|
|
|
|
from typing import IO, Any, Literal, overload
|
2020-06-27 02:37:49 +02:00
|
|
|
|
from urllib.parse import SplitResult
|
2016-07-12 17:08:35 +02:00
|
|
|
|
|
2013-10-04 19:19:57 +02:00
|
|
|
|
DEPLOYMENTS_DIR = "/home/zulip/deployments"
|
2013-05-16 18:02:25 +02:00
|
|
|
|
LOCK_DIR = os.path.join(DEPLOYMENTS_DIR, "lock")
|
2021-02-12 08:20:45 +01:00
|
|
|
|
TIMESTAMP_FORMAT = "%Y-%m-%d-%H-%M-%S"
|
2013-06-05 00:21:47 +02:00
|
|
|
|
|
|
|
|
|
# Color codes
|
2021-02-12 08:20:45 +01:00
|
|
|
|
OKBLUE = "\033[94m"
|
|
|
|
|
OKGREEN = "\033[92m"
|
|
|
|
|
WARNING = "\033[93m"
|
|
|
|
|
FAIL = "\033[91m"
|
|
|
|
|
ENDC = "\033[0m"
|
|
|
|
|
BLACKONYELLOW = "\x1b[0;30;43m"
|
|
|
|
|
WHITEONRED = "\x1b[0;37;41m"
|
2023-12-05 18:45:07 +01:00
|
|
|
|
BOLDRED = "\x1b[1;31m"
|
2022-04-27 21:55:02 +02:00
|
|
|
|
BOLD = "\x1b[1m"
|
|
|
|
|
GRAY = "\x1b[90m"
|
2021-02-12 08:20:45 +01:00
|
|
|
|
|
|
|
|
|
GREEN = "\x1b[32m"
|
|
|
|
|
YELLOW = "\x1b[33m"
|
|
|
|
|
BLUE = "\x1b[34m"
|
|
|
|
|
MAGENTA = "\x1b[35m"
|
|
|
|
|
CYAN = "\x1b[36m"
|
2013-11-13 20:57:31 +01:00
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
python: Convert function type annotations to Python 3 style.
Generated by com2ann (slightly patched to avoid also converting
assignment type annotations, which require Python 3.6), followed by
some manual whitespace adjustment, and six fixes for runtime issues:
- def __init__(self, token: Token, parent: Optional[Node]) -> None:
+ def __init__(self, token: Token, parent: "Optional[Node]") -> None:
-def main(options: argparse.Namespace) -> NoReturn:
+def main(options: argparse.Namespace) -> "NoReturn":
-def fetch_request(url: str, callback: Any, **kwargs: Any) -> Generator[Callable[..., Any], Any, None]:
+def fetch_request(url: str, callback: Any, **kwargs: Any) -> "Generator[Callable[..., Any], Any, None]":
-def assert_server_running(server: subprocess.Popen[bytes], log_file: Optional[str]) -> None:
+def assert_server_running(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> None:
-def server_is_up(server: subprocess.Popen[bytes], log_file: Optional[str]) -> bool:
+def server_is_up(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> bool:
- method_kwarg_pairs: List[FuncKwargPair],
+ method_kwarg_pairs: "List[FuncKwargPair]",
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-19 03:48:37 +02:00
|
|
|
|
def overwrite_symlink(src: str, dst: str) -> None:
|
2020-07-09 20:31:34 +02:00
|
|
|
|
dir, base = os.path.split(dst)
|
2018-07-27 01:23:27 +02:00
|
|
|
|
while True:
|
2020-07-09 20:31:34 +02:00
|
|
|
|
# Note: creating a temporary filename like this is not generally
|
|
|
|
|
# secure. It’s fine in this case because os.symlink refuses to
|
|
|
|
|
# overwrite an existing target; we handle the error and try again.
|
2021-09-22 06:03:56 +02:00
|
|
|
|
tmp = os.path.join(dir, f".{base}.{random.randrange(1 << 40):010x}")
|
2018-07-27 01:23:27 +02:00
|
|
|
|
try:
|
|
|
|
|
os.symlink(src, tmp)
|
|
|
|
|
except FileExistsError:
|
|
|
|
|
continue
|
|
|
|
|
break
|
|
|
|
|
try:
|
|
|
|
|
os.rename(tmp, dst)
|
2020-10-09 03:00:21 +02:00
|
|
|
|
except BaseException:
|
2018-07-27 01:23:27 +02:00
|
|
|
|
os.remove(tmp)
|
|
|
|
|
raise
|
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
python: Convert function type annotations to Python 3 style.
Generated by com2ann (slightly patched to avoid also converting
assignment type annotations, which require Python 3.6), followed by
some manual whitespace adjustment, and six fixes for runtime issues:
- def __init__(self, token: Token, parent: Optional[Node]) -> None:
+ def __init__(self, token: Token, parent: "Optional[Node]") -> None:
-def main(options: argparse.Namespace) -> NoReturn:
+def main(options: argparse.Namespace) -> "NoReturn":
-def fetch_request(url: str, callback: Any, **kwargs: Any) -> Generator[Callable[..., Any], Any, None]:
+def fetch_request(url: str, callback: Any, **kwargs: Any) -> "Generator[Callable[..., Any], Any, None]":
-def assert_server_running(server: subprocess.Popen[bytes], log_file: Optional[str]) -> None:
+def assert_server_running(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> None:
-def server_is_up(server: subprocess.Popen[bytes], log_file: Optional[str]) -> bool:
+def server_is_up(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> bool:
- method_kwarg_pairs: List[FuncKwargPair],
+ method_kwarg_pairs: "List[FuncKwargPair]",
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-19 03:48:37 +02:00
|
|
|
|
def parse_cache_script_args(description: str) -> argparse.Namespace:
|
2020-04-30 19:12:13 +02:00
|
|
|
|
# Keep this in sync with clean_unused_caches in provision_inner.py
|
2017-09-23 20:42:53 +02:00
|
|
|
|
parser = argparse.ArgumentParser(description=description)
|
|
|
|
|
|
|
|
|
|
parser.add_argument(
|
2021-02-12 08:19:30 +01:00
|
|
|
|
"--threshold",
|
|
|
|
|
dest="threshold_days",
|
|
|
|
|
type=int,
|
|
|
|
|
default=14,
|
|
|
|
|
metavar="<days>",
|
|
|
|
|
help="Any cache which is not in "
|
2017-09-23 20:42:53 +02:00
|
|
|
|
"use by a deployment not older than threshold days(current "
|
|
|
|
|
"installation in dev) and older than threshold days will be "
|
2021-02-12 08:19:30 +01:00
|
|
|
|
"deleted. (defaults to 14)",
|
|
|
|
|
)
|
2017-09-23 20:42:53 +02:00
|
|
|
|
parser.add_argument(
|
2021-02-12 08:19:30 +01:00
|
|
|
|
"--dry-run",
|
|
|
|
|
action="store_true",
|
2017-09-23 20:42:53 +02:00
|
|
|
|
help="If specified then script will only print the caches "
|
2021-02-12 08:19:30 +01:00
|
|
|
|
"that it will delete/keep back. It will not delete any cache.",
|
|
|
|
|
)
|
2017-09-23 20:42:53 +02:00
|
|
|
|
parser.add_argument(
|
2021-02-12 08:19:30 +01:00
|
|
|
|
"--verbose",
|
|
|
|
|
action="store_true",
|
2017-09-23 20:42:53 +02:00
|
|
|
|
help="If specified then script will print a detailed report "
|
2021-02-12 08:19:30 +01:00
|
|
|
|
"of what is being will deleted/kept back.",
|
|
|
|
|
)
|
2019-09-29 01:49:13 +02:00
|
|
|
|
parser.add_argument(
|
2021-02-12 08:19:30 +01:00
|
|
|
|
"--no-print-headings",
|
|
|
|
|
dest="no_headings",
|
|
|
|
|
action="store_true",
|
2019-09-29 01:49:13 +02:00
|
|
|
|
help="If specified then script will not print headings for "
|
2021-02-12 08:19:30 +01:00
|
|
|
|
"what will be deleted/kept back.",
|
|
|
|
|
)
|
2017-09-23 20:42:53 +02:00
|
|
|
|
|
|
|
|
|
args = parser.parse_args()
|
2021-02-12 08:19:30 +01:00
|
|
|
|
args.verbose |= args.dry_run # Always print a detailed report in case of dry run.
|
2017-09-23 20:42:53 +02:00
|
|
|
|
return args
|
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
2019-02-07 01:32:34 +01:00
|
|
|
|
def get_deploy_root() -> str:
|
get_deploy_root: Avoid useless extra realpath call.
The comment that tabbott edited into my commit while wimpifying this
function is wrong on multiple levels.
Firstly, the way in which users might be “running our scripts” was
never relevant. `__file__` is not the script that the user ran, it’s
zulip_tools.py itself. What matters is not how the user ran the
script, but rather how zulip_tools was imported. If zulip_tools was
imported as scripts.lib.zulip_tools, then `__file__` must end with
`scripts/lib/zulip_tools.py`, so running dirname three times on it is
fine. In fact, in Python ≥ 3.4 (we don’t support anything older),
`__file__` in an imported module is always an absolute path, so it
must end with `scripts/lib/zulip_tools.py` in any case.
(At present, there’s one script that imports lib.zulip_tools, and the
installer runs scripts/lib/zulip_tools.py as a script, but those uses
don’t hit this function.)
Secondly, even if we do care about `__file__` being a funny relative
path, there’s still no reason to have two calls to `realpath`.
`realpath(dirname(dirname(dirname(realpath(…)))))` is equivalent to
`dirname(dirname(dirname(realpath(…)))), as the inner `realpath` has
already canonicalized symlinks at every level.
This version also deals with `__file__` being a funny relative
path (assuming none of scripts, lib, and zulip_tools.py are themselves
symlinks), while making fewer `lstat` calls than either of the above
constructions.
Signed-off-by: Anders Kaseorg <andersk@mit.edu>
2019-03-05 23:45:00 +01:00
|
|
|
|
return os.path.realpath(
|
python: Use trailing commas consistently.
Automatically generated by the following script, based on the output
of lint with flake8-comma:
import re
import sys
last_filename = None
last_row = None
lines = []
for msg in sys.stdin:
m = re.match(
r"\x1b\[35mflake8 \|\x1b\[0m \x1b\[1;31m(.+):(\d+):(\d+): (\w+)", msg
)
if m:
filename, row_str, col_str, err = m.groups()
row, col = int(row_str), int(col_str)
if filename == last_filename:
assert last_row != row
else:
if last_filename is not None:
with open(last_filename, "w") as f:
f.writelines(lines)
with open(filename) as f:
lines = f.readlines()
last_filename = filename
last_row = row
line = lines[row - 1]
if err in ["C812", "C815"]:
lines[row - 1] = line[: col - 1] + "," + line[col - 1 :]
elif err in ["C819"]:
assert line[col - 2] == ","
lines[row - 1] = line[: col - 2] + line[col - 1 :].lstrip(" ")
if last_filename is not None:
with open(last_filename, "w") as f:
f.writelines(lines)
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-10 05:23:40 +02:00
|
|
|
|
os.path.normpath(os.path.join(os.path.dirname(__file__), "..", "..")),
|
get_deploy_root: Avoid useless extra realpath call.
The comment that tabbott edited into my commit while wimpifying this
function is wrong on multiple levels.
Firstly, the way in which users might be “running our scripts” was
never relevant. `__file__` is not the script that the user ran, it’s
zulip_tools.py itself. What matters is not how the user ran the
script, but rather how zulip_tools was imported. If zulip_tools was
imported as scripts.lib.zulip_tools, then `__file__` must end with
`scripts/lib/zulip_tools.py`, so running dirname three times on it is
fine. In fact, in Python ≥ 3.4 (we don’t support anything older),
`__file__` in an imported module is always an absolute path, so it
must end with `scripts/lib/zulip_tools.py` in any case.
(At present, there’s one script that imports lib.zulip_tools, and the
installer runs scripts/lib/zulip_tools.py as a script, but those uses
don’t hit this function.)
Secondly, even if we do care about `__file__` being a funny relative
path, there’s still no reason to have two calls to `realpath`.
`realpath(dirname(dirname(dirname(realpath(…)))))` is equivalent to
`dirname(dirname(dirname(realpath(…)))), as the inner `realpath` has
already canonicalized symlinks at every level.
This version also deals with `__file__` being a funny relative
path (assuming none of scripts, lib, and zulip_tools.py are themselves
symlinks), while making fewer `lstat` calls than either of the above
constructions.
Signed-off-by: Anders Kaseorg <andersk@mit.edu>
2019-03-05 23:45:00 +01:00
|
|
|
|
)
|
2019-02-07 01:32:34 +01:00
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
2023-04-05 04:16:30 +02:00
|
|
|
|
def parse_version_from(deploy_path: str, merge_base: bool = False) -> str:
|
upgrade-zulip-from-git: We may need to fill in a zulip-git-version file.
Installs which are upgrading to current `main`, and are upgrading for
the very first time from an install which was originally from git,
have a `/home/zulip/deployments/current` which, unlike all later
upgrades, is not a `git worktree` of `/srv/zulip.git`, but rather a
direct `git clone` of some arbitrary URL. As such, it does not have
an `upstream` remote, nor a cached `zulip-git-version` file.
This makes later attempts to determine the pre-upgrade revision of
git (for pre-deploy hooks) fail, as without a `zulip-git-version`
file, `ZULIP_VERSION` is insufficiently-specific (e.g. `6.1+git`), and
there is no guarantee the necessary tags exist either.
While we can make fresh git installs set up an `upstream` and run
`./tools/cache-zulip-git-version` going forward (see subsequent
commit), that does not address the issue for deploys which already
exist. For those, we must configure and fetch a `remote` in the old
checkout, followed by re-generating a cached `zulip-git-version`.
Fixes: #25076.
2023-04-14 20:36:34 +02:00
|
|
|
|
if not os.path.exists(os.path.join(deploy_path, "zulip-git-version")):
|
|
|
|
|
try:
|
|
|
|
|
# Pull this tool from _our_ deploy root, since it may not
|
|
|
|
|
# exist historically, but run it the cwd of the old
|
|
|
|
|
# deploy, so we set up its remote.
|
|
|
|
|
subprocess.check_call(
|
|
|
|
|
[os.path.join(get_deploy_root(), "scripts", "lib", "update-git-upstream")],
|
|
|
|
|
cwd=deploy_path,
|
|
|
|
|
preexec_fn=su_to_zulip,
|
|
|
|
|
)
|
|
|
|
|
subprocess.check_call(
|
|
|
|
|
[os.path.join(deploy_path, "tools", "cache-zulip-git-version")],
|
|
|
|
|
cwd=deploy_path,
|
|
|
|
|
preexec_fn=su_to_zulip,
|
|
|
|
|
)
|
|
|
|
|
except subprocess.CalledProcessError:
|
|
|
|
|
pass
|
2023-01-30 21:26:46 +01:00
|
|
|
|
try:
|
2023-04-05 04:16:30 +02:00
|
|
|
|
varname = "ZULIP_MERGE_BASE" if merge_base else "ZULIP_VERSION"
|
2023-01-30 21:26:46 +01:00
|
|
|
|
return subprocess.check_output(
|
2023-04-05 04:16:30 +02:00
|
|
|
|
[sys.executable, "-c", f"from version import {varname}; print({varname})"],
|
2023-01-30 21:26:46 +01:00
|
|
|
|
cwd=deploy_path,
|
|
|
|
|
text=True,
|
|
|
|
|
).strip()
|
|
|
|
|
except subprocess.CalledProcessError:
|
|
|
|
|
return "0.0.0"
|
2022-02-03 02:27:45 +01:00
|
|
|
|
|
|
|
|
|
|
python: Convert function type annotations to Python 3 style.
Generated by com2ann (slightly patched to avoid also converting
assignment type annotations, which require Python 3.6), followed by
some manual whitespace adjustment, and six fixes for runtime issues:
- def __init__(self, token: Token, parent: Optional[Node]) -> None:
+ def __init__(self, token: Token, parent: "Optional[Node]") -> None:
-def main(options: argparse.Namespace) -> NoReturn:
+def main(options: argparse.Namespace) -> "NoReturn":
-def fetch_request(url: str, callback: Any, **kwargs: Any) -> Generator[Callable[..., Any], Any, None]:
+def fetch_request(url: str, callback: Any, **kwargs: Any) -> "Generator[Callable[..., Any], Any, None]":
-def assert_server_running(server: subprocess.Popen[bytes], log_file: Optional[str]) -> None:
+def assert_server_running(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> None:
-def server_is_up(server: subprocess.Popen[bytes], log_file: Optional[str]) -> bool:
+def server_is_up(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> bool:
- method_kwarg_pairs: List[FuncKwargPair],
+ method_kwarg_pairs: "List[FuncKwargPair]",
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-19 03:48:37 +02:00
|
|
|
|
def get_deployment_version(extract_path: str) -> str:
|
2021-02-12 08:20:45 +01:00
|
|
|
|
version = "0.0.0"
|
2017-06-21 14:32:22 +02:00
|
|
|
|
for item in os.listdir(extract_path):
|
|
|
|
|
item_path = os.path.join(extract_path, item)
|
2021-02-12 08:20:45 +01:00
|
|
|
|
if item.startswith("zulip-server") and os.path.isdir(item_path):
|
2022-02-03 02:27:45 +01:00
|
|
|
|
version = parse_version_from(item_path)
|
2017-06-21 14:32:22 +02:00
|
|
|
|
break
|
|
|
|
|
return version
|
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
python: Convert function type annotations to Python 3 style.
Generated by com2ann (slightly patched to avoid also converting
assignment type annotations, which require Python 3.6), followed by
some manual whitespace adjustment, and six fixes for runtime issues:
- def __init__(self, token: Token, parent: Optional[Node]) -> None:
+ def __init__(self, token: Token, parent: "Optional[Node]") -> None:
-def main(options: argparse.Namespace) -> NoReturn:
+def main(options: argparse.Namespace) -> "NoReturn":
-def fetch_request(url: str, callback: Any, **kwargs: Any) -> Generator[Callable[..., Any], Any, None]:
+def fetch_request(url: str, callback: Any, **kwargs: Any) -> "Generator[Callable[..., Any], Any, None]":
-def assert_server_running(server: subprocess.Popen[bytes], log_file: Optional[str]) -> None:
+def assert_server_running(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> None:
-def server_is_up(server: subprocess.Popen[bytes], log_file: Optional[str]) -> bool:
+def server_is_up(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> bool:
- method_kwarg_pairs: List[FuncKwargPair],
+ method_kwarg_pairs: "List[FuncKwargPair]",
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-19 03:48:37 +02:00
|
|
|
|
def is_invalid_upgrade(current_version: str, new_version: str) -> bool:
|
2021-02-12 08:20:45 +01:00
|
|
|
|
if new_version > "1.4.3" and current_version <= "1.3.10":
|
2017-06-21 14:32:22 +02:00
|
|
|
|
return True
|
|
|
|
|
return False
|
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
2019-03-04 23:21:44 +01:00
|
|
|
|
def get_zulip_pwent() -> pwd.struct_passwd:
|
|
|
|
|
deploy_root_uid = os.stat(get_deploy_root()).st_uid
|
|
|
|
|
if deploy_root_uid != 0:
|
|
|
|
|
return pwd.getpwuid(deploy_root_uid)
|
|
|
|
|
|
|
|
|
|
# In the case that permissions got messed up and the deployment
|
|
|
|
|
# directory is unexpectedly owned by root, we fallback to the
|
|
|
|
|
# `zulip` user as that's the correct value in production.
|
|
|
|
|
return pwd.getpwnam("zulip")
|
2019-02-07 01:41:10 +01:00
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
2020-02-29 16:29:16 +01:00
|
|
|
|
def get_postgres_pwent() -> pwd.struct_passwd:
|
|
|
|
|
try:
|
|
|
|
|
return pwd.getpwnam("postgres")
|
|
|
|
|
except KeyError:
|
|
|
|
|
return get_zulip_pwent()
|
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
python: Convert function type annotations to Python 3 style.
Generated by com2ann (slightly patched to avoid also converting
assignment type annotations, which require Python 3.6), followed by
some manual whitespace adjustment, and six fixes for runtime issues:
- def __init__(self, token: Token, parent: Optional[Node]) -> None:
+ def __init__(self, token: Token, parent: "Optional[Node]") -> None:
-def main(options: argparse.Namespace) -> NoReturn:
+def main(options: argparse.Namespace) -> "NoReturn":
-def fetch_request(url: str, callback: Any, **kwargs: Any) -> Generator[Callable[..., Any], Any, None]:
+def fetch_request(url: str, callback: Any, **kwargs: Any) -> "Generator[Callable[..., Any], Any, None]":
-def assert_server_running(server: subprocess.Popen[bytes], log_file: Optional[str]) -> None:
+def assert_server_running(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> None:
-def server_is_up(server: subprocess.Popen[bytes], log_file: Optional[str]) -> bool:
+def server_is_up(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> bool:
- method_kwarg_pairs: List[FuncKwargPair],
+ method_kwarg_pairs: "List[FuncKwargPair]",
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-19 03:48:37 +02:00
|
|
|
|
def su_to_zulip(save_suid: bool = False) -> None:
|
2019-02-07 01:41:10 +01:00
|
|
|
|
"""Warning: su_to_zulip assumes that the zulip checkout is owned by
|
|
|
|
|
the zulip user (or whatever normal user is running the Zulip
|
|
|
|
|
installation). It should never be run from the installer or other
|
|
|
|
|
production contexts before /home/zulip/deployments/current is
|
|
|
|
|
created."""
|
2019-03-04 23:21:44 +01:00
|
|
|
|
pwent = get_zulip_pwent()
|
2013-11-13 21:54:30 +01:00
|
|
|
|
os.setgid(pwent.pw_gid)
|
2019-01-16 03:17:33 +01:00
|
|
|
|
if save_suid:
|
|
|
|
|
os.setresuid(pwent.pw_uid, pwent.pw_uid, os.getuid())
|
|
|
|
|
else:
|
|
|
|
|
os.setuid(pwent.pw_uid)
|
2021-02-12 08:20:45 +01:00
|
|
|
|
os.environ["HOME"] = pwent.pw_dir
|
2013-11-13 21:54:30 +01:00
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
python: Convert function type annotations to Python 3 style.
Generated by com2ann (slightly patched to avoid also converting
assignment type annotations, which require Python 3.6), followed by
some manual whitespace adjustment, and six fixes for runtime issues:
- def __init__(self, token: Token, parent: Optional[Node]) -> None:
+ def __init__(self, token: Token, parent: "Optional[Node]") -> None:
-def main(options: argparse.Namespace) -> NoReturn:
+def main(options: argparse.Namespace) -> "NoReturn":
-def fetch_request(url: str, callback: Any, **kwargs: Any) -> Generator[Callable[..., Any], Any, None]:
+def fetch_request(url: str, callback: Any, **kwargs: Any) -> "Generator[Callable[..., Any], Any, None]":
-def assert_server_running(server: subprocess.Popen[bytes], log_file: Optional[str]) -> None:
+def assert_server_running(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> None:
-def server_is_up(server: subprocess.Popen[bytes], log_file: Optional[str]) -> bool:
+def server_is_up(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> bool:
- method_kwarg_pairs: List[FuncKwargPair],
+ method_kwarg_pairs: "List[FuncKwargPair]",
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-19 03:48:37 +02:00
|
|
|
|
def make_deploy_path() -> str:
|
2023-11-19 19:45:19 +01:00
|
|
|
|
timestamp = datetime.now().strftime(TIMESTAMP_FORMAT) # noqa: DTZ005
|
2013-11-13 20:57:31 +01:00
|
|
|
|
return os.path.join(DEPLOYMENTS_DIR, timestamp)
|
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
2019-06-11 18:36:27 +02:00
|
|
|
|
TEMPLATE_DATABASE_DIR = "test-backend/databases"
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
|
|
|
|
|
python: Convert function type annotations to Python 3 style.
Generated by com2ann (slightly patched to avoid also converting
assignment type annotations, which require Python 3.6), followed by
some manual whitespace adjustment, and six fixes for runtime issues:
- def __init__(self, token: Token, parent: Optional[Node]) -> None:
+ def __init__(self, token: Token, parent: "Optional[Node]") -> None:
-def main(options: argparse.Namespace) -> NoReturn:
+def main(options: argparse.Namespace) -> "NoReturn":
-def fetch_request(url: str, callback: Any, **kwargs: Any) -> Generator[Callable[..., Any], Any, None]:
+def fetch_request(url: str, callback: Any, **kwargs: Any) -> "Generator[Callable[..., Any], Any, None]":
-def assert_server_running(server: subprocess.Popen[bytes], log_file: Optional[str]) -> None:
+def assert_server_running(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> None:
-def server_is_up(server: subprocess.Popen[bytes], log_file: Optional[str]) -> bool:
+def server_is_up(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> bool:
- method_kwarg_pairs: List[FuncKwargPair],
+ method_kwarg_pairs: "List[FuncKwargPair]",
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-19 03:48:37 +02:00
|
|
|
|
def get_dev_uuid_var_path(create_if_missing: bool = False) -> str:
|
2019-02-07 01:32:34 +01:00
|
|
|
|
zulip_path = get_deploy_root()
|
2017-10-18 04:14:06 +02:00
|
|
|
|
uuid_path = os.path.join(os.path.realpath(os.path.dirname(zulip_path)), ".zulip-dev-uuid")
|
|
|
|
|
if os.path.exists(uuid_path):
|
|
|
|
|
with open(uuid_path) as f:
|
|
|
|
|
zulip_uuid = f.read().strip()
|
|
|
|
|
else:
|
|
|
|
|
if create_if_missing:
|
|
|
|
|
zulip_uuid = str(uuid.uuid4())
|
2019-02-26 21:47:35 +01:00
|
|
|
|
# We need root access here, since the path will be under /srv/ in the
|
2017-10-18 04:14:06 +02:00
|
|
|
|
# development environment.
|
2021-02-12 08:19:30 +01:00
|
|
|
|
run_as_root(["sh", "-c", 'echo "$1" > "$2"', "-", zulip_uuid, uuid_path])
|
2017-10-18 04:14:06 +02:00
|
|
|
|
else:
|
|
|
|
|
raise AssertionError("Missing UUID file; please run tools/provision!")
|
|
|
|
|
|
|
|
|
|
result_path = os.path.join(zulip_path, "var", zulip_uuid)
|
2017-10-25 20:06:11 +02:00
|
|
|
|
os.makedirs(result_path, exist_ok=True)
|
2017-10-18 04:14:06 +02:00
|
|
|
|
return result_path
|
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
python: Convert function type annotations to Python 3 style.
Generated by com2ann (slightly patched to avoid also converting
assignment type annotations, which require Python 3.6), followed by
some manual whitespace adjustment, and six fixes for runtime issues:
- def __init__(self, token: Token, parent: Optional[Node]) -> None:
+ def __init__(self, token: Token, parent: "Optional[Node]") -> None:
-def main(options: argparse.Namespace) -> NoReturn:
+def main(options: argparse.Namespace) -> "NoReturn":
-def fetch_request(url: str, callback: Any, **kwargs: Any) -> Generator[Callable[..., Any], Any, None]:
+def fetch_request(url: str, callback: Any, **kwargs: Any) -> "Generator[Callable[..., Any], Any, None]":
-def assert_server_running(server: subprocess.Popen[bytes], log_file: Optional[str]) -> None:
+def assert_server_running(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> None:
-def server_is_up(server: subprocess.Popen[bytes], log_file: Optional[str]) -> bool:
+def server_is_up(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> bool:
- method_kwarg_pairs: List[FuncKwargPair],
+ method_kwarg_pairs: "List[FuncKwargPair]",
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-19 03:48:37 +02:00
|
|
|
|
def get_deployment_lock(error_rerun_script: str) -> None:
|
2016-01-10 20:58:11 +01:00
|
|
|
|
start_time = time.time()
|
|
|
|
|
got_lock = False
|
|
|
|
|
while time.time() - start_time < 300:
|
|
|
|
|
try:
|
|
|
|
|
os.mkdir(LOCK_DIR)
|
|
|
|
|
got_lock = True
|
|
|
|
|
break
|
|
|
|
|
except OSError:
|
2021-02-12 08:19:30 +01:00
|
|
|
|
print(
|
|
|
|
|
WARNING
|
|
|
|
|
+ "Another deployment in progress; waiting for lock... "
|
2021-09-22 06:03:56 +02:00
|
|
|
|
+ f"(If no deployment is running, rmdir {LOCK_DIR})"
|
2021-06-09 22:11:26 +02:00
|
|
|
|
+ ENDC,
|
|
|
|
|
flush=True,
|
2021-02-12 08:19:30 +01:00
|
|
|
|
)
|
2016-01-10 20:58:11 +01:00
|
|
|
|
time.sleep(3)
|
|
|
|
|
|
|
|
|
|
if not got_lock:
|
2021-02-12 08:19:30 +01:00
|
|
|
|
print(
|
|
|
|
|
FAIL
|
|
|
|
|
+ "Deployment already in progress. Please run\n"
|
2021-09-22 06:03:56 +02:00
|
|
|
|
+ f" {error_rerun_script}\n"
|
2021-02-12 08:19:30 +01:00
|
|
|
|
+ "manually when the previous deployment finishes, or run\n"
|
2021-09-22 06:03:56 +02:00
|
|
|
|
+ f" rmdir {LOCK_DIR}\n"
|
2021-02-12 08:19:30 +01:00
|
|
|
|
+ "if the previous deployment crashed."
|
|
|
|
|
+ ENDC
|
|
|
|
|
)
|
2016-01-10 20:58:11 +01:00
|
|
|
|
sys.exit(1)
|
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
python: Convert function type annotations to Python 3 style.
Generated by com2ann (slightly patched to avoid also converting
assignment type annotations, which require Python 3.6), followed by
some manual whitespace adjustment, and six fixes for runtime issues:
- def __init__(self, token: Token, parent: Optional[Node]) -> None:
+ def __init__(self, token: Token, parent: "Optional[Node]") -> None:
-def main(options: argparse.Namespace) -> NoReturn:
+def main(options: argparse.Namespace) -> "NoReturn":
-def fetch_request(url: str, callback: Any, **kwargs: Any) -> Generator[Callable[..., Any], Any, None]:
+def fetch_request(url: str, callback: Any, **kwargs: Any) -> "Generator[Callable[..., Any], Any, None]":
-def assert_server_running(server: subprocess.Popen[bytes], log_file: Optional[str]) -> None:
+def assert_server_running(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> None:
-def server_is_up(server: subprocess.Popen[bytes], log_file: Optional[str]) -> bool:
+def server_is_up(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> bool:
- method_kwarg_pairs: List[FuncKwargPair],
+ method_kwarg_pairs: "List[FuncKwargPair]",
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-19 03:48:37 +02:00
|
|
|
|
def release_deployment_lock() -> None:
|
2016-01-10 20:58:11 +01:00
|
|
|
|
shutil.rmtree(LOCK_DIR)
|
2016-04-06 17:15:31 +02:00
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
python: Convert function type annotations to Python 3 style.
Generated by com2ann (slightly patched to avoid also converting
assignment type annotations, which require Python 3.6), followed by
some manual whitespace adjustment, and six fixes for runtime issues:
- def __init__(self, token: Token, parent: Optional[Node]) -> None:
+ def __init__(self, token: Token, parent: "Optional[Node]") -> None:
-def main(options: argparse.Namespace) -> NoReturn:
+def main(options: argparse.Namespace) -> "NoReturn":
-def fetch_request(url: str, callback: Any, **kwargs: Any) -> Generator[Callable[..., Any], Any, None]:
+def fetch_request(url: str, callback: Any, **kwargs: Any) -> "Generator[Callable[..., Any], Any, None]":
-def assert_server_running(server: subprocess.Popen[bytes], log_file: Optional[str]) -> None:
+def assert_server_running(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> None:
-def server_is_up(server: subprocess.Popen[bytes], log_file: Optional[str]) -> bool:
+def server_is_up(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> bool:
- method_kwarg_pairs: List[FuncKwargPair],
+ method_kwarg_pairs: "List[FuncKwargPair]",
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-19 03:48:37 +02:00
|
|
|
|
def run(args: Sequence[str], **kwargs: Any) -> None:
|
2016-04-06 17:15:31 +02:00
|
|
|
|
# Output what we're doing in the `set -x` style
|
2022-04-27 02:10:28 +02:00
|
|
|
|
print(f"+ {shlex.join(args)}", flush=True)
|
2016-09-23 11:27:14 +02:00
|
|
|
|
|
2016-10-27 21:07:55 +02:00
|
|
|
|
try:
|
|
|
|
|
subprocess.check_call(args, **kwargs)
|
2023-03-09 02:50:11 +01:00
|
|
|
|
except subprocess.CalledProcessError as error:
|
2017-01-11 17:07:12 +01:00
|
|
|
|
print()
|
2023-03-09 02:50:11 +01:00
|
|
|
|
if error.returncode < 0:
|
|
|
|
|
try:
|
|
|
|
|
signal_name = signal.Signals(-error.returncode).name
|
|
|
|
|
except ValueError:
|
|
|
|
|
signal_name = f"unknown signal {-error.returncode}"
|
|
|
|
|
print(
|
|
|
|
|
WHITEONRED
|
|
|
|
|
+ f"Subcommand of {sys.argv[0]} died with {signal_name}: {shlex.join(args)}"
|
|
|
|
|
+ ENDC
|
|
|
|
|
)
|
|
|
|
|
else:
|
|
|
|
|
print(
|
|
|
|
|
WHITEONRED
|
|
|
|
|
+ f"Subcommand of {sys.argv[0]} failed with exit status {error.returncode}: {shlex.join(args)}"
|
|
|
|
|
+ ENDC
|
|
|
|
|
)
|
|
|
|
|
print(WHITEONRED + "Actual error output for the subcommand is just above this." + ENDC)
|
2017-01-11 17:07:12 +01:00
|
|
|
|
print()
|
2021-04-21 03:26:33 +02:00
|
|
|
|
sys.exit(1)
|
2017-08-18 06:36:37 +02:00
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
2021-01-26 20:49:37 +01:00
|
|
|
|
def log_management_command(cmd: Sequence[str], log_path: str) -> None:
|
2017-08-18 06:36:37 +02:00
|
|
|
|
log_dir = os.path.dirname(log_path)
|
|
|
|
|
if not os.path.exists(log_dir):
|
|
|
|
|
os.makedirs(log_dir)
|
|
|
|
|
|
|
|
|
|
formatter = logging.Formatter("%(asctime)s: %(message)s")
|
|
|
|
|
file_handler = logging.FileHandler(log_path)
|
|
|
|
|
file_handler.setFormatter(formatter)
|
|
|
|
|
logger = logging.getLogger("zulip.management")
|
|
|
|
|
logger.addHandler(file_handler)
|
|
|
|
|
logger.setLevel(logging.INFO)
|
|
|
|
|
|
2022-04-27 02:10:28 +02:00
|
|
|
|
logger.info("Ran %s", shlex.join(cmd))
|
2017-08-18 19:14:09 +02:00
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
python: Convert function type annotations to Python 3 style.
Generated by com2ann (slightly patched to avoid also converting
assignment type annotations, which require Python 3.6), followed by
some manual whitespace adjustment, and six fixes for runtime issues:
- def __init__(self, token: Token, parent: Optional[Node]) -> None:
+ def __init__(self, token: Token, parent: "Optional[Node]") -> None:
-def main(options: argparse.Namespace) -> NoReturn:
+def main(options: argparse.Namespace) -> "NoReturn":
-def fetch_request(url: str, callback: Any, **kwargs: Any) -> Generator[Callable[..., Any], Any, None]:
+def fetch_request(url: str, callback: Any, **kwargs: Any) -> "Generator[Callable[..., Any], Any, None]":
-def assert_server_running(server: subprocess.Popen[bytes], log_file: Optional[str]) -> None:
+def assert_server_running(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> None:
-def server_is_up(server: subprocess.Popen[bytes], log_file: Optional[str]) -> bool:
+def server_is_up(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> bool:
- method_kwarg_pairs: List[FuncKwargPair],
+ method_kwarg_pairs: "List[FuncKwargPair]",
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-19 03:48:37 +02:00
|
|
|
|
def get_environment() -> str:
|
2017-08-18 19:14:09 +02:00
|
|
|
|
if os.path.exists(DEPLOYMENTS_DIR):
|
|
|
|
|
return "prod"
|
|
|
|
|
return "dev"
|
2017-08-18 20:34:00 +02:00
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
2024-07-12 02:30:17 +02:00
|
|
|
|
def get_recent_deployments(threshold_days: int) -> set[str]:
|
2017-08-18 20:34:00 +02:00
|
|
|
|
# Returns a list of deployments not older than threshold days
|
|
|
|
|
# including `/root/zulip` directory if it exists.
|
|
|
|
|
recent = set()
|
2023-11-19 19:45:19 +01:00
|
|
|
|
threshold_date = datetime.now() - timedelta(days=threshold_days) # noqa: DTZ005
|
2017-08-18 20:34:00 +02:00
|
|
|
|
for dir_name in os.listdir(DEPLOYMENTS_DIR):
|
2017-10-29 21:06:30 +01:00
|
|
|
|
target_dir = os.path.join(DEPLOYMENTS_DIR, dir_name)
|
|
|
|
|
if not os.path.isdir(target_dir):
|
2017-09-26 00:11:18 +02:00
|
|
|
|
# Skip things like uwsgi sockets, symlinks, etc.
|
|
|
|
|
continue
|
2017-10-29 21:06:30 +01:00
|
|
|
|
if not os.path.exists(os.path.join(target_dir, "zerver")):
|
2017-09-26 00:11:18 +02:00
|
|
|
|
# Skip things like "lock" that aren't actually a deployment directory
|
2017-08-28 03:16:15 +02:00
|
|
|
|
continue
|
2017-08-18 20:34:00 +02:00
|
|
|
|
try:
|
2023-11-19 19:45:19 +01:00
|
|
|
|
date = datetime.strptime(dir_name, TIMESTAMP_FORMAT) # noqa: DTZ007
|
2017-08-18 20:34:00 +02:00
|
|
|
|
if date >= threshold_date:
|
2017-10-29 21:06:30 +01:00
|
|
|
|
recent.add(target_dir)
|
2017-08-18 20:34:00 +02:00
|
|
|
|
except ValueError:
|
|
|
|
|
# Always include deployments whose name is not in the format of a timestamp.
|
2017-10-29 21:06:30 +01:00
|
|
|
|
recent.add(target_dir)
|
2017-10-29 21:07:41 +01:00
|
|
|
|
# If it is a symlink then include the target as well.
|
|
|
|
|
if os.path.islink(target_dir):
|
|
|
|
|
recent.add(os.path.realpath(target_dir))
|
2017-08-18 20:34:00 +02:00
|
|
|
|
if os.path.exists("/root/zulip"):
|
|
|
|
|
recent.add("/root/zulip")
|
|
|
|
|
return recent
|
2017-08-19 20:13:44 +02:00
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
python: Convert function type annotations to Python 3 style.
Generated by com2ann (slightly patched to avoid also converting
assignment type annotations, which require Python 3.6), followed by
some manual whitespace adjustment, and six fixes for runtime issues:
- def __init__(self, token: Token, parent: Optional[Node]) -> None:
+ def __init__(self, token: Token, parent: "Optional[Node]") -> None:
-def main(options: argparse.Namespace) -> NoReturn:
+def main(options: argparse.Namespace) -> "NoReturn":
-def fetch_request(url: str, callback: Any, **kwargs: Any) -> Generator[Callable[..., Any], Any, None]:
+def fetch_request(url: str, callback: Any, **kwargs: Any) -> "Generator[Callable[..., Any], Any, None]":
-def assert_server_running(server: subprocess.Popen[bytes], log_file: Optional[str]) -> None:
+def assert_server_running(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> None:
-def server_is_up(server: subprocess.Popen[bytes], log_file: Optional[str]) -> bool:
+def server_is_up(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> bool:
- method_kwarg_pairs: List[FuncKwargPair],
+ method_kwarg_pairs: "List[FuncKwargPair]",
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-19 03:48:37 +02:00
|
|
|
|
def get_threshold_timestamp(threshold_days: int) -> int:
|
2017-08-19 20:13:44 +02:00
|
|
|
|
# Given number of days, this function returns timestamp corresponding
|
|
|
|
|
# to the time prior to given number of days.
|
2023-11-19 19:45:19 +01:00
|
|
|
|
threshold = datetime.now() - timedelta(days=threshold_days) # noqa: DTZ005
|
2017-08-19 20:13:44 +02:00
|
|
|
|
threshold_timestamp = int(time.mktime(threshold.utctimetuple()))
|
|
|
|
|
return threshold_timestamp
|
2017-08-20 00:07:31 +02:00
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
|
|
|
|
def get_caches_to_be_purged(
|
2024-07-12 02:30:17 +02:00
|
|
|
|
caches_dir: str, caches_in_use: set[str], threshold_days: int
|
|
|
|
|
) -> set[str]:
|
2017-08-20 00:07:31 +02:00
|
|
|
|
# Given a directory containing caches, a list of caches in use
|
|
|
|
|
# and threshold days, this function return a list of caches
|
|
|
|
|
# which can be purged. Remove the cache only if it is:
|
|
|
|
|
# 1: Not in use by the current installation(in dev as well as in prod).
|
2023-12-14 08:28:24 +01:00
|
|
|
|
# 2: Not in use by a deployment not older than `threshold_days` (in prod).
|
2017-08-20 00:07:31 +02:00
|
|
|
|
# 3: Not in use by '/root/zulip'.
|
|
|
|
|
# 4: Not older than `threshold_days`.
|
|
|
|
|
caches_to_purge = set()
|
|
|
|
|
threshold_timestamp = get_threshold_timestamp(threshold_days)
|
|
|
|
|
for cache_dir_base in os.listdir(caches_dir):
|
|
|
|
|
cache_dir = os.path.join(caches_dir, cache_dir_base)
|
|
|
|
|
if cache_dir in caches_in_use:
|
|
|
|
|
# Never purge a cache which is in use.
|
|
|
|
|
continue
|
|
|
|
|
if os.path.getctime(cache_dir) < threshold_timestamp:
|
|
|
|
|
caches_to_purge.add(cache_dir)
|
|
|
|
|
return caches_to_purge
|
2017-08-23 22:44:28 +02:00
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
python: Convert function type annotations to Python 3 style.
Generated by com2ann (slightly patched to avoid also converting
assignment type annotations, which require Python 3.6), followed by
some manual whitespace adjustment, and six fixes for runtime issues:
- def __init__(self, token: Token, parent: Optional[Node]) -> None:
+ def __init__(self, token: Token, parent: "Optional[Node]") -> None:
-def main(options: argparse.Namespace) -> NoReturn:
+def main(options: argparse.Namespace) -> "NoReturn":
-def fetch_request(url: str, callback: Any, **kwargs: Any) -> Generator[Callable[..., Any], Any, None]:
+def fetch_request(url: str, callback: Any, **kwargs: Any) -> "Generator[Callable[..., Any], Any, None]":
-def assert_server_running(server: subprocess.Popen[bytes], log_file: Optional[str]) -> None:
+def assert_server_running(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> None:
-def server_is_up(server: subprocess.Popen[bytes], log_file: Optional[str]) -> bool:
+def server_is_up(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> bool:
- method_kwarg_pairs: List[FuncKwargPair],
+ method_kwarg_pairs: "List[FuncKwargPair]",
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-19 03:48:37 +02:00
|
|
|
|
def purge_unused_caches(
|
2021-02-12 08:19:30 +01:00
|
|
|
|
caches_dir: str,
|
2024-07-12 02:30:17 +02:00
|
|
|
|
caches_in_use: set[str],
|
2021-02-12 08:19:30 +01:00
|
|
|
|
cache_type: str,
|
|
|
|
|
args: argparse.Namespace,
|
python: Convert function type annotations to Python 3 style.
Generated by com2ann (slightly patched to avoid also converting
assignment type annotations, which require Python 3.6), followed by
some manual whitespace adjustment, and six fixes for runtime issues:
- def __init__(self, token: Token, parent: Optional[Node]) -> None:
+ def __init__(self, token: Token, parent: "Optional[Node]") -> None:
-def main(options: argparse.Namespace) -> NoReturn:
+def main(options: argparse.Namespace) -> "NoReturn":
-def fetch_request(url: str, callback: Any, **kwargs: Any) -> Generator[Callable[..., Any], Any, None]:
+def fetch_request(url: str, callback: Any, **kwargs: Any) -> "Generator[Callable[..., Any], Any, None]":
-def assert_server_running(server: subprocess.Popen[bytes], log_file: Optional[str]) -> None:
+def assert_server_running(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> None:
-def server_is_up(server: subprocess.Popen[bytes], log_file: Optional[str]) -> bool:
+def server_is_up(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> bool:
- method_kwarg_pairs: List[FuncKwargPair],
+ method_kwarg_pairs: "List[FuncKwargPair]",
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-19 03:48:37 +02:00
|
|
|
|
) -> None:
|
2023-03-20 19:52:59 +01:00
|
|
|
|
if not os.path.exists(caches_dir):
|
|
|
|
|
return
|
|
|
|
|
|
2020-04-09 21:51:58 +02:00
|
|
|
|
all_caches = {os.path.join(caches_dir, cache) for cache in os.listdir(caches_dir)}
|
2017-09-23 20:25:26 +02:00
|
|
|
|
caches_to_purge = get_caches_to_be_purged(caches_dir, caches_in_use, args.threshold_days)
|
2017-08-23 22:44:28 +02:00
|
|
|
|
caches_to_keep = all_caches - caches_to_purge
|
|
|
|
|
|
2022-01-12 21:52:48 +01:00
|
|
|
|
maybe_perform_purging(
|
2021-02-12 08:19:30 +01:00
|
|
|
|
caches_to_purge, caches_to_keep, cache_type, args.dry_run, args.verbose, args.no_headings
|
|
|
|
|
)
|
2017-09-26 01:12:29 +02:00
|
|
|
|
if args.verbose:
|
|
|
|
|
print("Done!")
|
2017-08-19 16:23:30 +02:00
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
python: Convert function type annotations to Python 3 style.
Generated by com2ann (slightly patched to avoid also converting
assignment type annotations, which require Python 3.6), followed by
some manual whitespace adjustment, and six fixes for runtime issues:
- def __init__(self, token: Token, parent: Optional[Node]) -> None:
+ def __init__(self, token: Token, parent: "Optional[Node]") -> None:
-def main(options: argparse.Namespace) -> NoReturn:
+def main(options: argparse.Namespace) -> "NoReturn":
-def fetch_request(url: str, callback: Any, **kwargs: Any) -> Generator[Callable[..., Any], Any, None]:
+def fetch_request(url: str, callback: Any, **kwargs: Any) -> "Generator[Callable[..., Any], Any, None]":
-def assert_server_running(server: subprocess.Popen[bytes], log_file: Optional[str]) -> None:
+def assert_server_running(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> None:
-def server_is_up(server: subprocess.Popen[bytes], log_file: Optional[str]) -> bool:
+def server_is_up(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> bool:
- method_kwarg_pairs: List[FuncKwargPair],
+ method_kwarg_pairs: "List[FuncKwargPair]",
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-19 03:48:37 +02:00
|
|
|
|
def generate_sha1sum_emoji(zulip_path: str) -> str:
|
2017-08-19 16:23:30 +02:00
|
|
|
|
sha = hashlib.sha1()
|
|
|
|
|
|
2020-07-16 04:59:13 +02:00
|
|
|
|
filenames = [
|
2023-02-22 23:03:47 +01:00
|
|
|
|
"web/images/zulip-emoji/zulip.png",
|
2021-02-12 08:20:45 +01:00
|
|
|
|
"tools/setup/emoji/emoji_map.json",
|
|
|
|
|
"tools/setup/emoji/build_emoji",
|
|
|
|
|
"tools/setup/emoji/emoji_setup_utils.py",
|
|
|
|
|
"tools/setup/emoji/emoji_names.py",
|
2023-09-12 23:13:12 +02:00
|
|
|
|
"zerver/management/data/unified_reactions.json",
|
2020-07-16 04:59:13 +02:00
|
|
|
|
]
|
2017-08-19 16:23:30 +02:00
|
|
|
|
|
|
|
|
|
for filename in filenames:
|
2020-07-16 04:59:13 +02:00
|
|
|
|
file_path = os.path.join(zulip_path, filename)
|
2021-02-12 08:20:45 +01:00
|
|
|
|
with open(file_path, "rb") as reader:
|
2017-08-19 16:23:30 +02:00
|
|
|
|
sha.update(reader.read())
|
|
|
|
|
|
2018-03-13 20:34:31 +01:00
|
|
|
|
# Take into account the version of `emoji-datasource-google` package
|
|
|
|
|
# while generating success stamp.
|
2023-03-20 19:52:59 +01:00
|
|
|
|
with open(os.path.join(zulip_path, "node_modules/emoji-datasource-google/package.json")) as fp:
|
|
|
|
|
emoji_datasource_version = json.load(fp)["version"]
|
2020-02-05 05:45:02 +01:00
|
|
|
|
sha.update(emoji_datasource_version.encode())
|
2017-08-19 16:23:30 +02:00
|
|
|
|
|
|
|
|
|
return sha.hexdigest()
|
2017-08-30 23:58:00 +02:00
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
2022-01-12 21:52:48 +01:00
|
|
|
|
def maybe_perform_purging(
|
2024-07-12 02:30:17 +02:00
|
|
|
|
dirs_to_purge: set[str],
|
|
|
|
|
dirs_to_keep: set[str],
|
python: Convert function type annotations to Python 3 style.
Generated by com2ann (slightly patched to avoid also converting
assignment type annotations, which require Python 3.6), followed by
some manual whitespace adjustment, and six fixes for runtime issues:
- def __init__(self, token: Token, parent: Optional[Node]) -> None:
+ def __init__(self, token: Token, parent: "Optional[Node]") -> None:
-def main(options: argparse.Namespace) -> NoReturn:
+def main(options: argparse.Namespace) -> "NoReturn":
-def fetch_request(url: str, callback: Any, **kwargs: Any) -> Generator[Callable[..., Any], Any, None]:
+def fetch_request(url: str, callback: Any, **kwargs: Any) -> "Generator[Callable[..., Any], Any, None]":
-def assert_server_running(server: subprocess.Popen[bytes], log_file: Optional[str]) -> None:
+def assert_server_running(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> None:
-def server_is_up(server: subprocess.Popen[bytes], log_file: Optional[str]) -> bool:
+def server_is_up(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> bool:
- method_kwarg_pairs: List[FuncKwargPair],
+ method_kwarg_pairs: "List[FuncKwargPair]",
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-19 03:48:37 +02:00
|
|
|
|
dir_type: str,
|
|
|
|
|
dry_run: bool,
|
|
|
|
|
verbose: bool,
|
|
|
|
|
no_headings: bool,
|
|
|
|
|
) -> None:
|
2017-08-30 23:58:00 +02:00
|
|
|
|
if dry_run:
|
|
|
|
|
print("Performing a dry run...")
|
2019-09-29 01:49:13 +02:00
|
|
|
|
if not no_headings:
|
2021-09-22 06:03:56 +02:00
|
|
|
|
print(f"Cleaning unused {dir_type}s...")
|
2017-08-30 23:58:00 +02:00
|
|
|
|
|
|
|
|
|
for directory in dirs_to_purge:
|
2017-09-23 21:15:13 +02:00
|
|
|
|
if verbose:
|
2021-09-22 06:03:56 +02:00
|
|
|
|
print(f"Cleaning unused {dir_type}: {directory}")
|
2017-08-30 23:58:00 +02:00
|
|
|
|
if not dry_run:
|
2019-02-26 21:47:35 +01:00
|
|
|
|
run_as_root(["rm", "-rf", directory])
|
2017-08-30 23:58:00 +02:00
|
|
|
|
|
|
|
|
|
for directory in dirs_to_keep:
|
2017-09-23 21:15:13 +02:00
|
|
|
|
if verbose:
|
2021-09-22 06:03:56 +02:00
|
|
|
|
print(f"Keeping used {dir_type}: {directory}")
|
2018-05-28 21:55:07 +02:00
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
2019-08-30 00:14:43 +02:00
|
|
|
|
@functools.lru_cache(None)
|
2024-07-12 02:30:17 +02:00
|
|
|
|
def parse_os_release() -> dict[str, str]:
|
2019-08-25 01:23:14 +02:00
|
|
|
|
"""
|
|
|
|
|
Example of the useful subset of the data:
|
|
|
|
|
{
|
|
|
|
|
'ID': 'ubuntu',
|
|
|
|
|
'VERSION_ID': '18.04',
|
|
|
|
|
'NAME': 'Ubuntu',
|
|
|
|
|
'VERSION': '18.04.3 LTS (Bionic Beaver)',
|
|
|
|
|
'PRETTY_NAME': 'Ubuntu 18.04.3 LTS',
|
|
|
|
|
}
|
|
|
|
|
|
2021-06-24 21:01:35 +02:00
|
|
|
|
VERSION_CODENAME (e.g. 'bionic') is nice and readable to Ubuntu
|
|
|
|
|
developers, but we avoid using it, as it is not available on
|
|
|
|
|
RHEL-based platforms.
|
2019-08-25 01:23:14 +02:00
|
|
|
|
"""
|
2024-07-12 02:30:17 +02:00
|
|
|
|
distro_info: dict[str, str] = {}
|
2021-02-12 08:20:45 +01:00
|
|
|
|
with open("/etc/os-release") as fp:
|
2019-08-25 01:23:14 +02:00
|
|
|
|
for line in fp:
|
|
|
|
|
line = line.strip()
|
2021-02-12 08:20:45 +01:00
|
|
|
|
if not line or line.startswith("#"):
|
2019-08-25 01:23:14 +02:00
|
|
|
|
# The line may be blank or a comment, see:
|
|
|
|
|
# https://www.freedesktop.org/software/systemd/man/os-release.html
|
2018-07-13 13:41:08 +02:00
|
|
|
|
continue
|
2021-02-12 08:20:45 +01:00
|
|
|
|
k, v = line.split("=", 1)
|
2019-08-25 01:23:14 +02:00
|
|
|
|
[distro_info[k]] = shlex.split(v)
|
2018-05-28 21:55:07 +02:00
|
|
|
|
return distro_info
|
2018-06-14 14:19:27 +02:00
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
2019-08-30 00:14:43 +02:00
|
|
|
|
@functools.lru_cache(None)
|
2024-07-12 02:30:17 +02:00
|
|
|
|
def os_families() -> set[str]:
|
2019-08-30 00:14:43 +02:00
|
|
|
|
"""
|
|
|
|
|
Known families:
|
|
|
|
|
debian (includes: debian, ubuntu)
|
|
|
|
|
ubuntu (includes: ubuntu)
|
|
|
|
|
fedora (includes: fedora, rhel, centos)
|
|
|
|
|
rhel (includes: rhel, centos)
|
|
|
|
|
centos (includes: centos)
|
|
|
|
|
"""
|
|
|
|
|
distro_info = parse_os_release()
|
|
|
|
|
return {distro_info["ID"], *distro_info.get("ID_LIKE", "").split()}
|
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
2022-06-28 00:43:57 +02:00
|
|
|
|
def get_tzdata_zi() -> IO[str]:
|
|
|
|
|
for path in zoneinfo.TZPATH:
|
|
|
|
|
filename = os.path.join(path, "tzdata.zi")
|
|
|
|
|
if os.path.exists(filename):
|
2024-11-19 01:49:34 +01:00
|
|
|
|
return open(filename)
|
2022-12-11 10:48:05 +01:00
|
|
|
|
raise RuntimeError("Missing time zone data (tzdata.zi)")
|
2022-06-28 00:43:57 +02:00
|
|
|
|
|
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
def files_and_string_digest(filenames: Sequence[str], extra_strings: Sequence[str]) -> str:
|
2020-04-22 23:03:18 +02:00
|
|
|
|
# see is_digest_obsolete for more context
|
2018-06-14 14:19:27 +02:00
|
|
|
|
sha1sum = hashlib.sha1()
|
2020-04-22 23:03:18 +02:00
|
|
|
|
for fn in filenames:
|
2021-02-12 08:20:45 +01:00
|
|
|
|
with open(fn, "rb") as file_to_hash:
|
2018-06-14 14:19:27 +02:00
|
|
|
|
sha1sum.update(file_to_hash.read())
|
|
|
|
|
|
2020-04-22 23:03:18 +02:00
|
|
|
|
for extra_string in extra_strings:
|
2021-08-02 23:20:39 +02:00
|
|
|
|
sha1sum.update(extra_string.encode())
|
2018-06-22 12:56:25 +02:00
|
|
|
|
|
2020-04-20 14:44:48 +02:00
|
|
|
|
return sha1sum.hexdigest()
|
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
|
|
|
|
def is_digest_obsolete(
|
|
|
|
|
hash_name: str, filenames: Sequence[str], extra_strings: Sequence[str] = []
|
|
|
|
|
) -> bool:
|
|
|
|
|
"""
|
2020-04-22 23:03:18 +02:00
|
|
|
|
In order to determine if we need to run some
|
|
|
|
|
process, we calculate a digest of the important
|
|
|
|
|
files and strings whose respective contents
|
|
|
|
|
or values may indicate such a need.
|
|
|
|
|
|
|
|
|
|
filenames = files we should hash the contents of
|
|
|
|
|
extra_strings = strings we should hash directly
|
|
|
|
|
|
|
|
|
|
Grep for callers to see examples of how this is used.
|
|
|
|
|
|
|
|
|
|
To elaborate on extra_strings, they will typically
|
|
|
|
|
be things like:
|
|
|
|
|
|
|
|
|
|
- package versions (that we import)
|
|
|
|
|
- settings values (that we stringify with
|
|
|
|
|
json, deterministically)
|
2021-02-12 08:19:30 +01:00
|
|
|
|
"""
|
2020-04-20 15:16:16 +02:00
|
|
|
|
last_hash_path = os.path.join(get_dev_uuid_var_path(), hash_name)
|
|
|
|
|
try:
|
|
|
|
|
with open(last_hash_path) as f:
|
|
|
|
|
old_hash = f.read()
|
|
|
|
|
except FileNotFoundError:
|
|
|
|
|
# This is normal for a fresh checkout--a missing
|
|
|
|
|
# digest is an obsolete digest.
|
|
|
|
|
return True
|
|
|
|
|
|
2020-04-22 23:03:18 +02:00
|
|
|
|
new_hash = files_and_string_digest(filenames, extra_strings)
|
2020-04-20 14:44:48 +02:00
|
|
|
|
|
2020-04-20 15:16:16 +02:00
|
|
|
|
return new_hash != old_hash
|
2018-06-14 14:19:27 +02:00
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
|
|
|
|
def write_new_digest(
|
|
|
|
|
hash_name: str, filenames: Sequence[str], extra_strings: Sequence[str] = []
|
|
|
|
|
) -> None:
|
2020-04-20 15:16:16 +02:00
|
|
|
|
hash_path = os.path.join(get_dev_uuid_var_path(), hash_name)
|
2020-04-22 23:03:18 +02:00
|
|
|
|
new_hash = files_and_string_digest(filenames, extra_strings)
|
2021-02-12 08:20:45 +01:00
|
|
|
|
with open(hash_path, "w") as f:
|
2020-04-20 15:16:16 +02:00
|
|
|
|
f.write(new_hash)
|
|
|
|
|
|
|
|
|
|
# Be a little verbose here--our callers ensure we
|
|
|
|
|
# only write new digests when things have changed, and
|
|
|
|
|
# making this system more transparent to developers
|
|
|
|
|
# can help them troubleshoot provisioning glitches.
|
2021-02-12 08:20:45 +01:00
|
|
|
|
print("New digest written to: " + hash_path)
|
2018-11-15 10:53:34 +01:00
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
2018-11-15 10:53:34 +01:00
|
|
|
|
def is_root() -> bool:
|
2021-02-12 08:20:45 +01:00
|
|
|
|
if "posix" in os.name and os.geteuid() == 0:
|
2018-11-15 10:53:34 +01:00
|
|
|
|
return True
|
|
|
|
|
return False
|
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
2024-07-12 02:30:17 +02:00
|
|
|
|
def run_as_root(args: list[str], **kwargs: Any) -> None:
|
2021-02-12 08:20:45 +01:00
|
|
|
|
sudo_args = kwargs.pop("sudo_args", [])
|
2019-02-26 20:20:46 +01:00
|
|
|
|
if not is_root():
|
2020-10-30 00:49:51 +01:00
|
|
|
|
args = ["sudo", *sudo_args, "--", *args]
|
2019-02-26 20:20:46 +01:00
|
|
|
|
run(args, **kwargs)
|
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
2018-11-19 19:50:25 +01:00
|
|
|
|
def assert_not_running_as_root() -> None:
|
2018-11-15 10:53:34 +01:00
|
|
|
|
script_name = os.path.abspath(sys.argv[0])
|
|
|
|
|
if is_root():
|
2019-03-04 23:21:44 +01:00
|
|
|
|
pwent = get_zulip_pwent()
|
2021-02-12 08:19:30 +01:00
|
|
|
|
msg = (
|
2024-03-21 03:43:05 +01:00
|
|
|
|
f"{os.path.basename(script_name)} should not be run as root. Use `su {pwent.pw_name}` to switch to the 'zulip'\n"
|
|
|
|
|
f"user before rerunning this, or use \n su {pwent.pw_name} -c '{script_name} ...'\n"
|
2021-02-12 08:19:30 +01:00
|
|
|
|
"to switch users and run this as a single command."
|
2024-03-21 03:43:05 +01:00
|
|
|
|
)
|
2018-11-15 10:53:34 +01:00
|
|
|
|
print(msg)
|
|
|
|
|
sys.exit(1)
|
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
|
|
|
|
def assert_running_as_root(strip_lib_from_paths: bool = False) -> None:
|
2018-11-15 10:53:34 +01:00
|
|
|
|
script_name = os.path.abspath(sys.argv[0])
|
|
|
|
|
# Since these Python scripts are run inside a thin shell wrapper,
|
|
|
|
|
# we need to replace the paths in order to ensure we instruct
|
|
|
|
|
# users to (re)run the right command.
|
|
|
|
|
if strip_lib_from_paths:
|
|
|
|
|
script_name = script_name.replace("scripts/lib/upgrade", "scripts/upgrade")
|
|
|
|
|
if not is_root():
|
2021-09-22 06:03:56 +02:00
|
|
|
|
print(f"{script_name} must be run as root.")
|
2018-11-15 10:53:34 +01:00
|
|
|
|
sys.exit(1)
|
2018-12-15 07:05:27 +01:00
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
2024-03-05 17:16:31 +01:00
|
|
|
|
@overload
|
|
|
|
|
def get_config(
|
2024-03-12 19:20:51 +01:00
|
|
|
|
config_file: configparser.RawConfigParser,
|
|
|
|
|
section: str,
|
|
|
|
|
key: str,
|
2024-03-05 17:22:49 +01:00
|
|
|
|
default_value: None = None,
|
2024-07-12 02:30:23 +02:00
|
|
|
|
) -> str | None: ...
|
2024-03-12 19:20:51 +01:00
|
|
|
|
@overload
|
|
|
|
|
def get_config(
|
|
|
|
|
config_file: configparser.RawConfigParser,
|
|
|
|
|
section: str,
|
|
|
|
|
key: str,
|
|
|
|
|
default_value: str,
|
2024-03-05 17:16:31 +01:00
|
|
|
|
) -> str: ...
|
|
|
|
|
@overload
|
|
|
|
|
def get_config(
|
|
|
|
|
config_file: configparser.RawConfigParser, section: str, key: str, default_value: bool
|
|
|
|
|
) -> bool: ...
|
python: Convert function type annotations to Python 3 style.
Generated by com2ann (slightly patched to avoid also converting
assignment type annotations, which require Python 3.6), followed by
some manual whitespace adjustment, and six fixes for runtime issues:
- def __init__(self, token: Token, parent: Optional[Node]) -> None:
+ def __init__(self, token: Token, parent: "Optional[Node]") -> None:
-def main(options: argparse.Namespace) -> NoReturn:
+def main(options: argparse.Namespace) -> "NoReturn":
-def fetch_request(url: str, callback: Any, **kwargs: Any) -> Generator[Callable[..., Any], Any, None]:
+def fetch_request(url: str, callback: Any, **kwargs: Any) -> "Generator[Callable[..., Any], Any, None]":
-def assert_server_running(server: subprocess.Popen[bytes], log_file: Optional[str]) -> None:
+def assert_server_running(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> None:
-def server_is_up(server: subprocess.Popen[bytes], log_file: Optional[str]) -> bool:
+def server_is_up(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> bool:
- method_kwarg_pairs: List[FuncKwargPair],
+ method_kwarg_pairs: "List[FuncKwargPair]",
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-19 03:48:37 +02:00
|
|
|
|
def get_config(
|
|
|
|
|
config_file: configparser.RawConfigParser,
|
|
|
|
|
section: str,
|
|
|
|
|
key: str,
|
2024-07-12 02:30:23 +02:00
|
|
|
|
default_value: str | bool | None = None,
|
|
|
|
|
) -> str | bool | None:
|
2022-01-20 05:14:57 +01:00
|
|
|
|
if config_file.has_option(section, key):
|
|
|
|
|
val = config_file.get(section, key)
|
2024-03-05 17:16:31 +01:00
|
|
|
|
if isinstance(default_value, bool):
|
|
|
|
|
# This list is parallel to puppet/zulip/lib/puppet/functions/zulipconf.rb
|
|
|
|
|
return val.lower() in ["1", "y", "t", "true", "yes", "enable", "enabled"]
|
|
|
|
|
return val
|
2022-01-20 05:14:57 +01:00
|
|
|
|
return default_value
|
|
|
|
|
|
|
|
|
|
|
2018-12-15 07:05:27 +01:00
|
|
|
|
def get_config_file() -> configparser.RawConfigParser:
|
|
|
|
|
config_file = configparser.RawConfigParser()
|
|
|
|
|
config_file.read("/etc/zulip/zulip.conf")
|
|
|
|
|
return config_file
|
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
2024-07-12 02:30:17 +02:00
|
|
|
|
def get_deploy_options(config_file: configparser.RawConfigParser) -> list[str]:
|
2022-04-27 02:10:28 +02:00
|
|
|
|
return shlex.split(get_config(config_file, "deployment", "deploy_options", ""))
|
2019-06-14 22:56:34 +02:00
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
2021-04-11 19:59:48 +02:00
|
|
|
|
def run_psql_as_postgres(
|
2021-05-25 05:44:38 +02:00
|
|
|
|
config_file: configparser.RawConfigParser,
|
2021-04-11 19:59:48 +02:00
|
|
|
|
sql_query: str,
|
|
|
|
|
) -> None:
|
2021-05-25 05:44:38 +02:00
|
|
|
|
dbname = get_config(config_file, "postgresql", "database_name", "zulip")
|
2022-04-27 02:10:28 +02:00
|
|
|
|
subcmd = shlex.join(["psql", "-v", "ON_ERROR_STOP=1", "-d", dbname, "-c", sql_query])
|
2021-04-11 19:59:48 +02:00
|
|
|
|
subprocess.check_call(["su", "postgres", "-c", subcmd])
|
|
|
|
|
|
|
|
|
|
|
2024-07-12 02:30:17 +02:00
|
|
|
|
def get_tornado_ports(config_file: configparser.RawConfigParser) -> list[int]:
|
2020-09-15 02:01:33 +02:00
|
|
|
|
ports = []
|
|
|
|
|
if config_file.has_section("tornado_sharding"):
|
2022-09-01 01:11:27 +02:00
|
|
|
|
ports = sorted(
|
|
|
|
|
{
|
2022-09-22 22:09:34 +02:00
|
|
|
|
int(port)
|
2022-09-01 01:11:27 +02:00
|
|
|
|
for key in config_file.options("tornado_sharding")
|
2024-09-03 19:42:14 +02:00
|
|
|
|
for port in key.removesuffix("_regex").split("_")
|
2022-09-01 01:11:27 +02:00
|
|
|
|
}
|
|
|
|
|
)
|
2020-09-15 02:01:33 +02:00
|
|
|
|
if not ports:
|
|
|
|
|
ports = [9800]
|
|
|
|
|
return ports
|
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
2019-06-14 22:56:34 +02:00
|
|
|
|
def get_or_create_dev_uuid_var_path(path: str) -> str:
|
2021-09-22 06:03:56 +02:00
|
|
|
|
absolute_path = f"{get_dev_uuid_var_path()}/{path}"
|
2019-06-14 22:56:34 +02:00
|
|
|
|
os.makedirs(absolute_path, exist_ok=True)
|
|
|
|
|
return absolute_path
|
2019-06-18 01:09:07 +02:00
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
2019-07-06 06:03:08 +02:00
|
|
|
|
def is_vagrant_env_host(path: str) -> bool:
|
2021-02-12 08:20:45 +01:00
|
|
|
|
return ".vagrant" in os.listdir(path)
|
2019-07-06 06:03:08 +02:00
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
2021-06-11 22:58:09 +02:00
|
|
|
|
def has_application_server(once: bool = False) -> bool:
|
|
|
|
|
if once:
|
|
|
|
|
return os.path.exists("/etc/supervisor/conf.d/zulip/zulip-once.conf")
|
2021-05-14 03:08:38 +02:00
|
|
|
|
return (
|
|
|
|
|
# Current path
|
|
|
|
|
os.path.exists("/etc/supervisor/conf.d/zulip/zulip.conf")
|
|
|
|
|
# Old path, relevant for upgrades
|
|
|
|
|
or os.path.exists("/etc/supervisor/conf.d/zulip.conf")
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def has_process_fts_updates() -> bool:
|
|
|
|
|
return (
|
|
|
|
|
# Current path
|
|
|
|
|
os.path.exists("/etc/supervisor/conf.d/zulip/zulip_db.conf")
|
|
|
|
|
# Old path, relevant for upgrades
|
|
|
|
|
or os.path.exists("/etc/supervisor/conf.d/zulip_db.conf")
|
|
|
|
|
)
|
2021-04-27 20:48:19 +02:00
|
|
|
|
|
|
|
|
|
|
2020-06-27 02:37:49 +02:00
|
|
|
|
def deport(netloc: str) -> str:
|
|
|
|
|
"""Remove the port from a hostname:port string. Brackets on a literal
|
|
|
|
|
IPv6 address are included."""
|
|
|
|
|
r = SplitResult("", netloc, "", "", "")
|
|
|
|
|
assert r.hostname is not None
|
|
|
|
|
return "[" + r.hostname + "]" if ":" in r.hostname else r.hostname
|
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
2021-12-13 20:39:56 +01:00
|
|
|
|
def start_arg_parser(action: str, add_help: bool = False) -> argparse.ArgumentParser:
|
|
|
|
|
parser = argparse.ArgumentParser(add_help=add_help)
|
|
|
|
|
parser.add_argument("--fill-cache", action="store_true", help="Fill the memcached caches")
|
2022-10-14 00:35:30 +02:00
|
|
|
|
parser.add_argument(
|
|
|
|
|
"--skip-checks", action="store_true", help="Skip syntax and database checks"
|
|
|
|
|
)
|
2024-10-08 17:21:34 +02:00
|
|
|
|
which_services = parser.add_mutually_exclusive_group()
|
|
|
|
|
which_services.add_argument(
|
2024-02-08 22:04:07 +01:00
|
|
|
|
"--skip-client-reloads",
|
|
|
|
|
action="store_true",
|
|
|
|
|
help="Do not send reload events to web clients",
|
|
|
|
|
)
|
2024-10-08 17:21:34 +02:00
|
|
|
|
which_services.add_argument(
|
|
|
|
|
"--only-django",
|
|
|
|
|
action="store_true",
|
|
|
|
|
help=f"Only {action} Django (not Tornado or workers)",
|
|
|
|
|
)
|
2021-12-13 20:39:56 +01:00
|
|
|
|
if action == "restart":
|
|
|
|
|
parser.add_argument(
|
|
|
|
|
"--less-graceful",
|
|
|
|
|
action="store_true",
|
|
|
|
|
help="Restart with more concern for expediency than minimizing availability interruption",
|
|
|
|
|
)
|
|
|
|
|
return parser
|
|
|
|
|
|
|
|
|
|
|
2024-07-12 02:30:17 +02:00
|
|
|
|
def listening_publicly(port: int) -> list[str]:
|
2021-12-07 21:55:17 +01:00
|
|
|
|
filter = f"sport = :{port} and not src 127.0.0.1:{port} and not src [::1]:{port}"
|
|
|
|
|
# Parse lines that look like this:
|
|
|
|
|
# tcp LISTEN 0 128 0.0.0.0:25672 0.0.0.0:*
|
|
|
|
|
lines = (
|
|
|
|
|
subprocess.check_output(
|
|
|
|
|
["/bin/ss", "-Hnl", filter],
|
2022-04-27 01:45:36 +02:00
|
|
|
|
text=True,
|
2021-12-07 21:55:17 +01:00
|
|
|
|
# Hosts with IPv6 disabled will get "RTNETLINK answers: Invalid
|
|
|
|
|
# argument"; eat stderr to hide that
|
|
|
|
|
stderr=subprocess.DEVNULL,
|
|
|
|
|
)
|
|
|
|
|
.strip()
|
|
|
|
|
.splitlines()
|
|
|
|
|
)
|
|
|
|
|
return [line.split()[4] for line in lines]
|
|
|
|
|
|
|
|
|
|
|
2024-05-22 06:22:22 +02:00
|
|
|
|
def atomic_nagios_write(
|
|
|
|
|
name: str,
|
|
|
|
|
status: Literal["ok", "warning", "critical", "unknown"],
|
2024-07-12 02:30:23 +02:00
|
|
|
|
message: str | None = None,
|
|
|
|
|
event_time: int | None = None,
|
2024-05-22 06:22:22 +02:00
|
|
|
|
) -> int:
|
|
|
|
|
if message is None:
|
|
|
|
|
message = status
|
|
|
|
|
if event_time is None:
|
|
|
|
|
event_time = int(time.time())
|
|
|
|
|
if status == "ok":
|
|
|
|
|
status_int = 0
|
|
|
|
|
elif status == "warning":
|
|
|
|
|
status_int = 1
|
|
|
|
|
elif status == "critical":
|
|
|
|
|
status_int = 2
|
|
|
|
|
elif status == "unknown":
|
|
|
|
|
status_int = 3
|
|
|
|
|
|
|
|
|
|
path = "/var/lib/nagios_state/" + name
|
|
|
|
|
with open(path + ".tmp", "w") as fh:
|
|
|
|
|
fh.write("|".join([str(event_time), str(status_int), status, message]) + "\n")
|
|
|
|
|
os.rename(path + ".tmp", path)
|
|
|
|
|
return status_int
|
|
|
|
|
|
|
|
|
|
|
2021-02-12 08:20:45 +01:00
|
|
|
|
if __name__ == "__main__":
|
2019-06-18 01:09:07 +02:00
|
|
|
|
cmd = sys.argv[1]
|
2021-02-12 08:20:45 +01:00
|
|
|
|
if cmd == "make_deploy_path":
|
2019-06-18 01:09:07 +02:00
|
|
|
|
print(make_deploy_path())
|
2021-02-12 08:20:45 +01:00
|
|
|
|
elif cmd == "get_dev_uuid":
|
2019-06-18 01:09:07 +02:00
|
|
|
|
print(get_dev_uuid_var_path())
|