# ██████╗ ██╗ ██╗ ██╗███████╗██████╗ █████╗ ███╗ ██╗ ██████╗ ██╗ ██╗██╗███████╗███████╗ # ██╔══██╗██║ ██║ ██║██╔════╝██╔══██╗██╔══██╗████╗ ██║██╔═══██╗██║ ██║██║██╔════╝██╔════╝ # ██████╔╝██║ ██║ ██║█████╗ ██████╔╝███████║██╔██╗ ██║██║ ██║██║ ██║██║███████╗█████╗ # ██╔══██╗██║ ██║ ██║██╔══╝ ██╔══██╗██╔══██║██║╚██╗██║██║▄▄ ██║██║ ██║██║╚════██║██╔══╝ # ██████╔╝███████╗╚██████╔╝███████╗██████╔╝██║ ██║██║ ╚████║╚██████╔╝╚██████╔╝██║███████║███████╗ # ╚═════╝ ╚══════╝ ╚═════╝ ╚══════╝╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚══▀▀═╝ ╚═════╝ ╚═╝╚══════╝╚══════╝ # # kernel_manager: # This module allow to manage kernels globaly. It # allow to make basic actions on kernels. # # 1.3.0: Role update. David Pieters # 1.2.0: Role update. David Pieters , Benoit Leveugle # 1.1.0: Role update. Benoit Leveugle , Bruno Travouillon # 1.0.0: Role creation. Benoit Leveugle # # https://github.com/bluebanquise/bluebanquise - MIT license # Import basic modules import os import distro import logging from diskless.utils import Color, inform, ask, ok, select_from_list from diskless.image_manager import ImageManager # Class to manage kernels class KernelManager: """Class to manage kernels of the diskless tool.""" # Path where diskless kernels are if distro.id() != 'slackware': KERNELS_PATH = '/var/www/html/preboot_execution_environment/diskless/kernels' elif distro.id() == 'slackware': KERNELS_PATH = '/var/www/htdocs/preboot_execution_environment/diskless/kernels' @staticmethod def get_kernels(): """Get the list of kernels inside KernelManager.KERNELS_PATH. :return: `kernel_list` if there is at least one kernel, `None` overwise :rtype: list of str """ # Select only files with 'vmlinuz' inside file name -> it's kernel files kernel_list = [kernel for kernel in os.listdir(KernelManager.KERNELS_PATH) if 'vmlinuz' in kernel] # if there are kernels if kernel_list: # Return kernel names list return kernel_list else: return None @staticmethod def get_available_kernels(): """Get only kernels which have an initramfs file associated in KernelManager.KERNELS_PATH. :return: `kernel_list` if there is at least one available kernel, `None` overwise :rtype: list of str """ # Get all kernels kernel_list = KernelManager.get_kernels() # If there are kernels if kernel_list: # Return only kernels with initramfs-kernel return [kernel for kernel in kernel_list if os.path.exists(KernelManager.KERNELS_PATH + '/initramfs-kernel-' + (kernel.replace('vmlinuz-', '')))] # If there are no kernels else: return None @staticmethod def change_kernel(image, kernel): """Change the kernel of an image object. :param image: A created image object :type image: Image :param kernel: An available kernel :type kernel: str """ logging.info('Setting up kernel \'' + kernel + '\' for image \'' + image.name + '\'') # Use image method to set kernel image.kernel = kernel # Update initramfs for selected kernel image.image = 'initramfs-kernel-' + kernel.replace('vmlinuz-', '') # Change the kernel in the image_data file image.register_image() # Change the kernel in the boot.ipxe file image.generate_ipxe_boot_file() # Generate initramfs from kernel @staticmethod def generate_initramfs(kernel): import distro """Generate an initramfs from a kernel. The new initramfs will be generated in KernelManager.KERNELS_PATH. :param kernel: A kernel in KernelManager.KERNELS_PATH :type kernel: str """ logging.info('Start generating initramfs for kernel \'' + kernel + '\'') # Create a generation path for the initramfs kernel_version = kernel.replace('vmlinuz-', '') generation_path = KernelManager.KERNELS_PATH + '/initramfs-kernel-' + kernel_version inform('Now generating initramfs... May take some time') if distro.id() != 'slackware': # Generate the new initramfs file with dracut command on the kernel logging.info('Executing \'dracut --xz -v -m "network base nfs" --add "ifcfg livenet systemd systemd-initrd dracut-systemd" --add-drivers xfs --no-hostonly --nolvmconf --force ' + generation_path + ' --kver ' + kernel_version + '\'') os.system('dracut --xz -v -m "network base nfs" --add "ifcfg livenet systemd systemd-initrd dracut-systemd" --add-drivers xfs --no-hostonly --nolvmconf --force ' + generation_path + ' --kver ' + kernel_version) else: import re kernel_release = kernel.rsplit('-',2)[2] logging.info('[INFO] Kernel release number: ' + kernel_release, Color.BLUE) slackpkgs_source = ('/var/www/html/repositories/slackware/%s/x86_64/os' % distro.version()) extra_mods = ':virtio_blk:virtio_pci_modern_dev:virtio_pci:virtio:virtio_balloon:virtio_ring:virtio_net' initrd_working_directory = os.path.join('/var/tmp/diskless', 'initrd-' + kernel_version) try: os.makedirs(initrd_working_directory) except FileExistsError: logging.info('[WARNING] The directory ' + initrd_working_directory + ' already exists. Cleaning.') os.system('rm -fr ' + initrd_working_directory) os.makedirs(initrd_working_directory) except OSError: logging.info('[ERROR] Cannot create directory ' + initrd_working_directory) os.system('tar xf /usr/share/mkinitrd/initrd-tree.tar.gz -C {}'.format(initrd_working_directory)) slackpkgs="dhcpcd,squashfs-tools" os.system('installpkg --terse --root {}'.format(initrd_working_directory) + ' '+slackpkgs_source+'/slackware64/*/{'+slackpkgs+'}-*.t?z') if int(distro.version_parts()[0]) > 14: upgrade_args = '--terse' else: upgrade_args = '' for pkg in slackpkgs.split(","): os.system('find '+slackpkgs_source+'/patches/packages -iname "' + pkg + '-*.t?z" -exec echo ROOT={}'.format(initrd_working_directory)+' upgradepkg '+upgrade_args+' "{}" \; | sh -') logging.info('[INFO] Customizing /init') # handling custom arguments os.system('sed -i \'/root=\/dev\/\*/ i\ root=nfs:*|root=live:*) \# bluebanquise \\n ROOTDEV=$(echo $ARG | cut -f2 -d=)\\n ;;\' {}/init'.format(initrd_working_directory)) if int(distro.version_parts()[0]) < 15: os.system('sed -i \'/root=\/dev\/*/ i\ rootflags=*) \# bluebanquise \\n ROOTFLAGS=$(echo $ARG | cut -f2- -d=)\\n ;;\' {}/init'.format(initrd_working_directory)) os.system('sed -i \'/mount -o ro/ s/ro/ro,$ROOTFLAGS/\' {}/init'.format(initrd_working_directory)) init_chroot_line = os.popen('grep -n "# Switch to real" {}/init'.format(initrd_working_directory)).read() print("init line: " + init_chroot_line) init_linen = int(re.match(r'^[0-9]+', init_chroot_line).group()) os.system('sed -i \'{0}i\ \ echo "# BlueBanquise diskless..."\' {1}/init'.format(init_linen, initrd_working_directory)) os.system('sed -i "{0}i\ \ /sbin/dhcpcd -w -e force_hostname=True" {1}/init'.format(init_linen+1, initrd_working_directory)) #os.system('sed -i "{0}i\ \ /sbin/dhcpcd -w" {1}/init'.format(init_linen+1, initrd_working_directory)) os.system('sed -i "{0}i\ \ hostname ; sleep 2" {1}/init'.format(init_linen+2, initrd_working_directory)) os.system('sed -i \'{0}i\ \ case "\$ROOTDEV" in\' {1}/init'.format(init_linen+3, initrd_working_directory)) os.system('sed -i \'{0}i\ nfs:*)\\n ROOTDEV=\$(echo \$ROOTDEV | cut -d: -f2-) ROOTFS=nfs;;\' {1}/init'.format(init_linen+4, initrd_working_directory)) os.system('sed -i \'{0}i\ live:*)\\n wget \$(echo \$ROOTDEV | cut -d: -f2-)\' {1}/init'.format(init_linen+6, initrd_working_directory)) # os.system('sed -i \'332i\ ROOTDEV=/squashfs-root/LiveOS/rootfs.img ROOTFS=xfs;\\n ;;\\n esac\\n\' {}/init'.format(initrd_working_directory)) os.system('sed -i \'{0}i\ ROOTDEV=/dev/loop0 ROOTFS=xfs\\n\' {1}/init'.format(init_linen+8, initrd_working_directory)) os.system('sed -i \'{0}i\ unsquashfs squashfs.img\\n\' {1}/init'.format(init_linen+9, initrd_working_directory)) os.system('sed -i \'{0}i\ losetup /dev/loop0 /squashfs-root/LiveOS/rootfs.img\\n ;;\\n esac\' {1}/init'.format(init_linen+10, initrd_working_directory)) os.system('sed -i \'{0}i\ echo "Switching to $ROOTDEV"\' {1}/init'.format(init_linen+13, initrd_working_directory)) os.system('sed -i \'{0}i\ sleep 3\' {1}/init'.format(init_linen+14, initrd_working_directory)) os.system('mkinitrd -k {}'.format(kernel_release) + ' -m jbd2:mbcache:crc32c_intel:crc32c_generic:loop:squashfs:overlay:nfsd:xfs:ext4:nfs4'+extra_mods+' -f auto -r \${root} -o ' + generation_path + ' -s {}'.format(initrd_working_directory)) # Change the permisssions on the generated file logging.info('Changing permission to 0o644 on ' + generation_path) os.chmod(generation_path, 0o644) ##################### # CLI reserved part # ##################### @staticmethod def cli_select_kernel(): """Select a kernel from an available kernels list in KernelManager.KERNELS_PATH :raises UserWarning: When there is no kernel to select :return: `kernel` if there is at least one kernel :rtype: str """ # Get available kernels list kernels_list = KernelManager.get_kernels() # If there are available kernels if kernels_list: ask('Select the kernel:') # return selected kernel return select_from_list(kernels_list) else: raise UserWarning('No available kernel.') # [CLI] Display a list of available kernels @staticmethod def cli_display_kernels(): """Display all kernels inside KernelManager.KERNELS_PATH :raises UserWarning: When there is no kernel to display """ # Get kernel list kernel_list = KernelManager.get_kernels() # If here are kernels if kernel_list: print('Available kernels:') print(' │') # For each kernel for kernel in kernel_list: # If the iniramfs file is present if os.path.exists(KernelManager.KERNELS_PATH + '/initramfs-kernel-' + (kernel.replace('vmlinuz-', ''))): initramfs_status = Color.GREEN + 'initramfs present'+Color.TAG_END # If the iniramfs file is not present else: initramfs_status = Color.YELLOW + 'missing initramfs-kernel-' + kernel.replace('vmlinuz-', '') + Color.TAG_END # If it is the last kernel of the list if kernel == kernel_list[-1]: print(" └── "+str(kernel)+' - ' + initramfs_status) # If it is not the last kernel of the list else: print(" ├── "+str(kernel)+' - ' + initramfs_status) ok() # If the list of kernels is empty else: inform('No kernels found in %s/'.format(KERNELS_PATH), 'Please refer to readme.rst for details on how to obtain kernels.') return @staticmethod def cli_change_kernel(): """Change the kernel of an image :raises UserWarning: When there is no image with kernel """ # Get all images images_list = ImageManager.get_created_images() if not images_list: inform('No images.') return # Select only images with kernel attribut images_with_kernel = [] for image in images_list: if hasattr(image, 'kernel'): images_with_kernel.append(image.name) # If there is no image with kernel, raise an exception if not images_with_kernel: inform('Not any image with a kernel') return # Select the image to change kernel image_name = select_from_list(images_with_kernel) image = ImageManager.get_created_image(image_name) print('\nCurrent kernel is: ' + image.kernel + '\n') # Select an available kernel new_kernel = KernelManager.cli_select_kernel() # Set image kernel by using image method KernelManager.change_kernel(image, new_kernel) ok() def cli_generate_initramfs(): selected_kernel = KernelManager.cli_select_kernel() KernelManager.generate_initramfs(selected_kernel) ok()