NextERP-scripts/services/odoo/service.py
2025-04-03 16:20:17 +07:00

74 lines
2.9 KiB
Python

import subprocess
from services.odoo.connection import OdooConnection
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:
print(f"Executing: {cmd}")
subprocess.run(cmd, shell=True, check=True, capture_output=True, text=True)
print(f"Service operation successful for {instance_name}")
except subprocess.CalledProcessError as e:
print(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"sudo 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:
print(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"]:
raise ValueError("Action must be 'stop' or 'restart'.")
for instance in self.config.get_instances():
if instance_name and instance["name"] != instance_name:
continue
print(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)