Compare commits

...

2 Commits

3 changed files with 142 additions and 31 deletions

View File

@ -1,20 +1,48 @@
# Installing Dependencies for Python
# Git component installer
Converting the code to Python 3 currently requires the packages specified in `requirements.txt`.
This directory contains the installer for the git component for OpenGnsys.
To install Python dependencies, the `venv` module (https://docs.python.org/3/library/venv.html) is used, which installs all dependencies in an isolated environment separate from the system.
It downloads, installs and configures Forgejo, creates the default repositories and configures SSH keys.
# Quick Installation
## Ubuntu 24.04
sudo apt install python3-git opengnsys-libarchive-c python3-termcolor bsdextrautils
### Add the repository
Create the file `/etc/apt/sources.list.d/opengnsys.sources` with these contents:
Types: deb
URIs: https://ognproject.evlt.uma.es/debian-opengnsys/
Suites: noble
Components: main
Signed-By:
-----BEGIN PGP PUBLIC KEY BLOCK-----
.
mDMEZzx/SxYJKwYBBAHaRw8BAQdAa83CuAJ5/+7Pn9LHT/k34EAGpx5FnT/ExHSj
XZG1JES0Ik9wZW5HbnN5cyA8b3Blbmduc3lzQG9wZW5nbnN5cy5lcz6ImQQTFgoA
QRYhBC+J38Xsso227ZbDVt2S5xJQRhKDBQJnPH9LAhsDBQkFo5qABQsJCAcCAiIC
BhUKCQgLAgQWAgMBAh4HAheAAAoJEN2S5xJQRhKDW/MBAO6swnpwdrbm48ypMyPh
NboxvF7rCqBqHWwRHvkvrq7pAP9zd98r7z2AvqVXZxnaCsLTUNMEL12+DVZAUZ1G
EquRBbg4BGc8f0sSCisGAQQBl1UBBQEBB0B6D6tkrwXSHi7ebGYsiMPntqwdkQ/S
84SFTlSxRqdXfgMBCAeIfgQYFgoAJhYhBC+J38Xsso227ZbDVt2S5xJQRhKDBQJn
PH9LAhsMBQkFo5qAAAoJEN2S5xJQRhKDJ+cBAM9jYbeq5VXkHLfODeVztgSXnSUe
yklJ18oQmpeK5eWeAQDKYk/P0R+1ZJDItxkeP6pw62bCDYGQDvdDGPMAaIT6CA==
=xcNc
-----END PGP PUBLIC KEY BLOCK-----
It's required to run `apt update` after creating this file
### Install packages
sudo apt install -y python3-git opengnsys-libarchive-c python3-termcolor python3-requests bsdextrautils
## Add SSH Keys to oglive
The Git system accesses the ogrepository via SSH. To work, it needs the oglive to have an SSH key, and the ogrepository must accept it.
The Git installer can make the required changes with:
The Git installer can make the required changes in the Forgejo configuration by extracting a key from the oglive. When invoked without arguments, it extracts the key from the default oglive. This process can also be done by hand, with:
./opengnsys_git_installer.py --set-ssh-key
@ -24,7 +52,12 @@ Or to do it for a specific oglive:
Running this command automatically adds the SSH key to Forgejo.
The existing key can be extracted with:
It's also possible to specify a squashfs file, for the cases where the Git component is not installed on the same machine as ogboot. To do this, copy the squashfs image over, and run the installer with the `--squashfs-file` argument, like this:
./opengnsys_git_installer.py --set-ssh-key --squashfs-file /home/user/initrd.sqfs
The existing key can be dumped to the console with:
./opengnsys_git_installer.py --extract-ssh-key --quiet

View File

@ -1,37 +1,64 @@
# Instalación de dependencias para python
# Instalador de componente Git
La conversion del código a Python 3 requiere actualmente los paquetes especificados en `requirements.txt`
Para instalar dependencias de python se usa el modulo venv (https://docs.python.org/3/library/venv.html) que instala todas las dependencias en un entorno independiente del sistema.
Este directorio contiene el instalador de Git para OpenGnsys.
Descarga, instala y configura Forgejo, crea los repositorios por defecto, y configura claves de SSH.
# Instalación rápida
## Ubuntu 24.04
sudo apt install python3-git opengnsys-libarchive-c python3-termcolor bsdextrautils
### Agregar repositorio
Crear el archivo `/etc/apt/sources.list.d/opengnsys.sources` con este contenido:
Types: deb
URIs: https://ognproject.evlt.uma.es/debian-opengnsys/
Suites: noble
Components: main
Signed-By:
-----BEGIN PGP PUBLIC KEY BLOCK-----
.
mDMEZzx/SxYJKwYBBAHaRw8BAQdAa83CuAJ5/+7Pn9LHT/k34EAGpx5FnT/ExHSj
XZG1JES0Ik9wZW5HbnN5cyA8b3Blbmduc3lzQG9wZW5nbnN5cy5lcz6ImQQTFgoA
QRYhBC+J38Xsso227ZbDVt2S5xJQRhKDBQJnPH9LAhsDBQkFo5qABQsJCAcCAiIC
BhUKCQgLAgQWAgMBAh4HAheAAAoJEN2S5xJQRhKDW/MBAO6swnpwdrbm48ypMyPh
NboxvF7rCqBqHWwRHvkvrq7pAP9zd98r7z2AvqVXZxnaCsLTUNMEL12+DVZAUZ1G
EquRBbg4BGc8f0sSCisGAQQBl1UBBQEBB0B6D6tkrwXSHi7ebGYsiMPntqwdkQ/S
84SFTlSxRqdXfgMBCAeIfgQYFgoAJhYhBC+J38Xsso227ZbDVt2S5xJQRhKDBQJn
PH9LAhsMBQkFo5qAAAoJEN2S5xJQRhKDJ+cBAM9jYbeq5VXkHLfODeVztgSXnSUe
yklJ18oQmpeK5eWeAQDKYk/P0R+1ZJDItxkeP6pw62bCDYGQDvdDGPMAaIT6CA==
=xcNc
-----END PGP PUBLIC KEY BLOCK-----
Es necesario ejecutar `apt update` después de crear el archivo.
### Instalar paquetes:
sudo apt install -y python3-git opengnsys-libarchive-c python3-termcolor python3-requests bsdextrautils
## Agregar claves de SSH a oglive
El sistema de Git accede al ogrepository por SSH. Para funcionar, necesita que el oglive tenga una clave de SSH, y que el ogrepository la acepte.
El instalador de Git puede realizar los cambios requeridos, extrayendo una clave de SSH de un oglive e instalándola en Forgejo, con:
El instalador de Git puede realizar los cambios requeridos, extrayendo una clave de SSH de un oglive e instalándola en Forgejo. Esto se hace por defecto cuando se ejecuta `./opengnsys_git_installer.py` sin parámetros, pero es posible hacer esta parte del proceso a mano, con:
./opengnsys_git_installer.py --extract-ssh-key-from-initrd
./opengnsys_git_installer.py --set-ssh-key
O para hacerlo contra un oglive especifico:
./opengnsys_git_installer.py --extract-ssh-key-from-initrd --oglive 1 # numero de oglive
./opengnsys_git_installer.py --set-ssh-key --oglive 1 # numero de oglive
O contra un archivo de initrd directamente:
O contra un archivo de initrd directamente. Esto se puede usar si el sistema sobre el que se despliega el componente no es el sistema que alberga los archivos de ogboot. En este caso, basta con copiar la imagen de squashfs para que el instalador extraiga su clave.
./opengnsys_git_installer.py --extract-ssh-key-from-initrd --initrd-file /home/user/initrd.img
./opengnsys_git_installer.py --set-ssh-key --squashfs-file /home/user/initrd.sqfs
Ejecutar este comando agrega la clave de SSH a Forgejo automáticamente.
La clave existente puede extraerse con:
La clave existente puede extraerse a la consola con:
./opengnsys_git_installer.py --extract-ssh-key --quiet
@ -53,6 +80,8 @@ El usuario por defecto es `oggit` con password `opengnsys`.
El sistema OgGit requiere módulos de Python que no vienen en Ubuntu 24.04 o tienen versiones demasiado antiguas.
Los paquetes se pueden obtener desde el repositorio de OpenGnsys (ver arriba).
Los fuentes de los paquetes se encuentran en oggit/packages.
# Documentación de código fuente

View File

@ -65,6 +65,23 @@ class RequirementException(Exception):
super().__init__(message)
self.message = message
class OptionalDependencyException(Exception):
"""Excepción que indica que nos falta algún requisito opcional
Attributes:
message (str): Mensaje de error mostrado al usuario
"""
def __init__(self, message):
"""Inicializar OptionalDependencyException.
Args:
message (str): Mensaje de error mostrado al usuario
"""
super().__init__(message)
self.message = message
class FakeTemporaryDirectory:
"""Imitación de TemporaryDirectory para depuración"""
def __init__(self, dirname):
@ -88,6 +105,10 @@ class Oglive:
def _cmd(self, args):
cmd = [self.binary] + args
if not os.path.exists(self.binary):
raise OptionalDependencyException("Missing oglivecli command. Please use --squashfs-file (see README.md for more details)")
self.__logger.debug("comando: %s", cmd)
proc = subprocess.run(cmd, shell=False, check=True, capture_output=True)
@ -297,19 +318,26 @@ class OpengnsysGitInstaller:
def add_ssh_key_from_squashfs(self, oglive_num = None, squashfs_file = None):
if oglive_num is None:
self.__logger.info("Using default oglive")
oglive_num = int(self.oglive.get_default())
else:
self.__logger.info("Using oglive %i", oglive_num)
name = "(unknown)"
if squashfs_file is None:
if oglive_num is None:
self.__logger.info("Using default oglive")
oglive_num = self.oglive.get_default()
else:
self.__logger.info("Using oglive %i", oglive_num)
name = self.oglive.get_clients()[str(oglive_num)]
else:
self.__logger.info("Using specified squashfs file %s", squashfs_file)
name = os.path.basename(squashfs_file)
oglive_client = self.oglive.get_clients()[str(oglive_num)]
self.__logger.info("Oglive is %s", oglive_client)
keys = installer.extract_ssh_keys_from_squashfs(oglive_num = oglive_num, squashfs_file=squashfs_file)
for k in keys:
timestamp = '{:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now())
installer.add_forgejo_sshkey(k, f"Key for {oglive_client} ({timestamp})")
installer.add_forgejo_sshkey(k, f"Key for {name} ({timestamp})")
@ -416,6 +444,21 @@ class OpengnsysGitInstaller:
return public_key
def get_image_paths(self, oglive_num = None):
squashfs = "ogclient.sqfs"
if oglive_num is None:
self.__logger.info("Will modify default client")
oglive_num = self.oglive.get_default()
tftp_dir = os.path.join(self.base_path, "tftpboot")
oglive_client = self.oglive.get_clients()[str(oglive_num)]
client_squashfs_path = os.path.join(tftp_dir, oglive_client, squashfs)
self.__logger.info("Squashfs: %s", client_squashfs_path)
def set_ssh_key_in_initrd(self, client_num = None):
INITRD = "oginitrd.img"
@ -618,7 +661,7 @@ class OpengnsysGitInstaller:
return ret.stdout.strip()
def install_forgejo(self):
self.__logger.info("Installing Forgejo")
self.__logger.info("Installing Forgejo version %s", FORGEJO_VERSION)
@ -642,8 +685,9 @@ class OpengnsysGitInstaller:
conf_path = os.path.join(conf_dir_path, "app.ini")
self.__logger.debug("Stopping opengnsys-forgejo service")
subprocess.run(["systemctl", "stop", "opengnsys-forgejo"], check=False)
self.__logger.info("Stopping opengnsys-forgejo service. This may cause a harmless warning.")
subprocess.run(["/usr/bin/systemctl", "stop", "opengnsys-forgejo"], check=False)
self.__logger.debug("Downloading from %s into %s", FORGEJO_URL, bin_path)
pathlib.Path(opengnsys_bin_path).mkdir(parents=True, exist_ok=True)
@ -816,8 +860,7 @@ if __name__ == '__main__':
streamLog = logging.StreamHandler()
streamLog.setLevel(logging.INFO)
if not os.path.exists(opengnsys_log_dir):
os.mkdir(opengnsys_log_dir)
pathlib.Path(opengnsys_log_dir).mkdir(parents=True, exist_ok=True)
logFilePath = f"{opengnsys_log_dir}/git_installer.log"
fileLog = logging.FileHandler(logFilePath)
@ -853,6 +896,7 @@ if __name__ == '__main__':
parser.add_argument('--set-ssh-key-in-initrd', action='store_true', help="Configure SSH key in oglive (obsolete)")
parser.add_argument('--oglive', type=int, metavar='NUM', help = "Do SSH key manipulation on this oglive")
parser.add_argument('--quiet', action='store_true', help="Quiet console output")
parser.add_argument('--get-image-paths', action='store_true', help="Get paths to image files")
parser.add_argument("-v", "--verbose", action="store_true", help = "Verbose console output")
@ -886,9 +930,11 @@ if __name__ == '__main__':
key = installer.extract_ssh_key_from_initrd(oglive_number = args.oglive, initrd_file = args.initrd_file)
print(f"{key}")
elif args.set_ssh_key:
installer.add_ssh_key_from_squashfs(oglive_num=args.oglive)
installer.add_ssh_key_from_squashfs(oglive_num=args.oglive, squashfs_file=args.squashfs_file)
elif args.set_ssh_key_in_initrd:
installer.set_ssh_key_in_initrd()
elif args.get_image_paths:
installer.get_image_paths(oglive_num = args.oglive)
else:
installer.install_dependencies()
installer.install_forgejo()
@ -902,5 +948,8 @@ if __name__ == '__main__':
except RequirementException as req:
show_error(f"Requisito para la instalación no satisfecho: {req.message}")
exit(1)
except OptionalDependencyException as optreq:
show_error(optreq.message)
exit(1)