refs #208 adds dameon script to execute oglivecli

pull/3/head
Luis Gerardo Romero Garcia 2024-06-21 16:20:50 +02:00
parent 8ffe2cae85
commit 49dfba6c95
1 changed files with 74 additions and 0 deletions

View File

@ -0,0 +1,74 @@
import socket
import json
import subprocess
import logging
import os
# Configuración de logging
logging.basicConfig(level=logging.INFO, filename='/var/log/oglive_daemon.log', filemode='a', format='%(asctime)s - %(levelname)s - %(message)s')
def handle_command(command):
action = command.get('action')
args = command.get('args', [])
if action in ['install', 'download', 'uninstall', 'show', 'check']:
try:
logging.info(f'Handling command: {action} with args: {args}')
cleaned_args = [arg.strip('\'"') for arg in args] # Limpiar comillas
command_to_run = ['sudo', '/opt/ogboot/bin/oglivecli', action] + cleaned_args
process = subprocess.Popen(command_to_run, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
stdout, stderr = process.communicate()
if process.returncode == 0:
logging.info(f'Command executed successfully: {stdout}')
return {"success": True, "output": stdout}
else:
logging.error(f'Command failed with error: {stderr}')
return {"success": False, "error": stderr.strip()}
except Exception as e:
logging.error(f'Failed to handle command {action}: {e}')
return {"success": False, "error": str(e)}
else:
logging.error(f'Unknown command action: {action}')
return {"success": False, "error": "Unknown command action"}
def main():
socket_path = '/tmp/oglive_daemon.sock'
# Elimina el socket si existe
if os.path.exists(socket_path):
os.remove(socket_path)
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
server.bind(socket_path)
server.listen()
try:
while True:
logging.info('Daemon ready to accept connections')
conn, _ = server.accept()
with conn:
logging.info('Accepted connection')
data = conn.recv(1024)
if not data:
continue
try:
command = json.loads(data.decode('utf-8'))
logging.info(f'Received command: {command}')
except json.JSONDecodeError:
logging.error('Failed to decode JSON')
conn.sendall(json.dumps({"success": False, "error": "Invalid JSON"}).encode('utf-8'))
continue
response = handle_command(command)
conn.sendall(json.dumps(response).encode('utf-8'))
finally:
server.close()
if os.path.exists(socket_path):
os.remove(socket_path)
if __name__ == '__main__':
main()