refs #1025 fix whitespace
parent
9cf9742ec8
commit
b57e80aa00
|
@ -21,7 +21,7 @@ PROGRAM_NAME = os.path.basename(sys.argv[0])
|
||||||
|
|
||||||
config_file = os.path.join(PROGRAM_DIR, 'config.json')
|
config_file = os.path.join(PROGRAM_DIR, 'config.json')
|
||||||
with open(config_file, 'r') as f:
|
with open(config_file, 'r') as f:
|
||||||
config = json.load(f)
|
config = json.load(f)
|
||||||
|
|
||||||
OGCORE_IP = config["ogCore_ServerIP"]
|
OGCORE_IP = config["ogCore_ServerIP"]
|
||||||
INSTALL_OGBOOT_TARGET = config["ogBoot_Dir"]
|
INSTALL_OGBOOT_TARGET = config["ogBoot_Dir"]
|
||||||
|
@ -63,114 +63,114 @@ logger.addHandler(console_handler)
|
||||||
###::::::::::::::::::::::::::::::: UTILS :::::::::::::::::::::::::::::::::::###
|
###::::::::::::::::::::::::::::::: UTILS :::::::::::::::::::::::::::::::::::###
|
||||||
###############################################################################
|
###############################################################################
|
||||||
def check_python_version():
|
def check_python_version():
|
||||||
try:
|
try:
|
||||||
python_version = platform.python_version()
|
python_version = platform.python_version()
|
||||||
python_version_tuple = tuple(map(int, python_version.split('.')))
|
python_version_tuple = tuple(map(int, python_version.split('.')))
|
||||||
if python_version_tuple >= (PYTHON_VERSION, 0):
|
if python_version_tuple >= (PYTHON_VERSION, 0):
|
||||||
logger.info(f"Python version installed: {python_version}")
|
logger.info(f"Python version installed: {python_version}")
|
||||||
else:
|
else:
|
||||||
logger.error(f"Python version is lower than required. Installed version: {python_version}" + ".")
|
logger.error(f"Python version is lower than required. Installed version: {python_version}" + ".")
|
||||||
exit()
|
exit()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Problem verifying Python version: {e}")
|
logger.error(f"Problem verifying Python version: {e}")
|
||||||
exit()
|
exit()
|
||||||
|
|
||||||
def check_distribution():
|
def check_distribution():
|
||||||
if os.path.exists("/etc/os-release"):
|
if os.path.exists("/etc/os-release"):
|
||||||
with open("/etc/os-release", "r") as file:
|
with open("/etc/os-release", "r") as file:
|
||||||
for line in file:
|
for line in file:
|
||||||
if line.startswith("VERSION"):
|
if line.startswith("VERSION"):
|
||||||
VERSION = line.split("=")[1].strip().strip('"')
|
VERSION = line.split("=")[1].strip().strip('"')
|
||||||
break
|
break
|
||||||
if VERSION.startswith(UBUNTU_OS_VERSION + "."):
|
if VERSION.startswith(UBUNTU_OS_VERSION + "."):
|
||||||
return
|
return
|
||||||
logger.info(f"The ogBoot installation has been tested with full functionality on Ubuntu. {UBUNTU_OS_VERSION}")
|
logger.info(f"The ogBoot installation has been tested with full functionality on Ubuntu. {UBUNTU_OS_VERSION}")
|
||||||
go_on = input("Would you like to continue? [y/N]: ")
|
go_on = input("Would you like to continue? [y/N]: ")
|
||||||
if go_on.upper() != "Y":
|
if go_on.upper() != "Y":
|
||||||
logger.error("Leaving the installation.")
|
logger.error("Leaving the installation.")
|
||||||
exit()
|
exit()
|
||||||
|
|
||||||
###############################################################################
|
###############################################################################
|
||||||
###:::::::::::::::::::::::::::::: INSTALL ::::::::::::::::::::::::::::::::::###
|
###:::::::::::::::::::::::::::::: INSTALL ::::::::::::::::::::::::::::::::::###
|
||||||
###############################################################################
|
###############################################################################
|
||||||
|
|
||||||
def get_missing_packages():
|
def get_missing_packages():
|
||||||
PACKAGES_TO_INSTALL = []
|
PACKAGES_TO_INSTALL = []
|
||||||
|
|
||||||
OSDISTRIB = distro.name()
|
OSDISTRIB = distro.name()
|
||||||
OSVERSION = distro.version()
|
OSVERSION = distro.version()
|
||||||
logger.info(f"OSDISTRIB: {OSDISTRIB}")
|
logger.info(f"OSDISTRIB: {OSDISTRIB}")
|
||||||
logger.info(f"OSVERSION: {OSVERSION}")
|
logger.info(f"OSVERSION: {OSVERSION}")
|
||||||
match OSDISTRIB.lower():
|
match OSDISTRIB.lower():
|
||||||
case "ubuntu":
|
case "ubuntu":
|
||||||
match OSVERSION:
|
match OSVERSION:
|
||||||
case "20.04":
|
case "20.04":
|
||||||
PACKAGES_TO_INSTALL = ["vim", "curl", "htop"]
|
PACKAGES_TO_INSTALL = ["vim", "curl", "htop"]
|
||||||
case "18.04":
|
case "18.04":
|
||||||
PACKAGES_TO_INSTALL = ["nano", "wget", "tree"]
|
PACKAGES_TO_INSTALL = ["nano", "wget", "tree"]
|
||||||
case "22.04":
|
case "22.04":
|
||||||
PACKAGES_TO_INSTALL = ["nfs-common", "xorriso", "genisoimage", "syslinux", "liblzma-dev", "nginx", "arp-scan", "automake", "build-essential", "btrfs-progs", "composer", "curl", "ctorrent", "debootstrap", "g++-multilib", "gawk", "gettext", "graphviz", "grub-efi-amd64-signed", "jq", "libdbi-dev", "libdbi1", "libev-dev", "libjansson-dev", "liblz4-tool", "libssl-dev", "moreutils", "netpipes", "php", "php-bcmath", "php-cli", "php-curl", "php-fpm", "php-gd", "php-json", "php-ldap", "php-mbstring", "php-mysql", "php8.1-common", "php-pear", "php-xml", "php-zip", "procps", "coreutils", "rsync", "samba", "samba-common-bin", "schroot", "shim-signed", "squashfs-tools", "subversion", "tftpd-hpa", "udpcast", "unzip", "wakeonlan", "wget", "xinetd", "jq", "moreutils", "net-tools", "isolinux", "syslinux"]
|
PACKAGES_TO_INSTALL = ["nfs-common", "xorriso", "genisoimage", "syslinux", "liblzma-dev", "nginx", "arp-scan", "automake", "build-essential", "btrfs-progs", "composer", "curl", "ctorrent", "debootstrap", "g++-multilib", "gawk", "gettext", "graphviz", "grub-efi-amd64-signed", "jq", "libdbi-dev", "libdbi1", "libev-dev", "libjansson-dev", "liblz4-tool", "libssl-dev", "moreutils", "netpipes", "php", "php-bcmath", "php-cli", "php-curl", "php-fpm", "php-gd", "php-json", "php-ldap", "php-mbstring", "php-mysql", "php8.1-common", "php-pear", "php-xml", "php-zip", "procps", "coreutils", "rsync", "samba", "samba-common-bin", "schroot", "shim-signed", "squashfs-tools", "subversion", "tftpd-hpa", "udpcast", "unzip", "wakeonlan", "wget", "xinetd", "jq", "moreutils", "net-tools", "isolinux", "syslinux"]
|
||||||
case "24.04":
|
case "24.04":
|
||||||
PACKAGES_TO_INSTALL = ["nfs-common", "xorriso", "genisoimage", "syslinux", "liblzma-dev", "nginx", "arp-scan", "automake", "build-essential", "btrfs-progs", "composer", "curl", "ctorrent", "debootstrap", "g++-multilib", "gawk", "gettext", "graphviz", "grub-efi-amd64-signed", "jq", "libdbi-dev", "libdbi1", "libev-dev", "libjansson-dev", "liblz4-tool", "libssl-dev", "moreutils", "netpipes", "php8.3", "php8.3-bcmath", "php8.3-cli", "php8.3-curl", "php8.3-fpm", "php8.3-gd", "php8.3-ldap", "php8.3-mbstring", "php8.3-mysql", "php8.3-common", "php-pear", "php8.3-xml", "php8.3-zip", "procps", "coreutils", "rsync", "samba", "samba-common-bin", "schroot", "shim-signed", "squashfs-tools", "subversion", "tftpd-hpa", "udpcast", "unzip", "wakeonlan", "wget", "xinetd", "jq", "moreutils", "isolinux", "syslinux", "file"]
|
PACKAGES_TO_INSTALL = ["nfs-common", "xorriso", "genisoimage", "syslinux", "liblzma-dev", "nginx", "arp-scan", "automake", "build-essential", "btrfs-progs", "composer", "curl", "ctorrent", "debootstrap", "g++-multilib", "gawk", "gettext", "graphviz", "grub-efi-amd64-signed", "jq", "libdbi-dev", "libdbi1", "libev-dev", "libjansson-dev", "liblz4-tool", "libssl-dev", "moreutils", "netpipes", "php8.3", "php8.3-bcmath", "php8.3-cli", "php8.3-curl", "php8.3-fpm", "php8.3-gd", "php8.3-ldap", "php8.3-mbstring", "php8.3-mysql", "php8.3-common", "php-pear", "php8.3-xml", "php8.3-zip", "procps", "coreutils", "rsync", "samba", "samba-common-bin", "schroot", "shim-signed", "squashfs-tools", "subversion", "tftpd-hpa", "udpcast", "unzip", "wakeonlan", "wget", "xinetd", "jq", "moreutils", "isolinux", "syslinux", "file"]
|
||||||
case _:
|
case _:
|
||||||
PACKAGES_TO_INSTALL = ["bash", "rsync"]
|
PACKAGES_TO_INSTALL = ["bash", "rsync"]
|
||||||
#case "suse":
|
#case "suse":
|
||||||
# match OSVERSION:
|
# match OSVERSION:
|
||||||
# case "15":
|
# case "15":
|
||||||
# PACKAGES_TO_INSTALL = ["zypper", "mc", "gcc"]
|
# PACKAGES_TO_INSTALL = ["zypper", "mc", "gcc"]
|
||||||
# case "12":
|
# case "12":
|
||||||
# PACKAGES_TO_INSTALL = ["perl", "tar", "man"]
|
# PACKAGES_TO_INSTALL = ["perl", "tar", "man"]
|
||||||
# case _:
|
# case _:
|
||||||
# PACKAGES_TO_INSTALL = ["openssl", "ncurses", "zip"]
|
# PACKAGES_TO_INSTALL = ["openssl", "ncurses", "zip"]
|
||||||
#case "redhat":
|
#case "redhat":
|
||||||
# match OSVERSION:
|
# match OSVERSION:
|
||||||
# case "8":
|
# case "8":
|
||||||
# PACKAGES_TO_INSTALL = ["yum", "tar", "perl"]
|
# PACKAGES_TO_INSTALL = ["yum", "tar", "perl"]
|
||||||
# case "7":
|
# case "7":
|
||||||
# PACKAGES_TO_INSTALL = ["bash", "rpm", "tcpdump"]
|
# PACKAGES_TO_INSTALL = ["bash", "rpm", "tcpdump"]
|
||||||
# case _:
|
# case _:
|
||||||
# PACKAGES_TO_INSTALL = ["grep", "sed", "awk"]
|
# PACKAGES_TO_INSTALL = ["grep", "sed", "awk"]
|
||||||
case _:
|
case _:
|
||||||
logger.error("Distribution not supported by ogBoot.")
|
logger.error("Distribution not supported by ogBoot.")
|
||||||
exit(1)
|
exit(1)
|
||||||
|
|
||||||
installed = []
|
installed = []
|
||||||
for l in subprocess.run (['dpkg', '-s'] + PACKAGES_TO_INSTALL, capture_output=True, text=True).stdout.splitlines():
|
for l in subprocess.run (['dpkg', '-s'] + PACKAGES_TO_INSTALL, capture_output=True, text=True).stdout.splitlines():
|
||||||
if l.startswith ('Package:'):
|
if l.startswith ('Package:'):
|
||||||
installed.append (l.split (':')[1].strip())
|
installed.append (l.split (':')[1].strip())
|
||||||
faltantes = list (set(PACKAGES_TO_INSTALL) - set(installed))
|
faltantes = list (set(PACKAGES_TO_INSTALL) - set(installed))
|
||||||
logger.info(f"Packages to install: {faltantes}")
|
logger.info(f"Packages to install: {faltantes}")
|
||||||
return faltantes
|
return faltantes
|
||||||
|
|
||||||
def install_packages(log_packages_file="/tmp/installed_packages.log"):
|
def install_packages(log_packages_file="/tmp/installed_packages.log"):
|
||||||
missing = get_missing_packages()
|
missing = get_missing_packages()
|
||||||
if not missing:
|
if not missing:
|
||||||
logger.info("All packages are already installed.")
|
logger.info("All packages are already installed.")
|
||||||
return
|
return
|
||||||
|
|
||||||
logger.info("Upgrading the system...")
|
logger.info("Upgrading the system...")
|
||||||
|
|
||||||
subprocess.run(["apt-get", "update"], check=True)
|
subprocess.run(["apt-get", "update"], check=True)
|
||||||
subprocess.run(
|
subprocess.run(
|
||||||
["apt-get", "install", "--allow-change-held-packages", "-y", "--no-install-recommends"] + missing + ['apache2-'],
|
["apt-get", "install", "--allow-change-held-packages", "-y", "--no-install-recommends"] + missing + ['apache2-'],
|
||||||
check=True
|
check=True
|
||||||
)
|
)
|
||||||
|
|
||||||
with open(log_packages_file, "a") as log:
|
with open(log_packages_file, "a") as log:
|
||||||
for package in missing:
|
for package in missing:
|
||||||
logger.info(f"{package} installed correctly.")
|
logger.info(f"{package} installed correctly.")
|
||||||
log.write(package + "\n")
|
log.write(package + "\n")
|
||||||
|
|
||||||
logger.info("All missing packages have been installed.")
|
logger.info("All missing packages have been installed.")
|
||||||
|
|
||||||
# Check PHP version and install corresponding php-fpm package
|
# Check PHP version and install corresponding php-fpm package
|
||||||
php_version = subprocess.check_output(["php", "-v"]).decode("utf-8")
|
php_version = subprocess.check_output(["php", "-v"]).decode("utf-8")
|
||||||
if "PHP 8.1" in php_version:
|
if "PHP 8.1" in php_version:
|
||||||
subprocess.run(["apt-get", "install", "-y", "php8.1-fpm"], check=True)
|
subprocess.run(["apt-get", "install", "-y", "php8.1-fpm"], check=True)
|
||||||
elif "PHP 8.3" in php_version:
|
elif "PHP 8.3" in php_version:
|
||||||
subprocess.run(["apt-get", "install", "-y", "php8.3-fpm"], check=True)
|
subprocess.run(["apt-get", "install", "-y", "php8.3-fpm"], check=True)
|
||||||
else:
|
else:
|
||||||
logger.warning("PHP version not supported.")
|
logger.warning("PHP version not supported.")
|
||||||
|
|
||||||
def add_sudoers_permissions():
|
def add_sudoers_permissions():
|
||||||
sudoers_entry = """
|
sudoers_entry = """
|
||||||
|
@ -189,123 +189,123 @@ ogboot ALL=(root) NOPASSWD: __OGBOOT_TARGET__/lib/*.iso /mnt
|
||||||
print(f"Failed to write to {sudoers_file}: {e}")
|
print(f"Failed to write to {sudoers_file}: {e}")
|
||||||
|
|
||||||
def og_core_create_user(u):
|
def og_core_create_user(u):
|
||||||
try:
|
try:
|
||||||
pwd.getpwnam(u)
|
pwd.getpwnam(u)
|
||||||
logger.warning(f"User {u} already exists")
|
logger.warning(f"User {u} already exists")
|
||||||
except KeyError:
|
except KeyError:
|
||||||
subprocess.run(["useradd", "--create-home", u, "--shell", "/bin/bash"])
|
subprocess.run(["useradd", "--create-home", u, "--shell", "/bin/bash"])
|
||||||
logger.info(f"User {u} created successfully.")
|
logger.info(f"User {u} created successfully.")
|
||||||
|
|
||||||
def og_boot_create_dirs():
|
def og_boot_create_dirs():
|
||||||
if os.path.exists(INSTALL_OGBOOT_TARGET):
|
if os.path.exists(INSTALL_OGBOOT_TARGET):
|
||||||
if not os.path.isdir(INSTALL_OGBOOT_TARGET):
|
if not os.path.isdir(INSTALL_OGBOOT_TARGET):
|
||||||
raise NotADirectoryError(f"{INSTALL_OGBOOT_TARGET} exists and is not a directory.")
|
raise NotADirectoryError(f"{INSTALL_OGBOOT_TARGET} exists and is not a directory.")
|
||||||
else:
|
else:
|
||||||
logger.warning(f"{INSTALL_OGBOOT_TARGET} directory already exists.")
|
logger.warning(f"{INSTALL_OGBOOT_TARGET} directory already exists.")
|
||||||
else:
|
else:
|
||||||
try:
|
try:
|
||||||
# Crear los directorios necesarios
|
# Crear los directorios necesarios
|
||||||
os.makedirs(INSTALL_OGBOOT_TARGET, mode=0o775, exist_ok=True)
|
os.makedirs(INSTALL_OGBOOT_TARGET, mode=0o775, exist_ok=True)
|
||||||
os.makedirs(os.path.join(INSTALL_OGBOOT_TARGET, "client"), mode=0o775, exist_ok=True)
|
os.makedirs(os.path.join(INSTALL_OGBOOT_TARGET, "client"), mode=0o775, exist_ok=True)
|
||||||
|
|
||||||
# Cambiar el propietario de los directorios
|
# Cambiar el propietario de los directorios
|
||||||
subprocess.run(["chown", "-R", "ogboot:ogboot", INSTALL_OGBOOT_TARGET])
|
subprocess.run(["chown", "-R", "ogboot:ogboot", INSTALL_OGBOOT_TARGET])
|
||||||
|
|
||||||
|
|
||||||
logger.info(f"{INSTALL_OGBOOT_TARGET} directory created successfully.")
|
logger.info(f"{INSTALL_OGBOOT_TARGET} directory created successfully.")
|
||||||
except OSError:
|
except OSError:
|
||||||
logger.error("Error while creating directory paths!")
|
logger.error("Error while creating directory paths!")
|
||||||
exit(1)
|
exit(1)
|
||||||
|
|
||||||
def og_boot_symfony_install():
|
def og_boot_symfony_install():
|
||||||
logger.info("Creating Symfony application skeleton...")
|
logger.info("Creating Symfony application skeleton...")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Copiar los archivos .env y composer.json primero
|
# Copiar los archivos .env y composer.json primero
|
||||||
env_src = os.path.join(f"{REPO_DIR}", ".env")
|
env_src = os.path.join(f"{REPO_DIR}", ".env")
|
||||||
composer_src = os.path.join(f"{REPO_DIR}", "composer.json")
|
composer_src = os.path.join(f"{REPO_DIR}", "composer.json")
|
||||||
env_dest = os.path.join(f"{INSTALL_OGBOOT_TARGET}", ".env")
|
env_dest = os.path.join(f"{INSTALL_OGBOOT_TARGET}", ".env")
|
||||||
composer_dest = os.path.join(f"{INSTALL_OGBOOT_TARGET}", "composer.json")
|
composer_dest = os.path.join(f"{INSTALL_OGBOOT_TARGET}", "composer.json")
|
||||||
|
|
||||||
shutil.copy(env_src, env_dest)
|
shutil.copy(env_src, env_dest)
|
||||||
shutil.copy(composer_src, composer_dest)
|
shutil.copy(composer_src, composer_dest)
|
||||||
logger.info(f"Copied environment source {env_src} to {env_dest}")
|
logger.info(f"Copied environment source {env_src} to {env_dest}")
|
||||||
logger.info(f"Copied composer source {composer_src} to {composer_dest}")
|
logger.info(f"Copied composer source {composer_src} to {composer_dest}")
|
||||||
|
|
||||||
# Cambiar permisos y propietario de los archivos copiados
|
# Cambiar permisos y propietario de los archivos copiados
|
||||||
os.chmod(env_dest, 0o644)
|
os.chmod(env_dest, 0o644)
|
||||||
os.chmod(composer_dest, 0o644)
|
os.chmod(composer_dest, 0o644)
|
||||||
shutil.chown(env_dest, user='ogboot', group='ogboot')
|
shutil.chown(env_dest, user='ogboot', group='ogboot')
|
||||||
shutil.chown(composer_dest, user='ogboot', group='ogboot')
|
shutil.chown(composer_dest, user='ogboot', group='ogboot')
|
||||||
logger.info(f"Set permissions and owner for {env_dest} and {composer_dest}")
|
logger.info(f"Set permissions and owner for {env_dest} and {composer_dest}")
|
||||||
|
|
||||||
# Añadir la línea OGCORE_API_URL utilizando OGCORE_IP
|
# Añadir la línea OGCORE_API_URL utilizando OGCORE_IP
|
||||||
ogcore_api_url = f'OGCORE_API_URL="https://{OGCORE_IP}"'
|
ogcore_api_url = f'OGCORE_API_URL="https://{OGCORE_IP}"'
|
||||||
with open(env_dest, 'a') as env_file:
|
with open(env_dest, 'a') as env_file:
|
||||||
env_file.write(f"\n{ogcore_api_url}\n")
|
env_file.write(f"\n{ogcore_api_url}\n")
|
||||||
logger.info(f"Added OGCORE_API_URL to {env_dest} with IP: {OGCORE_IP}")
|
logger.info(f"Added OGCORE_API_URL to {env_dest} with IP: {OGCORE_IP}")
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"An error occurred while copying files or modifying .env: {e}")
|
logger.error(f"An error occurred while copying files or modifying .env: {e}")
|
||||||
raise
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def og_boot_copy_files():
|
def og_boot_copy_files():
|
||||||
bin_source = os.path.join(REPO_DIR, "bin")
|
bin_source = os.path.join(REPO_DIR, "bin")
|
||||||
bin_dest = os.path.join(INSTALL_OGBOOT_TARGET, "bin")
|
bin_dest = os.path.join(INSTALL_OGBOOT_TARGET, "bin")
|
||||||
src_source = os.path.join(REPO_DIR, "src")
|
src_source = os.path.join(REPO_DIR, "src")
|
||||||
src_dest = os.path.join(INSTALL_OGBOOT_TARGET, "src")
|
src_dest = os.path.join(INSTALL_OGBOOT_TARGET, "src")
|
||||||
|
|
||||||
config_source = os.path.join(REPO_DIR, "config")
|
config_source = os.path.join(REPO_DIR, "config")
|
||||||
config_dest = os.path.join(INSTALL_OGBOOT_TARGET, "config")
|
config_dest = os.path.join(INSTALL_OGBOOT_TARGET, "config")
|
||||||
|
|
||||||
lib_source = os.path.join(REPO_DIR, "lib")
|
lib_source = os.path.join(REPO_DIR, "lib")
|
||||||
lib_dest = os.path.join(INSTALL_OGBOOT_TARGET, "lib")
|
lib_dest = os.path.join(INSTALL_OGBOOT_TARGET, "lib")
|
||||||
|
|
||||||
#os.makedirs("/tmp/opt", exist_ok=True)
|
#os.makedirs("/tmp/opt", exist_ok=True)
|
||||||
|
|
||||||
#subprocess.run(["chown", "-R", "ogboot:ogboot", "/tmp/opt"])
|
#subprocess.run(["chown", "-R", "ogboot:ogboot", "/tmp/opt"])
|
||||||
|
|
||||||
if os.path.exists(bin_dest):
|
if os.path.exists(bin_dest):
|
||||||
shutil.rmtree(bin_dest)
|
shutil.rmtree(bin_dest)
|
||||||
shutil.copytree(bin_source, bin_dest)
|
shutil.copytree(bin_source, bin_dest)
|
||||||
|
|
||||||
if os.path.exists(src_dest):
|
if os.path.exists(src_dest):
|
||||||
shutil.rmtree(src_dest)
|
shutil.rmtree(src_dest)
|
||||||
shutil.copytree(src_source, src_dest)
|
shutil.copytree(src_source, src_dest)
|
||||||
|
|
||||||
if os.path.exists(config_dest):
|
if os.path.exists(config_dest):
|
||||||
shutil.rmtree(config_dest)
|
shutil.rmtree(config_dest)
|
||||||
shutil.copytree(config_source, config_dest)
|
shutil.copytree(config_source, config_dest)
|
||||||
|
|
||||||
if os.path.exists(lib_dest):
|
if os.path.exists(lib_dest):
|
||||||
shutil.rmtree(lib_dest)
|
shutil.rmtree(lib_dest)
|
||||||
shutil.copytree(lib_source, lib_dest)
|
shutil.copytree(lib_source, lib_dest)
|
||||||
|
|
||||||
os.makedirs(os.path.join(INSTALL_OGBOOT_TARGET, "etc"), mode=0o775, exist_ok=True)
|
os.makedirs(os.path.join(INSTALL_OGBOOT_TARGET, "etc"), mode=0o775, exist_ok=True)
|
||||||
os.makedirs(os.path.join(INSTALL_OGBOOT_TARGET, "client"), mode=0o775, exist_ok=True)
|
os.makedirs(os.path.join(INSTALL_OGBOOT_TARGET, "client"), mode=0o775, exist_ok=True)
|
||||||
os.makedirs(os.path.join(INSTALL_OGBOOT_TARGET, "public"), mode=0o775, exist_ok=True)
|
os.makedirs(os.path.join(INSTALL_OGBOOT_TARGET, "public"), mode=0o775, exist_ok=True)
|
||||||
|
|
||||||
subprocess.run(["chmod", "-R", "775", INSTALL_OGBOOT_TARGET])
|
subprocess.run(["chmod", "-R", "775", INSTALL_OGBOOT_TARGET])
|
||||||
subprocess.run(["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
|
||||||
result = subprocess.run(["sudo", "-u", "ogboot", "composer", "install", "--no-interaction", "--working-dir", INSTALL_OGBOOT_TARGET])
|
result = subprocess.run(["sudo", "-u", "ogboot", "composer", "install", "--no-interaction", "--working-dir", INSTALL_OGBOOT_TARGET])
|
||||||
if result.returncode != 0:
|
if result.returncode != 0:
|
||||||
logger.error("Error creating Symfony project using Composer")
|
logger.error("Error creating Symfony project using Composer")
|
||||||
return
|
return
|
||||||
|
|
||||||
# Ejecutar Composer como el usuario 'ogboot' para actualizar el paquete doctrine/dbal
|
# Ejecutar Composer como el usuario 'ogboot' para actualizar el paquete doctrine/dbal
|
||||||
result = subprocess.run(["sudo", "-u", "ogboot", INSTALL_OGBOOT_TARGET+"/bin/composer.phar", "update", "doctrine/dbal", "--working-dir", INSTALL_OGBOOT_TARGET])
|
result = subprocess.run(["sudo", "-u", "ogboot", INSTALL_OGBOOT_TARGET+"/bin/composer.phar", "update", "doctrine/dbal", "--working-dir", INSTALL_OGBOOT_TARGET])
|
||||||
if result.returncode != 0:
|
if result.returncode != 0:
|
||||||
logger.error("Error updating doctrine/dbal package using Composer")
|
logger.error("Error updating doctrine/dbal package using Composer")
|
||||||
return
|
return
|
||||||
|
|
||||||
subprocess.call(["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.")
|
logger.info("Application skeleton created.")
|
||||||
|
|
||||||
###############################################################################
|
###############################################################################
|
||||||
###:::::::::::::::::::::::::::: CONFIGURE ::::::::::::::::::::::::::::::::::###
|
###:::::::::::::::::::::::::::: CONFIGURE ::::::::::::::::::::::::::::::::::###
|
||||||
|
@ -323,26 +323,26 @@ def get_ogboot_uid_gid():
|
||||||
|
|
||||||
# Añadir líneas al fstab
|
# Añadir líneas al fstab
|
||||||
def add_fstab_entries(uid, gid):
|
def add_fstab_entries(uid, gid):
|
||||||
try:
|
try:
|
||||||
fstab_entries = [
|
fstab_entries = [
|
||||||
f'{INSTALL_OGBOOT_TARGET}/lib/oglive.iso {INSTALL_OGBOOT_TARGET}/mnt iso9660 loop,ro,users,uid={uid},gid={gid},noauto 0 0\n',
|
f'{INSTALL_OGBOOT_TARGET}/lib/oglive.iso {INSTALL_OGBOOT_TARGET}/mnt iso9660 loop,ro,users,uid={uid},gid={gid},noauto 0 0\n',
|
||||||
f'/var/lib/tftpboot/ogLive/ogclient.sqfs /tmp/ogclient_mount squashfs loop,ro,user,noauto 0 0\n'
|
f'/var/lib/tftpboot/ogLive/ogclient.sqfs /tmp/ogclient_mount squashfs loop,ro,user,noauto 0 0\n'
|
||||||
]
|
]
|
||||||
|
|
||||||
with open('/etc/fstab', 'r') as fstab:
|
with open('/etc/fstab', 'r') as fstab:
|
||||||
existing_entries = fstab.readlines()
|
existing_entries = fstab.readlines()
|
||||||
|
|
||||||
# Check if the entries already exist in /etc/fstab
|
# Check if the entries already exist in /etc/fstab
|
||||||
for entry in fstab_entries:
|
for entry in fstab_entries:
|
||||||
if entry not in existing_entries:
|
if entry not in existing_entries:
|
||||||
with open('/etc/fstab', 'a') as fstab:
|
with open('/etc/fstab', 'a') as fstab:
|
||||||
fstab.writelines(entry)
|
fstab.writelines(entry)
|
||||||
logger.info("Entradas añadidas a /etc/fstab correctamente.")
|
logger.info("Entradas añadidas a /etc/fstab correctamente.")
|
||||||
else:
|
else:
|
||||||
logger.info("Las entradas ya existen en /etc/fstab. No se añadieron nuevamente.")
|
logger.info("Las entradas ya existen en /etc/fstab. No se añadieron nuevamente.")
|
||||||
|
|
||||||
except IOError:
|
except IOError:
|
||||||
raise Exception("Error al escribir en /etc/fstab.")
|
raise Exception("Error al escribir en /etc/fstab.")
|
||||||
|
|
||||||
# Añadir el usuario ogboot al grupo disk
|
# Añadir el usuario ogboot al grupo disk
|
||||||
def add_user_to_disk_group():
|
def add_user_to_disk_group():
|
||||||
|
@ -353,95 +353,95 @@ def add_user_to_disk_group():
|
||||||
raise Exception("Error al añadir el usuario 'ogboot' al grupo 'disk'.")
|
raise Exception("Error al añadir el usuario 'ogboot' al grupo 'disk'.")
|
||||||
|
|
||||||
def tftpConfigure():
|
def tftpConfigure():
|
||||||
logger.info("Configuring tftpd-hpa...")
|
logger.info("Configuring tftpd-hpa...")
|
||||||
tftpd_config = """# /etc/default/tftpd-hpa
|
tftpd_config = """# /etc/default/tftpd-hpa
|
||||||
|
|
||||||
TFTP_USERNAME="tftp"
|
TFTP_USERNAME="tftp"
|
||||||
TFTP_DIRECTORY="/var/lib/tftpboot"
|
TFTP_DIRECTORY="/var/lib/tftpboot"
|
||||||
TFTP_ADDRESS="0.0.0.0:69"
|
TFTP_ADDRESS="0.0.0.0:69"
|
||||||
TFTP_OPTIONS="--secure"
|
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)
|
||||||
|
|
||||||
shutil.move("/tmp/tftpd-hpa", "/etc/default/tftpd-hpa")
|
shutil.move("/tmp/tftpd-hpa", "/etc/default/tftpd-hpa")
|
||||||
|
|
||||||
logger.info("\t2-Creating and setting permissions for the TFTP directory...")
|
logger.info("\t2-Creating and setting permissions for the TFTP directory...")
|
||||||
os.makedirs(TFTPCFGDIR, exist_ok=True)
|
os.makedirs(TFTPCFGDIR, exist_ok=True)
|
||||||
|
|
||||||
logger.info("\t3-Setting permissions for /var/lib/tftpboot directory...")
|
logger.info("\t3-Setting permissions for /var/lib/tftpboot directory...")
|
||||||
subprocess.run(f"chown -R tftp:ogboot {TFTPCFGDIR}", shell=True, text=True, capture_output=True)
|
subprocess.run(f"chown -R tftp:ogboot {TFTPCFGDIR}", shell=True, text=True, capture_output=True)
|
||||||
subprocess.run(f"chmod -R 775 {TFTPCFGDIR}", shell=True, text=True, capture_output=True)
|
subprocess.run(f"chmod -R 775 {TFTPCFGDIR}", shell=True, text=True, capture_output=True)
|
||||||
|
|
||||||
subprocess.run("systemctl restart tftpd-hpa", shell=True, text=True, capture_output=True)
|
subprocess.run("systemctl restart tftpd-hpa", shell=True, text=True, capture_output=True)
|
||||||
|
|
||||||
symlink_target = f"{INSTALL_OGBOOT_TARGET}/tftpboot"
|
symlink_target = f"{INSTALL_OGBOOT_TARGET}/tftpboot"
|
||||||
logger.info(f"Creating symbolic link from {TFTPCFGDIR} to {symlink_target}")
|
logger.info(f"Creating symbolic link from {TFTPCFGDIR} to {symlink_target}")
|
||||||
if not os.path.exists(symlink_target):
|
if not os.path.exists(symlink_target):
|
||||||
os.symlink(TFTPCFGDIR, symlink_target)
|
os.symlink(TFTPCFGDIR, symlink_target)
|
||||||
#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}")
|
||||||
|
|
||||||
logger.info("Downloading oglive...")
|
logger.info("Downloading oglive...")
|
||||||
try:
|
try:
|
||||||
result = subprocess.run(
|
result = subprocess.run(
|
||||||
[INSTALL_OGBOOT_TARGET+"/bin/oglivecli", "download", oglive_iso_url],
|
[INSTALL_OGBOOT_TARGET+"/bin/oglivecli", "downloadkk", oglive_iso_url],
|
||||||
check=True,
|
check=True,
|
||||||
capture_output=True,
|
capture_output=True,
|
||||||
text=True
|
text=True
|
||||||
)
|
)
|
||||||
# Comprobar si oglivecli ha fallado
|
# Comprobar si oglivecli ha fallado
|
||||||
if result.returncode != 0:
|
if result.returncode != 0:
|
||||||
try:
|
try:
|
||||||
# Parsear la salida como JSON
|
# Parsear la salida como JSON
|
||||||
error_output = json.loads(result.stdout)
|
error_output = json.loads(result.stdout)
|
||||||
if error_output.get("status") == "error":
|
if error_output.get("status") == "error":
|
||||||
logger.error(f"oglivecli error: {error_output.get('error')}")
|
logger.error(f"oglivecli error: {error_output.get('error')}")
|
||||||
except json.JSONDecodeError:
|
except json.JSONDecodeError:
|
||||||
logger.error("Failed to parse oglivecli error output.")
|
logger.error("Failed to parse oglivecli error output.")
|
||||||
logger.error("Continuing with the installation despite oglivecli failure.")
|
logger.error("Continuing with the installation despite oglivecli failure.")
|
||||||
else:
|
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"
|
||||||
if os.path.exists(symlink_target_ogLive):
|
if os.path.exists(symlink_target_ogLive):
|
||||||
subprocess.run(["chown", "-R", f"tftp:ogboot", f"{INSTALL_OGBOOT_TARGET}/tftpboot"], check=True)
|
subprocess.run(["chown", "-R", f"tftp:ogboot", f"{INSTALL_OGBOOT_TARGET}/tftpboot"], check=True)
|
||||||
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:
|
else:
|
||||||
logger.error(f"{symlink_target_ogLive} link does not exist.")
|
logger.error(f"{symlink_target_ogLive} link does not exist.")
|
||||||
except subprocess.CalledProcessError as e:
|
except subprocess.CalledProcessError as e:
|
||||||
logger.error(f"Subprocess failed: {e}")
|
logger.error(f"Subprocess failed: {e}")
|
||||||
logger.error("Continuing with the installation...")
|
logger.error("Continuing with the installation...")
|
||||||
|
|
||||||
def copyInterfaceAdm():
|
def copyInterfaceAdm():
|
||||||
hayErrores = 0
|
hayErrores = 0
|
||||||
cp_process = subprocess.run(["cp", "-ar", f"{REPO_DIR}/sources/interface", f"{INSTALL_OGBOOT_TARGET}/client/interfaceAdm"])
|
cp_process = subprocess.run(["cp", "-ar", f"{REPO_DIR}/sources/interface", f"{INSTALL_OGBOOT_TARGET}/client/interfaceAdm"])
|
||||||
if cp_process.returncode != 0:
|
if cp_process.returncode != 0:
|
||||||
logger.error(f"Error while copying Administration Interface Folder")
|
logger.error(f"Error while copying Administration Interface Folder")
|
||||||
hayErrores = 1
|
hayErrores = 1
|
||||||
return hayErrores
|
return hayErrores
|
||||||
|
|
||||||
def copyClientFiles():
|
def copyClientFiles():
|
||||||
errstatus = 0
|
errstatus = 0
|
||||||
logger.info(f"Copying OpenGnsys Client files.")
|
logger.info(f"Copying OpenGnsys Client files.")
|
||||||
if 0 != subprocess.run (['rsync', '-aH', f'{REPO_DIR}/client/shared/', f'{INSTALL_OGBOOT_TARGET}/client/']).returncode:
|
if 0 != subprocess.run (['rsync', '-aH', f'{REPO_DIR}/client/shared/', f'{INSTALL_OGBOOT_TARGET}/client/']).returncode:
|
||||||
logger.error(f"Error while copying client structure")
|
logger.error(f"Error while copying client structure")
|
||||||
errstatus = 1
|
errstatus = 1
|
||||||
|
|
||||||
logger.info(f"Copying OpenGnsys Cloning Engine files.")
|
logger.info(f"Copying OpenGnsys Cloning Engine files.")
|
||||||
os.makedirs(f"{INSTALL_OGBOOT_TARGET}/client/lib/engine/bin", mode=0o775, exist_ok=True)
|
os.makedirs(f"{INSTALL_OGBOOT_TARGET}/client/lib/engine/bin", mode=0o775, exist_ok=True)
|
||||||
if 0 != subprocess.run (['rsync', '-aH', f'{REPO_DIR}/client/engine/', f'{INSTALL_OGBOOT_TARGET}/client/lib/engine/bin/']).returncode:
|
if 0 != subprocess.run (['rsync', '-aH', f'{REPO_DIR}/client/engine/', f'{INSTALL_OGBOOT_TARGET}/client/lib/engine/bin/']).returncode:
|
||||||
logger.error(f"Error while copying engine files")
|
logger.error(f"Error while copying engine files")
|
||||||
errstatus = 1
|
errstatus = 1
|
||||||
|
|
||||||
if errstatus == 0:
|
if errstatus == 0:
|
||||||
logger.info(f"Client copy files success.")
|
logger.info(f"Client copy files success.")
|
||||||
else:
|
else:
|
||||||
logger.error(f"Client copy files with errors")
|
logger.error(f"Client copy files with errors")
|
||||||
return not errstatus
|
return not errstatus
|
||||||
|
|
||||||
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:
|
||||||
|
@ -460,65 +460,65 @@ def get_first_network_interface_with_traffic():
|
||||||
|
|
||||||
|
|
||||||
def tzConfigure():
|
def tzConfigure():
|
||||||
tdctl = subprocess.run (['timedatectl', 'show'], capture_output=True, text=True)
|
tdctl = subprocess.run (['timedatectl', 'show'], capture_output=True, text=True)
|
||||||
lines = tdctl.stdout.split ('\n')
|
lines = tdctl.stdout.split ('\n')
|
||||||
TZ = list (filter (lambda elem: 'Timezone' in elem, lines))[0]
|
TZ = list (filter (lambda elem: 'Timezone' in elem, lines))[0]
|
||||||
_, TZ = TZ.split ('=')
|
_, TZ = TZ.split ('=')
|
||||||
|
|
||||||
if TZ:
|
if TZ:
|
||||||
with open(f"{INSTALL_OGBOOT_TARGET}/client/etc/engine.cfg", "a") as file:
|
with open(f"{INSTALL_OGBOOT_TARGET}/client/etc/engine.cfg", "a") as file:
|
||||||
file.write(f"# OpenGnsys Server timezone.\nTZ=\"{TZ}\"\n")
|
file.write(f"# OpenGnsys Server timezone.\nTZ=\"{TZ}\"\n")
|
||||||
|
|
||||||
def install_ipxe():
|
def install_ipxe():
|
||||||
if os.path.exists (f"{INSTALL_OGBOOT_TARGET}/tftpboot/undionly.kpxe"):
|
if os.path.exists (f"{INSTALL_OGBOOT_TARGET}/tftpboot/undionly.kpxe"):
|
||||||
logger.info ('iPXE already present--not compiling again')
|
logger.info ('iPXE already present--not compiling again')
|
||||||
return True
|
return True
|
||||||
|
|
||||||
cwd = os.getcwd()
|
cwd = os.getcwd()
|
||||||
with tempfile.TemporaryDirectory() as clone_dir:
|
with tempfile.TemporaryDirectory() as clone_dir:
|
||||||
logger.info(f"Clonando el repositorio {ipxe_repo_url}")
|
logger.info(f"Clonando el repositorio {ipxe_repo_url}")
|
||||||
if subprocess.call(["git", "-c", "http.sslVerify=false", "clone", ipxe_repo_url, clone_dir]) == 0:
|
if subprocess.call(["git", "-c", "http.sslVerify=false", "clone", ipxe_repo_url, clone_dir]) == 0:
|
||||||
logger.info("Repositorio clonado correctamente.")
|
logger.info("Repositorio clonado correctamente.")
|
||||||
else:
|
else:
|
||||||
logger.error(f"ERROR\tNo se pudo clonar el repositorio {ipxe_repo_url}.")
|
logger.error(f"ERROR\tNo se pudo clonar el repositorio {ipxe_repo_url}.")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
# Ejecutar el comando make en el directorio src
|
# Ejecutar el comando make en el directorio src
|
||||||
#logger.info(f"Ejecutando make en {clone_dir}/src")
|
#logger.info(f"Ejecutando make en {clone_dir}/src")
|
||||||
os.chdir(f"{clone_dir}/src")
|
os.chdir(f"{clone_dir}/src")
|
||||||
#if subprocess.run(["make", "-s", "-j", "4"], capture_output=True).returncode == 0:
|
#if subprocess.run(["make", "-s", "-j", "4"], capture_output=True).returncode == 0:
|
||||||
# logger.info(f"Directorio {clone_dir}/src correctamente compilado.")
|
# logger.info(f"Directorio {clone_dir}/src correctamente compilado.")
|
||||||
#else:
|
#else:
|
||||||
# logger.error(f"ERROR\tNo se pudo compilar el directorio {clone_dir}/src.")
|
# logger.error(f"ERROR\tNo se pudo compilar el directorio {clone_dir}/src.")
|
||||||
# return False
|
# return False
|
||||||
|
|
||||||
logger.info("Generando make de undionly.kpxe:")
|
logger.info("Generando make de undionly.kpxe:")
|
||||||
if subprocess.run(["make", "-s", "bin/undionly.kpxe", f"EMBED={INSTALL_OGBOOT_TARGET}/tftpboot/ipxe_scripts/dhcp_boot.ipxe"], capture_output=True).returncode == 0:
|
if subprocess.run(["make", "-s", "bin/undionly.kpxe", f"EMBED={INSTALL_OGBOOT_TARGET}/tftpboot/ipxe_scripts/dhcp_boot.ipxe"], capture_output=True).returncode == 0:
|
||||||
logger.info("Boot file mounted correctly.")
|
logger.info("Boot file mounted correctly.")
|
||||||
else:
|
else:
|
||||||
logger.error("Failed to mount boot file.")
|
logger.error("Failed to mount boot file.")
|
||||||
return False
|
return False
|
||||||
logger.info("Copiando undionly.kpxe con usuario ogboot:")
|
logger.info("Copiando undionly.kpxe con usuario ogboot:")
|
||||||
subprocess.call(["cp", "bin/undionly.kpxe", f"{INSTALL_OGBOOT_TARGET}/tftpboot"])
|
subprocess.call(["cp", "bin/undionly.kpxe", f"{INSTALL_OGBOOT_TARGET}/tftpboot"])
|
||||||
subprocess.call(["chown", "ogboot:ogboot", f"{INSTALL_OGBOOT_TARGET}/tftpboot"])
|
subprocess.call(["chown", "ogboot:ogboot", f"{INSTALL_OGBOOT_TARGET}/tftpboot"])
|
||||||
|
|
||||||
logger.info("Generando make de ipxe.efi:")
|
logger.info("Generando make de ipxe.efi:")
|
||||||
if subprocess.run(["make", "-s", "bin-x86_64-efi/ipxe.efi", f"EMBED={INSTALL_OGBOOT_TARGET}/tftpboot/ipxe_scripts/dhcp_boot.ipxe"], capture_output=True).returncode == 0:
|
if subprocess.run(["make", "-s", "bin-x86_64-efi/ipxe.efi", f"EMBED={INSTALL_OGBOOT_TARGET}/tftpboot/ipxe_scripts/dhcp_boot.ipxe"], capture_output=True).returncode == 0:
|
||||||
logger.info("Properly constructed EFI file.")
|
logger.info("Properly constructed EFI file.")
|
||||||
else:
|
else:
|
||||||
logger.error("Could not build EFI file.")
|
logger.error("Could not build EFI file.")
|
||||||
return False
|
return False
|
||||||
subprocess.call(["cp", "bin-x86_64-efi/ipxe.efi", f"{INSTALL_OGBOOT_TARGET}/tftpboot"])
|
subprocess.call(["cp", "bin-x86_64-efi/ipxe.efi", f"{INSTALL_OGBOOT_TARGET}/tftpboot"])
|
||||||
subprocess.call(["chown", "-R", "tftp:ogboot", f"{INSTALL_OGBOOT_TARGET}/tftpboot/"])
|
subprocess.call(["chown", "-R", "tftp:ogboot", f"{INSTALL_OGBOOT_TARGET}/tftpboot/"])
|
||||||
|
|
||||||
subprocess.run(["chmod", "-R", "775", f"{INSTALL_OGBOOT_TARGET}/tftpboot/"])
|
subprocess.run(["chmod", "-R", "775", f"{INSTALL_OGBOOT_TARGET}/tftpboot/"])
|
||||||
os.makedirs(f"{INSTALL_OGBOOT_TARGET}/tftpboot/ipxe_scripts/templates", exist_ok=True)
|
os.makedirs(f"{INSTALL_OGBOOT_TARGET}/tftpboot/ipxe_scripts/templates", exist_ok=True)
|
||||||
subprocess.call(["chown", "-R", "tftp:ogboot", f"{INSTALL_OGBOOT_TARGET}/tftpboot/ipxe_scripts/templates"])
|
subprocess.call(["chown", "-R", "tftp:ogboot", f"{INSTALL_OGBOOT_TARGET}/tftpboot/ipxe_scripts/templates"])
|
||||||
subprocess.call(["chmod", "-R", "775", f"{INSTALL_OGBOOT_TARGET}/tftpboot/ipxe_scripts/templates"])
|
subprocess.call(["chmod", "-R", "775", f"{INSTALL_OGBOOT_TARGET}/tftpboot/ipxe_scripts/templates"])
|
||||||
subprocess.call(["cp", f"{REPO_DIR}/tftpboot/ipxe_scripts/templates/pxe_default", f"{INSTALL_OGBOOT_TARGET}/tftpboot/ipxe_scripts/templates"])
|
subprocess.call(["cp", f"{REPO_DIR}/tftpboot/ipxe_scripts/templates/pxe_default", f"{INSTALL_OGBOOT_TARGET}/tftpboot/ipxe_scripts/templates"])
|
||||||
os.chdir(cwd)
|
os.chdir(cwd)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def get_ip_address(interface):
|
def get_ip_address(interface):
|
||||||
try:
|
try:
|
||||||
|
@ -532,25 +532,25 @@ def get_ip_address(interface):
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def generate_ipxe_script():
|
def generate_ipxe_script():
|
||||||
ip_address_server = get_ip_address(DEFAULTDEV)
|
ip_address_server = get_ip_address(DEFAULTDEV)
|
||||||
template = os.path.join(REPO_DIR, "etc/dhcp_boot.ipxe.tmpl")
|
template = os.path.join(REPO_DIR, "etc/dhcp_boot.ipxe.tmpl")
|
||||||
ipxe_output = f"{INSTALL_OGBOOT_TARGET}/tftpboot/ipxe_scripts/dhcp_boot.ipxe"
|
ipxe_output = f"{INSTALL_OGBOOT_TARGET}/tftpboot/ipxe_scripts/dhcp_boot.ipxe"
|
||||||
os.makedirs(os.path.dirname(ipxe_output), mode=0o775, exist_ok=True)
|
os.makedirs(os.path.dirname(ipxe_output), mode=0o775, exist_ok=True)
|
||||||
#shutil.copy(template, ipxe_output)
|
#shutil.copy(template, ipxe_output)
|
||||||
with open(template, "r") as ipxe_file:
|
with open(template, "r") as ipxe_file:
|
||||||
ipxe_content = ipxe_file.read()
|
ipxe_content = ipxe_file.read()
|
||||||
ipxe_content = ipxe_content.replace("__SERVERIP__", ip_address_server)
|
ipxe_content = ipxe_content.replace("__SERVERIP__", ip_address_server)
|
||||||
with open(ipxe_output, "w") as ipxe_file:
|
with open(ipxe_output, "w") as ipxe_file:
|
||||||
ipxe_file.write(ipxe_content)
|
ipxe_file.write(ipxe_content)
|
||||||
|
|
||||||
template_default = os.path.join(REPO_DIR, "tftpboot/ipxe_scripts/default.ipxe")
|
template_default = os.path.join(REPO_DIR, "tftpboot/ipxe_scripts/default.ipxe")
|
||||||
default_output = os.path.join(INSTALL_OGBOOT_TARGET, "tftpboot/ipxe_scripts/default.ipxe")
|
default_output = os.path.join(INSTALL_OGBOOT_TARGET, "tftpboot/ipxe_scripts/default.ipxe")
|
||||||
with open(template_default, "r") as default_tmpl_file:
|
with open(template_default, "r") as default_tmpl_file:
|
||||||
default_template_content = default_tmpl_file.read()
|
default_template_content = default_tmpl_file.read()
|
||||||
default_ipxe_content = default_template_content.replace("__SERVERIP__", ip_address_server)
|
default_ipxe_content = default_template_content.replace("__SERVERIP__", ip_address_server)
|
||||||
with open(default_output, "w") as default_ipxe_file:
|
with open(default_output, "w") as default_ipxe_file:
|
||||||
default_ipxe_file.write(default_ipxe_content)
|
default_ipxe_file.write(default_ipxe_content)
|
||||||
logger.info("ipxe files created correctly.")
|
logger.info("ipxe files created correctly.")
|
||||||
|
|
||||||
def user_exists(user):
|
def user_exists(user):
|
||||||
try:
|
try:
|
||||||
|
@ -561,102 +561,102 @@ def user_exists(user):
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def smbConfigure():
|
def smbConfigure():
|
||||||
smb_conf = f"{SAMBACFGDIR}/smb.conf"
|
smb_conf = f"{SAMBACFGDIR}/smb.conf"
|
||||||
if os.path.exists (smb_conf):
|
if os.path.exists (smb_conf):
|
||||||
dateymd = datetime.datetime.now().strftime("%Y%m%d")
|
dateymd = datetime.datetime.now().strftime("%Y%m%d")
|
||||||
shutil.copy2 (smb_conf, f"{smb_conf}-{dateymd}")
|
shutil.copy2 (smb_conf, f"{smb_conf}-{dateymd}")
|
||||||
|
|
||||||
# Copiar plantilla de recursos para OpenGnsys
|
# Copiar plantilla de recursos para OpenGnsys
|
||||||
with open(os.path.join(REPO_DIR, 'etc/smb-ogboot.conf.tmpl'), 'r') as tmpl_file:
|
with open(os.path.join(REPO_DIR, 'etc/smb-ogboot.conf.tmpl'), 'r') as tmpl_file:
|
||||||
template = tmpl_file.read()
|
template = tmpl_file.read()
|
||||||
replaced_template = template.replace('__OGBOOTDIR__', INSTALL_OGBOOT_TARGET)
|
replaced_template = template.replace('__OGBOOTDIR__', INSTALL_OGBOOT_TARGET)
|
||||||
with open(os.path.join(SAMBACFGDIR, 'smb-ogboot.conf'), 'w') as conf_file:
|
with open(os.path.join(SAMBACFGDIR, 'smb-ogboot.conf'), 'w') as conf_file:
|
||||||
conf_file.write(replaced_template)
|
conf_file.write(replaced_template)
|
||||||
# Configurar y recargar Samba"
|
# Configurar y recargar Samba"
|
||||||
subprocess.run(["perl", "-pi", "-e", "s/WORKGROUP/OPENGNSYS/; s/server string \\=.*/server string \\= ogBoot Samba Server/", smb_conf])
|
subprocess.run(["perl", "-pi", "-e", "s/WORKGROUP/OPENGNSYS/; s/server string \\=.*/server string \\= ogBoot Samba Server/", smb_conf])
|
||||||
if "smb-ogboot" not in open(smb_conf).read():
|
if "smb-ogboot" not in open(smb_conf).read():
|
||||||
with open(smb_conf, "a") as file:
|
with open(smb_conf, "a") as file:
|
||||||
file.write(f"include = {SAMBACFGDIR}/smb-ogboot.conf\n")
|
file.write(f"include = {SAMBACFGDIR}/smb-ogboot.conf\n")
|
||||||
service = "smbd"
|
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.")
|
||||||
subprocess.run(["systemctl", "restart", f"{service}.service"])
|
subprocess.run(["systemctl", "restart", f"{service}.service"])
|
||||||
# Comprobar si se ha configurado correctamente Samba
|
# Comprobar si se ha configurado correctamente Samba
|
||||||
if subprocess.run(["systemctl", "is-active", f"{service}.service"]).returncode == 0:
|
if subprocess.run(["systemctl", "is-active", f"{service}.service"]).returncode == 0:
|
||||||
logger.info(f"{service} service started successfully.")
|
logger.info(f"{service} service started successfully.")
|
||||||
else:
|
else:
|
||||||
logger.error(f"Failed to start {service} service.")
|
logger.error(f"Failed to start {service} service.")
|
||||||
return 1
|
return 1
|
||||||
# Ejecutar el comando smbpasswd para agregar el usuario de Samba
|
# Ejecutar el comando smbpasswd para agregar el usuario de Samba
|
||||||
try:
|
try:
|
||||||
if user_exists(OPENGNSYS_CLIENT_USER):
|
if user_exists(OPENGNSYS_CLIENT_USER):
|
||||||
logger.info(f"{OPENGNSYS_CLIENT_USER} user exists. Changing password...")
|
logger.info(f"{OPENGNSYS_CLIENT_USER} user exists. Changing password...")
|
||||||
extra_params = []
|
extra_params = []
|
||||||
else:
|
else:
|
||||||
logger.info(f"{OPENGNSYS_CLIENT_USER} user does not exist. Registering user...")
|
logger.info(f"{OPENGNSYS_CLIENT_USER} user does not exist. Registering user...")
|
||||||
extra_params = ['-a']
|
extra_params = ['-a']
|
||||||
|
|
||||||
subprocess.run(
|
subprocess.run(
|
||||||
["smbpasswd"] + extra_params + [OPENGNSYS_CLIENT_USER],
|
["smbpasswd"] + extra_params + [OPENGNSYS_CLIENT_USER],
|
||||||
input=f"{OPENGNSYS_CLIENT_PASSWD}\n{OPENGNSYS_CLIENT_PASSWD}\n",
|
input=f"{OPENGNSYS_CLIENT_PASSWD}\n{OPENGNSYS_CLIENT_PASSWD}\n",
|
||||||
text=True,
|
text=True,
|
||||||
capture_output=True,
|
capture_output=True,
|
||||||
check=True
|
check=True
|
||||||
)
|
)
|
||||||
logger.info("Add/Modify user: Operation completed successfully.")
|
logger.info("Add/Modify user: Operation completed successfully.")
|
||||||
except subprocess.CalledProcessError as e:
|
except subprocess.CalledProcessError as e:
|
||||||
logger.error(f"Error adding/modifying user: {e}")
|
logger.error(f"Error adding/modifying user: {e}")
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
def setup_nginx():
|
def setup_nginx():
|
||||||
try:
|
try:
|
||||||
# Obtener la IP del servidor
|
# Obtener la IP del servidor
|
||||||
ip_address_server = get_ip_address(DEFAULTDEV)
|
ip_address_server = get_ip_address(DEFAULTDEV)
|
||||||
php_version = get_php_fpm_version()
|
php_version = get_php_fpm_version()
|
||||||
|
|
||||||
# Leer y modificar la plantilla de configuración de nginx
|
# Leer y modificar la plantilla de configuración de nginx
|
||||||
template_path = os.path.join(REPO_DIR, "etc/nginxServer.conf.tmpl")
|
template_path = os.path.join(REPO_DIR, "etc/nginxServer.conf.tmpl")
|
||||||
with open(template_path, 'r') as nginx_file:
|
with open(template_path, 'r') as nginx_file:
|
||||||
nginx_content = nginx_file.read()
|
nginx_content = nginx_file.read()
|
||||||
|
|
||||||
nginx_content = nginx_content.replace("__SERVERIP__", ip_address_server)
|
nginx_content = nginx_content.replace("__SERVERIP__", ip_address_server)
|
||||||
nginx_content = nginx_content.replace("__PHPVERSION__", php_version)
|
nginx_content = nginx_content.replace("__PHPVERSION__", php_version)
|
||||||
nginx_content = nginx_content.replace("__ROOT__", INSTALL_OGBOOT_TARGET)
|
nginx_content = nginx_content.replace("__ROOT__", INSTALL_OGBOOT_TARGET)
|
||||||
|
|
||||||
# Ruta de destino para la configuración de nginx
|
# Ruta de destino para la configuración de nginx
|
||||||
nginx_output = "/etc/nginx/sites-available/ogboot.conf"
|
nginx_output = "/etc/nginx/sites-available/ogboot.conf"
|
||||||
with open(nginx_output, 'w') as nginx_file:
|
with open(nginx_output, 'w') as nginx_file:
|
||||||
nginx_file.write(nginx_content)
|
nginx_file.write(nginx_content)
|
||||||
|
|
||||||
logger.info("Nginx configuration file created successfully.")
|
logger.info("Nginx configuration file created successfully.")
|
||||||
|
|
||||||
# Crear el enlace simbólico en sites-enabled
|
# Crear el enlace simbólico en sites-enabled
|
||||||
subprocess.run(["ln", "-sf", nginx_output, "/etc/nginx/sites-enabled/ogboot.conf"])
|
subprocess.run(["ln", "-sf", nginx_output, "/etc/nginx/sites-enabled/ogboot.conf"])
|
||||||
|
|
||||||
logger.info("Symbolic link for nginx configuration created successfully.")
|
logger.info("Symbolic link for nginx configuration created successfully.")
|
||||||
|
|
||||||
# Modificar el archivo de configuración de nginx para ejecutarse como ogboot
|
# Modificar el archivo de configuración de nginx para ejecutarse como ogboot
|
||||||
nginx_conf_path = "/etc/nginx/nginx.conf"
|
nginx_conf_path = "/etc/nginx/nginx.conf"
|
||||||
with open(nginx_conf_path, 'r') as nginx_conf_file:
|
with open(nginx_conf_path, 'r') as nginx_conf_file:
|
||||||
nginx_conf_content = nginx_conf_file.read()
|
nginx_conf_content = nginx_conf_file.read()
|
||||||
|
|
||||||
nginx_conf_content = nginx_conf_content.replace("user www-data;", "user ogboot;")
|
nginx_conf_content = nginx_conf_content.replace("user www-data;", "user ogboot;")
|
||||||
|
|
||||||
with open(nginx_conf_path, 'w') as nginx_conf_file:
|
with open(nginx_conf_path, 'w') as nginx_conf_file:
|
||||||
nginx_conf_file.write(nginx_conf_content)
|
nginx_conf_file.write(nginx_conf_content)
|
||||||
|
|
||||||
logger.info("Nginx configuration file modified to run as ogboot.")
|
logger.info("Nginx configuration file modified to run as ogboot.")
|
||||||
|
|
||||||
# Reiniciar el servicio de samba
|
# Reiniciar el servicio de samba
|
||||||
subprocess.run(["systemctl", "restart", "nginx.service"])
|
subprocess.run(["systemctl", "restart", "nginx.service"])
|
||||||
|
|
||||||
except subprocess.CalledProcessError as e:
|
except subprocess.CalledProcessError as e:
|
||||||
logger.error(f"Subprocess error: {e}")
|
logger.error(f"Subprocess error: {e}")
|
||||||
exit(1)
|
exit(1)
|
||||||
except OSError as e:
|
except OSError as e:
|
||||||
logger.error(f"OS error: {e}")
|
logger.error(f"OS error: {e}")
|
||||||
exit(1)
|
exit(1)
|
||||||
|
|
||||||
def get_php_fpm_version():
|
def get_php_fpm_version():
|
||||||
try:
|
try:
|
||||||
|
@ -808,18 +808,18 @@ except Exception as e:
|
||||||
exit(1)
|
exit(1)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
logger.info("Obteniendo UID y GID del usuario 'ogboot'.")
|
logger.info("Obteniendo UID y GID del usuario 'ogboot'.")
|
||||||
uid, gid = get_ogboot_uid_gid()
|
uid, gid = get_ogboot_uid_gid()
|
||||||
|
|
||||||
logger.info("Añadiendo entradas al archivo /etc/fstab.")
|
logger.info("Añadiendo entradas al archivo /etc/fstab.")
|
||||||
add_fstab_entries(uid, gid)
|
add_fstab_entries(uid, gid)
|
||||||
|
|
||||||
logger.info("Añadiendo el usuario 'ogboot' al grupo 'disk'.")
|
logger.info("Añadiendo el usuario 'ogboot' al grupo 'disk'.")
|
||||||
add_user_to_disk_group()
|
add_user_to_disk_group()
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Error durante la configuración: {e}")
|
logger.error(f"Error durante la configuración: {e}")
|
||||||
exit(1)
|
exit(1)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
logger.info("Configuring tftpd-hpa service.")
|
logger.info("Configuring tftpd-hpa service.")
|
||||||
|
|
Loading…
Reference in New Issue