Exemple #1
0
def run(dest_dir, settings, mount_devices, blvm):
    """ Runs mkinitcpio """

    cpu = get_cpu()

    # Add lvm and encrypt hooks if necessary
    hooks = ["base", "udev", "autodetect", "modconf", "block", "keyboard", "keymap"]
    modules = []

    # It is important that the plymouth hook comes before any encrypt hook

    plymouth_bin = os.path.join(dest_dir, "usr/bin/plymouth")
    if os.path.exists(plymouth_bin):
        hooks.append("plymouth")

    # It is important that the encrypt hook comes before the filesystems hook
    # (in case you are using LVM on LUKS, the order should be: encrypt lvm2 filesystems)

    if settings.get("use_luks"):
        if os.path.exists(plymouth_bin):
            hooks.append("plymouth-encrypt")
        else:
            hooks.append("encrypt")

        modules.extend(["dm_mod", "dm_crypt", "ext4"])

        arch = os.uname()[-1]
        if arch == 'x86_64':
            modules.extend(["aes_x86_64"])
        else:
            modules.extend(["aes_i586"])

        modules.extend(["sha256", "sha512"])

    if settings.get("f2fs"):
        modules.append("f2fs")

    if blvm or settings.get("use_lvm"):
        hooks.append("lvm2")

    if "swap" in mount_devices:
        hooks.append("resume")

    hooks.append("filesystems")

    if settings.get('btrfs') and cpu is not 'genuineintel':
        modules.append('crc32c')
    elif settings.get('btrfs') and cpu is 'genuineintel':
        modules.append('crc32c-intel')
    else:
        hooks.append("fsck")

    set_hooks_and_modules(dest_dir, hooks, modules)

    # Run mkinitcpio on the target system
    # Fix for bsdcpio error. See: http://forum.antergos.com/viewtopic.php?f=5&t=1378&start=20#p5450
    locale = settings.get('locale')
    kernel = configuration['install']['KERNEL']
    cmd = ['sh', '-c', 'LANG={0} /usr/bin/mkinitcpio -p {1}'.format(locale,kernel)]
    chroot.run(cmd, dest_dir)
Exemple #2
0
    def install_grub2_bios(self):
        """ Install Grub2 bootloader in a BIOS system """
        grub_location = self.settings.get('bootloader_device')
        txt = _("Installing GRUB(2) BIOS boot loader in {0}").format(grub_location)
        logging.info(txt)

        # /dev and others need to be mounted (binded).
        # We call mount_special_dirs here just to be sure
        chroot.mount_special_dirs(self.dest_dir)

        grub_install = ['grub-install',
                        '--directory=/usr/lib/grub/i386-pc',
                        '--target=i386-pc',
                        '--boot-directory=/boot',
                        '--recheck']

        if len(grub_location) > len("/dev/sdX"):  # Use --force when installing in /dev/sdXY
            grub_install.append("--force")

        grub_install.append(grub_location)

        try:
            chroot.run(grub_install, self.dest_dir)
        except subprocess.CalledProcessError as process_error:
            logging.error(_('Command grub-install failed. Error output: %s'), process_error.output)
        except subprocess.TimeoutExpired:
            logging.error(_('Command grub-install timed out.'))
        except Exception as general_error:
            logging.error(_('Command grub-install failed. Unknown Error: %s'), general_error)

        self.install_grub2_locales()

        self.copy_grub2_theme_files()

        # Add -l option to os-prober's umount call so that it does not hang
        self.apply_osprober_patch()

        # Run grub-mkconfig last
        logging.debug(_("Running grub-mkconfig..."))
        locale = self.settings.get("locale")
        try:
            cmd = ['sh', '-c', 'LANG={0} grub-mkconfig -o /boot/grub/grub.cfg'.format(locale)]
            chroot.run(cmd, self.dest_dir, 300)
        except subprocess.TimeoutExpired:
            msg = _("grub-mkconfig does not respond. Killing grub-mount and os-prober so we can continue.")
            logging.error(msg)
            subprocess.check_call(['killall', 'grub-mount'])
            subprocess.check_call(['killall', 'os-prober'])

        cfg = os.path.join(self.dest_dir, "boot/grub/grub.cfg")
        with open(cfg) as grub_cfg:
            if "Apricity" in grub_cfg.read():
                txt = _("GRUB(2) BIOS has been successfully installed.")
                logging.info(txt)
                self.settings.set('bootloader_installation_successful', True)
            else:
                txt = _("ERROR installing GRUB(2) BIOS.")
                logging.warning(txt)
                self.settings.set('bootloader_installation_successful', False)
Exemple #3
0
def run(params, dest_dir="/install"):
    cmd = ["ufw"]
    cmd.extend(params)

    if not _UFW:
        # Could not import ufw module (missing?)
        # Will call ufw command directly
        try:
            chroot.run(cmd, dest_dir)
        except OSError as os_error:
            logging.warning(os_error)
        finally:
            return

    app_action = False

    # Remember, will have to take --force into account if we use it with 'app'
    idx = 1
    if len(cmd) > 1 and cmd[1].lower() == "--dry-run":
        idx += 1

    if len(cmd) > idx and cmd[idx].lower() == "app":
        app_action = True

    res = ""
    try:
        cmd_line = ufw.frontend.parse_command(cmd)
        ui = ufw.frontend.UFWFrontend(cmd_line.dryrun)
        if app_action and 'type' in cmd_line.data and cmd_line.data[
                'type'] == 'app':
            res = ui.do_application_action(cmd_line.action,
                                           cmd_line.data['name'])
        else:
            bailout = False
            if cmd_line.action == "enable" and not cmd_line.force and \
               not ui.continue_under_ssh():
                res = _("Aborted")
                bailout = True

            if not bailout:
                if 'rule' in cmd_line.data:
                    res = ui.do_action(cmd_line.action, cmd_line.data['rule'],
                                       cmd_line.data['iptype'], cmd_line.force)
                else:
                    res = ui.do_action(cmd_line.action, "", "", cmd_line.force)
    except (ValueError, ufw.UFWError) as ufw_error:
        logging.error(ufw_error)
        # Error using ufw module
        # Will call ufw command directly
        try:
            chroot.run(cmd, dest_dir)
        except OSError as os_error:
            logging.warning(os_error)
        finally:
            return

    logging.debug(res)
