2024-08-28 10:39:20 +02:00
|
|
|
import os
|
2024-08-28 22:20:36 +02:00
|
|
|
import shutil
|
2024-08-28 10:39:20 +02:00
|
|
|
import subprocess
|
2024-10-05 14:20:45 +02:00
|
|
|
from pathlib import Path
|
|
|
|
from typing import Union, List, Optional
|
2024-08-28 10:39:20 +02:00
|
|
|
|
2024-08-28 20:05:46 +02:00
|
|
|
import psutil
|
|
|
|
|
2024-10-05 14:20:45 +02:00
|
|
|
from core import utils, screen
|
2024-10-05 14:35:58 +02:00
|
|
|
from core.screen import Screen
|
2024-08-28 22:20:36 +02:00
|
|
|
from core.vars import logger, PYTHON_EXEC
|
2024-08-29 12:03:37 +02:00
|
|
|
from ui import choices
|
|
|
|
|
|
|
|
|
2024-08-28 10:39:20 +02:00
|
|
|
class Stack:
|
2024-08-28 22:20:36 +02:00
|
|
|
def __init__(self, name: str, id: str, port: int, url: str):
|
2024-10-05 14:20:45 +02:00
|
|
|
"""
|
|
|
|
Initialize the Stack instance.
|
|
|
|
|
|
|
|
:param name: The name of the stack
|
|
|
|
:param id: A unique identifier for the stack
|
|
|
|
:param port: The port the stack service uses
|
|
|
|
:param url: The URL associated with the stack
|
|
|
|
"""
|
2024-08-28 10:39:20 +02:00
|
|
|
self.name = name
|
2024-08-28 22:20:36 +02:00
|
|
|
self.id = id
|
2024-10-05 14:20:45 +02:00
|
|
|
self.path = Path.home() / ".ai-suite-rocm" / id
|
2024-08-28 10:39:20 +02:00
|
|
|
self.url = url
|
|
|
|
self.port = port
|
2024-10-05 14:20:45 +02:00
|
|
|
self.pid_file = self.path / f".pid"
|
|
|
|
self.pid = self.read_pid()
|
2024-10-05 14:35:58 +02:00
|
|
|
self.screen_session: Screen = None
|
2024-10-05 14:20:45 +02:00
|
|
|
|
|
|
|
def read_pid(self) -> Optional[int]:
|
|
|
|
"""
|
|
|
|
Read the PID from the PID file, if it exists.
|
|
|
|
|
|
|
|
:return: The PID as an integer, or None if the file does not exist or an error occurs.
|
|
|
|
"""
|
|
|
|
if self.pid_file.exists():
|
|
|
|
return int(self.pid_file.read_text())
|
|
|
|
else:
|
|
|
|
return None
|
|
|
|
|
|
|
|
def write_pid(self, pid: int) -> None:
|
|
|
|
"""
|
|
|
|
Write the PID to the PID file.
|
|
|
|
|
|
|
|
:param pid: Process ID to write
|
|
|
|
"""
|
|
|
|
with self.pid_file.open('w') as f:
|
|
|
|
f.write(str(pid))
|
2024-08-28 10:39:20 +02:00
|
|
|
|
2024-10-05 14:20:45 +02:00
|
|
|
def remove_pid_file(self) -> None:
|
|
|
|
"""Remove the PID file if it exists."""
|
|
|
|
if self.pid_file.exists():
|
|
|
|
self.pid_file.unlink()
|
2024-08-28 10:39:20 +02:00
|
|
|
|
2024-10-05 14:20:45 +02:00
|
|
|
def install(self) -> None:
|
|
|
|
"""Install the stack, creating the virtual environment and performing initial setup."""
|
2024-08-29 12:50:18 +02:00
|
|
|
if self.is_installed():
|
|
|
|
self.update()
|
|
|
|
else:
|
|
|
|
self.check_for_broken_install()
|
2024-10-05 14:20:45 +02:00
|
|
|
self.create_dir('')
|
2024-08-29 12:50:18 +02:00
|
|
|
self.create_venv()
|
|
|
|
self._install()
|
2024-08-29 12:26:37 +02:00
|
|
|
|
2024-08-29 12:50:18 +02:00
|
|
|
self.create_file('.installed', 'true')
|
|
|
|
logger.info(f"Installed {self.name}")
|
2024-08-28 10:39:20 +02:00
|
|
|
|
2024-10-05 14:20:45 +02:00
|
|
|
def _install(self) -> None:
|
|
|
|
"""Additional installation steps specific to the stack (override as needed)."""
|
2024-08-29 12:26:37 +02:00
|
|
|
pass
|
|
|
|
|
2024-10-05 14:20:45 +02:00
|
|
|
def is_installed(self) -> bool:
|
|
|
|
"""
|
|
|
|
Check if the stack is installed by verifying the existence of the '.installed' file.
|
|
|
|
|
|
|
|
:return: True if the stack is installed, False otherwise.
|
|
|
|
"""
|
2024-08-28 10:39:20 +02:00
|
|
|
return self.file_exists('.installed')
|
|
|
|
|
2024-10-05 14:20:45 +02:00
|
|
|
def check_for_broken_install(self) -> None:
|
|
|
|
"""Check for a broken installation and clean up any leftover files."""
|
|
|
|
if not self.is_installed() and self.path.exists():
|
|
|
|
logger.warning("Found files from a previous/broken/crashed installation, cleaning up...")
|
|
|
|
self.remove_dir('')
|
2024-08-28 10:39:20 +02:00
|
|
|
|
2024-10-05 14:20:45 +02:00
|
|
|
def update(self, folder: str = 'webui') -> None:
|
|
|
|
"""Update the stack by pulling the latest changes from the repository."""
|
2024-08-29 12:26:37 +02:00
|
|
|
if self.is_installed():
|
2024-10-05 14:20:45 +02:00
|
|
|
was_running = self.status()
|
|
|
|
if was_running:
|
2024-08-29 12:50:18 +02:00
|
|
|
self.stop()
|
|
|
|
|
2024-08-28 10:39:20 +02:00
|
|
|
logger.info(f"Updating {self.name}")
|
2024-10-05 10:55:04 +02:00
|
|
|
symlinks = utils.find_symlink_in_folder(self.path)
|
2024-08-28 10:39:20 +02:00
|
|
|
self.git_pull(folder)
|
2024-08-29 12:50:18 +02:00
|
|
|
self._update()
|
2024-10-05 10:55:04 +02:00
|
|
|
utils.create_symlinks(symlinks)
|
2024-08-29 12:50:18 +02:00
|
|
|
|
2024-10-05 14:20:45 +02:00
|
|
|
if was_running:
|
2024-08-29 12:50:18 +02:00
|
|
|
self.start()
|
2024-08-28 10:39:20 +02:00
|
|
|
else:
|
2024-08-29 12:26:37 +02:00
|
|
|
logger.warning(f"Could not update {self.name} as {self.name} is not installed")
|
2024-08-28 10:39:20 +02:00
|
|
|
|
2024-10-05 14:20:45 +02:00
|
|
|
def _update(self) -> None:
|
|
|
|
"""Additional update steps specific to the stack (override as needed)."""
|
2024-08-29 12:50:18 +02:00
|
|
|
pass
|
|
|
|
|
2024-10-05 14:20:45 +02:00
|
|
|
def uninstall(self) -> None:
|
|
|
|
"""Uninstall the stack by stopping it and removing its files."""
|
2024-08-29 12:26:37 +02:00
|
|
|
logger.info(f"Uninstalling {self.name}")
|
2024-08-29 12:50:18 +02:00
|
|
|
if self.status():
|
|
|
|
self.stop()
|
2024-08-28 10:39:20 +02:00
|
|
|
self.bash(f"rm -rf {self.path}")
|
2024-10-05 14:20:45 +02:00
|
|
|
self.remove_pid_file()
|
2024-08-28 10:39:20 +02:00
|
|
|
|
2024-10-05 14:20:45 +02:00
|
|
|
def start(self) -> None:
|
|
|
|
"""Start the stack service."""
|
2024-08-29 12:50:18 +02:00
|
|
|
if self.status():
|
|
|
|
logger.warning(f"{self.name} is already running")
|
2024-10-05 14:20:45 +02:00
|
|
|
return
|
2024-08-29 12:50:18 +02:00
|
|
|
|
2024-08-28 20:05:46 +02:00
|
|
|
if self.is_installed():
|
2024-08-29 12:26:37 +02:00
|
|
|
self._start()
|
2024-08-28 20:05:46 +02:00
|
|
|
else:
|
2024-08-29 12:26:37 +02:00
|
|
|
logger.error(f"{self.name} is not installed")
|
2024-08-28 20:05:46 +02:00
|
|
|
|
2024-10-05 14:20:45 +02:00
|
|
|
def _start(self) -> None:
|
|
|
|
"""Additional start steps specific to the stack (override as needed)."""
|
2024-08-28 10:39:20 +02:00
|
|
|
pass
|
|
|
|
|
2024-10-05 14:20:45 +02:00
|
|
|
def stop(self) -> None:
|
|
|
|
"""Stop the stack service by terminating the associated process."""
|
2024-08-29 12:03:37 +02:00
|
|
|
if self.status():
|
2024-10-05 14:20:45 +02:00
|
|
|
logger.debug(f"Stopping {self.name} with PID: {self.pid}")
|
|
|
|
try:
|
|
|
|
proc = psutil.Process(self.pid)
|
|
|
|
proc.terminate() # Graceful shutdown
|
|
|
|
proc.wait(timeout=5)
|
|
|
|
except (psutil.NoSuchProcess, psutil.TimeoutExpired):
|
|
|
|
logger.warning(f"{self.name} did not terminate gracefully, forcing kill")
|
|
|
|
psutil.Process(self.pid).kill()
|
|
|
|
self.remove_pid_file()
|
2024-08-29 12:50:18 +02:00
|
|
|
else:
|
|
|
|
logger.warning(f"{self.name} is not running")
|
2024-08-29 12:03:37 +02:00
|
|
|
|
2024-10-05 14:20:45 +02:00
|
|
|
def restart(self) -> None:
|
|
|
|
"""Restart the stack service."""
|
2024-08-28 10:39:20 +02:00
|
|
|
self.stop()
|
|
|
|
self.start()
|
|
|
|
|
2024-08-28 20:05:46 +02:00
|
|
|
def status(self) -> bool:
|
2024-10-05 14:20:45 +02:00
|
|
|
"""
|
|
|
|
Check if the stack service is running.
|
2024-08-29 12:03:37 +02:00
|
|
|
|
2024-10-05 14:20:45 +02:00
|
|
|
:return: True if the service is running, False otherwise.
|
|
|
|
"""
|
2024-10-05 14:35:58 +02:00
|
|
|
if self.screen_session and self.pid:
|
|
|
|
return screen.exists(self.screen_session.pid)
|
|
|
|
else:
|
|
|
|
return self.pid is not None and psutil.pid_exists(self.pid)
|
2024-08-28 10:39:20 +02:00
|
|
|
|
2024-10-05 14:20:45 +02:00
|
|
|
def create_venv(self) -> None:
|
|
|
|
"""Create a Python virtual environment for the stack."""
|
|
|
|
venv_path = self.path / 'venv'
|
2024-08-28 10:39:20 +02:00
|
|
|
if not self.has_venv():
|
2024-08-28 20:05:46 +02:00
|
|
|
logger.info(f"Creating venv for {self.name}")
|
2024-08-28 10:39:20 +02:00
|
|
|
self.bash(f"{PYTHON_EXEC} -m venv {venv_path} --system-site-packages")
|
2024-08-28 20:05:46 +02:00
|
|
|
self.pip_install("pip")
|
2024-08-28 10:39:20 +02:00
|
|
|
else:
|
|
|
|
logger.debug(f"Venv already exists for {self.name}")
|
|
|
|
|
|
|
|
def has_venv(self) -> bool:
|
2024-10-05 14:20:45 +02:00
|
|
|
"""
|
|
|
|
Check if the virtual environment exists.
|
|
|
|
|
|
|
|
:return: True if the virtual environment exists, False otherwise.
|
|
|
|
"""
|
|
|
|
return (self.path / 'venv').exists()
|
2024-08-28 10:39:20 +02:00
|
|
|
|
2024-10-05 14:20:45 +02:00
|
|
|
def pip_install(self, package: Union[str, List[str]], no_deps: bool = False, env: List[str] = [],
|
|
|
|
args: List[str] = []) -> None:
|
|
|
|
"""Install a Python package or list of packages using pip."""
|
2024-08-28 20:05:46 +02:00
|
|
|
if no_deps:
|
|
|
|
args.append("--no-deps")
|
|
|
|
|
2024-08-28 10:39:20 +02:00
|
|
|
if isinstance(package, list):
|
|
|
|
for p in package:
|
2024-08-28 20:05:46 +02:00
|
|
|
logger.info(f"Installing {p}")
|
|
|
|
self.pip(f"install -U {p}", env=env, args=args)
|
2024-08-28 10:39:20 +02:00
|
|
|
else:
|
2024-08-28 20:05:46 +02:00
|
|
|
logger.info(f"Installing {package}")
|
|
|
|
self.pip(f"install -U {package}", env=env, args=args)
|
2024-08-28 10:39:20 +02:00
|
|
|
|
2024-10-05 14:20:45 +02:00
|
|
|
def install_requirements(self, filename: str = 'requirements.txt', env: List[str] = []) -> None:
|
|
|
|
"""Install requirements from a given file."""
|
2024-08-28 20:05:46 +02:00
|
|
|
logger.info(f"Installing requirements for {self.name} ({filename})")
|
|
|
|
self.pip(f"install -r {filename}", env=env)
|
2024-08-28 10:39:20 +02:00
|
|
|
|
2024-10-05 14:20:45 +02:00
|
|
|
def pip(self, cmd: str, env: List[str] = [], args: List[str] = [], current_dir: Optional[Path] = None) -> None:
|
|
|
|
"""Run pip with a given command."""
|
2024-08-29 12:03:37 +02:00
|
|
|
self.python(f"-m pip {cmd}", env=env, args=args, current_dir=current_dir)
|
2024-08-28 10:39:20 +02:00
|
|
|
|
2024-10-05 14:20:45 +02:00
|
|
|
def python(self, cmd: str, env: List[str] = [], args: List[str] = [], current_dir: Optional[Path] = None,
|
|
|
|
daemon: bool = False) -> None:
|
|
|
|
"""Run a Python command inside the stack's virtual environment."""
|
|
|
|
self.bash(f"{' '.join(env)} {self.path / 'venv' / 'bin' / 'python'} {cmd} {' '.join(args)}", current_dir,
|
|
|
|
daemon)
|
2024-08-28 10:39:20 +02:00
|
|
|
|
2024-10-05 14:20:45 +02:00
|
|
|
def bash(self, cmd: str, current_dir: Optional[Path] = None, daemon: bool = False) -> None:
|
|
|
|
"""Run a bash command, optionally as a daemon."""
|
|
|
|
full_cmd = f"cd {current_dir or self.path} && {cmd}"
|
2024-08-28 10:39:20 +02:00
|
|
|
|
2024-08-28 20:05:46 +02:00
|
|
|
if daemon:
|
2024-08-29 12:03:37 +02:00
|
|
|
if self.status():
|
|
|
|
choice = choices.already_running.ask()
|
|
|
|
if choice is True:
|
|
|
|
self.stop()
|
2024-08-29 12:26:37 +02:00
|
|
|
self._start()
|
2024-08-29 12:03:37 +02:00
|
|
|
return
|
2024-08-28 20:05:46 +02:00
|
|
|
else:
|
2024-08-29 12:03:37 +02:00
|
|
|
return
|
2024-08-28 20:05:46 +02:00
|
|
|
else:
|
2024-10-05 14:20:45 +02:00
|
|
|
logger.debug(f"Running command as daemon: {full_cmd}")
|
|
|
|
|
|
|
|
# process = subprocess.Popen(full_cmd, shell=True, preexec_fn=os.setpgrp,
|
|
|
|
# stdout=config.open_file(f"{self.id}-stdout"),
|
|
|
|
# stderr=config.open_file(f"{self.id}-stderr"))
|
2024-10-05 14:35:58 +02:00
|
|
|
self.screen_session = screen.create(name=self.id)
|
|
|
|
self.screen_session.send(f"'{full_cmd} && screen -wipe'")
|
|
|
|
self.write_pid(self.screen_session.pid)
|
2024-08-29 12:03:37 +02:00
|
|
|
return
|
2024-08-28 10:39:20 +02:00
|
|
|
else:
|
2024-10-05 14:20:45 +02:00
|
|
|
logger.debug(f"Running command: {full_cmd}")
|
2024-08-28 20:05:46 +02:00
|
|
|
|
2024-10-05 14:20:45 +02:00
|
|
|
process = subprocess.Popen(full_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
|
|
|
out, err = process.communicate()
|
2024-08-28 20:05:46 +02:00
|
|
|
|
2024-10-05 14:20:45 +02:00
|
|
|
if process.returncode != 0:
|
|
|
|
logger.fatal(f"Failed to run command: {full_cmd}")
|
|
|
|
logger.fatal(f"Error: {err.decode('utf-8')}")
|
|
|
|
logger.fatal(f"Output: {out.decode('utf-8')}")
|
|
|
|
raise Exception(f"Failed to run command: {full_cmd}")
|
2024-08-28 10:39:20 +02:00
|
|
|
|
2024-10-05 14:20:45 +02:00
|
|
|
def git_clone(self, url: str, branch: Optional[str] = None, dest: Optional[Path] = None) -> None:
|
|
|
|
"""Clone a git repository."""
|
2024-08-28 20:05:46 +02:00
|
|
|
logger.info(f"Cloning {url}")
|
2024-10-05 14:20:45 +02:00
|
|
|
self.bash(f"git clone {f'-b {branch}' if branch else ''} {url} {dest or ''}")
|
2024-08-28 10:39:20 +02:00
|
|
|
|
2024-10-05 14:20:45 +02:00
|
|
|
def git_pull(self, repo_folder: str, force: bool = False) -> None:
|
|
|
|
"""Pull changes from a git repository."""
|
|
|
|
self.bash(f"git reset --hard HEAD {'&& git clean -f -d' if force else ''} && git pull", Path(repo_folder))
|
2024-08-28 10:39:20 +02:00
|
|
|
|
|
|
|
def install_from_prebuilt(self, name):
|
|
|
|
for prebuilt in utils.get_prebuilts():
|
|
|
|
if prebuilt['name'].split("-")[0] == name:
|
|
|
|
self.pip(f"install {prebuilt['browser_download_url']}")
|
|
|
|
return
|
|
|
|
|
2024-10-05 14:20:45 +02:00
|
|
|
def create_file(self, name: str, content: str) -> None:
|
|
|
|
"""Create a file with the given content."""
|
|
|
|
(self.path / name).write_text(content)
|
2024-08-28 20:05:46 +02:00
|
|
|
|
2024-10-05 14:20:45 +02:00
|
|
|
def create_dir(self, name: str) -> None:
|
|
|
|
"""Create a directory."""
|
|
|
|
dir_path = self.path / name
|
|
|
|
logger.debug(f"Creating directory {dir_path}")
|
|
|
|
dir_path.mkdir(parents=True, exist_ok=True)
|
2024-08-28 10:39:20 +02:00
|
|
|
|
2024-10-05 14:20:45 +02:00
|
|
|
def remove_file(self, name: str) -> None:
|
|
|
|
"""Remove a file."""
|
2024-08-28 10:39:20 +02:00
|
|
|
logger.debug(f"Removing file {name}")
|
|
|
|
os.remove(os.path.join(self.path, name))
|
|
|
|
|
2024-10-05 14:20:45 +02:00
|
|
|
def remove_dir(self, name: str) -> None:
|
|
|
|
"""Remove a directory."""
|
|
|
|
logger.debug(f"Removing directory {name or self.path}")
|
|
|
|
if not name:
|
|
|
|
shutil.rmtree(self.path)
|
|
|
|
else:
|
|
|
|
shutil.rmtree(os.path.join(self.path, name))
|
2024-08-28 10:39:20 +02:00
|
|
|
|
2024-10-05 14:20:45 +02:00
|
|
|
def move_file_or_dir(self, src: str, dest: str) -> None:
|
|
|
|
"""Move a file or directory."""
|
2024-08-28 10:39:20 +02:00
|
|
|
logger.debug(f"Moving file/dir {src} to {dest}")
|
|
|
|
os.rename(os.path.join(self.path, src), os.path.join(self.path, dest))
|
|
|
|
|
2024-10-05 14:20:45 +02:00
|
|
|
def move_all_files_in_dir(self, src: str, dest: str) -> None:
|
|
|
|
"""Move all files in a directory to another directory"""
|
2024-08-28 10:39:20 +02:00
|
|
|
logger.debug(f"Moving all files in directory {src} to {dest}")
|
|
|
|
for file in os.listdir(os.path.join(self.path, src)):
|
|
|
|
os.rename(os.path.join(self.path, src, file), os.path.join(self.path, dest, file))
|
|
|
|
|
2024-10-05 14:20:45 +02:00
|
|
|
def file_exists(self, name: str) -> bool:
|
|
|
|
"""Check if a file exists."""
|
|
|
|
return (self.path / name).exists()
|
2024-08-28 10:39:20 +02:00
|
|
|
|
2024-10-05 14:20:45 +02:00
|
|
|
def dir_exists(self, name: str) -> bool:
|
|
|
|
"""Check if a directory exists."""
|
|
|
|
return (self.path / name).exists()
|
2024-08-28 10:39:20 +02:00
|
|
|
|
|
|
|
def remove_line_in_file(self, contains: str | list, file: str):
|
2024-10-05 14:20:45 +02:00
|
|
|
"""Remove lines containing a specific string from a file."""
|
|
|
|
target_file = self.path / file
|
|
|
|
logger.debug(f"Removing lines containing {contains} in {target_file}")
|
2024-08-28 10:39:20 +02:00
|
|
|
if isinstance(contains, list):
|
|
|
|
for c in contains:
|
2024-10-05 14:20:45 +02:00
|
|
|
self.bash(f"sed -i '/{c}/d' {target_file}")
|
2024-08-28 10:39:20 +02:00
|
|
|
else:
|
2024-10-05 14:20:45 +02:00
|
|
|
self.bash(f"sed -i '/{contains}/d' {target_file}")
|
2024-08-28 10:39:20 +02:00
|
|
|
|
|
|
|
def replace_line_in_file(self, match: str, replace: str, file: str):
|
2024-10-05 14:20:45 +02:00
|
|
|
"""Replace lines containing a specific string in a file."""
|
|
|
|
target_file = self.path / file
|
|
|
|
logger.debug(f"Replacing lines containing {match} with {replace} in {target_file}")
|
|
|
|
self.bash(f"sed -i 's/{match}/{replace}/g' {target_file}")
|