From 01003cdacc488ac4c3bfa7d8b6b3b218271cdcca Mon Sep 17 00:00:00 2001 From: Stephane de Labrusse Date: Mon, 2 Sep 2024 15:46:34 +0200 Subject: [PATCH] fix: Check if SFTPGo service port is in use before starting it in restore action --- imageroot/actions/restore-module/60systemd | 39 ++++++++++++++++++++-- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/imageroot/actions/restore-module/60systemd b/imageroot/actions/restore-module/60systemd index 588b8ec..e6a81be 100755 --- a/imageroot/actions/restore-module/60systemd +++ b/imageroot/actions/restore-module/60systemd @@ -24,14 +24,48 @@ import subprocess import glob import re import agent +import socket +def is_port_in_use(port): + # Check if the port is in use for IPv4 + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: + try: + sock.bind(('', port)) + except socket.error: + return True # Port is in use for IPv4 + + # Check if the port is in use for IPv6 + with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as sock: + try: + sock.bind(('', port)) + except socket.error: + return True # Port is in use for IPv6 + + return False # Port is not in use for both IPv4 and IPv6 + + +def start_service(): + try: + # Enable and start the service + subprocess.run(["systemctl", "--user", "enable", "--now", "sftpgo.service"], check=True) + subprocess.run(["systemctl", "--user", "restart", "sftpgo.service"], check=True) + print("Service started successfully sftpgo.service", file=sys.stderr) + except subprocess.CalledProcessError as e: + print(f"Failed to start the service: {e}", file=sys.stderr) + # expand configuration subprocess.run(["systemctl", "--user", "enable","--now", "nginx.service"]) subprocess.run(["systemctl", "--user", "restart", "nginx.service"]) -agent.run_helper("systemctl", "--user", "enable","--now", "sftpgo.service").check_returncode() -agent.run_helper("systemctl", "--user", "restart", "sftpgo.service").check_returncode() +# we test if the port is not in use with the previous module +# sftpgo.service is a standalone service without require from other services +port = os.environ['SFTP_TCP_PORT'] +if not is_port_in_use(port): + start_service() +else: + # port is in use, we state to restart it later + print(f"The TCP port {port} of STFPGo is already in use you have to restart it manually later", file=sys.stderr) # detect if a service has configurations, hence start it PhpServiceArray = glob.glob('php*-fpm-custom.d') @@ -41,4 +75,3 @@ for folder in PhpServiceArray: if ListConfigurations : subprocess.run(["download-php-fpm",ConfiguredServices[0].replace('php','')]) subprocess.run(["systemctl", "--user", "enable","--now", "phpfpm@"+ConfiguredServices[0].replace('php','')+".service"]) -