Exemple #4
0
    def install_grub2_efi(self):
        """ Install Grub2 bootloader in a UEFI system """
        uefi_arch = "x86_64"
        spec_uefi_arch = "x64"
        spec_uefi_arch_caps = "X64"
        bootloader_id = 'apricity_grub' if not os.path.exists('/install/boot/efi/EFI/apricity_grub') else \
            'apricity_grub_{0}'.format(self.random_generator())

        txt = _("Installing GRUB(2) UEFI {0} boot loader").format(uefi_arch)
        logging.info(txt)

        grub_install = [
            'grub-install',
            '--target={0}-efi'.format(uefi_arch),
            '--efi-directory=/install/boot/efi',
            '--bootloader-id={0}'.format(bootloader_id),
            '--boot-directory=/install/boot',
            '--recheck']
        load_module = ['modprobe', '-a', 'efivarfs']

        try:
            subprocess.call(load_module, timeout=15)
            subprocess.check_call(grub_install, timeout=120)
        except subprocess.CalledProcessError as process_error:
            logging.error('Command grub-install failed. Error output: %s', process_error.output)
        except subprocess.TimeoutExpired:
            logging.error('Command grub-install timed out.')
        except Exception as general_error:
            logging.error('Command grub-install failed. Unknown Error: %s', general_error)

        self.install_grub2_locales()

        self.copy_grub2_theme_files()

        # Copy grub into dirs known to be used as default by some OEMs if they do not exist yet.
        grub_defaults = [os.path.join(self.dest_dir, "boot/efi/EFI/BOOT", "BOOT{0}.efi".format(spec_uefi_arch_caps)),
                         os.path.join(self.dest_dir, "boot/efi/EFI/Microsoft/Boot", 'bootmgfw.efi')]

        grub_path = os.path.join(self.dest_dir, "boot/efi/EFI/apricity_grub", "grub{0}.efi".format(spec_uefi_arch))

        for grub_default in grub_defaults:
            path = grub_default.split()[0]
            if not os.path.exists(path):
                msg = _("No OEM loader found in %s. Copying Grub(2) into dir.")
                logging.info(msg, path)
                os.makedirs(path)
                msg_failed = _("Copying Grub(2) into OEM dir failed: %s")
                try:
                    shutil.copy(grub_path, grub_default)
                except FileNotFoundError:
                    logging.warning(msg_failed, _("File not found."))
                except FileExistsError:
                    logging.warning(msg_failed, _("File already exists."))
                except Exception as general_error:
                    logging.warning(msg_failed, general_error)

        # Copy uefi shell if none exists in /boot/efi/EFI
        shell_src = "/usr/share/cnchi/grub2-theme/shellx64_v2.efi"
        shell_dst = os.path.join(self.dest_dir, "boot/efi/EFI/")
        try:
            shutil.copy2(shell_src, shell_dst)
        except FileNotFoundError:
            logging.warning(_("UEFI Shell drop-in not found at %s"), shell_src)
        except FileExistsError:
            pass
        except Exception as general_error:
            logging.warning(_("UEFI Shell drop-in could not be copied."))
            logging.warning(general_error)

        # Run grub-mkconfig last
        logging.info(_("Generating grub.cfg"))

        # /dev and others need to be mounted (binded).
        # We call mount_special_dirs here just to be sure
        chroot.mount_special_dirs(self.dest_dir)

        # Add -l option to os-prober's umount call so that it does not hang
        self.apply_osprober_patch()

        logging.debug(_("Running grub-mkconfig..."))
        locale = self.settings.get("locale")
        try:
            cmd = ['sh', '-c', 'LANG={0} grub-mkconfig -o /boot/grub/grub.cfg'.format(locale)]
            chroot.run(cmd, self.dest_dir, 300)
        except subprocess.TimeoutExpired:
            txt = _("grub-mkconfig appears to be hung. Killing grub-mount and os-prober so we can continue.")
            logging.error(txt)
            subprocess.check_call(['killall', 'grub-mount'])
            subprocess.check_call(['killall', 'os-prober'])

        paths = [os.path.join(self.dest_dir, "boot/grub/x86_64-efi/core.efi"),
                 os.path.join(self.dest_dir, "boot/efi/EFI/{0}".format(bootloader_id), "grub{0}.efi".format(spec_uefi_arch))]

        exists = True

        for path in paths:
            if not os.path.exists(path):
                exists = False
                logging.debug(_("Path '%s' doesn't exist, when it should"), path)

        if exists:
            txt = _("GRUB(2) UEFI install completed successfully")
            logging.info(txt)
            self.settings.set('bootloader_installation_successful', True)
        else:
            txt = _("GRUB(2) UEFI install may not have completed successfully.")
            logging.warning(txt)
            self.settings.set('bootloader_installation_successful', False)
Exemple #5
0
def chroot_run(cmd):
    chroot.run(cmd, DEST_DIR)
