refs #444 the logging system is implemented
parent
30c2a9eed4
commit
9d7aa23312
|
@ -5,7 +5,21 @@
|
|||
##### Autor: Antonio Emmanuel Guerrero Silva <aguerrero@qindel.com> ########
|
||||
#################################################################################
|
||||
|
||||
import platform, os, sys, subprocess, datetime, shutil, argparse, time, pwd, glob, zipfile, urllib.request
|
||||
import platform, os, sys, subprocess, datetime, shutil, argparse, time, pwd, glob, zipfile, urllib.request, logging
|
||||
|
||||
PROGRAM = os.path.splitext(os.path.basename(sys.argv[0]))[0]
|
||||
|
||||
#Configurar el registro
|
||||
logging.basicConfig(level=logging.DEBUG,
|
||||
format='%(asctime)s %(levelname)s\t%(message)s',
|
||||
filename=f'/var/log/{PROGRAM}.log',
|
||||
filemode='a')
|
||||
logger = logging.getLogger()
|
||||
console_handler = logging.StreamHandler()
|
||||
console_handler.setLevel(logging.DEBUG)
|
||||
formatter = logging.Formatter('%(levelname)s\t%(message)s')
|
||||
console_handler.setFormatter(formatter)
|
||||
logger.addHandler(console_handler)
|
||||
|
||||
global UBUNTU_OS_VERSION, OPENGNGYS_VERSION, PYTHON_VERSION, DEPENDENCIES2, INSTALL_OGBOOT_TARGET, LOG_FILE, CHECKPKG, INSTALLPKG, PATH, PROGRAM_DIR, OPENGNSYS_SERVER, UPDATEPKGLIST
|
||||
|
||||
|
@ -91,38 +105,17 @@ required_packages_22 = [
|
|||
###############################################################################
|
||||
###::::::::::::::::::::::::::::::: UTILS :::::::::::::::::::::::::::::::::::###
|
||||
###############################################################################
|
||||
def echoAndLog(message):
|
||||
datetime_now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
log_file = LOG_FILE
|
||||
print(message)
|
||||
with open(log_file, "a") as file:
|
||||
file.write(f"{datetime_now}\tINFO\t{message}\n")
|
||||
|
||||
def warningAndLog(message):
|
||||
datetime_now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
log_entry = f"{datetime_now}\t{message}"
|
||||
print(message)
|
||||
with open(LOG_FILE, "a") as log_file:
|
||||
log_file.write(f"{datetime_now}\tWARN\t{message}\n")
|
||||
|
||||
def errorAndLog(message):
|
||||
datetime_now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
log_entry = f"{datetime_now}\t{message}"
|
||||
print(message)
|
||||
with open(LOG_FILE, "a") as log_file:
|
||||
log_file.write(f"{datetime_now}\tERROR\t{message}\n")
|
||||
|
||||
def check_python_version():
|
||||
try:
|
||||
python_version = platform.python_version()
|
||||
python_version_tuple = tuple(map(int, python_version.split('.')))
|
||||
if python_version_tuple >= (PYTHON_VERSION, 0):
|
||||
echoAndLog(f"Python version installed: {python_version}")
|
||||
logger.info(f"Python version installed: {python_version}")
|
||||
else:
|
||||
errorAndLog(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()
|
||||
except Exception as e:
|
||||
errorAndLog(f"Problem verifying Python version: {e}")
|
||||
logger.error(f"Problem verifying Python version: {e}")
|
||||
exit()
|
||||
|
||||
def check_distribution():
|
||||
|
@ -134,10 +127,10 @@ def check_distribution():
|
|||
break
|
||||
if VERSION.startswith(UBUNTU_OS_VERSION + "."):
|
||||
return
|
||||
echoAndLog(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("Desea continuar? [s/N]: ")
|
||||
if go_on.upper() != "S":
|
||||
errorAndLog("Leaving the installation.")
|
||||
logger.error("Leaving the installation.")
|
||||
exit()
|
||||
|
||||
def cidr2mask(cidr):
|
||||
|
@ -150,14 +143,14 @@ def cidr2mask(cidr):
|
|||
|
||||
def downloadCode(url):
|
||||
if len(url) != 1:
|
||||
errorAndLog("Invalid number of parameters")
|
||||
logger.error("Invalid number of parameters")
|
||||
exit(1)
|
||||
subprocess.run(["GIT_SSH_COMMAND=ssh -o StrictHostKeyChecking=accept-new git archive --remote=" + url + " --format zip --output opengnsys.zip --prefix=opengnsys/ " + BRANCH + " && unzip opengnsys.zip"], shell=True)
|
||||
if subprocess.returncode != 0:
|
||||
errorAndLog("Error getting OpenGnsys code from " + url)
|
||||
logger.error("Error getting OpenGnsys code from " + url)
|
||||
return 1
|
||||
subprocess.run(["rm -f opengnsys.zip"], shell=True)
|
||||
echoAndLog("downloadCode(): code was downloaded")
|
||||
logger.info("downloadCode(): code was downloaded")
|
||||
return 0
|
||||
|
||||
###############################################################################
|
||||
|
@ -180,16 +173,16 @@ def get_missing_packages(packages):
|
|||
|
||||
def install_packages(missing, log_packages_file=f"/tmp/installed_packages.log"):
|
||||
if not missing:
|
||||
warningAndLog("All packages are already installed.")
|
||||
logger.warning("All packages are already installed.")
|
||||
return
|
||||
echoAndLog("Upgrading the system...")
|
||||
logger.info("Upgrading the system...")
|
||||
subprocess.run(["sudo", "apt-get", "update"], check=True)
|
||||
with open(log_packages_file, "a") as log:
|
||||
for package in missing:
|
||||
subprocess.run(["sudo", "apt-get", "install", "--force-yes", "-y", package], check=True)
|
||||
echoAndLog(f"{package} installed correctly.")
|
||||
logger.info(f"{package} installed correctly.")
|
||||
log.write(package + "\n")
|
||||
echoAndLog("All missing packages have been installed.")
|
||||
logger.info("All missing packages have been installed.")
|
||||
|
||||
def autoConfigure():
|
||||
os_info = platform.uname()
|
||||
|
@ -210,7 +203,7 @@ def autoConfigure():
|
|||
OSDISTRIB = OSDISTRIB.lower()
|
||||
OSVERSION = OSVERSION.split('.')[0]
|
||||
# Configuración según la distribución GNU/Linux (usar minúsculas)
|
||||
echoAndLog(f"Linux OS distribution: {OSDISTRIB} {OSVERSION}")
|
||||
logger.info(f"Linux OS distribution: {OSDISTRIB} {OSVERSION}")
|
||||
if OSDISTRIB in ['ubuntu', 'debian', 'linuxmint']:
|
||||
DEPENDENCIES2= []
|
||||
elif OSDISTRIB in ['fedora', 'centos']:
|
||||
|
@ -218,10 +211,10 @@ def autoConfigure():
|
|||
if OSDISTRIB == 'centos':
|
||||
UPDATEPKGLIST = f"yum install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-{OSVERSION}.noarch.rpm http://rpms.remirepo.net/enterprise/remi-release-{OSVERSION}.rpm"
|
||||
else:
|
||||
errorAndLog("Distribution not supported by OpenGnsys.")
|
||||
logger.error("Distribution not supported by OpenGnsys.")
|
||||
exit(1)
|
||||
else:
|
||||
errorAndLog("Unknown Linux distribution.")
|
||||
logger.error("Unknown Linux distribution.")
|
||||
exit(1)
|
||||
|
||||
def generate_config_url():
|
||||
|
@ -238,13 +231,13 @@ def generate_config_url():
|
|||
return f"https://dl.cloudsmith.io/public/isc/kea-2-0/config.deb.txt?distro=ubuntu&codename={codename}&version={version}&arch={arch}"
|
||||
|
||||
def downloadComposer():
|
||||
#echoAndLog("Downloading composer.phar...")
|
||||
#logger.info("Downloading composer.phar...")
|
||||
os.makedirs(os.path.join(WORKDIR, "ogboot", "bin"), 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")):
|
||||
errorAndLog("Failed to download composer.phar")
|
||||
logger.error("Failed to download composer.phar")
|
||||
return 1
|
||||
echoAndLog("composer.phar downloaded to /opt/ogboot/bin")
|
||||
logger.info("composer.phar downloaded to /opt/ogboot/bin")
|
||||
return 0
|
||||
|
||||
def install_swagger_ui():
|
||||
|
@ -270,16 +263,16 @@ def install_swagger_ui():
|
|||
shutil.rmtree(swagger_ui_path)
|
||||
# Genera el archivo swagger.json
|
||||
os.system(f"{os.path.join(INSTALL_TARGET, 'vendor', 'bin', 'openapi')} {INSTALL_TARGET}/src/OgBootBundle/Controller/ -o {destination_path}/swagger.json")
|
||||
echoAndLog(f"Swagger UI installed on {destination_path}.")
|
||||
logger.info(f"Swagger UI installed on {destination_path}.")
|
||||
|
||||
def create_ogboot_project(path_opengnsys_base):
|
||||
try:
|
||||
pwd.getpwnam('ogboot')
|
||||
warningAndLog("User 'ogboot' already exists")
|
||||
logger.warning("User 'ogboot' already exists")
|
||||
except KeyError:
|
||||
subprocess.run(["sudo", "useradd", "-m", "ogboot"])
|
||||
#PROGRAM_DIR
|
||||
#echoAndLog(f"creando enlace simbólico de {PROGRAM_DIR} a {WORKDIR}/ogboot")
|
||||
#logger.info(f"creando enlace simbólico de {PROGRAM_DIR} a {WORKDIR}/ogboot")
|
||||
#os.symlink(PROGRAM_DIR, f"{WORKDIR}/ogboot")
|
||||
#os.symlink(WORKDIR, path_opengnsys_base)
|
||||
|
||||
|
@ -287,7 +280,7 @@ def create_ogboot_project(path_opengnsys_base):
|
|||
if not os.path.isdir(path_opengnsys_base):
|
||||
raise NotADirectoryError(f"{path_opengnsys_base} existe y no es un directorio.")
|
||||
else:
|
||||
warningAndLog(f"{path_opengnsys_base} directory already exists.")
|
||||
logger.warning(f"{path_opengnsys_base} directory already exists.")
|
||||
else:
|
||||
os.makedirs(path_opengnsys_base)
|
||||
subprocess.run(["sudo", "chown", "-R", "ogboot:ogboot", path_opengnsys_base])
|
||||
|
@ -297,24 +290,24 @@ def create_ogboot_project(path_opengnsys_base):
|
|||
#if 'opengnsys' not in hosts_content:
|
||||
# with open('/etc/hosts', 'a') as hosts_file:
|
||||
# hosts_file.write(f'{SERVER_OPENGNSYS} opengnsys\n')
|
||||
# echoAndLog(f"Entrada {SERVER_OPENGNSYS} opengnsys' agregada a /etc/hosts")
|
||||
# logger.info(f"Entrada {SERVER_OPENGNSYS} opengnsys' agregada a /etc/hosts")
|
||||
|
||||
with open('/etc/hosts', 'r') as hosts_file:
|
||||
hosts_content = hosts_file.read()
|
||||
if f'{SERVER_OPENGNSYS} opengnsys' not in hosts_content:
|
||||
with open('/etc/hosts', 'a') as hosts_file:
|
||||
hosts_file.write(f'{SERVER_OPENGNSYS} opengnsys\n')
|
||||
echoAndLog(f"Entry '{SERVER_OPENGNSYS} opengnsys' has been added to /etc/hosts")
|
||||
logger.info(f"Entry '{SERVER_OPENGNSYS} opengnsys' has been added to /etc/hosts")
|
||||
else:
|
||||
warningAndLog(f"The entry '{SERVER_OPENGNSYS} opengnsys' already exists in /etc/hosts" )
|
||||
logger.warning(f"The entry '{SERVER_OPENGNSYS} opengnsys' already exists in /etc/hosts" )
|
||||
|
||||
echoAndLog("Creating Symfony application skeleton...")
|
||||
logger.info("Creating Symfony application skeleton...")
|
||||
downloadComposer()
|
||||
# Copiar los archivos .env y composer.json primero
|
||||
echoAndLog(f"Copying files (.env and composer.json) from {WORKDIR}/ogboot/.env to {path_opengnsys_base}/.env")
|
||||
logger.info(f"Copying files (.env and composer.json) from {WORKDIR}/ogboot/.env to {path_opengnsys_base}/.env")
|
||||
shutil.copy(f"{WORKDIR}/ogboot/.env", os.path.join(path_opengnsys_base, ".env"))
|
||||
shutil.copy(f"{WORKDIR}/ogboot/composer.json", os.path.join(path_opengnsys_base, "composer.json"))
|
||||
echoAndLog(f".env and composer.json files copied to {path_opengnsys_base}")
|
||||
logger.info(f".env and composer.json files copied to {path_opengnsys_base}")
|
||||
bin_source = os.path.join(WORKDIR, "ogboot/bin")
|
||||
bin_dest = os.path.join(path_opengnsys_base, "bin")
|
||||
src_source = os.path.join(WORKDIR, "ogboot/src")
|
||||
|
@ -353,7 +346,7 @@ def create_ogboot_project(path_opengnsys_base):
|
|||
os.chdir(os.path.join(path_opengnsys_base, 'bin'))
|
||||
result = subprocess.run(["sudo", "-u", "ogboot", "php", os.path.join(path_opengnsys_base, "bin", "composer.phar"), "install", "--no-interaction", "--working-dir", path_opengnsys_base])
|
||||
if result.returncode != 0:
|
||||
errorAndLog("Error creating Symfony project using Composer")
|
||||
logger.error("Error creating Symfony project using Composer")
|
||||
return
|
||||
os.chdir(path_opengnsys_base)
|
||||
result = subprocess.run(["sudo", "-u", "ogboot", "php", os.path.join(path_opengnsys_base, "bin", "composer.phar"), "install", "--no-interaction", "--working-dir", path_opengnsys_base])
|
||||
|
@ -364,19 +357,19 @@ def create_ogboot_project(path_opengnsys_base):
|
|||
|
||||
install_swagger_ui() # Instalar Swagger UI
|
||||
|
||||
echoAndLog("Application skeleton created and composer.lock file removed.")
|
||||
logger.info("Application skeleton created and composer.lock file removed.")
|
||||
|
||||
def createDirs(INSTALL_TARGET):
|
||||
if not os.path.exists(INSTALL_TARGET):
|
||||
try:
|
||||
os.makedirs(INSTALL_TARGET)
|
||||
os.makedirs(os.path.join(INSTALL_TARGET, "client"))
|
||||
echoAndLog(f"{INSTALL_TARGET} directory created successfully.")
|
||||
logger.info(f"{INSTALL_TARGET} directory created successfully.")
|
||||
except OSError:
|
||||
errorAndLog("Error while creating directory paths!")
|
||||
logger.error("Error while creating directory paths!")
|
||||
exit(1)
|
||||
else:
|
||||
echoAndLog(f"Directory {INSTALL_TARGET} already exists.")
|
||||
logger.info(f"Directory {INSTALL_TARGET} already exists.")
|
||||
|
||||
###############################################################################
|
||||
###:::::::::::::::::::::::::::: CONFIGURE ::::::::::::::::::::::::::::::::::###
|
||||
|
@ -442,15 +435,15 @@ def install_kea():
|
|||
|
||||
def backupFile(file):
|
||||
if not os.path.isfile(file):
|
||||
warningAndLog(f"File {file} doesn't exist")
|
||||
logger.warning(f"File {file} doesn't exist")
|
||||
return
|
||||
echoAndLog(f"Making backup of {file}")
|
||||
logger.info(f"Making backup of {file}")
|
||||
shutil.copy2(file, f"{file}-LAST")
|
||||
dateymd = datetime.datetime.now().strftime("%Y%m%d")
|
||||
backup_file = f"{file}-{dateymd}"
|
||||
if not os.path.isfile(backup_file):
|
||||
shutil.copy2(file, backup_file)
|
||||
echoAndLog(f"Backup of {file} successful")
|
||||
logger.info(f"Backup of {file} successful")
|
||||
|
||||
def isc_keaDhcpConfigure():
|
||||
print(f"{isc_keaDhcpConfigure.__name__}(): Configuración de muestra para el servicio DHCP de Kea.")
|
||||
|
@ -491,43 +484,43 @@ def isc_keaDhcpConfigure():
|
|||
return 0
|
||||
|
||||
def testPxe():
|
||||
echoAndLog(f"Checking TFTP service... please wait.")
|
||||
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)
|
||||
echoAndLog("TFTP service is OK.")
|
||||
logger.info("TFTP service is OK.")
|
||||
except subprocess.CalledProcessError:
|
||||
errorAndLog("TFTP service is down.")
|
||||
logger.error("TFTP service is down.")
|
||||
os.remove(f"{TFTPCFGDIR}/testpxe")
|
||||
|
||||
def tftpConfigure():
|
||||
if TFTPSERV:
|
||||
echoAndLog(f"TFTPSERV is configured: {TFTPSERV}")
|
||||
logger.info(f"TFTPSERV is configured: {TFTPSERV}")
|
||||
inetd_cfg_path = f"{INETDCFGDIR}/{TFTPSERV}"
|
||||
if os.path.isfile(inetd_cfg_path):
|
||||
errorAndLog(f"The inetd configuration file exists: {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()
|
||||
echoAndLog(f"Modified inetd configuration file: {inetd_cfg_path}")
|
||||
logger.info(f"Modified inetd configuration file: {inetd_cfg_path}")
|
||||
else:
|
||||
service = TFTPSERV
|
||||
echoAndLog(f"Enabling and starting the service {service}.service")
|
||||
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
|
||||
echoAndLog(f"Enabling and starting the service {service}.service")
|
||||
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 not os.path.exists(TFTPCFGDIR):
|
||||
os.makedirs(TFTPCFGDIR)
|
||||
echoAndLog(f"Directory {TFTPCFGDIR} created.")
|
||||
logger.info(f"Directory {TFTPCFGDIR} created.")
|
||||
#Descargar oglive
|
||||
echoAndLog("Downloading oglive...")
|
||||
logger.info("Downloading oglive...")
|
||||
#Temporalmente se copia desde ~/oglive
|
||||
subprocess.run(["cp", "-r", f"{PROGRAM_DIR}/../../oglive/ogLive-5.11.0-r20210413", f"/var/lib/tftpboot/"])
|
||||
subprocess.run(["cp", "-r", f"{PROGRAM_DIR}/../../tftpboot/ipxe_scripts", f"/var/lib/tftpboot/"])
|
||||
|
@ -537,19 +530,19 @@ def tftpConfigure():
|
|||
subprocess.run(["ln", "-s", "/var/lib/tftpboot/ogLive", "/var/lib/tftpboot/ogclient"])
|
||||
|
||||
symlink_target = f"{INSTALL_TARGET}/tftpboot"
|
||||
echoAndLog(f"Creating symbolic link from /var/lib/tftpboot to {symlink_target}")
|
||||
logger.info(f"Creating symbolic link from /var/lib/tftpboot to {symlink_target}")
|
||||
if not os.path.exists(symlink_target):
|
||||
os.symlink("/var/lib/tftpboot", symlink_target)
|
||||
os.chown(symlink_target, pwd.getpwnam("ogboot").pw_uid, pwd.getpwnam("ogboot").pw_gid)
|
||||
else:
|
||||
warningAndLog(f"The symbolic link already exists: {symlink_target}")
|
||||
logger.warning(f"The symbolic link already exists: {symlink_target}")
|
||||
|
||||
def servicesCompilation():
|
||||
hayErrores = 0
|
||||
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"])
|
||||
if process.returncode != 0:
|
||||
echoAndLog(f"{servicesCompilation.__name__}(): error while compiling OpenGnsys Admin Client")
|
||||
logger.info(f"{servicesCompilation.__name__}(): error while compiling OpenGnsys Admin Client")
|
||||
hayErrores = 1
|
||||
return hayErrores
|
||||
|
||||
|
@ -557,33 +550,33 @@ def copyInterfaceAdm():
|
|||
hayErrores = 0
|
||||
cp_process = subprocess.run(["cp", "-ar", f"{WORKDIR}/ogboot/sources/interface", f"{INSTALL_TARGET}/client/interfaceAdm"])
|
||||
if cp_process.returncode != 0:
|
||||
errorAndLog(f"Error while copying Administration Interface Folder")
|
||||
logger.error(f"Error while copying Administration Interface Folder")
|
||||
hayErrores = 1
|
||||
return hayErrores
|
||||
|
||||
def copyClientFiles():
|
||||
errstatus = 0
|
||||
echoAndLog(f"Copying OpenGnsys Client files.")
|
||||
logger.info(f"Copying OpenGnsys Client files.")
|
||||
source_files = glob.glob(f"{WORKDIR}/ogboot/client/shared/*")
|
||||
# Copy each file individually
|
||||
for file in source_files:
|
||||
cp_process = subprocess.run(["cp", "-a", file, f"{INSTALL_TARGET}/client"])
|
||||
if cp_process.returncode != 0:
|
||||
errorAndLog(f"Error while copying client structure: {file}")
|
||||
logger.error(f"Error while copying client structure: {file}")
|
||||
errstatus = 1
|
||||
echoAndLog(f"Copying OpenGnsys Cloning Engine files.")
|
||||
logger.info(f"Copying OpenGnsys Cloning Engine files.")
|
||||
os.makedirs(f"{INSTALL_TARGET}/client/lib/engine/bin", exist_ok=True)
|
||||
engine_files = glob.glob(f"{WORKDIR}/ogboot/client/engine/*.lib*")
|
||||
# Copiar cada archivo individualmente
|
||||
for file in engine_files:
|
||||
cp_engine_process = subprocess.run(["cp", "-a", file, f"{INSTALL_TARGET}/client/lib/engine/bin"])
|
||||
if cp_engine_process.returncode != 0:
|
||||
errorAndLog(f"Error while copying engine files: {file}")
|
||||
logger.error(f"Error while copying engine files: {file}")
|
||||
errstatus = 1
|
||||
if errstatus == 0:
|
||||
echoAndLog(f"Client copy files success.")
|
||||
logger.info(f"Client copy files success.")
|
||||
else:
|
||||
errorAndLog(f"Client copy files with errors")
|
||||
logger.error(f"Client copy files with errors")
|
||||
return errstatus
|
||||
|
||||
def cidr2mask(bits):
|
||||
|
@ -647,32 +640,32 @@ def openGnsysConfigure():
|
|||
TZ = subprocess.check_output(["timedatectl", "status"]).decode().split("\n")[2].split(":")[1].strip()
|
||||
with open(f"{INSTALL_TARGET}/client/etc/engine.cfg", "a") as file:
|
||||
file.write(f"# OpenGnsys Server timezone.\nTZ=\"{TZ.replace(' ', '')}\"\n")
|
||||
echoAndLog(f"OpenGnsys config files created.")
|
||||
logger.info(f"OpenGnsys config files created.")
|
||||
|
||||
def mount_NFS():
|
||||
if subprocess.call(["sudo", "mount", "-t", "nfs", "ognartefactos.evlt.uma.es:/", "/mnt"]) == 0:
|
||||
echoAndLog("Properly mounted NFS system.")
|
||||
logger.info("Properly mounted NFS system.")
|
||||
else:
|
||||
errorAndLog("Could not mount the NFS system.")
|
||||
logger.error("Could not mount the NFS system.")
|
||||
exit(1)
|
||||
subprocess.call(["ls", "/mnt/"])
|
||||
subprocess.call(["sudo", "cp", "-r", "/mnt/srv/artefactos/ipxe/", "/tmp"])
|
||||
os.chdir("/tmp/ipxe/src")
|
||||
if subprocess.call(["sudo", "make", "-j", "4"]) == 0:
|
||||
echoAndLog("Directory /tmp/ipxe/src correctly mounted.")
|
||||
logger.info("Directory /tmp/ipxe/src correctly mounted.")
|
||||
else:
|
||||
errorAndLog("ERROR\tCould not mount the directory /tmp/ipxe/src.")
|
||||
logger.error("ERROR\tCould not mount the directory /tmp/ipxe/src.")
|
||||
exit(1)
|
||||
if subprocess.call(["sudo", "make", "bin/undionly.kpxe", "EMBED=/opt/opengnsys/tftpboot/ipxe_scripts/dhcp_boot.ipxe"]) == 0:
|
||||
echoAndLog("Boot file mounted correctly.")
|
||||
logger.info("Boot file mounted correctly.")
|
||||
else:
|
||||
errorAndLog("Failed to mount boot file.")
|
||||
logger.error("Failed to mount boot file.")
|
||||
exit(1)
|
||||
subprocess.call(["sudo", "cp", "bin/undionly.kpxe", "/opt/opengnsys/tftpboot"])
|
||||
if subprocess.call(["sudo", "make", "bin-x86_64-efi/ipxe.efi", "EMBED=/opt/opengnsys/tftpboot/ipxe_scripts/dhcp_boot.ipxe"]) == 0:
|
||||
echoAndLog("Properly constructed EFI file.")
|
||||
logger.info("Properly constructed EFI file.")
|
||||
else:
|
||||
errorAndLog("Could not build EFI file.")
|
||||
logger.error("Could not build EFI file.")
|
||||
exit(1)
|
||||
subprocess.call(["sudo", "cp", "bin-x86_64-efi/ipxe.efi", "/opt/opengnsys/tftpboot"])
|
||||
|
||||
|
@ -700,10 +693,10 @@ def generate_ipxe_script():
|
|||
default_ipxe_content = default_template_content.replace("__SERVERIP__", ip_address_server)
|
||||
with open(default_output, "w") as default_ipxe_file:
|
||||
default_ipxe_file.write(default_ipxe_content)
|
||||
echoAndLog("ipxe files created correctly.")
|
||||
logger.info("ipxe files created correctly.")
|
||||
|
||||
def smbConfigure():
|
||||
#echoAndLog(f"{smbConfigure.__name__}(): Configuring Samba service.")
|
||||
#logger.info(f"{smbConfigure.__name__}(): Configuring Samba service.")
|
||||
backupFile(f"{SAMBACFGDIR}/smb.conf")
|
||||
# Copiar plantilla de recursos para OpenGnsys
|
||||
with open(os.path.join(WORKDIR, 'ogboot/etc/smb-ogboot.conf.tmpl'), 'r') as tmpl_file:
|
||||
|
@ -721,112 +714,116 @@ def smbConfigure():
|
|||
subprocess.run(["systemctl", "restart", f"{service}.service"])
|
||||
# Comprobar si se ha configurado correctamente Samba
|
||||
if subprocess.run(["systemctl", "is-active", f"{service}.service"]).returncode == 0:
|
||||
echoAndLog(f"{service} service started successfully.")
|
||||
logger.info(f"{service} service started successfully.")
|
||||
else:
|
||||
errorAndLog(f"Failed to start {service} service.")
|
||||
logger.error(f"Failed to start {service} service.")
|
||||
return 1
|
||||
# Establecer la contraseña para el usuario opengnsys
|
||||
smbpasswd_command = f"(echo {OPENGNSYS_CLIENT_PASSWD}; echo {OPENGNSYS_CLIENT_PASSWD}) | sudo smbpasswd -s -a {OPENGNSYS_CLIENT_USER}"
|
||||
if "Python 3.7" in {PYTHON_VERSION}:
|
||||
result = subprocess.run(smbpasswd_command, shell=True, capture_output=True, text=True)
|
||||
if result.returncode == 0:
|
||||
echoAndLog(f"The password for the user {OPENGNSYS_CLIENT_USER} has been set correctly..")
|
||||
logger.info(f"The password for the user {OPENGNSYS_CLIENT_USER} has been set correctly..")
|
||||
else:
|
||||
errorAndLog(f"Error setting password: {result.stderr}")
|
||||
logger.error(f"Error setting password: {result.stderr}")
|
||||
else:
|
||||
process = subprocess.Popen(smbpasswd_command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
stdout, stderr = process.communicate()
|
||||
if process.returncode == 0:
|
||||
echoAndLog(f"The password for the user {OPENGNSYS_CLIENT_USER} has been set correctly..")
|
||||
logger.info(f"The password for the user {OPENGNSYS_CLIENT_USER} has been set correctly..")
|
||||
else:
|
||||
errorAndLog(f"Error setting password: {stderr}")
|
||||
echoAndLog(f"Added Samba configuration.")
|
||||
logger.error(f"Error setting password: {stderr}")
|
||||
logger.info(f"Added Samba configuration.")
|
||||
return 0
|
||||
|
||||
###############################################################################
|
||||
###:::::::::::::::::::::::::::::::: MAIN :::::::::::::::::::::::::::::::::::###
|
||||
###############################################################################
|
||||
|
||||
echoAndLog(f"Starting installation of ogBoot.")
|
||||
logger.info(f"Starting installation of ogBoot.")
|
||||
if os.geteuid() != 0:
|
||||
errorAndLog("This program must be run with root privileges..")
|
||||
logger.error("This program must be run with root privileges..")
|
||||
exit(1)
|
||||
if os.path.exists(os.path.join(INSTALL_OGBOOT_TARGET + "/doc/")):
|
||||
warningAndLog(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)
|
||||
|
||||
echoAndLog("Verifying Python distribution and version.")
|
||||
logger.info("Verifying Python distribution and version.")
|
||||
check_distribution()
|
||||
check_python_version()
|
||||
|
||||
echoAndLog("Checking the operating system.")
|
||||
logger.info("Checking the operating system.")
|
||||
autoConfigure()
|
||||
|
||||
echoAndLog("Installing necessary packages.")
|
||||
logger.info("Installing necessary packages.")
|
||||
Missing = get_missing_packages (required_packages_18)
|
||||
install_packages(Missing)
|
||||
|
||||
echoAndLog("Obtaining the default network configuration.")
|
||||
logger.info("Obtaining the default network configuration.")
|
||||
if getNetworkSettings() != 0:
|
||||
errorAndLog("Error reading default network settings.")
|
||||
logger.error("Error reading default network settings.")
|
||||
exit(1)
|
||||
|
||||
echoAndLog("Configuring package repositories.")
|
||||
logger.info("Configuring package repositories.")
|
||||
if REMOTE == 1:
|
||||
downloadCode(GIT_REPO)
|
||||
if os.system("echo $?") != 0:
|
||||
errorAndLog("Error while getting code from the repository")
|
||||
logger.error("Error while getting code from the repository")
|
||||
exit(1)
|
||||
else:
|
||||
if not os.path.exists(f"{WORKDIR}/ogboot"):
|
||||
echoAndLog(f"Does not exist {WORKDIR}/ogboot")
|
||||
logger.info(f"Does not exist {WORKDIR}/ogboot")
|
||||
if not os.path.exists(WORKDIR):
|
||||
os.makedirs(WORKDIR)
|
||||
errorAndLog(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.error(f"ogBoot directory not found, create a symbolic link to the directory where the code is located {WORKDIR} To {os.path.dirname(PROGRAM_DIR)}")
|
||||
os.symlink(os.path.dirname(PROGRAM_DIR), f"{WORKDIR}/ogboot")
|
||||
|
||||
echoAndLog("Creating directories.")
|
||||
logger.info("Creating directories.")
|
||||
createDirs(INSTALL_TARGET)
|
||||
if os.system("echo $?") != 0:
|
||||
errorAndLog("Error while creating directory paths!")
|
||||
logger.error("Error while creating directory paths!")
|
||||
exit(1)
|
||||
|
||||
echoAndLog("Creating ogBoot project.")
|
||||
logger.info("Creating ogBoot project.")
|
||||
create_ogboot_project(INSTALL_TARGET)
|
||||
if os.system("echo $?") != 0:
|
||||
errorAndLog("Error while creating skeleton directory!")
|
||||
logger.error("Error while creating skeleton directory!")
|
||||
exit(1)
|
||||
|
||||
echoAndLog("Configuring TFTP service.")
|
||||
logger.info("Configuring TFTP service.")
|
||||
tftpConfigure()
|
||||
|
||||
echoAndLog("Compiling OpenGnsys services source code")
|
||||
logger.info("Compiling OpenGnsys services source code")
|
||||
servicesCompilation()
|
||||
if subprocess.run(["echo", "$?"]).returncode != 0:
|
||||
errorAndLog("Error while compiling OpenGnsys services")
|
||||
logger.error("Error while compiling OpenGnsys services")
|
||||
exit(1)
|
||||
|
||||
echoAndLog("Copy folder Interface between administration and cloning engine")
|
||||
logger.info("Copy folder Interface between administration and cloning engine")
|
||||
copyInterfaceAdm()
|
||||
if subprocess.run(["echo", "$?"]).returncode != 0:
|
||||
errorAndLog("Error while copying Administration Interface")
|
||||
logger.error("Error while copying Administration Interface")
|
||||
exit(1)
|
||||
|
||||
echoAndLog("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()
|
||||
if subprocess.run(["echo", "$?"]).returncode != 0:
|
||||
errorAndLog("Error creating client structure")
|
||||
logger.error("Error creating client structure")
|
||||
|
||||
echoAndLog("Configuring IPXE services")
|
||||
logger.info("Configuring IPXE services")
|
||||
generate_ipxe_script()
|
||||
|
||||
echoAndLog("Configuring ogCore")
|
||||
logger.info("Configuring ogCore")
|
||||
openGnsysConfigure()
|
||||
|
||||
echoAndLog("Setting up NFS system")
|
||||
logger.info("Setting up NFS system")
|
||||
mount_NFS()
|
||||
|
||||
echoAndLog("Configuring Samba")
|
||||
logger.info("Configuring Samba")
|
||||
smbConfigure()
|
||||
|
||||
echoAndLog(f"ogBoot installation finished.")
|
||||
logger.info(f"ogBoot installation finished.")
|
||||
|
||||
# Cerrar el logger
|
||||
logging.shutdown()
|
||||
console_handler.close()
|
Loading…
Reference in New Issue