import subprocess from services.odoo.connection import OdooConnection import lib.color_log as color_log class OdooServiceManager: def __init__(self, config_path="config/settings.yaml"): self.config = OdooConnection(config_path) def _execute_command(self, cmd, instance_name): """Execute a shell command and handle errors.""" try: color_log.Show("INFO", f"Executing command: {cmd}") subprocess.run(cmd, shell=True, check=True, capture_output=True, text=True) color_log.Show("OK", f"Command executed successfully for {instance_name}") except subprocess.CalledProcessError as e: color_log.Show( "FAILED", f"Error performing service operation for {instance_name}: {e}", ) raise def _get_command(self, instance, action): """ Generate the appropriate command based on instance type and action (stop/restart). """ service_type = instance.get("type", "systemctl") host = instance["host"] service_name = instance.get("service_name", f"odoo_{instance['name']}") ssh_settings = instance.get("ssh", {}) ssh_user = ssh_settings.get("user", "root") ssh_key_path = ssh_settings.get("key_path") local_host = host in ["localhost", "127.0.0.1"] if service_type == "systemctl": cmd = f"systemctl {action} {service_name}" elif service_type == "docker": container_name = instance.get("container_name", f"odoo_{instance['name']}") cmd = f"docker {action} {container_name}" else: color_log.Show( "WARNING", f"Unsupported service type '{service_type}' for {instance['name']}", ) return None if not local_host: if not ssh_key_path: cmd = f"ssh -t {ssh_user}@{host} 'sudo {cmd}'" else: cmd = f"ssh -i {ssh_key_path} {ssh_user}@{host} 'sudo {cmd}'" return cmd def manage_service(self, action, instance_name=None): """ Manage the Odoo service (stop or restart) for given instances. :param action: "stop" or "restart" :param instance_name: Specific instance name, or None for all instances. """ if action not in ["stop", "restart", "start"]: raise ValueError("Action must be 'stop' or 'restart'.") for instance in self.config.get_instances(): if instance_name and instance["name"] != instance_name: continue color_log.Show( "INFO", f"{action.capitalize()}ing service for instance: {instance['name']}", ) cmd = self._get_command(instance, action) if cmd: self._execute_command(cmd, instance["name"]) def stop_service(self, instance_name=None): """Stop the Odoo service based on the instance type""" self.manage_service("stop", instance_name) def restart_service(self, instance_name=None): """Restart the Odoo service based on the instance type""" self.manage_service("restart", instance_name) def start_service(self, instance_name=None): """Start the Odoo service based on the instance type""" self.manage_service("start", instance_name)