Exemple #6
0
    def install_systemd_boot(self):
        """ Install Systemd-boot (Gummiboot) bootloader to the EFI System Partition """
        # Setup bootloader menu
        menu_dir = os.path.join(self.dest_dir, "boot/loader")
        os.makedirs(menu_dir, mode=0o755, exist_ok=True)
        menu_path = os.path.join(menu_dir, "loader.conf")
        with open(menu_path, 'w') as menu_file:
            menu_file.write("default antergos")

        # Setup boot entries
        conf = {}

        if not self.settings.get('use_luks'):
            conf['default'] = []
            conf['default'].append("title\tAntergos\n")
            conf['default'].append("linux\t/vmlinuz-linux\n")
            conf['default'].append("initrd\t/initramfs-linux.img\n")
            conf['default'].append(
                "options\troot=UUID={0} rw quiet\n\n".format(self.root_uuid))

            conf['fallback'] = []
            conf['fallback'].append("title\tAntergos (fallback)\n")
            conf['fallback'].append("linux\t/vmlinuz-linux\n")
            conf['fallback'].append("initrd\t/initramfs-linux-fallback.img\n")
            conf['fallback'].append(
                "options\troot=UUID={0} rw quiet\n\n".format(self.root_uuid))

            if self.settings.get('feature_lts'):
                conf['lts'] = []
                conf['lts'].append("title\tAntergos LTS\n")
                conf['lts'].append("linux\t/vmlinuz-linux-lts\n")
                conf['lts'].append("initrd\t/initramfs-linux-lts.img\n")
                conf['lts'].append(
                    "options\troot=UUID={0} rw quiet\n\n".format(
                        self.root_uuid))

                conf['lts_fallback'] = []
                conf['lts_fallback'].append(
                    "title\tAntergos LTS (fallback)\n\n")
                conf['lts_fallback'].append("linux\t/vmlinuz-linux-lts\n")
                conf['lts_fallback'].append(
                    "initrd\t/initramfs-linux-lts-fallback.img\n")
                conf['lts_fallback'].append(
                    "options\troot=UUID={0} rw quiet\n\n".format(
                        self.root_uuid))
        else:
            luks_root_volume = self.settings.get('luks_root_volume')
            luks_root_volume_uuid = fs.get_uuid(
                "/dev/mapper/{0}".format(luks_root_volume))

            # In automatic mode, root_device is in self.mount_devices, as it should be
            root_device = self.root_device

            if self.method == "advanced" and self.settings.get(
                    'use_luks_in_root'):
                root_device = self.settings.get('luks_root_device')

            root_uuid = fs.get_uuid(root_device)

            key = ""
            if self.settings.get("luks_root_password") == "":
                key = "cryptkey=UUID={0}:ext2:/.keyfile-root".format(
                    self.boot_uuid)

            root_uuid_line = "cryptdevice=UUID={0}:{1} {2} root=UUID={3} rw quiet"
            root_uuid_line = root_uuid_line.format(root_uuid, luks_root_volume,
                                                   key, luks_root_volume_uuid)

            conf['default'] = []
            conf['default'].append("title\tAntergos\n")
            conf['default'].append("linux\t/vmlinuz-linux\n")
            conf['default'].append(
                "options\tinitrd=/initramfs-linux.img {0}\n\n".format(
                    root_uuid_line))

            conf['fallback'] = []
            conf['fallback'].append("title\tAntergos (fallback)\n")
            conf['fallback'].append("linux\t/vmlinuz-linux\n")
            conf['fallback'].append(
                "options\tinitrd=/initramfs-linux-fallback.img {0}\n\n".format(
                    root_uuid_line))

            if self.settings.get('feature_lts'):
                conf['lts'] = []
                conf['lts'].append("title\tAntergos LTS\n")
                conf['lts'].append("linux\t/vmlinuz-linux-lts\n")
                conf['lts'].append(
                    "options\tinitrd=/initramfs-linux-lts.img {0}\n\n".format(
                        root_uuid_line))

                conf['lts_fallback'] = []
                conf['lts_fallback'].append("title\tAntergos LTS (fallback)\n")
                conf['lts_fallback'].append("linux\t/vmlinuz-linux-lts\n")
                conf['lts_fallback'].append(
                    "options\tinitrd=/initramfs-linux-lts-fallback.img {0}\n\n"
                    .format(root_uuid_line))

        # Write boot entries
        entries_dir = os.path.join(self.dest_dir, "boot/loader/entries")
        os.makedirs(entries_dir, mode=0o755, exist_ok=True)

        entry_path = os.path.join(entries_dir, "antergos.conf")
        with open(entry_path, 'w') as entry_file:
            for line in conf['default']:
                entry_file.write(line)

        entry_path = os.path.join(entries_dir, "antergos-fallback.conf")
        with open(entry_path, 'w') as entry_file:
            for line in conf['fallback']:
                entry_file.write(line)

        if self.settings.get('feature_lts'):
            entry_path = os.path.join(entries_dir, "antergos-lts.conf")
            with open(entry_path, 'w') as entry_file:
                for line in conf['lts']:
                    entry_file.write(line)

            entry_path = os.path.join(entries_dir,
                                      "antergos-lts-fallback.conf")
            with open(entry_path, 'w') as entry_file:
                for line in conf['lts_fallback']:
                    entry_file.write(line)

        # Install bootloader
        logging.debug("Installing Systemd-boot bootloader...")
        try:
            # chroot.mount_special_dirs(self.dest_dir)
            cmd = ['bootctl', '--path=/boot', 'install']
            chroot.run(cmd, self.dest_dir, 300)
            # chroot.umount_special_dirs(self.dest_dir)
            logging.info("Systemd-boot install completed successfully")
            self.settings.set('bootloader_installation_successful', True)
        except subprocess.CalledProcessError as process_error:
            logging.error('Command %s failed. Error output: %s', " ".join(cmd),
                          process_error.output)
            self.settings.set('bootloader_installation_successful', False)
        except subprocess.TimeoutExpired:
            logging.error('Command %s timed out.', " ".join(cmd))
            self.settings.set('bootloader_installation_successful', False)
        except Exception as general_error:
            logging.error('Command %s failed. Unknown Error: %s',
                          " ".join(cmd), general_error)
            self.settings.set('bootloader_installation_successful', False)
Exemple #7
0
    def install_grub2_efi(self):
        """ Install Grub2 bootloader in a UEFI system """
        uefi_arch = "x86_64"
        spec_uefi_arch = "x64"
        spec_uefi_arch_caps = "X64"
        bootloader_id = 'antergos_grub' if not os.path.exists('/install/boot/efi/EFI/antergos_grub') else \
            'antergos_grub_{0}'.format(self.random_generator())

        txt = _("Installing GRUB(2) UEFI {0} boot loader").format(uefi_arch)
        logging.info(txt)

        grub_install = [
            'grub-install', '--target={0}-efi'.format(uefi_arch),
            '--efi-directory=/install/boot/efi',
            '--bootloader-id={0}'.format(bootloader_id),
            '--boot-directory=/install/boot', '--recheck'
        ]
        load_module = ['modprobe', '-a', 'efivarfs']

        try:
            subprocess.call(load_module, timeout=15)
            subprocess.check_call(grub_install, timeout=120)
        except subprocess.CalledProcessError as process_error:
            logging.error('Command grub-install failed. Error output: %s',
                          process_error.output)
        except subprocess.TimeoutExpired:
            logging.error('Command grub-install timed out.')
        except Exception as general_error:
            logging.error('Command grub-install failed. Unknown Error: %s',
                          general_error)

        self.install_grub2_locales()

        # Copy grub into dirs known to be used as default by some OEMs if they do not exist yet.
        grub_defaults = [
            os.path.join(self.dest_dir, "boot/efi/EFI/BOOT",
                         "BOOT{0}.efi".format(spec_uefi_arch_caps)),
            os.path.join(self.dest_dir, "boot/efi/EFI/Microsoft/Boot",
                         'bootmgfw.efi')
        ]

        grub_path = os.path.join(self.dest_dir, "boot/efi/EFI/antergos_grub",
                                 "grub{0}.efi".format(spec_uefi_arch))

        for grub_default in grub_defaults:
            path = grub_default.split()[0]
            if not os.path.exists(path):
                msg = _("No OEM loader found in %s. Copying Grub(2) into dir.")
                logging.info(msg, path)
                os.makedirs(path, mode=0o755)
                msg_failed = _("Copying Grub(2) into OEM dir failed: %s")
                try:
                    shutil.copy(grub_path, grub_default)
                except FileNotFoundError:
                    logging.warning(msg_failed, _("File not found."))
                except FileExistsError:
                    logging.warning(msg_failed, _("File already exists."))
                except Exception as general_error:
                    logging.warning(msg_failed, general_error)

        # Run grub-mkconfig last
        logging.debug("Generating grub.cfg")

        # /dev and others need to be mounted (binded).
        # We call mount_special_dirs here just to be sure
        chroot.mount_special_dirs(self.dest_dir)

        # Add -l option to os-prober's umount call so that it does not hang
        self.apply_osprober_patch()

        logging.debug("Running grub-mkconfig...")
        locale = self.settings.get("locale")
        try:
            cmd = [
                'sh', '-c',
                'LANG={0} grub-mkconfig -o /boot/grub/grub.cfg'.format(locale)
            ]
            chroot.run(cmd, self.dest_dir, 300)
        except subprocess.TimeoutExpired:
            txt = _(
                "grub-mkconfig appears to be hung. Killing grub-mount and os-prober so we can continue."
            )
            logging.error(txt)
            subprocess.check_call(['killall', 'grub-mount'])
            subprocess.check_call(['killall', 'os-prober'])

        paths = [
            os.path.join(self.dest_dir, "boot/grub/x86_64-efi/core.efi"),
            os.path.join(self.dest_dir,
                         "boot/efi/EFI/{0}".format(bootloader_id),
                         "grub{0}.efi".format(spec_uefi_arch))
        ]

        exists = True

        for path in paths:
            if not os.path.exists(path):
                exists = False
                logging.debug("Path '%s' doesn't exist, when it should", path)

        if exists:
            logging.info("GRUB(2) UEFI install completed successfully")
            self.settings.set('bootloader_installation_successful', True)
        else:
            logging.warning(
                "GRUB(2) UEFI install may not have completed successfully.")
            self.settings.set('bootloader_installation_successful', False)
