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
|
2016-01-10 20:58:11 +01:00
|
|
|
import datetime
|
2019-08-30 00:14:43 +02:00
|
|
|
import functools
|
2017-08-19 16:23:30 +02:00
|
|
|
import hashlib
|
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
|
2017-06-21 14:32:22 +02:00
|
|
|
import re
|
2018-07-18 23:26:44 +02:00
|
|
|
import shlex
|
2016-01-10 20:58:11 +01:00
|
|
|
import shutil
|
2016-04-06 17:15:31 +02:00
|
|
|
import subprocess
|
2016-01-10 20:58:11 +01:00
|
|
|
import sys
|
2018-07-27 01:23:27 +02:00
|
|
|
import tempfile
|
2016-01-10 20:58:11 +01:00
|
|
|
import time
|
2017-08-19 16:23:30 +02:00
|
|
|
import json
|
2017-10-18 04:14:06 +02:00
|
|
|
import uuid
|
2018-12-15 07:05:27 +01:00
|
|
|
import configparser
|
2013-02-19 02:36:59 +01:00
|
|
|
|
2019-07-23 23:58:11 +02:00
|
|
|
from typing import Sequence, Set, Any, Dict, List
|
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")
|
|
|
|
TIMESTAMP_FORMAT = '%Y-%m-%d-%H-%M-%S'
|
2013-06-05 00:21:47 +02:00
|
|
|
|
|
|
|
# Color codes
|
|
|
|
OKBLUE = '\033[94m'
|
|
|
|
OKGREEN = '\033[92m'
|
|
|
|
WARNING = '\033[93m'
|
|
|
|
FAIL = '\033[91m'
|
|
|
|
ENDC = '\033[0m'
|
2017-01-11 17:07:12 +01:00
|
|
|
BLACKONYELLOW = '\x1b[0;30;43m'
|
|
|
|
WHITEONRED = '\x1b[0;37;41m'
|
2017-07-06 06:09:45 +02:00
|
|
|
BOLDRED = '\x1B[1;31m'
|
|
|
|
|
|
|
|
GREEN = '\x1b[32m'
|
|
|
|
YELLOW = '\x1b[33m'
|
|
|
|
BLUE = '\x1b[34m'
|
|
|
|
MAGENTA = '\x1b[35m'
|
|
|
|
CYAN = '\x1b[36m'
|
2013-11-13 20:57:31 +01:00
|
|
|
|
2018-07-27 01:23:27 +02:00
|
|
|
def overwrite_symlink(src, dst):
|
|
|
|
# type: (str, str) -> None
|
|
|
|
while True:
|
|
|
|
tmp = tempfile.mktemp(
|
|
|
|
prefix='.' + os.path.basename(dst) + '.',
|
2019-11-13 10:06:02 +01:00
|
|
|
dir=os.path.dirname(dst)) # type: ignore # https://github.com/python/typeshed/issues/3449
|
2018-07-27 01:23:27 +02:00
|
|
|
try:
|
|
|
|
os.symlink(src, tmp)
|
|
|
|
except FileExistsError:
|
|
|
|
continue
|
|
|
|
break
|
|
|
|
try:
|
|
|
|
os.rename(tmp, dst)
|
|
|
|
except Exception:
|
|
|
|
os.remove(tmp)
|
|
|
|
raise
|
|
|
|
|
2017-09-23 20:42:53 +02:00
|
|
|
def parse_cache_script_args(description):
|
2018-05-10 18:54:59 +02:00
|
|
|
# type: (str) -> argparse.Namespace
|
2017-09-23 20:42:53 +02:00
|
|
|
parser = argparse.ArgumentParser(description=description)
|
|
|
|
|
|
|
|
parser.add_argument(
|
|
|
|
"--threshold", dest="threshold_days", type=int, default=14,
|
|
|
|
nargs="?", metavar="<days>", help="Any cache which is not in "
|
|
|
|
"use by a deployment not older than threshold days(current "
|
|
|
|
"installation in dev) and older than threshold days will be "
|
|
|
|
"deleted. (defaults to 14)")
|
|
|
|
parser.add_argument(
|
|
|
|
"--dry-run", dest="dry_run", action="store_true",
|
|
|
|
help="If specified then script will only print the caches "
|
|
|
|
"that it will delete/keep back. It will not delete any cache.")
|
|
|
|
parser.add_argument(
|
|
|
|
"--verbose", dest="verbose", action="store_true",
|
|
|
|
help="If specified then script will print a detailed report "
|
|
|
|
"of what is being will deleted/kept back.")
|
2019-09-29 01:49:13 +02:00
|
|
|
parser.add_argument(
|
|
|
|
"--no-print-headings", dest="no_headings", action="store_true",
|
|
|
|
help="If specified then script will not print headings for "
|
|
|
|
"what will be deleted/kept back.")
|
2017-09-23 20:42:53 +02:00
|
|
|
|
|
|
|
args = parser.parse_args()
|
|
|
|
args.verbose |= args.dry_run # Always print a detailed report in case of dry run.
|
|
|
|
return args
|
|
|
|
|
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(
|
|
|
|
os.path.normpath(os.path.join(os.path.dirname(__file__), "..", ".."))
|
|
|
|
)
|
2019-02-07 01:32:34 +01:00
|
|
|
|
2017-06-21 14:32:22 +02:00
|
|
|
def get_deployment_version(extract_path):
|
|
|
|
# type: (str) -> str
|
|
|
|
version = '0.0.0'
|
|
|
|
for item in os.listdir(extract_path):
|
|
|
|
item_path = os.path.join(extract_path, item)
|
|
|
|
if item.startswith('zulip-server') and os.path.isdir(item_path):
|
|
|
|
with open(os.path.join(item_path, 'version.py')) as f:
|
|
|
|
result = re.search('ZULIP_VERSION = "(.*)"', f.read())
|
|
|
|
if result:
|
|
|
|
version = result.groups()[0]
|
|
|
|
break
|
|
|
|
return version
|
|
|
|
|
|
|
|
def is_invalid_upgrade(current_version, new_version):
|
|
|
|
# type: (str, str) -> bool
|
|
|
|
if new_version > '1.4.3' and current_version <= '1.3.10':
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
2016-07-12 16:55:20 +02:00
|
|
|
def subprocess_text_output(args):
|
2016-07-12 17:08:35 +02:00
|
|
|
# type: (Sequence[str]) -> str
|
2016-07-12 16:55:20 +02:00
|
|
|
return subprocess.check_output(args, universal_newlines=True).strip()
|
|
|
|
|
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
|
|
|
|
2019-01-16 03:17:33 +01:00
|
|
|
def su_to_zulip(save_suid=False):
|
|
|
|
# type: (bool) -> 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)
|
2019-02-07 01:41:10 +01:00
|
|
|
os.environ['HOME'] = pwent.pw_dir
|
2013-11-13 21:54:30 +01:00
|
|
|
|
2013-11-13 20:57:31 +01:00
|
|
|
def make_deploy_path():
|
2016-07-12 17:08:35 +02:00
|
|
|
# type: () -> str
|
2013-11-13 20:57:31 +01:00
|
|
|
timestamp = datetime.datetime.now().strftime(TIMESTAMP_FORMAT)
|
|
|
|
return os.path.join(DEPLOYMENTS_DIR, timestamp)
|
|
|
|
|
2019-06-11 18:36:27 +02:00
|
|
|
TEMPLATE_DATABASE_DIR = "test-backend/databases"
|
2017-10-18 04:14:06 +02:00
|
|
|
def get_dev_uuid_var_path(create_if_missing=False):
|
|
|
|
# type: (bool) -> 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.
|
2019-03-04 23:32:06 +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
|
|
|
|
|
2016-01-10 20:58:11 +01:00
|
|
|
def get_deployment_lock(error_rerun_script):
|
2016-07-12 17:08:35 +02:00
|
|
|
# type: (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:
|
2017-01-24 05:50:04 +01:00
|
|
|
print(WARNING + "Another deployment in progress; waiting for lock... " +
|
|
|
|
"(If no deployment is running, rmdir %s)" % (LOCK_DIR,) + ENDC)
|
2016-01-10 21:03:02 +01:00
|
|
|
sys.stdout.flush()
|
2016-01-10 20:58:11 +01:00
|
|
|
time.sleep(3)
|
|
|
|
|
|
|
|
if not got_lock:
|
2017-01-24 05:50:04 +01:00
|
|
|
print(FAIL + "Deployment already in progress. Please run\n" +
|
|
|
|
" %s\n" % (error_rerun_script,) +
|
|
|
|
"manually when the previous deployment finishes, or run\n" +
|
|
|
|
" rmdir %s\n" % (LOCK_DIR,) +
|
|
|
|
"if the previous deployment crashed." +
|
|
|
|
ENDC)
|
2016-01-10 20:58:11 +01:00
|
|
|
sys.exit(1)
|
|
|
|
|
|
|
|
def release_deployment_lock():
|
2016-07-12 17:08:35 +02:00
|
|
|
# type: () -> None
|
2016-01-10 20:58:11 +01:00
|
|
|
shutil.rmtree(LOCK_DIR)
|
2016-04-06 17:15:31 +02:00
|
|
|
|
2016-08-18 13:50:36 +02:00
|
|
|
def run(args, **kwargs):
|
2017-03-03 20:30:49 +01:00
|
|
|
# type: (Sequence[str], **Any) -> None
|
2016-04-06 17:15:31 +02:00
|
|
|
# Output what we're doing in the `set -x` style
|
2018-07-18 23:26:44 +02:00
|
|
|
print("+ %s" % (" ".join(map(shlex.quote, args)),))
|
2016-09-23 11:27:14 +02:00
|
|
|
|
2016-10-27 21:07:55 +02:00
|
|
|
try:
|
|
|
|
subprocess.check_call(args, **kwargs)
|
|
|
|
except subprocess.CalledProcessError:
|
2017-01-11 17:07:12 +01:00
|
|
|
print()
|
2018-07-18 23:26:44 +02:00
|
|
|
print(WHITEONRED + "Error running a subcommand of %s: %s" %
|
|
|
|
(sys.argv[0], " ".join(map(shlex.quote, args))) +
|
2017-01-24 05:50:04 +01:00
|
|
|
ENDC)
|
|
|
|
print(WHITEONRED + "Actual error output for the subcommand is just above this." +
|
|
|
|
ENDC)
|
2017-01-11 17:07:12 +01:00
|
|
|
print()
|
2016-10-27 21:07:55 +02:00
|
|
|
raise
|
2017-08-18 06:36:37 +02:00
|
|
|
|
|
|
|
def log_management_command(cmd, log_path):
|
2018-05-10 18:54:59 +02:00
|
|
|
# type: (str, 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)
|
|
|
|
|
|
|
|
logger.info("Ran '%s'" % (cmd,))
|
2017-08-18 19:14:09 +02:00
|
|
|
|
|
|
|
def get_environment():
|
2018-05-10 18:54:59 +02:00
|
|
|
# type: () -> str
|
2017-08-18 19:14:09 +02:00
|
|
|
if os.path.exists(DEPLOYMENTS_DIR):
|
|
|
|
return "prod"
|
|
|
|
if os.environ.get("TRAVIS"):
|
|
|
|
return "travis"
|
|
|
|
return "dev"
|
2017-08-18 20:34:00 +02:00
|
|
|
|
|
|
|
def get_recent_deployments(threshold_days):
|
2018-05-10 18:54:59 +02:00
|
|
|
# type: (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()
|
|
|
|
threshold_date = datetime.datetime.now() - datetime.timedelta(days=threshold_days)
|
|
|
|
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:
|
|
|
|
date = datetime.datetime.strptime(dir_name, TIMESTAMP_FORMAT)
|
|
|
|
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
|
|
|
|
|
|
|
def get_threshold_timestamp(threshold_days):
|
|
|
|
# type: (int) -> int
|
|
|
|
# Given number of days, this function returns timestamp corresponding
|
|
|
|
# to the time prior to given number of days.
|
|
|
|
threshold = datetime.datetime.now() - datetime.timedelta(days=threshold_days)
|
|
|
|
threshold_timestamp = int(time.mktime(threshold.utctimetuple()))
|
|
|
|
return threshold_timestamp
|
2017-08-20 00:07:31 +02:00
|
|
|
|
|
|
|
def get_caches_to_be_purged(caches_dir, caches_in_use, threshold_days):
|
2018-05-10 18:54:59 +02:00
|
|
|
# type: (str, Set[str], 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).
|
|
|
|
# 2: Not in use by a deployment not older than `threshold_days`(in prod).
|
|
|
|
# 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
|
|
|
|
2017-09-23 21:21:55 +02:00
|
|
|
def purge_unused_caches(caches_dir, caches_in_use, cache_type, args):
|
2018-05-10 18:54:59 +02:00
|
|
|
# type: (str, Set[str], str, argparse.Namespace) -> None
|
2017-08-23 22:44:28 +02:00
|
|
|
all_caches = set([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
|
|
|
|
|
2017-09-23 21:15:13 +02:00
|
|
|
may_be_perform_purging(
|
2019-09-29 01:49:13 +02: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
|
|
|
|
|
|
|
def generate_sha1sum_emoji(zulip_path):
|
2018-05-10 18:54:59 +02:00
|
|
|
# type: (str) -> str
|
2017-08-19 16:23:30 +02:00
|
|
|
ZULIP_EMOJI_DIR = os.path.join(zulip_path, 'tools', 'setup', 'emoji')
|
|
|
|
sha = hashlib.sha1()
|
|
|
|
|
2017-11-08 19:40:43 +01:00
|
|
|
filenames = ['emoji_map.json', 'build_emoji', 'emoji_setup_utils.py', 'emoji_names.py']
|
2017-08-19 16:23:30 +02:00
|
|
|
|
|
|
|
for filename in filenames:
|
|
|
|
file_path = os.path.join(ZULIP_EMOJI_DIR, filename)
|
|
|
|
with open(file_path, 'rb') as reader:
|
|
|
|
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.
|
2017-08-19 16:23:30 +02:00
|
|
|
PACKAGE_FILE_PATH = os.path.join(zulip_path, 'package.json')
|
|
|
|
with open(PACKAGE_FILE_PATH, 'r') as fp:
|
|
|
|
parsed_package_file = json.load(fp)
|
2017-09-26 02:01:56 +02:00
|
|
|
dependency_data = parsed_package_file['dependencies']
|
|
|
|
|
2018-03-13 20:34:31 +01:00
|
|
|
if 'emoji-datasource-google' in dependency_data:
|
2020-02-05 05:45:02 +01:00
|
|
|
with open(os.path.join(zulip_path, "yarn.lock")) as fp:
|
|
|
|
(emoji_datasource_version,) = re.findall(
|
|
|
|
r"^emoji-datasource-google@"
|
|
|
|
+ re.escape(dependency_data["emoji-datasource-google"])
|
|
|
|
+ r':\n version "(.*)"',
|
|
|
|
fp.read(),
|
|
|
|
re.M,
|
|
|
|
)
|
2017-09-26 02:01:56 +02:00
|
|
|
else:
|
2020-02-05 05:45:02 +01:00
|
|
|
emoji_datasource_version = "0"
|
|
|
|
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
|
|
|
|
2019-09-29 01:49:13 +02:00
|
|
|
def may_be_perform_purging(dirs_to_purge, dirs_to_keep, dir_type, dry_run, verbose, no_headings):
|
|
|
|
# type: (Set[str], Set[str], str, bool, bool, 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:
|
2017-08-30 23:58:00 +02:00
|
|
|
print("Cleaning unused %ss..." % (dir_type,))
|
|
|
|
|
|
|
|
for directory in dirs_to_purge:
|
2017-09-23 21:15:13 +02:00
|
|
|
if verbose:
|
|
|
|
print("Cleaning unused %s: %s" % (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:
|
|
|
|
print("Keeping used %s: %s" % (dir_type, directory))
|
2018-05-28 21:55:07 +02:00
|
|
|
|
2019-08-30 00:14:43 +02:00
|
|
|
@functools.lru_cache(None)
|
2019-08-25 01:23:14 +02:00
|
|
|
def parse_os_release():
|
2018-05-28 21:55:07 +02:00
|
|
|
# type: () -> 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',
|
|
|
|
}
|
|
|
|
|
|
|
|
VERSION_CODENAME (e.g. 'bionic') is nice and human-readable, but
|
|
|
|
we avoid using it, as it is not available on RHEL-based platforms.
|
|
|
|
"""
|
2018-12-10 15:11:08 +01:00
|
|
|
distro_info = {} # type: Dict[str, str]
|
2019-08-25 01:23:14 +02:00
|
|
|
with open('/etc/os-release', 'r') as fp:
|
|
|
|
for line in fp:
|
|
|
|
line = line.strip()
|
|
|
|
if not line or line.startswith('#'):
|
|
|
|
# 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
|
2019-08-25 01:23:14 +02:00
|
|
|
k, v = line.split('=', 1)
|
|
|
|
[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
|
|
|
|
2019-08-30 00:14:43 +02:00
|
|
|
@functools.lru_cache(None)
|
|
|
|
def os_families() -> Set[str]:
|
|
|
|
"""
|
|
|
|
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()}
|
|
|
|
|
2018-06-22 12:56:25 +02:00
|
|
|
def file_or_package_hash_updated(paths, hash_name, is_force, package_versions=[]):
|
|
|
|
# type: (List[str], str, bool, List[str]) -> bool
|
|
|
|
# Check whether the files or package_versions passed as arguments
|
|
|
|
# changed compared to the last execution.
|
2018-06-14 14:19:27 +02:00
|
|
|
sha1sum = hashlib.sha1()
|
|
|
|
for path in paths:
|
|
|
|
with open(path, 'rb') as file_to_hash:
|
|
|
|
sha1sum.update(file_to_hash.read())
|
|
|
|
|
2020-03-28 01:25:56 +01:00
|
|
|
# The output of tools like build_pygments_data depends
|
2018-06-22 12:56:25 +02:00
|
|
|
# on the version of some pip packages as well.
|
|
|
|
for package_version in package_versions:
|
|
|
|
sha1sum.update(package_version.encode("utf-8"))
|
|
|
|
|
2018-06-14 14:19:27 +02:00
|
|
|
hash_path = os.path.join(get_dev_uuid_var_path(), hash_name)
|
|
|
|
new_hash = sha1sum.hexdigest()
|
2018-07-18 23:50:15 +02:00
|
|
|
with open(hash_path, 'a+') as hash_file:
|
|
|
|
hash_file.seek(0)
|
2018-06-14 14:19:27 +02:00
|
|
|
last_hash = hash_file.read()
|
|
|
|
|
2018-07-18 23:50:15 +02:00
|
|
|
if is_force or (new_hash != last_hash):
|
|
|
|
hash_file.seek(0)
|
|
|
|
hash_file.truncate()
|
2018-06-14 14:19:27 +02:00
|
|
|
hash_file.write(new_hash)
|
2018-07-18 23:50:15 +02:00
|
|
|
return True
|
2018-06-14 14:19:27 +02:00
|
|
|
return False
|
2018-11-15 10:53:34 +01:00
|
|
|
|
|
|
|
def is_root() -> bool:
|
|
|
|
if 'posix' in os.name and os.geteuid() == 0:
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
2019-02-26 20:20:46 +01:00
|
|
|
def run_as_root(args, **kwargs):
|
|
|
|
# type: (List[str], **Any) -> None
|
|
|
|
sudo_args = kwargs.pop('sudo_args', [])
|
|
|
|
if not is_root():
|
|
|
|
args = ['sudo'] + sudo_args + ['--'] + args
|
|
|
|
run(args, **kwargs)
|
|
|
|
|
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()
|
2019-02-07 01:41:10 +01:00
|
|
|
msg = ("{shortname} should not be run as root. Use `su {user}` to switch to the 'zulip'\n"
|
|
|
|
"user before rerunning this, or use \n su {user} -c '{name} ...'\n"
|
2018-11-15 10:53:34 +01:00
|
|
|
"to switch users and run this as a single command.").format(
|
|
|
|
name=script_name,
|
2019-02-07 01:41:10 +01:00
|
|
|
shortname=os.path.basename(script_name),
|
|
|
|
user=pwent.pw_name)
|
2018-11-15 10:53:34 +01:00
|
|
|
print(msg)
|
|
|
|
sys.exit(1)
|
|
|
|
|
2018-11-19 19:50:25 +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():
|
|
|
|
print("{} must be run as root.".format(script_name))
|
|
|
|
sys.exit(1)
|
2018-12-15 07:05:27 +01:00
|
|
|
|
|
|
|
def get_config(config_file, section, key, default_value=""):
|
|
|
|
# type: (configparser.RawConfigParser, str, str, str) -> str
|
|
|
|
if config_file.has_option(section, key):
|
|
|
|
return config_file.get(section, key)
|
|
|
|
return default_value
|
|
|
|
|
|
|
|
def get_config_file() -> configparser.RawConfigParser:
|
|
|
|
config_file = configparser.RawConfigParser()
|
|
|
|
config_file.read("/etc/zulip/zulip.conf")
|
|
|
|
return config_file
|
|
|
|
|
|
|
|
def get_deploy_options(config_file):
|
|
|
|
# type: (configparser.RawConfigParser) -> List[str]
|
|
|
|
return get_config(config_file, 'deployment', 'deploy_options', "").strip().split()
|
2019-06-14 22:56:34 +02:00
|
|
|
|
|
|
|
def get_or_create_dev_uuid_var_path(path: str) -> str:
|
|
|
|
absolute_path = '{}/{}'.format(get_dev_uuid_var_path(), path)
|
|
|
|
os.makedirs(absolute_path, exist_ok=True)
|
|
|
|
return absolute_path
|
2019-06-18 01:09:07 +02:00
|
|
|
|
2019-07-06 06:03:08 +02:00
|
|
|
def is_vagrant_env_host(path: str) -> bool:
|
|
|
|
return '.vagrant' in os.listdir(path)
|
|
|
|
|
2019-06-18 01:09:07 +02:00
|
|
|
if __name__ == '__main__':
|
|
|
|
cmd = sys.argv[1]
|
|
|
|
if cmd == 'make_deploy_path':
|
|
|
|
print(make_deploy_path())
|
|
|
|
elif cmd == 'get_dev_uuid':
|
|
|
|
print(get_dev_uuid_var_path())
|