refs #404 deletes a lot of useless functions, changes some shell commands to manage files and directories to python commands, adds try except blocks in all main funcions and in the oglivecli download oglive

ogboot_debian_installer
Luis Gerardo Romero Garcia 2024-09-24 10:28:40 +02:00
parent 0fb46b1f2b
commit fa8cc772f9
1 changed files with 188 additions and 246 deletions

View File

@ -6,7 +6,7 @@
##### Last: 2024-07-08 #### ##### Last: 2024-07-08 ####
################################################################################## ##################################################################################
import platform, os, sys, subprocess, datetime, shutil, pwd, glob, zipfile, urllib.request, logging, distro, re, json import platform, os, sys, subprocess, datetime, shutil, pwd, glob, logging, distro, re, json
PROGRAM = os.path.splitext(os.path.basename(sys.argv[0]))[0] PROGRAM = os.path.splitext(os.path.basename(sys.argv[0]))[0]
PROGRAM_DIR = os.path.dirname(os.path.realpath(sys.argv[0])) PROGRAM_DIR = os.path.dirname(os.path.realpath(sys.argv[0]))
@ -29,11 +29,6 @@ OSDISTRIB = ""
OSVERSION = "" OSVERSION = ""
IPXE_DIR = "/tmp/ipxe" IPXE_DIR = "/tmp/ipxe"
WORKDIR ="/tmp/ogboot_installer" WORKDIR ="/tmp/ogboot_installer"
TFTPSERV = "tftpd-hpa"
SAMBASERV = "smbd"
SAMBACFGDIR = "/etc/samba"
TFTPCFGDIR = "/var/lib/tftpboot"
INETDCFGDIR = "/etc/xinetd.d/"
DEFAULTDEV = "" DEFAULTDEV = ""
PACKAGES_TO_INSTALL = ["htop"] PACKAGES_TO_INSTALL = ["htop"]
@ -54,11 +49,9 @@ if os.path.isdir(f"{PROGRAM_DIR}/../installer"):
else: else:
REMOTE = 1 REMOTE = 1
# Create log file with sudo and set owner to ogboot
log_file = f'/var/log/{PROGRAM}.log' log_file = f'/var/log/{PROGRAM}.log'
os.makedirs(os.path.dirname(log_file), exist_ok=True) os.makedirs(os.path.dirname(log_file), exist_ok=True)
subprocess.run(['sudo', 'touch', log_file]) subprocess.run(['sudo', 'touch', log_file])
#subprocess.run(['sudo', 'chown', 'ogboot', log_file])
subprocess.run(['sudo', 'chmod', '775', log_file]) subprocess.run(['sudo', 'chmod', '775', log_file])
#Configure the log #Configure the log
@ -104,13 +97,6 @@ def check_distribution():
logger.error("Leaving the installation.") logger.error("Leaving the installation.")
exit() exit()
def cidr2mask(cidr):
args = [5 - (cidr // 8), 255, 255, 255, 255, (255 << (8 - (cidr % 8))) & 255, 0, 0, 0]
if args[0] > 1:
args = args[args[0]:]
else:
args = args[1:]
return f"{args[0]}.{args[1]}.{args[2]}.{args[3]}"
def downloadCode(url): def downloadCode(url):
if len(url) != 1: if len(url) != 1:
@ -191,10 +177,7 @@ def install_packages(missing, log_packages_file="/tmp/installed_packages.log"):
try: try:
os.environ['DEBIAN_FRONTEND'] = 'noninteractive' os.environ['DEBIAN_FRONTEND'] = 'noninteractive'
# Actualizamos la lista de paquetes
subprocess.run(["sudo", "apt-get", "update"], check=True) subprocess.run(["sudo", "apt-get", "update"], check=True)
# Instalamos todos los paquetes de una sola vez
subprocess.run( subprocess.run(
["sudo", "apt-get", "install", "--allow-change-held-packages", "-y", "--no-install-recommends"] + missing, ["sudo", "apt-get", "install", "--allow-change-held-packages", "-y", "--no-install-recommends"] + missing,
check=True check=True
@ -208,7 +191,6 @@ def install_packages(missing, log_packages_file="/tmp/installed_packages.log"):
logger.info("All missing packages have been installed.") logger.info("All missing packages have been installed.")
finally: finally:
# Restaurar el valor original de DEBIAN_FRONTEND
if original_debian_frontend is not None: if original_debian_frontend is not None:
os.environ['DEBIAN_FRONTEND'] = original_debian_frontend os.environ['DEBIAN_FRONTEND'] = original_debian_frontend
else: else:
@ -242,18 +224,6 @@ ogboot ALL=(root) NOPASSWD: /opt/ogboot/lib/*.iso /mnt
except IOError as e: except IOError as e:
print(f"Failed to write to {sudoers_file}: {e}") print(f"Failed to write to {sudoers_file}: {e}")
def downloadComposer():
global WORKDIR, INSTALL_OGBOOT_TARGET
logger.info("Downloading composer.phar...")
os.makedirs(os.path.join(WORKDIR, "ogboot", "bin"), mode=0o775, exist_ok=True)
subprocess.run(["curl", "-sS", "-o", os.path.join(WORKDIR, "ogboot", "bin", "composer.phar"), "https://getcomposer.org/installer"], check=True)
if not os.path.isfile(os.path.join(WORKDIR, "ogboot", "bin", "composer.phar")):
logger.error("Failed to download composer.phar")
return 1
logger.info(f"composer.phar downloaded to {INSTALL_OGBOOT_TARGET}/bin")
return 0
def og_core_create_user(OPENGNSYS_CLIENT_USER): def og_core_create_user(OPENGNSYS_CLIENT_USER):
try: try:
pwd.getpwnam(OPENGNSYS_CLIENT_USER) pwd.getpwnam(OPENGNSYS_CLIENT_USER)
@ -279,8 +249,8 @@ def og_boot_create_dirs():
# os.makedirs("/opt/ogboot/tftpboot/ipxe_scripts/templates", mode=0o750, exist_ok=True) # os.makedirs("/opt/ogboot/tftpboot/ipxe_scripts/templates", mode=0o750, exist_ok=True)
# Cambiar el propietario de los directorios # Cambiar el propietario de los directorios
subprocess.run(["sudo", "chown", "-R", "ogboot:ogboot", INSTALL_OGBOOT_TARGET]) subprocess.run(["chown", "-R", "ogboot:ogboot", INSTALL_OGBOOT_TARGET])
# subprocess.run(["sudo", "chown", "-R", "ogboot:ogboot", "/opt/ogboot/tftpboot/"])
logger.info(f"{INSTALL_OGBOOT_TARGET} directory created successfully.") logger.info(f"{INSTALL_OGBOOT_TARGET} directory created successfully.")
except OSError: except OSError:
@ -332,7 +302,7 @@ def og_boot_copy_files():
os.makedirs("/tmp/opt") os.makedirs("/tmp/opt")
# Cambiar el propietario del directorio # Cambiar el propietario del directorio
subprocess.run(["sudo", "chown", "ogboot:ogboot", "/tmp/opt"]) subprocess.run(["chown", "ogboot:ogboot", "/tmp/opt"])
if os.path.exists(bin_dest): if os.path.exists(bin_dest):
shutil.rmtree(bin_dest) shutil.rmtree(bin_dest)
@ -354,8 +324,8 @@ def og_boot_copy_files():
os.makedirs(os.path.join(INSTALL_TARGET, "client"), mode=0o775, exist_ok=True) os.makedirs(os.path.join(INSTALL_TARGET, "client"), mode=0o775, exist_ok=True)
os.makedirs(os.path.join(INSTALL_TARGET, "public"), mode=0o775, exist_ok=True) os.makedirs(os.path.join(INSTALL_TARGET, "public"), mode=0o775, exist_ok=True)
subprocess.run(["sudo", "chmod", "-R", "775", INSTALL_OGBOOT_TARGET]) subprocess.run(["chmod", "-R", "775", INSTALL_OGBOOT_TARGET])
subprocess.run(["sudo", "chown", "-R", "ogboot:ogboot", INSTALL_OGBOOT_TARGET]) subprocess.run(["chown", "-R", "ogboot:ogboot", INSTALL_OGBOOT_TARGET])
def og_boot_composer_install(): def og_boot_composer_install():
# Ejecutar Composer como el usuario 'ogboot' para instalar el proyecto Symfony # Ejecutar Composer como el usuario 'ogboot' para instalar el proyecto Symfony
@ -374,7 +344,7 @@ def og_boot_composer_install():
if os.path.exists(composer_lock_path): if os.path.exists(composer_lock_path):
os.remove(composer_lock_path) os.remove(composer_lock_path)
subprocess.call(["sudo", "chown", "-R", "ogboot:ogboot", f"{INSTALL_OGBOOT_TARGET}/public"]) subprocess.call(["chown", "-R", "ogboot:ogboot", f"{INSTALL_OGBOOT_TARGET}/public"])
logger.info("Application skeleton created and composer.lock file removed.") logger.info("Application skeleton created and composer.lock file removed.")
@ -406,38 +376,11 @@ def backupFile(file):
shutil.copy2(file, backup_file) shutil.copy2(file, backup_file)
logger.info(f"Backup of {file} successful") logger.info(f"Backup of {file} successful")
def testPxe():
global TFTPCFGDIR
logger.info(f"Checking TFTP service... please wait.")
subprocess.run(["echo", "test"], stdout=open(f"{TFTPCFGDIR}/testpxe", "w"))
try:
subprocess.run(["tftp", "-v", "127.0.0.1", "-c", "get", "testpxe", "/tmp/testpxe"], check=True)
logger.info("TFTP service is OK.")
except subprocess.CalledProcessError:
logger.error("TFTP service is down.")
os.remove(f"{TFTPCFGDIR}/testpxe")
def run_command(command):
result = subprocess.run(command, shell=True, text=True, capture_output=True)
if result.returncode != 0:
logger.error(f"Error executing command: {command}")
logger.error(result.stderr)
exit(1)
#logger.info(result.stdout)
def tftpConfigure(): def tftpConfigure():
global TFTPSERV, INETDSERV, TFTPCFGDIR global INETDSERV
# Update the package list TFTPCFGDIR = "/var/lib/tftpboot"
#print("Updating package list...")
##################### run_command("sudo apt update")
##################### run_command("sudo DEBIAN_FRONTEND=noninteractive apt install -y build-essential")
# Install tftpd-hpa in non-interactive mode
##################### logger.info("Installing tftpd-hpa...")
##################### run_command("sudo DEBIAN_FRONTEND=noninteractive apt install -y tftpd-hpa")
# Configure tftpd-hpa
logger.info("Configuring tftpd-hpa...") logger.info("Configuring tftpd-hpa...")
tftpd_config = """ tftpd_config = """
# /etc/default/tftpd-hpa # /etc/default/tftpd-hpa
@ -450,45 +393,20 @@ TFTP_OPTIONS="--secure"
with open("/tmp/tftpd-hpa", "w") as config_file: with open("/tmp/tftpd-hpa", "w") as config_file:
config_file.write(tftpd_config) config_file.write(tftpd_config)
run_command("sudo mv /tmp/tftpd-hpa /etc/default/tftpd-hpa") shutil.move("/tmp/tftpd-hpa", "/etc/default/tftpd-hpa")
# Create and set permissions for the TFTP directory
logger.info("\t2-Creating and setting permissions for the TFTP directory...") logger.info("\t2-Creating and setting permissions for the TFTP directory...")
run_command("sudo mkdir -p /var/lib/tftpboot") os.makedirs("/var/lib/tftpboot", exist_ok=True)
run_command("sudo chown -R tftp:tftp /var/lib/tftpboot")
run_command("sudo chmod -R 775 /var/lib/tftpboot")
# Restart the tftpd-hpa service subprocess.run("sudo chown -R tftp:tftp /var/lib/tftpboot", shell=True, text=True, capture_output=True)
logger.info("Restarting tftpd-hpa service...") subprocess.run("sudo chmod -R 775 /var/lib/tftpboot", shell=True, text=True, capture_output=True)
run_command("sudo systemctl restart tftpd-hpa")
# Check the status of the tftpd-hpa service logger.info("\t3-Setting permissions for /var/lib/tftpboot directory...")
subprocess.run("sudo systemctl restart tftpd-hpa", shell=True, text=True, capture_output=True)
logger.info("Checking tftpd-hpa service status...") logger.info("Checking tftpd-hpa service status...")
run_command("sudo systemctl status tftpd-hpa") subprocess.run("sudo systemctl status tftpd-hpa", shell=True, text=True, capture_output=True)
# if TFTPSERV:
# logger.info(f"TFTPSERV is configured: {TFTPSERV}")
# inetd_cfg_path = f"{INETDCFGDIR}/{TFTPSERV}"
# if os.path.isfile(inetd_cfg_path):
# logger.error(f"The inetd configuration file exists: {inetd_cfg_path}")
# with open(inetd_cfg_path, "r+") as file:
# content = file.read()
# new_content = content.replace("disable.*", "disable = no")
# file.seek(0)
# file.write(new_content)
# file.truncate()
# logger.info(f"Modified inetd configuration file: {inetd_cfg_path}")
# else:
# service = TFTPSERV
# logger.info(f"Enabling and starting the service {service}.service")
# subprocess.run(["systemctl", "enable", f"{service}.service"], check=True)
# subprocess.run(["systemctl", "start", f"{service}.service"], check=True)
# service = INETDSERV
# logger.info(f"Enabling and starting the service {service}.service")
#subprocess.run(["systemctl", "enable", f"{service}.service"], check=True)
# subprocess.run(["systemctl", "start", f"{service}.service"], check=True)
#Crear directorio /var/lib/tftpboot
if os.path.exists(TFTPCFGDIR): if os.path.exists(TFTPCFGDIR):
############## os.makedirs(TFTPCFGDIR, mode=0o775, exist_ok=True)
subprocess.run(["chown", "-R", "tftp:ogboot", TFTPCFGDIR]) subprocess.run(["chown", "-R", "tftp:ogboot", TFTPCFGDIR])
logger.info(f"{TFTPCFGDIR} directory permissions modified correctly.") logger.info(f"{TFTPCFGDIR} directory permissions modified correctly.")
else: else:
@ -500,7 +418,6 @@ TFTP_OPTIONS="--secure"
os.lchown(symlink_target, pwd.getpwnam("tftp").pw_uid, pwd.getpwnam("ogboot").pw_gid) os.lchown(symlink_target, pwd.getpwnam("tftp").pw_uid, pwd.getpwnam("ogboot").pw_gid)
else: else:
logger.warning(f"The symbolic link already exists: {symlink_target}") logger.warning(f"The symbolic link already exists: {symlink_target}")
#Descargar oglive
logger.info("Downloading oglive...") logger.info("Downloading oglive...")
iso_url = "https://ognproject.evlt.uma.es/trac/downloads/ogLive-focal-5.13.0-27-beta-amd64-r20210706.5b4bf5f.iso" iso_url = "https://ognproject.evlt.uma.es/trac/downloads/ogLive-focal-5.13.0-27-beta-amd64-r20210706.5b4bf5f.iso"
try: try:
@ -510,6 +427,17 @@ TFTP_OPTIONS="--secure"
capture_output=True, capture_output=True,
text=True text=True
) )
# Comprobar si oglivecli ha fallado
if result.returncode != 0:
try:
# Parsear la salida como JSON
error_output = json.loads(result.stdout)
if error_output.get("status") == "error":
logger.error(f"oglivecli error: {error_output.get('error')}")
except json.JSONDecodeError:
logger.error("Failed to parse oglivecli error output.")
logger.error("Continuing with the installation despite oglivecli failure.")
else:
logger.info("Successful download") logger.info("Successful download")
symlink_target_ogLive = f"{INSTALL_OGBOOT_TARGET}/tftpboot/ogLive" symlink_target_ogLive = f"{INSTALL_OGBOOT_TARGET}/tftpboot/ogLive"
symlink_target_ogclient = f"{INSTALL_OGBOOT_TARGET}/tftpboot/ogclient" symlink_target_ogclient = f"{INSTALL_OGBOOT_TARGET}/tftpboot/ogclient"
@ -518,26 +446,19 @@ TFTP_OPTIONS="--secure"
os.lchown(symlink_target_ogLive, pwd.getpwnam("tftp").pw_uid, pwd.getpwnam("ogboot").pw_gid) os.lchown(symlink_target_ogLive, pwd.getpwnam("tftp").pw_uid, pwd.getpwnam("ogboot").pw_gid)
os.lchown(symlink_target_ogclient, pwd.getpwnam("tftp").pw_uid, pwd.getpwnam("ogboot").pw_gid) os.lchown(symlink_target_ogclient, pwd.getpwnam("tftp").pw_uid, pwd.getpwnam("ogboot").pw_gid)
logger.info(f"Changing properties for {symlink_target_ogLive} and {symlink_target_ogclient}") logger.info(f"Changing properties for {symlink_target_ogLive} and {symlink_target_ogclient}")
else:
logger.error(f"{symlink_target_ogLive} link does not exists.") logger.error(f"{symlink_target_ogLive} link does not exists.")
else:
logger.error(f"{symlink_target_ogLive} link does not exist.")
except subprocess.CalledProcessError as e: except subprocess.CalledProcessError as e:
logger.error(f"Failed to install ogLive client: {e}") logger.error(f"Subprocess failed: {e}")
logger.error("Continuing with the installation...") logger.error("Continuing with the installation...")
#----------------------------------------------------------------------------------------------
#----------------------------------------------------------------------------------------------
#logger.info("Creating symbolic link from /opt/ogboot/tftpboot to /var/lib/tftpboot...")
#if os.path.islink(symlink_target):
# run_command(f"sudo rm -rf {symlink_target}")
#elif os.path.exists(symlink_target):
# run_command(f"sudo ln -s {TFTPCFGDIR} {INSTALL_OGBOOT_TARGET}")
#----------------------------------------------------------------------------------------------
#----------------------------------------------------------------------------------------------
def servicesCompilation(): def servicesCompilation():
global WORKDIR global WORKDIR
hayErrores = 0 hayErrores = 0
process = subprocess.run(["make"], cwd=f"{WORKDIR}/ogboot/sources/clients/ogAdmClient") process = subprocess.run(["make"], cwd=f"{WORKDIR}/ogboot/sources/clients/ogAdmClient")
subprocess.run(["mv", f"{WORKDIR}/ogboot/sources/clients/ogAdmClient/ogAdmClient", f"{WORKDIR}/ogboot/client/shared/bin"]) shutil.move(f"{WORKDIR}/ogboot/sources/clients/ogAdmClient/ogAdmClient", f"{WORKDIR}/ogboot/client/shared/bin")
if process.returncode != 0: if process.returncode != 0:
logger.info(f"{servicesCompilation.__name__}(): error while compiling OpenGnsys Admin Client") logger.info(f"{servicesCompilation.__name__}(): error while compiling OpenGnsys Admin Client")
hayErrores = 1 hayErrores = 1
@ -578,21 +499,6 @@ def copyClientFiles():
logger.error(f"Client copy files with errors") logger.error(f"Client copy files with errors")
return errstatus return errstatus
def cidr2mask(bits):
args = [5 - (bits // 8), 255, 255, 255, 255, (255 << (8 - (bits % 8))) & 255, 0, 0, 0]
if args[0] > 1:
args = args[args[0]:]
else:
args = args[1:]
return ".".join(str(arg) for arg in args)
def mask2cidr(mask):
addr = mask.split(".")
cidr = 0
for i in addr:
cidr += bin(int(i)).count("1")
return cidr
def get_first_network_interface_with_traffic(): def get_first_network_interface_with_traffic():
with open('/proc/net/dev') as f: with open('/proc/net/dev') as f:
for line in f: for line in f:
@ -607,37 +513,7 @@ def get_first_network_interface_with_traffic():
if received_bytes > 0 or transmitted_bytes > 0: if received_bytes > 0 or transmitted_bytes > 0:
return interface return interface
def getNetworkSettings():
global DEVICE, SERVERIP, NETMASK, NETBROAD, NETIP, ROUTERIP, DEFAULTDEV
DHCPNET = "127.0.0.1"
#print("getNetworkSettings(): Detecting network parameters.")
output = subprocess.check_output(["ip", "-o", "link", "show", "up"]).decode("utf-8")
lines = output.strip().split("\n")
for line in lines:
dev = line.split(":")[1].split("@")[0].strip()
output = subprocess.check_output(["ip", "-o", "addr", "show", "dev", dev]).decode("utf-8")
addr_lines = output.strip().split("\n")
for addr_line in addr_lines:
addr_parts = addr_line.split()
cidr_netmask = addr_parts[3].split("/")[1]
cidr_netmask = int(cidr_netmask)
if cidr_netmask >= 0 and cidr_netmask <= 32:
netmask = ".".join([str((0xffffffff << (32 - cidr_netmask) >> i) & 0xff) for i in [24, 16, 8, 0]])
if addr_parts[2] == "inet":
DEVICE.append(dev)
SERVERIP.append(addr_parts[3].split("/")[0])
NETMASK.append(netmask)
NETBROAD.append(addr_parts[5])
NETIP.append(addr_parts[3].split("/")[0])
ROUTERIP.append(subprocess.check_output(["ip", "route", "list", "default"]).decode("utf-8").split()[2])
if DHCPNET == NETIP[-1]:
DEFAULTDEV = dev
else:
DEFAULTDEV = DEFAULTDEV if "DEFAULTDEV" in locals() else dev
if len(NETIP) == 0 or len(NETMASK) == 0:
return (1)
else:
return (0)
def openGnsysConfigure(): def openGnsysConfigure():
global DEFAULTDEV, INSTALL_TARGET, OGCORE_IP, WORKDIR global DEFAULTDEV, INSTALL_TARGET, OGCORE_IP, WORKDIR
@ -672,11 +548,9 @@ def mount_NFS():
logger.error("Could not mount the NFS system.") logger.error("Could not mount the NFS system.")
exit(1) exit(1)
logger.info("copying tftpboot files") logger.info("copying tftpboot files")
#subprocess.call(["ls", "/mnt/"])
subprocess.call(["sudo", "cp", "-r", "/mnt/srv/artefactos/ogboot/tftpboot/", "/tmp"]) subprocess.call(["sudo", "cp", "-r", "/mnt/srv/artefactos/ogboot/tftpboot/", "/tmp"])
if not os.path.exists(IPXE_DIR + "/tftpboot"): if not os.path.exists(IPXE_DIR + "/tftpboot"):
os.makedirs(IPXE_DIR + "/tftpboot") os.makedirs(IPXE_DIR + "/tftpboot")
#os.chdir(f"{IPXE_DIR}/tftpboot")
logger.info("copying ipxe files") logger.info("copying ipxe files")
subprocess.call(["sudo", "cp", "-r", "/mnt/srv/artefactos/ogboot/ipxe/", "/tmp"]) subprocess.call(["sudo", "cp", "-r", "/mnt/srv/artefactos/ogboot/ipxe/", "/tmp"])
if not os.path.exists(IPXE_DIR + "/src"): if not os.path.exists(IPXE_DIR + "/src"):
@ -763,7 +637,8 @@ def user_exists(user):
return False return False
def smbConfigure(): def smbConfigure():
global SAMBACFGDIR, SAMBASERV, OPENGNSYS_CLIENT_PASSWD, OPENGNSYS_CLIENT_USER, PYTHON_VERSION global OPENGNSYS_CLIENT_PASSWD, OPENGNSYS_CLIENT_USER, PYTHON_VERSION
SAMBACFGDIR = "/etc/samba"
#logger.info(f"{smbConfigure.__name__}(): Configuring Samba service.") #logger.info(f"{smbConfigure.__name__}(): Configuring Samba service.")
backupFile(f"{SAMBACFGDIR}/smb.conf") backupFile(f"{SAMBACFGDIR}/smb.conf")
# Copiar plantilla de recursos para OpenGnsys # Copiar plantilla de recursos para OpenGnsys
@ -777,7 +652,7 @@ def smbConfigure():
if "smb-ogboot" not in open(f"{SAMBACFGDIR}/smb.conf").read(): if "smb-ogboot" not in open(f"{SAMBACFGDIR}/smb.conf").read():
with open(f"{SAMBACFGDIR}/smb.conf", "a") as file: with open(f"{SAMBACFGDIR}/smb.conf", "a") as file:
file.write(f"include = {SAMBACFGDIR}/smb-ogboot.conf\n") file.write(f"include = {SAMBACFGDIR}/smb-ogboot.conf\n")
service = SAMBASERV service = "smbd"
logger.info(f"Enabling {service} service.") logger.info(f"Enabling {service} service.")
subprocess.run(["systemctl", "enable", f"{service}.service"]) subprocess.run(["systemctl", "enable", f"{service}.service"])
logger.info(f"Restarting {service} service.") logger.info(f"Restarting {service} service.")
@ -940,101 +815,168 @@ logger.info(f"GIT_REPO:{GIT_REPO}")
if os.geteuid() != 0: if os.geteuid() != 0:
logger.error("This program must be run with root privileges..") logger.error("This program must be run with root privileges..")
exit(1) exit(1)
if os.path.exists(os.path.join(INSTALL_OGBOOT_TARGET, "/doc/")): if os.path.exists(os.path.join(INSTALL_OGBOOT_TARGET, "/doc/")):
logger.warning(f"ogBoot is already installed. Run {INSTALL_OGBOOT_TARGET}/lib/ogboot_devel_update.py” with root privileges to update..") logger.warning(f"ogBoot is already installed. Run {INSTALL_OGBOOT_TARGET}/lib/ogboot_devel_update.py with root privileges to update..")
exit(2) exit(2)
try:
logger.info("Verifying Python distribution and version.") logger.info("Verifying Python distribution and version.")
check_distribution() check_distribution()
check_python_version() check_python_version()
except Exception as e:
logger.error(f"Error verifying Python distribution or version: {e}")
exit(1)
try:
logger.info("Checking the operating system.") logger.info("Checking the operating system.")
autoConfigure() autoConfigure()
except Exception as e:
logger.error(f"Error checking the operating system: {e}")
exit(1)
try:
logger.info("Installing necessary packages.") logger.info("Installing necessary packages.")
Missing = get_missing_packages() Missing = get_missing_packages()
install_packages(Missing) install_packages(Missing)
except Exception as e:
logger.error(f"Error installing necessary packages: {e}")
exit(1)
try:
logger.info("Obtaining the default network configuration.") logger.info("Obtaining the default network configuration.")
DEFAULTDEV = get_first_network_interface_with_traffic() DEFAULTDEV = get_first_network_interface_with_traffic()
logger.info(f"Network interface default:[{DEFAULTDEV}]") logger.info(f"Network interface default:[{DEFAULTDEV}]")
#if getNetworkSettings() != 0: except Exception as e:
# logger.error("Error reading default network settings.") logger.error(f"Error obtaining network configuration: {e}")
# exit(1) exit(1)
try:
logger.info("Configuring package repositories.") logger.info("Configuring package repositories.")
if REMOTE == 1: if REMOTE == 1:
downloadCode(GIT_REPO) downloadCode(GIT_REPO)
if os.system("echo $?") != 0:
logger.error("Error while getting code from the repository")
exit(1)
else: else:
if not os.path.exists(f"{WORKDIR}/ogboot"): if not os.path.exists(f"{WORKDIR}/ogboot"):
if not os.path.exists(WORKDIR): if not os.path.exists(WORKDIR):
os.makedirs(WORKDIR, mode=0o775, exist_ok=True) os.makedirs(WORKDIR, mode=0o775, exist_ok=True)
logger.info(f"{WORKDIR}/ogboot directory created") logger.info(f"{WORKDIR}/ogboot directory created")
logger.info(f"ogBoot directory not found, create a symbolic link to the directory where the code is located {WORKDIR} To {os.path.dirname(PROGRAM_DIR)}") logger.info(f"ogBoot directory not found, creating a symbolic link to the code directory")
os.symlink(os.path.dirname(PROGRAM_DIR), f"{WORKDIR}/ogboot") os.symlink(os.path.dirname(PROGRAM_DIR), f"{WORKDIR}/ogboot")
except Exception as e:
logger.error(f"Error configuring package repositories: {e}")
exit(1)
try:
add_sudoers_permissions() add_sudoers_permissions()
except Exception as e:
logger.error(f"Error adding sudoers permissions: {e}")
exit(1)
try:
logger.info("Creating ogBoot project.") logger.info("Creating ogBoot project.")
og_core_create_user("ogboot") og_core_create_user("ogboot")
og_core_create_user(OPENGNSYS_CLIENT_USER) og_core_create_user(OPENGNSYS_CLIENT_USER)
except Exception as e:
logger.error(f"Error creating ogBoot project or users: {e}")
exit(1)
try:
logger.info("Creating directories.") logger.info("Creating directories.")
og_boot_create_dirs() og_boot_create_dirs()
except Exception as e:
logger.error(f"Error creating directories: {e}")
exit(1)
try:
logger.info("Copying installation files.") logger.info("Copying installation files.")
og_boot_copy_files() og_boot_copy_files()
except Exception as e:
logger.error(f"Error copying installation files: {e}")
exit(1)
try:
logger.info("Installing Symfony.") logger.info("Installing Symfony.")
og_boot_symfony_install() og_boot_symfony_install()
except Exception as e:
logger.error(f"Error installing Symfony: {e}")
exit(1)
try:
logger.info("Installing Composer.") logger.info("Installing Composer.")
og_boot_composer_install() og_boot_composer_install()
except Exception as e:
logger.error(f"Error installing Composer: {e}")
exit(1)
try:
logger.info("Configuring tftpd-hpa service.") logger.info("Configuring tftpd-hpa service.")
tftpConfigure() tftpConfigure()
except Exception as e:
logger.error(f"Error configuring tftpd-hpa service: {e}")
exit(1)
try:
logger.info("Configuring IPXE services") logger.info("Configuring IPXE services")
generate_ipxe_script() generate_ipxe_script()
except Exception as e:
logger.error(f"Error configuring IPXE services: {e}")
exit(1)
try:
logger.info("Setting up NFS system") logger.info("Setting up NFS system")
mount_NFS() mount_NFS()
except Exception as e:
logger.error(f"Error setting up NFS system: {e}")
exit(1)
try:
logger.info("Compiling OpenGnsys services source code") logger.info("Compiling OpenGnsys services source code")
servicesCompilation() servicesCompilation()
if subprocess.run(["echo", "$?"]).returncode != 0: except Exception as e:
logger.error("Error while compiling OpenGnsys services") logger.error(f"Error compiling OpenGnsys services: {e}")
exit(1) exit(1)
try:
logger.info("Copy folder Interface between administration and cloning engine") logger.info("Copy folder Interface between administration and cloning engine")
copyInterfaceAdm() copyInterfaceAdm()
if subprocess.run(["echo", "$?"]).returncode != 0: except Exception as e:
logger.error("Error while copying Administration Interface") logger.error(f"Error copying Administration Interface: {e}")
exit(1) exit(1)
try:
logger.info("Create the structure of the accesses to the server from the client (shared)") logger.info("Create the structure of the accesses to the server from the client (shared)")
copyClientFiles() copyClientFiles()
if subprocess.run(["echo", "$?"]).returncode != 0: except Exception as e:
logger.error("Error creating client structure") logger.error(f"Error creating client structure: {e}")
exit(1)
try:
logger.info("Setup nginx") logger.info("Setup nginx")
setup_nginx() setup_nginx()
if subprocess.run(["echo", "$?"]).returncode != 0: except Exception as e:
logger.error("Error setup nginx") logger.error(f"Error setting up nginx: {e}")
exit(1)
try:
logger.info("Configure php fpm") logger.info("Configure php fpm")
modify_php_fpm_config() modify_php_fpm_config()
if subprocess.run(["echo", "$?"]).returncode != 0: except Exception as e:
logger.error("Error configure php fpm") logger.error(f"Error configuring php fpm: {e}")
exit(1)
try:
logger.info("Configuring ogCore") logger.info("Configuring ogCore")
openGnsysConfigure() openGnsysConfigure()
except Exception as e:
logger.error(f"Error configuring ogCore: {e}")
exit(1)
try:
logger.info("Configuring Samba") logger.info("Configuring Samba")
smbConfigure() smbConfigure()
except Exception as e:
logger.error(f"Error configuring Samba: {e}")
exit(1)
logger.info(f"ogBoot installation finished.") logger.info(f"ogBoot installation finished.")