Exemple #8
0
    def install_grub2_bios(self):
        """ Install Grub2 bootloader in a BIOS system """
        grub_location = self.settings.get('bootloader_device')
        txt = _("Installing GRUB(2) BIOS boot loader in {0}").format(
            grub_location)
        logging.info(txt)

        # /dev and others need to be mounted (binded).
        # We call mount_special_dirs here just to be sure
        chroot.mount_special_dirs(self.dest_dir)

        grub_install = [
            'grub-install', '--directory=/usr/lib/grub/i386-pc',
            '--target=i386-pc', '--boot-directory=/boot', '--recheck'
        ]

        if len(grub_location) > len(
                "/dev/sdX"):  # Use --force when installing in /dev/sdXY
            grub_install.append("--force")

        grub_install.append(grub_location)

        try:
            chroot.run(grub_install, self.dest_dir)
        except subprocess.CalledProcessError as process_error:
            logging.error('Command grub-install failed. Error output: %s',
                          process_error.output)
        except subprocess.TimeoutExpired:
            logging.error('Command grub-install timed out.')
        except Exception as general_error:
            logging.error('Command grub-install failed. Unknown Error: %s',
                          general_error)

        self.install_grub2_locales()

        # Add -l option to os-prober's umount call so that it does not hang
        self.apply_osprober_patch()

        # Run grub-mkconfig last
        logging.debug("Running grub-mkconfig...")
        locale = self.settings.get("locale")
        try:
            cmd = [
                'sh', '-c',
                'LANG={0} grub-mkconfig -o /boot/grub/grub.cfg'.format(locale)
            ]
            chroot.run(cmd, self.dest_dir, 300)
        except subprocess.TimeoutExpired:
            msg = _(
                "grub-mkconfig does not respond. Killing grub-mount and os-prober so we can continue."
            )
            logging.error(msg)
            subprocess.check_call(['killall', 'grub-mount'])
            subprocess.check_call(['killall', 'os-prober'])

        cfg = os.path.join(self.dest_dir, "boot/grub/grub.cfg")
        with open(cfg) as grub_cfg:
            if "Antergos" in grub_cfg.read():
                txt = _("GRUB(2) BIOS has been successfully installed.")
                logging.info(txt)
                self.settings.set('bootloader_installation_successful', True)
            else:
                txt = _("ERROR installing GRUB(2) BIOS.")
                logging.warning(txt)
                self.settings.set('bootloader_installation_successful', False)
Exemple #9
0
    def install_grub2_efi(self):
        """ Install Grub2 bootloader in a UEFI system """
        uefi_arch = "x86_64"
        spec_uefi_arch = "x64"
        spec_uefi_arch_caps = "X64"
        efi_path = self.settings.get('bootloader_device')
        logging.debug(_('The efi directory is: {0}'.format(efi_path)))

        if not os.path.exists('/install{0}/EFI/manjaro_grub'.format(efi_path)):
            bootloader_id = 'manjaro_grub'
        else:
            bootloader_id = 'manjaro_grub_{0}'.format(self.random_generator())

        logging.info(
            _("Installing GRUB(2) UEFI {0} boot loader in {1}".format(
                uefi_arch, efi_path)))

        grub_install = [
            'grub-install', '--target={0}-efi'.format(uefi_arch),
            '--efi-directory={0}'.format(efi_path),
            '--bootloader-id={0}'.format(bootloader_id),
            '--boot-directory=/boot', '--recheck'
        ]
        logging.debug(
            _("grub-install command: {0}".format(" ".join(grub_install))))

        try:
            chroot.run(grub_install, self.dest_dir, 300)
        except subprocess.CalledProcessError as process_error:
            logging.error(
                _('Command grub-install failed. Error output: {0}'.format(
                    process_error.output)))
        except subprocess.TimeoutExpired:
            logging.error(_('Command grub-install timed out.'))
        except Exception as general_error:
            logging.error(
                _('Command grub-install failed. Unknown Error: {0}'.format(
                    general_error)))

        self.install_grub2_locales()

        # self.copy_grub2_theme_files()

        # Copy grub into dirs known to be used as default by some OEMs if
        # they do not exist yet.
        grub_defaults = [
            os.path.join(self.dest_dir, "{0}/EFI/BOOT".format(efi_path[1:]),
                         "BOOT{0}.efi".format(spec_uefi_arch_caps)),
            os.path.join(self.dest_dir,
                         "{0}/EFI/Microsoft/Boot".format(efi_path[1:]),
                         'bootmgfw.efi')
        ]

        grub_path = os.path.join(self.dest_dir,
                                 "{0}/EFI/manjaro_grub".format(efi_path[1:]),
                                 "grub{0}.efi".format(spec_uefi_arch))

        for grub_default in grub_defaults:
            path = grub_default.split()[0]
            if not os.path.exists(path):
                logging.info(
                    _("No OEM loader found in {0}. Copying Grub(2) "
                      "into dir.").format(path))
                os.makedirs(path)
                msg = _("Copying Grub(2) into OEM dir failed: {0}")
                try:
                    shutil.copy(grub_path, grub_default)
                except FileNotFoundError:
                    logging.warning(msg.format(_("File not found.")))
                except FileExistsError:
                    logging.warning(msg.format(_("File already exists.")))
                except Exception as general_error:
                    logging.warning(msg.format(general_error))

        # Run grub-mkconfig last
        logging.info(_("Generating grub.cfg"))

        # Add -l option to os-prober's umount call so that it does not hang
        self.apply_osprober_patch()

        locale = self.settings.get("locale")
        try:
            cmd = [
                'sh', '-c',
                'LANG={0} grub-mkconfig -o /boot/grub/grub.cfg'.format(locale)
            ]
            chroot.run(cmd, self.dest_dir, 300)
        except subprocess.TimeoutExpired:
            txt = _("grub-mkconfig appears to be hung. Killing grub-mount and "
                    "os-prober so we can continue.")
            logging.error(txt)
            subprocess.check_call(['killall', 'grub-mount'])
            subprocess.check_call(['killall', 'os-prober'])

        paths = [
            os.path.join(self.dest_dir, "boot/grub/x86_64-efi/core.efi"),
            os.path.join(self.dest_dir,
                         "{0}/EFI/{1}".format(efi_path[1:], bootloader_id),
                         "grub{0}.efi".format(spec_uefi_arch))
        ]

        exists = True
        for path in paths:
            if not os.path.exists(path):
                logging.debug(
                    "Path '{0}' doesn't exists, when it should".format(path))
                exists = False

        if exists:
            txt = _("GRUB(2) UEFI install completed successfully")
            logging.info(txt)
            self.settings.set('bootloader_installation_successful', True)
        else:
            txt = _(
                "GRUB(2) UEFI install may not have completed successfully.")
            logging.warning(txt)
            self.settings.set('bootloader_installation_successful', False)
