# -*- coding: utf-8 -*- import os import subprocess from .paths import AUTOSTART_SVC_DIR, SERVICE_DIR, STARTED_SVC_DIR from .templates import SERVICE def create_service(app, container, image): depends = ' '.join(image['depends']) if 'depends' in image else '' check = 'lxc-execute {} -- sh -c \'until $({}); do sleep 0.1; done\''.format(container, image['check']) if 'check' in image else '' with open(os.path.join(SERVICE_DIR, container), 'w') as f: f.write(SERVICE.format(app=app, container=container, depends=depends, check=check)) update_services() def delete_service(service): if is_service_started(service): stop_service(service) if is_service_autostarted(service): update_service_autostart(service, False) try: os.unlink(os.path.join(SERVICE_DIR, service)) except FileNotFoundError: pass update_services() def update_services(): subprocess.run(['/sbin/rc-update', '-u'], check=True) def start_service(service): if not is_service_started(service): subprocess.run(['/sbin/service', service, 'stop'], check=True) def stop_service(service): if is_service_started(service): subprocess.run(['/sbin/service', service, 'stop'], check=True) def is_service_started(self, app): # Check OpenRC service status without calling any binary return os.path.exists(os.path.join(STARTED_SVC_DIR, app)) def is_service_autostarted(self, app): # Check OpenRC service enablement return os.path.exists(os.path.join(AUTOSTART_SVC_DIR, app)) def update_service_autostart(self, service, enabled): # Add/remove the app to OpenRC default runlevel subprocess.run(['/sbin/rc-update', 'add' if enabled else 'del', service])