From 8bf3836d66b65b1aa4c8d2415e2a9ddf6881c3b4 Mon Sep 17 00:00:00 2001 From: Justin Campbell Date: Thu, 17 Sep 2020 00:24:07 -0400 Subject: [PATCH] Working venv creation --- utils/venv-manager.py | 61 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/utils/venv-manager.py b/utils/venv-manager.py index 5f484f5..51391b6 100644 --- a/utils/venv-manager.py +++ b/utils/venv-manager.py @@ -27,6 +27,10 @@ VENV_DIR = Path(API_DIR, VENV_NAME) +# Set minimum pip major version +TARGET_PIP_VERSION = 19 + + # Configure the logger logger_name = "venv-manager" logger = logging.getLogger(logger_name) @@ -119,7 +123,64 @@ def run_logged_subprocess(command: Union[str, list], timeout: int = 10, shell: b return (logged_shell_process.returncode, process_output_stream) +def create_environment() -> int: + """Creates a virtual environment for webqueue2] + + Exit Codes: + 0 = Success + 5 = VENV_DIR already exists + 10 = Could not create VENV_DIR + 15 = Could not install requirements + Returns: + int: Exit code + """ + + # Check for an existing virtual environment + try: + os.mkdir(VENV_DIR) + except FileExistsError: + logger.warning(f"The directory {VENV_DIR} already exists. Exiting") + return 5 + + # Create virtual environment + logger.info(f"Creating virtual environment {VENV_NAME} at {VENV_DIR}") + create_env_returncode, _ = run_logged_subprocess(f"cd {API_DIR} && python3 -m venv {VENV_NAME}", shell=True) + if create_env_returncode == 0: + logger.info(f"Virtual environment {VENV_NAME} created at {VENV_DIR}") + else: + logger.critical(f"Could not create virtual environment {VENV_NAME} at {VENV_DIR}. Exiting") + return 10 + + # Check pip version + logger.debug("Checking pip version") + check_pip_returncode, check_pip_output = run_logged_subprocess(f"{VENV_DIR}/bin/pip --version") + + if check_pip_returncode != 0: + logger.warning("Could not check pip version. Virtual environment dependencies may not install") + + pip_version_full = check_pip_output.split()[1] + logger.debug(f"pip version is {pip_version_full}") + + pip_version_major = pip_version_full.split(".")[0] + if int(pip_version_major) < 19: + logger.info(f"pip verion is {pip_version_major}.x (pip >= {TARGET_PIP_VERSION}.x needed.) Upgrading pip") + update_pip_returncode, update_pip_output = run_logged_subprocess(f"{VENV_DIR}/bin/pip install --upgrade pip") + + if update_pip_returncode == 0: + logger.info(update_pip_output.split("\n")[-2]) + else: + logger.warning("Failed to update pip. Virtual environment dependencies may not install") + + # Install requirements + logger.info("Installing requirements") + install_requirements_returncode, _ = run_logged_subprocess(f"{VENV_DIR}/bin/pip install -r {API_DIR}/requirements.txt") + if install_requirements_returncode == 0: + logger.info("Successfully installed requirements") + return 0 + else: + logger.critical("Failed to install requirements. Exiting") + return 15 if __name__ == "__main__":