Exemple #10
0
def run(dest_dir, settings, mount_devices, blvm):
    """ Runs mkinitcpio """

    cpu = get_cpu()

    # Add lvm and encrypt hooks if necessary
    hooks = [
        "base", "udev", "autodetect", "modconf", "block", "keyboard", "keymap"
    ]
    modules = []

    # It is important that the plymouth hook comes before any encrypt hook

    plymouth_bin = os.path.join(dest_dir, "usr/bin/plymouth")
    if os.path.exists(plymouth_bin):
        hooks.append("plymouth")

    # It is important that the encrypt hook comes before the filesystems hook
    # (in case you are using LVM on LUKS, the order should be: encrypt lvm2 filesystems)

    if settings.get("use_luks"):
        if os.path.exists(plymouth_bin):
            hooks.append("plymouth-encrypt")
        else:
            hooks.append("encrypt")

        modules.extend(["dm_mod", "dm_crypt", "ext4"])

        arch = os.uname()[-1]
        if arch == 'x86_64':
            modules.extend(["aes_x86_64"])
        else:
            modules.extend(["aes_i586"])

        modules.extend(["sha256", "sha512"])

    if settings.get("f2fs"):
        modules.append("f2fs")

    if blvm or settings.get("use_lvm"):
        hooks.append("lvm2")

    if "swap" in mount_devices:
        hooks.append("resume")

    hooks.append("filesystems")

    if settings.get('btrfs') and cpu is not 'genuineintel':
        modules.append('crc32c')
    elif settings.get('btrfs') and cpu is 'genuineintel':
        modules.append('crc32c-intel')
    else:
        hooks.append("fsck")

    set_hooks_and_modules(dest_dir, hooks, modules)

    # Run mkinitcpio on the target system
    # Fix for bsdcpio error. See: http://forum.antergos.com/viewtopic.php?f=5&t=1378&start=20#p5450
    locale = settings.get('locale')
    # chroot.mount_special_dirs(dest_dir)
    cmd = ['sh', '-c', 'LANG={0} /usr/bin/mkinitcpio -p linux'.format(locale)]
    chroot.run(cmd, dest_dir)
    if settings.get('feature_lts'):
        cmd = [
            'sh', '-c',
            'LANG={0} /usr/bin/mkinitcpio -p linux-lts'.format(locale)
        ]
        chroot.run(cmd, dest_dir)
Exemple #11
0
    def install_systemd_boot(self):
        """
        Install Systemd-Boot bootloader to the EFI System Partition
        and configure entry files
        """
        logging.info("Installing the systemd-boot loader")
        # Setup bootloader menu
        menu_dir = os.path.join(self.dest_dir, "boot/loader")
        os.makedirs(menu_dir, exist_ok=True)
        menu_path = os.path.join(menu_dir, "loader.conf")
        with open(menu_path, 'w') as menu_file:
            menu_file.write("default manjaro-default")

        # Setup boot entries
        if not self.settings.get('use_luks'):
            conf = {
                'default': [
                    'title\tManjaro\n',
                    'linux\t/{0}\n'.format(self.vmlinuz),
                    'initrd\t/{0}\n'.format(self.initramfs),
                    'options\troot=UUID={0} rw quiet\n\n'.format(self.root_uuid)
                ],
                'fallback': [
                    "title\tManjaro (fallback)\n",
                    "linux\t/{0}\n".format(self.vmlinuz),
                    "initrd\t/{0}\n".format(self.fallback),
                    "options\troot=UUID={0} rw quiet\n\n".format(self.root_uuid)
                ]
            }

        else:
            luks_root_volume = self.settings.get('luks_root_volume')
            luks_root_volume_uuid = fs.get_info(luks_root_volume)['UUID']

            # In automatic mode, root_device is in self.mount_devices
            root_device = self.root_device

            if (self.method == "advanced" and
                    self.settings.get('use_luks_in_root')):
                root_device = self.settings.get('luks_root_device')

            root_uuid = fs.get_info(root_device)['UUID']

            key = ""
            if self.settings.get("luks_root_password") == "":
                key = ("cryptkey=UUID={0}:ext2:/.keyfile-root"
                       .format(self.boot_uuid))

            root_uuid_line = "cryptdevice=UUID={0}:{1} {2} root=UUID={3} rw quit"\
                .format(root_uuid, luks_root_volume, key, luks_root_volume_uuid)

            conf = {
                'default': [
                    "title\tManjaro\n",
                    "linux\t/{0}\n".format(self.vmlinuz),
                    "options\tinitrd=/{0} {1}\n\n".format(self.initramfs,
                                                          root_uuid_line)
                ],
                'fallback': [
                    "title\tManjaro (fallback)\n",
                    "linux\t/{0}\n".format(self.vmlinuz),
                    "options\tinitrd=/{0} {1}\n\n".format(self.fallback,
                                                          root_uuid_line)
                ]
            }

        # Write boot entries
        entries_dir = os.path.join(self.dest_dir, "boot/loader/entries")
        os.makedirs(entries_dir, exist_ok=True)

        for fname, entry in conf.items():
            entry_path = os.path.join(entries_dir,
                                      "manjaro-{}.conf".format(fname))
            with open(entry_path, 'w') as file:
                for line in entry:
                    file.write(line)

        # Install bootloader
        try:
            cmd = ['bootctl', '--path=/boot', 'install']
            chroot.run(cmd, self.dest_dir, 300)
            logging.info(_("Systemd-Boot install completed successfully"))
            self.settings.set('bootloader_installation_successful', True)
        except subprocess.CalledProcessError as process_error:
            logging.error(_('Command {0} failed. Error output: {1}'
                            .format(cmd,process_error.output)))
            self.settings.set('bootloader_installation_successful', False)
        except subprocess.TimeoutExpired:
            logging.error(_('Command {0} timed out.'.format(cmd)))
            self.settings.set('bootloader_installation_successful', False)
        except Exception as general_error:
            logging.error(_('Command {0} failed. Unknown Error: {1}'
                            .format(cmd,general_error)))
            self.settings.set('bootloader_installation_successful', False)
Exemple #12
0
    def install_grub2_efi(self):
        """ Install Grub2 bootloader in a UEFI system """
        uefi_arch = "x86_64"
        spec_uefi_arch = "x64"
        spec_uefi_arch_caps = "X64"
        efi_path = self.settings.get('bootloader_device')
        logging.debug(_('The efi directory is: {0}'.format(efi_path)))

        if not os.path.exists('/install{0}/EFI/manjaro_grub'.format(efi_path)):
            bootloader_id = 'manjaro_grub'
        else:
            bootloader_id = 'manjaro_grub_{0}'.format(self.random_generator())

        logging.info(_("Installing GRUB(2) UEFI {0} boot loader in {1}"
                       .format(uefi_arch, efi_path)))

        grub_install = [
            'grub-install',
            '--target={0}-efi'.format(uefi_arch),
            '--efi-directory={0}'.format(efi_path),
            '--bootloader-id={0}'.format(bootloader_id),
            '--boot-directory=/boot',
            '--recheck']
        logging.debug(_("grub-install command: {0}"
                        .format(" ".join(grub_install))))

        try:
            chroot.run(grub_install, self.dest_dir, 300)
        except subprocess.CalledProcessError as process_error:
            logging.error(_('Command grub-install failed. Error output: {0}'
                            .format(process_error.output)))
        except subprocess.TimeoutExpired:
            logging.error(_('Command grub-install timed out.'))
        except Exception as general_error:
            logging.error(_('Command grub-install failed. Unknown Error: {0}'
                            .format(general_error)))

        self.install_grub2_locales()

        # self.copy_grub2_theme_files()

        # Copy grub into dirs known to be used as default by some OEMs if
        # they do not exist yet.
        grub_defaults = [
            os.path.join(self.dest_dir,
                         "{0}/EFI/BOOT".format(efi_path[1:]),
                         "BOOT{0}.efi".format(spec_uefi_arch_caps)),
            os.path.join(self.dest_dir,
                         "{0}/EFI/Microsoft/Boot".format(efi_path[1:]),
                         'bootmgfw.efi')
        ]

        grub_path = os.path.join(self.dest_dir,
                                 "{0}/EFI/manjaro_grub".format(efi_path[1:]),
                                 "grub{0}.efi".format(spec_uefi_arch))

        for grub_default in grub_defaults:
            path = grub_default.split()[0]
            if not os.path.exists(path):
                logging.info(_("No OEM loader found in {0}. Copying Grub(2) "
                               "into dir.").format(path))
                os.makedirs(path)
                msg = _("Copying Grub(2) into OEM dir failed: {0}")
                try:
                    shutil.copy(grub_path, grub_default)
                except FileNotFoundError:
                    logging.warning(msg.format(_("File not found.")))
                except FileExistsError:
                    logging.warning(msg.format(_("File already exists.")))
                except Exception as general_error:
                    logging.warning(msg.format(general_error))

        # Run grub-mkconfig last
        logging.info(_("Generating grub.cfg"))

        # Add -l option to os-prober's umount call so that it does not hang
        self.apply_osprober_patch()

        locale = self.settings.get("locale")
        try:
            cmd = [
                'sh',
                '-c',
                'LANG={0} grub-mkconfig -o /boot/grub/grub.cfg'.format(locale)
            ]
            chroot.run(cmd, self.dest_dir, 300)
        except subprocess.TimeoutExpired:
            txt = _("grub-mkconfig appears to be hung. Killing grub-mount and "
                    "os-prober so we can continue.")
            logging.error(txt)
            subprocess.check_call(['killall', 'grub-mount'])
            subprocess.check_call(['killall', 'os-prober'])

        paths = [os.path.join(self.dest_dir, "boot/grub/x86_64-efi/core.efi"),
                 os.path.join(self.dest_dir,
                              "{0}/EFI/{1}".format(efi_path[1:], bootloader_id),
                              "grub{0}.efi".format(spec_uefi_arch))]

        exists = True
        for path in paths:
            if not os.path.exists(path):
                logging.debug("Path '{0}' doesn't exists, when it should"
                              .format(path))
                exists = False

        if exists:
            txt = _("GRUB(2) UEFI install completed successfully")
            logging.info(txt)
            self.settings.set('bootloader_installation_successful', True)
        else:
            txt = _("GRUB(2) UEFI install may not have completed successfully.")
            logging.warning(txt)
            self.settings.set('bootloader_installation_successful', False)
Exemple #13
0
    def install_grub2_bios(self):
        """ Install Grub2 bootloader in a BIOS system """
        grub_location = self.settings.get('bootloader_device')
        txt = _("Installing GRUB(2) BIOS boot loader in {0}"
                .format(grub_location))
        logging.info(txt)

        grub_install = ['grub-install',
                        '--directory=/usr/lib/grub/i386-pc',
                        '--target=i386-pc',
                        '--boot-directory=/boot',
                        '--recheck']
        logging.debug("grub-install command: {0}"
                      .format(" ".join(grub_install)))

        if len(grub_location) > len("/dev/sdX"):  # ex: /dev/sdXY > 8
            grub_install.append("--force")

        grub_install.append(grub_location)

        try:
            chroot.run(grub_install, self.dest_dir, 300)
        except subprocess.CalledProcessError as process_error:
            logging.error(_('Command grub-install failed. Error output: {0}'
                            .format(process_error.output)))
        except subprocess.TimeoutExpired:
            logging.error(_('Command grub-install timed out.'))
        except Exception as general_error:
            logging.error(_('Command grub-install failed. Unknown Error: {0}'
                            .format(general_error)))

        self.install_grub2_locales()

        # self.copy_grub2_theme_files()

        # Add -l option to os-prober's umount call so that it does not hang
        self.apply_osprober_patch()

        # Run grub-mkconfig last
        locale = self.settings.get("locale")
        try:
            cmd = [
                'sh',
                '-c',
                'LANG={0} grub-mkconfig -o /boot/grub/grub.cfg'.format(locale)
            ]
            chroot.run(cmd, self.dest_dir, 300)
        except subprocess.TimeoutExpired:
            logging.error(_("grub-mkconfig does not respond. Killing grub-mount"
                            " and os-prober so we can continue."))
            subprocess.check_call(['killall', 'grub-mount'])
            subprocess.check_call(['killall', 'os-prober'])

        cfg = os.path.join(self.dest_dir, "boot/grub/grub.cfg")
        with open(cfg) as grub_cfg:
            if "Manjaro" in grub_cfg.read():
                logging.info(_("GRUB(2) BIOS has been successfully installed."))
                self.settings.set('bootloader_installation_successful', True)
            else:
                logging.warning(_("ERROR installing GRUB(2) BIOS."))
                self.settings.set('bootloader_installation_successful', False)
Exemple #14
0
def run(params, dest_dir="/install"):
    cmd = ["ufw"]
    cmd.extend(params)

    if not _UFW:
        # Could not import ufw module (missing?)
        # Will call ufw command directly
        try:
            chroot.run(cmd, dest_dir)
        except OSError as os_error:
            logging.warning(os_error)
        finally:
            return

    app_action = False

    # Remember, will have to take --force into account if we use it with 'app'
    idx = 1
    if len(cmd) > 1 and cmd[1].lower() == "--dry-run":
        idx += 1

    if len(cmd) > idx and cmd[idx].lower() == "app":
        app_action = True

    res = ""
    try:
        cmd_line = ufw.frontend.parse_command(cmd)
        ui = ufw.frontend.UFWFrontend(cmd_line.dryrun)
        if app_action and 'type' in cmd_line.data and cmd_line.data['type'] == 'app':
            res = ui.do_application_action(cmd_line.action, cmd_line.data['name'])
        else:
            bailout = False
            if cmd_line.action == "enable" and not cmd_line.force and \
               not ui.continue_under_ssh():
                res = _("Aborted")
                bailout = True

            if not bailout:
                if 'rule' in cmd_line.data:
                    res = ui.do_action(
                        cmd_line.action,
                        cmd_line.data['rule'],
                        cmd_line.data['iptype'],
                        cmd_line.force)
                else:
                    res = ui.do_action(
                        cmd_line.action,
                        "",
                        "",
                        cmd_line.force)
    except (ValueError, ufw.UFWError) as ufw_error:
        logging.error(ufw_error)
        # Error using ufw module
        # Will call ufw command directly
        try:
            chroot.run(cmd, dest_dir)
        except OSError as os_error:
            logging.warning(os_error)
        finally:
            return

    logging.debug(res)
Exemple #15
0
    def install_systemd_boot(self):
        """
        Install Systemd-Boot bootloader to the EFI System Partition
        and configure entry files
        """
        logging.info("Installing the systemd-boot loader")
        # Setup bootloader menu
        menu_dir = os.path.join(self.dest_dir, "boot/loader")
        os.makedirs(menu_dir, exist_ok=True)
        menu_path = os.path.join(menu_dir, "loader.conf")
        with open(menu_path, 'w') as menu_file:
            menu_file.write("default manjaro-default")

        # Setup boot entries
        if not self.settings.get('use_luks'):
            conf = {
                'default': [
                    'title\tManjaro\n', 'linux\t/{0}\n'.format(self.vmlinuz),
                    'initrd\t/{0}\n'.format(self.initramfs),
                    'options\troot=UUID={0} rw quiet\n\n'.format(
                        self.root_uuid)
                ],
                'fallback': [
                    "title\tManjaro (fallback)\n",
                    "linux\t/{0}\n".format(self.vmlinuz),
                    "initrd\t/{0}\n".format(self.fallback),
                    "options\troot=UUID={0} rw quiet\n\n".format(
                        self.root_uuid)
                ]
            }

        else:
            luks_root_volume = self.settings.get('luks_root_volume')
            luks_root_volume_uuid = fs.get_info(luks_root_volume)['UUID']

            # In automatic mode, root_device is in self.mount_devices
            root_device = self.root_device

            if (self.method == "advanced"
                    and self.settings.get('use_luks_in_root')):
                root_device = self.settings.get('luks_root_device')

            root_uuid = fs.get_info(root_device)['UUID']

            key = ""
            if self.settings.get("luks_root_password") == "":
                key = ("cryptkey=UUID={0}:ext2:/.keyfile-root".format(
                    self.boot_uuid))

            root_uuid_line = "cryptdevice=UUID={0}:{1} {2} root=UUID={3} rw quit"\
                .format(root_uuid, luks_root_volume, key, luks_root_volume_uuid)

            conf = {
                'default': [
                    "title\tManjaro\n", "linux\t/{0}\n".format(self.vmlinuz),
                    "options\tinitrd=/{0} {1}\n\n".format(
                        self.initramfs, root_uuid_line)
                ],
                'fallback': [
                    "title\tManjaro (fallback)\n",
                    "linux\t/{0}\n".format(self.vmlinuz),
                    "options\tinitrd=/{0} {1}\n\n".format(
                        self.fallback, root_uuid_line)
                ]
            }

        # Write boot entries
        entries_dir = os.path.join(self.dest_dir, "boot/loader/entries")
        os.makedirs(entries_dir, exist_ok=True)

        for fname, entry in conf.items():
            entry_path = os.path.join(entries_dir,
                                      "manjaro-{}.conf".format(fname))
            with open(entry_path, 'w') as file:
                for line in entry:
                    file.write(line)

        # Install bootloader
        try:
            cmd = ['bootctl', '--path=/boot', 'install']
            chroot.run(cmd, self.dest_dir, 300)
            logging.info(_("Systemd-Boot install completed successfully"))
            self.settings.set('bootloader_installation_successful', True)
        except subprocess.CalledProcessError as process_error:
            logging.error(
                _('Command {0} failed. Error output: {1}'.format(
                    cmd, process_error.output)))
            self.settings.set('bootloader_installation_successful', False)
        except subprocess.TimeoutExpired:
            logging.error(_('Command {0} timed out.'.format(cmd)))
            self.settings.set('bootloader_installation_successful', False)
        except Exception as general_error:
            logging.error(
                _('Command {0} failed. Unknown Error: {1}'.format(
                    cmd, general_error)))
            self.settings.set('bootloader_installation_successful', False)
Exemple #16
0
    def install_gummiboot(self):
        """ Install Gummiboot bootloader to the EFI System Partition """
        # Setup bootloader menu
        menu_dir = os.path.join(self.dest_dir, "boot/loader")
        os.makedirs(menu_dir)
        menu_path = os.path.join(menu_dir, "loader.conf")
        with open(menu_path, 'w') as menu_file:
            menu_file.write("default apricity")

        # Setup boot entries
        conf = {}

        if not self.settings.get('use_luks'):
            conf['default'] = []
            conf['default'].append("title\tApricity\n")
            conf['default'].append("linux\t/vmlinuz-linux\n")
            conf['default'].append("initrd\t/initramfs-linux.img\n")
            conf['default'].append("options\troot=UUID={0} rw quiet\n\n".format(self.root_uuid))

            conf['fallback'] = []
            conf['fallback'].append("title\tApricity (fallback)\n")
            conf['fallback'].append("linux\t/vmlinuz-linux\n")
            conf['fallback'].append("initrd\t/initramfs-linux-fallback.img\n")
            conf['fallback'].append("options\troot=UUID={0} rw quiet\n\n".format(self.root_uuid))

            if self.settings.get('feature_lts'):
                conf['lts'] = []
                conf['lts'].append("title\tApricity LTS\n")
                conf['lts'].append("linux\t/vmlinuz-linux-lts\n")
                conf['lts'].append("initrd\t/initramfs-linux-lts.img\n")
                conf['lts'].append("options\troot=UUID={0} rw quiet\n\n".format(self.root_uuid))

                conf['lts_fallback'] = []
                conf['lts_fallback'].append("title\tApricity LTS (fallback)\n\n")
                conf['lts_fallback'].append("linux\t/vmlinuz-linux-lts\n")
                conf['lts_fallback'].append("initrd\t/initramfs-linux-lts-fallback.img\n")
                conf['lts_fallback'].append("options\troot=UUID={0} rw quiet\n\n".format(self.root_uuid))
        else:
            luks_root_volume = self.settings.get('luks_root_volume')
            luks_root_volume_device = "/dev/mapper/{0}".format(luks_root_volume)
            luks_root_volume_uuid = fs.get_info(luks_root_volume_device)['UUID']

            # In automatic mode, root_device is in self.mount_devices, as it should be
            root_device = self.root_device

            if self.method == "advanced" and self.settings.get('use_luks_in_root'):
                root_device = self.settings.get('luks_root_device')

            root_uuid = fs.get_info(root_device)['UUID']

            key = ""
            if self.settings.get("luks_root_password") == "":
                key = "cryptkey=UUID={0}:ext2:/.keyfile-root".format(self.boot_uuid)

            root_uuid_line = "cryptdevice=UUID={0}:{1} {2} root=UUID={3} rw quiet"
            root_uuid_line = root_uuid_line.format(root_uuid, luks_root_volume, key, luks_root_volume_uuid)

            conf['default'] = []
            conf['default'].append("title\tApricity\n")
            conf['default'].append("linux\t/vmlinuz-linux\n")
            conf['default'].append("options\tinitrd=/initramfs-linux.img {0}\n\n".format(root_uuid_line))

            conf['fallback'] = []
            conf['fallback'].append("title\tApricity (fallback)\n")
            conf['fallback'].append("linux\t/vmlinuz-linux\n")
            conf['fallback'].append("options\tinitrd=/initramfs-linux-fallback.img {0}\n\n".format(root_uuid_line))

            if self.settings.get('feature_lts'):
                conf['lts'] = []
                conf['lts'].append("title\tApricity LTS\n")
                conf['lts'].append("linux\t/vmlinuz-linux-lts\n")
                conf['lts'].append("options\tinitrd=/initramfs-linux-lts.img {0}\n\n".format(root_uuid_line))

                conf['lts_fallback'] = []
                conf['lts_fallback'].append("title\tApricity LTS (fallback)\n")
                conf['lts_fallback'].append("linux\t/vmlinuz-linux-lts\n")
                conf['lts_fallback'].append("options\tinitrd=/initramfs-linux-lts-fallback.img {0}\n\n".format(root_uuid_line))

        # Write boot entries
        entries_dir = os.path.join(self.dest_dir, "boot/loader/entries")
        os.makedirs(entries_dir)

        entry_path = os.path.join(entries_dir, "apricity.conf")
        with open(entry_path, 'w') as entry_file:
            for line in conf['default']:
                entry_file.write(line)

        entry_path = os.path.join(entries_dir, "apricity-fallback.conf")
        with open(entry_path, 'w') as entry_file:
            for line in conf['fallback']:
                entry_file.write(line)

        if self.settings.get('feature_lts'):
            entry_path = os.path.join(entries_dir, "apricity-lts.conf")
            with open(entry_path, 'w') as entry_file:
                for line in conf['lts']:
                    entry_file.write(line)

            entry_path = os.path.join(entries_dir, "apricity-lts-fallback.conf")
            with open(entry_path, 'w') as entry_file:
                for line in conf['lts_fallback']:
                    entry_file.write(line)

        # Install bootloader
        logging.debug(_("Installing gummiboot bootloader..."))
        try:
            chroot.mount_special_dirs(self.dest_dir)
            cmd = ['gummiboot', '--path=/boot', 'install']
            chroot.run(cmd, self.dest_dir, 300)
            chroot.umount_special_dirs(self.dest_dir)
            logging.info(_("Gummiboot install completed successfully"))
            self.settings.set('bootloader_installation_successful', True)
        except subprocess.CalledProcessError as process_error:
            logging.error(_('Command gummiboot failed. Error output: %s'), process_error.output)
            self.settings.set('bootloader_installation_successful', False)
        except subprocess.TimeoutExpired:
            logging.error(_('Command gummiboot timed out.'))
            self.settings.set('bootloader_installation_successful', False)
        except Exception as general_error:
            logging.error(_('Command gummiboot failed. Unknown Error: %s'), general_error)
            self.settings.set('bootloader_installation_successful', False)
Exemple #17
0
def chroot_run(cmd):
    chroot.run(cmd, DEST_DIR)
Exemple #18
0
    def install_grub2_bios(self):
        """ Install Grub2 bootloader in a BIOS system """
        grub_location = self.settings.get('bootloader_device')
        txt = _(
            "Installing GRUB(2) BIOS boot loader in {0}".format(grub_location))
        logging.info(txt)

        grub_install = [
            'grub-install', '--directory=/usr/lib/grub/i386-pc',
            '--target=i386-pc', '--boot-directory=/boot', '--recheck'
        ]
        logging.debug("grub-install command: {0}".format(
            " ".join(grub_install)))

        if len(grub_location) > len("/dev/sdX"):  # ex: /dev/sdXY > 8
            grub_install.append("--force")

        grub_install.append(grub_location)

        try:
            chroot.run(grub_install, self.dest_dir, 300)
        except subprocess.CalledProcessError as process_error:
            logging.error(
                _('Command grub-install failed. Error output: {0}'.format(
                    process_error.output)))
        except subprocess.TimeoutExpired:
            logging.error(_('Command grub-install timed out.'))
        except Exception as general_error:
            logging.error(
                _('Command grub-install failed. Unknown Error: {0}'.format(
                    general_error)))

        self.install_grub2_locales()

        # self.copy_grub2_theme_files()

        # Add -l option to os-prober's umount call so that it does not hang
        self.apply_osprober_patch()

        # Run grub-mkconfig last
        locale = self.settings.get("locale")
        try:
            cmd = [
                'sh', '-c',
                'LANG={0} grub-mkconfig -o /boot/grub/grub.cfg'.format(locale)
            ]
            chroot.run(cmd, self.dest_dir, 300)
        except subprocess.TimeoutExpired:
            logging.error(
                _("grub-mkconfig does not respond. Killing grub-mount"
                  " and os-prober so we can continue."))
            subprocess.check_call(['killall', 'grub-mount'])
            subprocess.check_call(['killall', 'os-prober'])

        cfg = os.path.join(self.dest_dir, "boot/grub/grub.cfg")
        with open(cfg) as grub_cfg:
            if "Manjaro" in grub_cfg.read():
                logging.info(
                    _("GRUB(2) BIOS has been successfully installed."))
                self.settings.set('bootloader_installation_successful', True)
            else:
                logging.warning(_("ERROR installing GRUB(2) BIOS."))
                self.settings.set('bootloader_installation_successful', False)