Пример #1
0
    def mount_root(self):
        """Mounts selected root and runs scripts."""
        # mount root fs
        try:
            mount_existing_system(self._storage.fsset,
                                  self.root.device,
                                  read_only=self.ro)
            log.info("System has been mounted under: %s", iutil.getSysroot())
        except StorageError as e:
            log.error("Mounting system under %s failed: %s",
                      iutil.getSysroot(), e)
            self.status = RescueModeStatus.MOUNT_FAILED
            return False

        # turn on swap
        if not flags.imageInstall or not self.ro:
            try:
                self._storage.turn_on_swap()
            except StorageError:
                log.error("Error enabling swap.")

        # turn on selinux also
        if flags.selinux:
            # we have to catch the possible exception, because we
            # support read-only mounting
            try:
                fd = open("%s/.autorelabel" % iutil.getSysroot(), "w+")
                fd.close()
            except IOError as e:
                log.warning("Error turning on selinux: %s", e)

        # set a libpath to use mounted fs
        libdirs = os.environ.get("LD_LIBRARY_PATH", "").split(":")
        mounted = ["/mnt/sysimage%s" % ldir for ldir in libdirs]
        iutil.setenv("LD_LIBRARY_PATH", ":".join(libdirs + mounted))

        # do we have bash?
        try:
            if os.access("/usr/bin/bash", os.R_OK):
                os.symlink("/usr/bin/bash", "/bin/bash")
        except OSError as e:
            log.error("Error symlinking bash: %s", e)

        # make resolv.conf in chroot
        if not self.ro:
            self._storage.make_mtab()
            try:
                makeResolvConf(iutil.getSysroot())
            except (OSError, IOError) as e:
                log.error("Error making resolv.conf: %s", e)

        # create /etc/fstab in ramdisk so it's easier to work with RO mounted fs
        makeFStab()

        # run %post if we've mounted everything
        if not self.ro and self._scripts:
            runPostScripts(self._scripts)

        self.status = RescueModeStatus.MOUNTED
        return True
Пример #2
0
    def mount_root(self):
        """Mounts selected root and runs scripts."""
        # mount root fs
        try:
            mount_existing_system(self._storage.fsset, self.root.device, read_only=self.ro)
            log.info("System has been mounted under: %s", iutil.getSysroot())
        except StorageError as e:
            log.error("Mounting system under %s failed: %s", iutil.getSysroot(), e)
            self.status = RescueModeStatus.MOUNT_FAILED
            return False

        # turn on swap
        if not flags.imageInstall or not self.ro:
            try:
                self._storage.turn_on_swap()
            except StorageError:
                log.error("Error enabling swap.")

        # turn on selinux also
        if flags.selinux:
            # we have to catch the possible exception, because we
            # support read-only mounting
            try:
                fd = open("%s/.autorelabel" % iutil.getSysroot(), "w+")
                fd.close()
            except IOError as e:
                log.warning("Error turning on selinux: %s", e)

        # set a libpath to use mounted fs
        libdirs = os.environ.get("LD_LIBRARY_PATH", "").split(":")
        mounted = ["/mnt/sysimage%s" % ldir for ldir in libdirs]
        iutil.setenv("LD_LIBRARY_PATH", ":".join(libdirs + mounted))

        # do we have bash?
        try:
            if os.access("/usr/bin/bash", os.R_OK):
                os.symlink("/usr/bin/bash", "/bin/bash")
        except OSError as e:
            log.error("Error symlinking bash: %s", e)

        # make resolv.conf in chroot
        if not self.ro:
            self._storage.make_mtab()
            try:
                makeResolvConf(iutil.getSysroot())
            except(OSError, IOError) as e:
                log.error("Error making resolv.conf: %s", e)

        # create /etc/fstab in ramdisk so it's easier to work with RO mounted fs
        makeFStab()

        # run %post if we've mounted everything
        if not self.ro and self._scripts:
            runPostScripts(self._scripts)

        self.status = RescueModeStatus.MOUNTED
        return True
Пример #3
0
    def _widgetScale(self):
        # First, check if the GDK_SCALE environment variable is already set. If so,
        # leave it alone.
        if "GDK_SCALE" in os.environ:
            log.debug("GDK_SCALE already set to %s, not scaling",
                      os.environ["GDK_SCALE"])
            return

        # Next, check if a scaling factor is already being applied via XSETTINGS,
        # such as by gnome-settings-daemon
        display = Gdk.Display.get_default()
        screen = display.get_default_screen()
        val = GObject.Value()
        val.init(GObject.TYPE_INT)
        if screen.get_setting("gdk-window-scaling-factor", val):
            log.debug("Window scale set to %s by XSETTINGS, not scaling",
                      val.get_int())
            return

        # Get the primary monitor dimensions in pixels and mm from Gdk
        primary = screen.get_primary_monitor()
        monitor_geometry = screen.get_monitor_geometry(primary)
        monitor_scale = screen.get_monitor_scale_factor(primary)
        monitor_width_mm = screen.get_monitor_width_mm(primary)
        monitor_height_mm = screen.get_monitor_height_mm(primary)

        # Sometimes gdk returns 0 for physical widths and heights
        if monitor_height_mm == 0 or monitor_width_mm == 0:
            return

        # Check if this monitor is high DPI, using heuristics from gnome-settings-dpi.
        # If the monitor has a height >= 1200 pixels and a resolution > 192 dpi in both
        # x and y directions, apply a scaling factor of 2 so that anaconda isn't all tiny
        monitor_width_px = monitor_geometry.width * monitor_scale
        monitor_height_px = monitor_geometry.height * monitor_scale
        monitor_dpi_x = monitor_width_px / (monitor_width_mm / 25.4)
        monitor_dpi_y = monitor_height_px / (monitor_height_mm / 25.4)

        log.debug("Detected primary monitor: %dx%d %ddpix %ddpiy",
                  monitor_width_px, monitor_height_px, monitor_dpi_x,
                  monitor_dpi_y)
        if monitor_height_px >= 1200 and monitor_dpi_x > 192 and monitor_dpi_y > 192:
            display.set_window_scale(2)
            # Export the scale so that Gtk programs launched by anaconda are also scaled
            iutil.setenv("GDK_SCALE", "2")
Пример #4
0
    def _widgetScale(self):
        # First, check if the GDK_SCALE environment variable is already set. If so,
        # leave it alone.
        if "GDK_SCALE" in os.environ:
            log.debug("GDK_SCALE already set to %s, not scaling", os.environ["GDK_SCALE"])
            return

        # Next, check if a scaling factor is already being applied via XSETTINGS,
        # such as by gnome-settings-daemon
        display = Gdk.Display.get_default()
        screen = display.get_default_screen()
        val = GObject.Value()
        val.init(GObject.TYPE_INT)
        if screen.get_setting("gdk-window-scaling-factor", val):
            log.debug("Window scale set to %s by XSETTINGS, not scaling", val.get_int())
            return

        # Get the primary monitor dimensions in pixels and mm from Gdk
        primary = screen.get_primary_monitor()
        monitor_geometry = screen.get_monitor_geometry(primary)
        monitor_scale = screen.get_monitor_scale_factor(primary)
        monitor_width_mm = screen.get_monitor_width_mm(primary)
        monitor_height_mm = screen.get_monitor_height_mm(primary)

        # Sometimes gdk returns 0 for physical widths and heights
        if monitor_height_mm == 0 or monitor_width_mm == 0:
            return

        # Check if this monitor is high DPI, using heuristics from gnome-settings-dpi.
        # If the monitor has a height >= 1200 pixels and a resolution > 192 dpi in both
        # x and y directions, apply a scaling factor of 2 so that anaconda isn't all tiny
        monitor_width_px = monitor_geometry.width * monitor_scale
        monitor_height_px = monitor_geometry.height * monitor_scale
        monitor_dpi_x = monitor_width_px / (monitor_width_mm / 25.4)
        monitor_dpi_y = monitor_height_px / (monitor_height_mm / 25.4)

        log.debug("Detected primary monitor: %dx%d %ddpix %ddpiy", monitor_width_px,
                monitor_height_px, monitor_dpi_x, monitor_dpi_y)
        if monitor_height_px >= 1200 and monitor_dpi_x > 192 and monitor_dpi_y > 192:
            display.set_window_scale(2)
            # Export the scale so that Gtk programs launched by anaconda are also scaled
            iutil.setenv("GDK_SCALE", "2")
Пример #5
0
def setup_locale(locale, lang=None):
    """
    Procedure setting the system to use the given locale and store it in to the
    ksdata.lang object (if given). DOES NOT PERFORM ANY CHECKS OF THE GIVEN
    LOCALE.

    $LANG must be set by the caller in order to set the language used by gettext.
    Doing this in a thread-safe way is up to the caller.

    :param locale: locale to setup
    :type locale: str
    :param lang: ksdata.lang object or None
    :return: None
    :rtype: None

    """

    if lang:
        lang.lang = locale

    setenv("LANG", locale)
    locale_mod.setlocale(locale_mod.LC_ALL, locale)
Пример #6
0
def setup_locale(locale, lang=None):
    """
    Procedure setting the system to use the given locale and store it in to the
    ksdata.lang object (if given). DOES NOT PERFORM ANY CHECKS OF THE GIVEN
    LOCALE.

    $LANG must be set by the caller in order to set the language used by gettext.
    Doing this in a thread-safe way is up to the caller.

    :param locale: locale to setup
    :type locale: str
    :param lang: ksdata.lang object or None
    :return: None
    :rtype: None

    """

    if lang:
        lang.lang = locale

    setenv("LANG", locale)
    locale_mod.setlocale(locale_mod.LC_ALL, locale)
Пример #7
0
def setup_locale(locale, lang=None, text_mode=False):
    """
    Procedure setting the system to use the given locale and store it in to the
    ksdata.lang object (if given). DOES NOT PERFORM ANY CHECKS OF THE GIVEN
    LOCALE.

    $LANG must be set by the caller in order to set the language used by gettext.
    Doing this in a thread-safe way is up to the caller.

    We also try to set a proper console font for the locale in text mode.
    If the font for the locale can't be displayed in the Linux console,
    we fall back to the English locale.

    This function returns the locale that was used in the setlocale call, which,
    depending on what the environment and interface is able to support, may be
    different from the locale requested.

    :param str locale: locale to setup
    :param lang: ksdata.lang object or None
    :param bool text_mode: if the locale is being setup for text mode
    :return: the locale that was actually set
    :rtype: str

    """

    if lang:
        lang.lang = locale

    # not all locales might be displayable in text mode
    if text_mode:
        # check if the script corresponding to the locale/language
        # can be displayed by the Linux console
        # * all scripts for the given locale/language need to be
        #   supported by the linux console
        # * otherwise users might get a screen full of white rectangles
        #   (also known as "tofu") in text mode
        # then we also need to check if we have information about what
        # font to use for correctly displaying the given language/locale

        script_supported = locale_supported_in_console(locale)
        log.debug("scripts found for locale %s: %s", locale,
                  get_locale_scripts(locale))

        console_fonts = get_locale_console_fonts(locale)
        log.debug("console fonts found for locale %s: %s", locale,
                  console_fonts)

        font_set = False
        if script_supported and console_fonts:
            # try to set console font
            for font in console_fonts:
                if set_console_font(font):
                    # console font set successfully, skip the rest
                    font_set = True
                    break

        if not font_set:
            log.warning("can't set console font for locale %s", locale)
            # report what exactly went wrong
            if not (script_supported):
                log.warning("script not supported by console for locale %s",
                            locale)
            if not (console_fonts):  # no fonts known for locale
                log.warning("no console font found for locale %s", locale)
            if script_supported and console_fonts:
                log.warning(
                    "none of the suggested fonts can be set for locale %s",
                    locale)
            log.warning("falling back to the English locale")
            locale = constants.DEFAULT_LANG
            os.environ["LANG"] = locale  # pylint: disable=environment-modify

    # set the locale to the value we have selected
    # Since glibc does not install all locales, an installable locale may not
    # actually be available right now. Give it a shot and fallback.
    log.debug("setting locale to: %s", locale)
    setenv("LANG", locale)

    try:
        locale_mod.setlocale(locale_mod.LC_ALL, locale)
    except locale_mod.Error as e:
        log.debug("setlocale failed: %s", e)
        locale = constants.DEFAULT_LANG
        setenv("LANG", locale)
        locale_mod.setlocale(locale_mod.LC_ALL, locale)

    # This part is pretty gross:
    # In python3, sys.stdout and friends are TextIOWrapper objects that translate
    # betwen str types (in python) and byte types (used to actually read from or
    # write to the console). These wrappers are configured at startup using the
    # locale at startup, which means that if anaconda starts with LANG=C or LANG
    # unset, sys.stdout.encoding will be "ascii". And if the language is then changed,
    # because anaconda read the kickstart or parsed the command line or whatever,
    # say, to Czech, text mode will crash because it's going to try to print non-ASCII
    # characters and sys.stdout doesn't know what to do with them. So, when changing
    # the locale, create new objects for the standard streams so they are created with
    # the new locale's encoding.

    # Replacing stdout is about as stable as it looks, and it seems to break when done
    # after the GUI is started. Only make the switch if the encoding actually changed.
    if locale_mod.getpreferredencoding() != sys.stdout.encoding:
        sys.stdin = io.TextIOWrapper(sys.stdin.detach())
        sys.stdout = io.TextIOWrapper(sys.stdout.detach())
        sys.stderr = io.TextIOWrapper(sys.stderr.detach())

    return locale
Пример #8
0
    # scripts.  Add those to the ksdata now.
    kickstart.appendPostScripts(ksdata)

    # cmdline flags override kickstart settings
    if anaconda.proxy:
        ksdata.method.proxy = anaconda.proxy

        # Setup proxy environmental variables so that pre/post scripts use it
        # as well as libreport
        try:
            proxy = ProxyString(anaconda.proxy)
        except ProxyStringError as e:
            log.info("Failed to parse proxy \"%s\": %s", anaconda.proxy, e)
        else:
            # Set environmental variables to be used by pre/post scripts
            iutil.setenv("PROXY", proxy.noauth_url)
            iutil.setenv("PROXY_USER", proxy.username or "")
            iutil.setenv("PROXY_PASSWORD", proxy.password or "")

            # Variables used by curl, libreport, etc.
            iutil.setenv("http_proxy", proxy.url)
            iutil.setenv("ftp_proxy", proxy.url)
            iutil.setenv("HTTPS_PROXY", proxy.url)

    if flags.noverifyssl:
        ksdata.method.noverifyssl = flags.noverifyssl
    if opts.multiLib:
        # sets dnf's multilib_policy to "all" (as opposed to "best")
        ksdata.packages.multiLib = opts.multiLib

    # set ksdata.method based on anaconda.method if it isn't already set
Пример #9
0
    def refresh(self, args=None):
        NormalTUISpoke.refresh(self, args)

        if self._root:
            try:
                mountExistingSystem(self.storage.fsset, self._root.device,
                                    readOnly=self.readOnly)
                if flags.automatedInstall:
                    log.info("System has been mounted under: %s", iutil.getSysroot())
                else:
                    text = TextWidget(_("Your system has been mounted under %(mountpoint)s.\n\nIf "
                                        "you would like to make your system the root "
                                        "environment, run the command:\n\n\tchroot %(mountpoint)s\n")
                                        % {"mountpoint": iutil.getSysroot()} )
                    self._window.append(text)
                rootmounted = True

                # now turn on swap
                if not flags.imageInstall or not self.readOnly:
                    try:
                        self.storage.turnOnSwap()
                    except StorageError:
                        log.error("Error enabling swap.")

                # turn on selinux also
                if flags.selinux:
                    # we have to catch the possible exception, because we
                    # support read-only mounting
                    try:
                        fd = open("%s/.autorelabel" % iutil.getSysroot(), "w+")
                        fd.close()
                    except IOError:
                        log.warning("Cannot touch %s/.autorelabel", iutil.getSysroot())

                # set a libpath to use mounted fs
                libdirs = os.environ.get("LD_LIBRARY_PATH", "").split(":")
                mounted = list(map(lambda dir: "/mnt/sysimage%s" % dir, libdirs))
                iutil.setenv("LD_LIBRARY_PATH", ":".join(libdirs + mounted))

                # do we have bash?
                try:
                    if os.access("/usr/bin/bash", os.R_OK):
                        os.symlink("/usr/bin/bash", "/bin/bash")
                except OSError:
                    pass
            except (ValueError, LookupError, SyntaxError, NameError):
                pass
            except Exception as e: # pylint: disable=broad-except
                if flags.automatedInstall:
                    msg = _("Run %s to unmount the system when you are finished.\n") % ANACONDA_CLEANUP

                text = TextWidget(_("An error occurred trying to mount some or all of "
                                    "your system.  Some of it may be mounted under %s\n\n") + iutil.getSysroot() + msg)
                self._window.append(text)
                return True
        else:
            if flags.automatedInstall and self.data.reboot.action in [KS_REBOOT, KS_SHUTDOWN]:
                log.info("No Linux partitions found.")
                text = TextWidget(_("You don't have any Linux partitions.  Rebooting.\n"))
                self._window.append(text)
                # should probably wait a few seconds to show the message
                time.sleep(5)
                iutil.execWithRedirect("systemctl", ["--no-wall", "reboot"])
            else:
                if not flags.imageInstall:
                    msg = _("The system will reboot automatically when you exit"
                            " from the shell.\n")
                else:
                    msg = ""
            text = TextWidget(_("You don't have any Linux partitions. %s\n") % msg)
            self._window.append(text)
            return True

        if rootmounted and not self.readOnly:
            self.storage.makeMtab()
            try:
                makeResolvConf(iutil.getSysroot())
            except(OSError, IOError) as e:
                log.error("Error making resolv.conf: %s", e)
            text = TextWidget(_("Your system is mounted under the %s directory.") % iutil.getSysroot())
            self._window.append(text)

        # create /etc/fstab in ramdisk so it's easier to work with RO mounted fs
        makeFStab()

        # run %post if we've mounted everything
        if rootmounted and not self.readOnly and flags.automatedInstall:
            runPostScripts(self.data.scripts)

        return True
Пример #10
0
    def refresh(self, args=None):
        NormalTUISpoke.refresh(self, args)

        if self._root:
            try:
                mount_existing_system(self.storage.fsset,
                                      self._root.device,
                                      read_only=self.readOnly)
                if flags.automatedInstall:
                    log.info("System has been mounted under: %s",
                             iutil.getSysroot())
                else:
                    text = TextWidget(
                        _("Your system has been mounted under %(mountpoint)s.\n\n"
                          "If you would like to make the root of your system the "
                          "root of the active system, run the command:\n\n"
                          "\tchroot %(mountpoint)s\n") %
                        {"mountpoint": iutil.getSysroot()})
                    self._window.append(text)
                rootmounted = True

                # now turn on swap
                if not flags.imageInstall or not self.readOnly:
                    try:
                        self.storage.turn_on_swap()
                    except StorageError:
                        log.error("Error enabling swap.")

                # turn on selinux also
                if flags.selinux:
                    # we have to catch the possible exception, because we
                    # support read-only mounting
                    try:
                        fd = open("%s/.autorelabel" % iutil.getSysroot(), "w+")
                        fd.close()
                    except IOError:
                        log.warning("Cannot touch %s/.autorelabel",
                                    iutil.getSysroot())

                # set a libpath to use mounted fs
                libdirs = os.environ.get("LD_LIBRARY_PATH", "").split(":")
                mounted = list(
                    map(lambda dir: "/mnt/sysimage%s" % dir, libdirs))
                iutil.setenv("LD_LIBRARY_PATH", ":".join(libdirs + mounted))

                # do we have bash?
                try:
                    if os.access("/usr/bin/bash", os.R_OK):
                        os.symlink("/usr/bin/bash", "/bin/bash")
                except OSError:
                    pass
            except (ValueError, LookupError, SyntaxError, NameError):
                pass
            except (OSError, StorageError) as e:
                if flags.automatedInstall:
                    msg = _(
                        "Run %s to unmount the system when you are finished.\n"
                    ) % ANACONDA_CLEANUP

                text = TextWidget(
                    _("An error occurred trying to mount some or all of "
                      "your system.  Some of it may be mounted under %s\n\n") +
                    iutil.getSysroot() + msg)
                self._window.append(text)
                return True
        else:
            if flags.automatedInstall and self.data.reboot.action in [
                    KS_REBOOT, KS_SHUTDOWN
            ]:
                log.info("No Linux partitions found.")
                text = TextWidget(
                    _("You don't have any Linux partitions.  Rebooting.\n"))
                self._window.append(text)
                # should probably wait a few seconds to show the message
                time.sleep(5)
                iutil.execWithRedirect("systemctl", ["--no-wall", "reboot"])
            else:
                if not flags.imageInstall:
                    msg = _(
                        "The system will reboot automatically when you exit"
                        " from the shell.\n")
                else:
                    msg = ""
            text = TextWidget(
                _("You don't have any Linux partitions. %s\n") % msg)
            self._window.append(text)
            return True

        if rootmounted and not self.readOnly:
            self.storage.make_mtab()
            try:
                makeResolvConf(iutil.getSysroot())
            except (OSError, IOError) as e:
                log.error("Error making resolv.conf: %s", e)
            text = TextWidget(
                _("Your system is mounted under the %s directory.") %
                iutil.getSysroot())
            self._window.append(text)

        # create /etc/fstab in ramdisk so it's easier to work with RO mounted fs
        makeFStab()

        # run %post if we've mounted everything
        if rootmounted and not self.readOnly and flags.automatedInstall:
            runPostScripts(self.data.scripts)

        return True
Пример #11
0
def setup_locale(locale, lang=None, text_mode=False):
    """
    Procedure setting the system to use the given locale and store it in to the
    ksdata.lang object (if given). DOES NOT PERFORM ANY CHECKS OF THE GIVEN
    LOCALE.

    $LANG must be set by the caller in order to set the language used by gettext.
    Doing this in a thread-safe way is up to the caller.

    We also try to set a proper console font for the locale in text mode.
    If the font for the locale can't be displayed in the Linux console,
    we fall back to the English locale.

    :param str locale: locale to setup
    :param lang: ksdata.lang object or None
    :param bool text_mode: if the locale is being setup for text mode
    :return: None
    :rtype: None

    """

    if lang:
        lang.lang = locale

    # not all locales might be displayable in text mode
    if text_mode:
        # check if the script corresponding to the locale/language
        # can be displayed by the Linux console
        # * all scripts for the given locale/language need to be
        #   supported by the linux console
        # * otherwise users might get a screen full of white rectangles
        #   (also known as "tofu") in text mode
        # then we also need to check if we have information about what
        # font to use for correctly displaying the given language/locale

        script_supported = locale_supported_in_console(locale)
        log.debug("scripts found for locale %s: %s", locale, get_locale_scripts(locale))

        console_fonts = get_locale_console_fonts(locale)
        log.debug("console fonts found for locale %s: %s", locale, console_fonts)

        font_set = False
        if script_supported and console_fonts:
            # try to set console font
            for font in console_fonts:
                if set_console_font(font):
                    # console font set successfully, skip the rest
                    font_set = True
                    break

        if not font_set:
            log.warning("can't set console font for locale %s", locale)
            # report what exactly went wrong
            if not(script_supported):
                log.warning("script not supported by console for locale %s", locale)
            if not(console_fonts):  # no fonts known for locale
                log.warning("no console font found for locale %s", locale)
            if script_supported and console_fonts:
                log.warning("none of the suggested fonts can be set for locale %s", locale)
            log.warning("falling back to the English locale")
            locale = constants.DEFAULT_LANG
            os.environ["LANG"] = locale  # pylint: disable=environment-modify

    # set the locale to the value we have selected
    log.debug("setting locale to: %s", locale)
    setenv("LANG", locale)
    locale_mod.setlocale(locale_mod.LC_ALL, locale)

    # This part is pretty gross:
    # In python3, sys.stdout and friends are TextIOWrapper objects that translate
    # betwen str types (in python) and byte types (used to actually read from or
    # write to the console). These wrappers are configured at startup using the
    # locale at startup, which means that if anaconda starts with LANG=C or LANG
    # unset, sys.stdout.encoding will be "ascii". And if the language is then changed,
    # because anaconda read the kickstart or parsed the command line or whatever,
    # say, to Czech, text mode will crash because it's going to try to print non-ASCII
    # characters and sys.stdout doesn't know what to do with them. So, when changing
    # the locale, create new objects for the standard streams so they are created with
    # the new locale's encoding.

    # Replacing stdout is about as stable as it looks, and it seems to break when done
    # after the GUI is started. Only make the switch if the encoding actually changed.
    if locale_mod.getpreferredencoding() != sys.stdout.encoding:
        sys.stdin = io.TextIOWrapper(sys.stdin.detach())
        sys.stdout = io.TextIOWrapper(sys.stdout.detach())
        sys.stderr = io.TextIOWrapper(sys.stderr.detach())
Пример #12
0
    # scripts.  Add those to the ksdata now.
    kickstart.appendPostScripts(ksdata)

    # cmdline flags override kickstart settings
    if anaconda.proxy:
        ksdata.method.proxy = anaconda.proxy

        # Setup proxy environmental variables so that pre/post scripts use it
        # as well as libreport
        try:
            proxy = ProxyString(anaconda.proxy)
        except ProxyStringError as e:
            log.info("Failed to parse proxy \"%s\": %s", anaconda.proxy, e)
        else:
            # Set environmental variables to be used by pre/post scripts
            iutil.setenv("PROXY", proxy.noauth_url)
            iutil.setenv("PROXY_USER", proxy.username or "")
            iutil.setenv("PROXY_PASSWORD", proxy.password or "")

            # Variables used by curl, libreport, etc.
            iutil.setenv("http_proxy", proxy.url)
            iutil.setenv("ftp_proxy", proxy.url)
            iutil.setenv("HTTPS_PROXY", proxy.url)

    if flags.noverifyssl:
        ksdata.method.noverifyssl = flags.noverifyssl
    if opts.multiLib:
        # sets dnf's multilib_policy to "all" (as opposed to "best")
        ksdata.packages.multiLib = opts.multiLib

    # set ksdata.method based on anaconda.method if it isn't already set
Пример #13
0
def doRescue(intf, rescue_mount, ksdata):
    import blivet

    # XXX: hook the exception handler wrapper that turns off snack first
    orig_hook = sys.excepthook
    sys.excepthook = lambda ty, val, tb: _exception_handler_wrapper(orig_hook,
                                                                    intf.screen,
                                                                    ty, val, tb)

    for f in ["services", "protocols", "group", "joe", "man.config",
              "nsswitch.conf", "selinux", "mke2fs.conf"]:
        try:
            os.symlink('/mnt/runtime/etc/' + f, '/etc/' + f)
        except OSError:
            pass

    # Early shell access with no disk access attempts
    if not rescue_mount:
        # the %post should be responsible for mounting all needed file systems
        # NOTE: 1st script must be bash or simple python as nothing else might be available in the rescue image
        if flags.automatedInstall and ksdata.scripts:
            runPostScripts(ksdata.scripts)
        else:
            runShell()

        sys.exit(0)

    if flags.automatedInstall:
        readOnly = ksdata.rescue.romount
    else:
        # prompt to see if we should try and find root filesystem and mount
        # everything in /etc/fstab on that root
        while True:
            rc = ButtonChoiceWindow(intf.screen, _("Rescue"),
                _("The rescue environment will now attempt to find your "
                  "Linux installation and mount it under the directory "
                  "%s.  You can then make any changes required to your "
                  "system.  If you want to proceed with this step choose "
                  "'Continue'.  You can also choose to mount your file systems "
                  "read-only instead of read-write by choosing 'Read-Only'.  "
                  "\n\n"
                  "If for some reason this process fails you can choose 'Skip' "
                  "and this step will be skipped and you will go directly to a "
                  "command shell.\n\n") % (iutil.getSysroot(),),
                  [_("Continue"), _("Read-Only"), _("Skip")])

            if rc == _("Skip").lower():
                runShell(intf.screen)
                sys.exit(0)
            else:
                readOnly = rc == _("Read-Only").lower()

            break

    sto = blivet.Blivet(ksdata=ksdata)
    storageInitialize(sto, ksdata, [])
    _unlock_devices(intf, sto)
    roots = osinstall.findExistingInstallations(sto.devicetree)

    if not roots:
        root = None
    elif len(roots) == 1:
        root = roots[0]
    else:
        height = min(len(roots), 12)
        if height == 12:
            scroll = 1
        else:
            scroll = 0

        lst = []
        for root in roots:
            lst.append("%s" % root.name)

        (button, choice) = \
            ListboxChoiceWindow(intf.screen, _("System to Rescue"),
                                _("Which device holds the root partition "
                                  "of your installation?"), lst,
                                [_("OK"), _("Exit")], width=30,
                                scroll=scroll, height=height,
                                help="multipleroot")

        if button == _("Exit").lower():
            root = None
        else:
            root = roots[choice]

    rootmounted = False

    if root:
        try:
            if not flags.imageInstall:
                msg = _("The system will reboot automatically when you exit "
                        "from the shell.")
            else:
                msg = _("Run %s to unmount the system "
                        "when you are finished.") % ANACONDA_CLEANUP

            mountExistingSystem(sto.fsset, root.device, readOnly=readOnly)

            if flags.automatedInstall:
                log.info("System has been mounted under: %s", iutil.getSysroot())
            else:
                ButtonChoiceWindow(intf.screen, _("Rescue"),
                   _("Your system has been mounted under %(rootPath)s.\n\n"
                     "Press <return> to get a shell. If you would like to "
                     "make your system the root environment, run the command:\n\n"
                     "\tchroot %(rootPath)s\n\n%(msg)s") %
                                   {'rootPath': iutil.getSysroot(),
                                    'msg': msg},
                                   [_("OK")])
            rootmounted = True

            # now turn on swap
            if not readOnly:
                try:
                    sto.turnOnSwap()
                except StorageError:
                    log.error("Error enabling swap")

            # and selinux too
            if flags.selinux:
                # we have to catch the possible exception
                # because we support read-only mounting
                try:
                    fd = open("%s/.autorelabel" % iutil.getSysroot(), "w+")
                    fd.close()
                except IOError:
                    log.warning("cannot touch /.autorelabel")

            # set a library path to use mounted fs
            libdirs = os.environ.get("LD_LIBRARY_PATH", "").split(":")
            mounted = ["/mnt/sysimage%s" % mdir for mdir in libdirs]
            iutil.setenv("LD_LIBRARY_PATH", ":".join(libdirs + mounted))

            # find groff data dir
            gversion = None
            try:
                glst = os.listdir("/mnt/sysimage/usr/share/groff")
            except OSError:
                pass
            else:
                # find a directory which is a numeral, its where
                # data files are
                for gdir in glst:
                    if re.match(r'\d[.\d]+\d$', gdir):
                        gversion = gdir
                        break

            if gversion is not None:
                gpath = "/mnt/sysimage/usr/share/groff/"+gversion
                iutil.setenv("GROFF_FONT_PATH", gpath + '/font')
                iutil.setenv("GROFF_TMAC_PATH", "%s:/mnt/sysimage/usr/share/groff/site-tmac" % (gpath + '/tmac',))

            # do we have bash?
            try:
                if os.access("/usr/bin/bash", os.R_OK):
                    os.symlink("/usr/bin/bash", "/bin/bash")
            except OSError:
                pass
        except (ValueError, LookupError, SyntaxError, NameError):
            raise
        except Exception as e:    # pylint: disable=broad-except
            log.error("doRescue caught exception: %s", e)
            if flags.automatedInstall:
                log.error("An error occurred trying to mount some or all of your system")
            else:
                if not flags.imageInstall:
                    msg = _("The system will reboot automatically when you "
                            "exit from the shell.")
                else:
                    msg = _("Run %s to unmount the system "
                            "when you are finished.") % ANACONDA_CLEANUP

                ButtonChoiceWindow(intf.screen, _("Rescue"),
                    _("An error occurred trying to mount some or all of your "
                      "system. Some of it may be mounted under %s.\n\n"
                      "Press <return> to get a shell.") % iutil.getSysroot() + msg,
                      [_("OK")])
    else:
        if flags.automatedInstall and ksdata.reboot.action in [KS_REBOOT, KS_SHUTDOWN]:
            log.info("No Linux partitions found")
            intf.screen.finish()
            print(_("You don't have any Linux partitions.  Rebooting.\n"))
            sys.exit(0)
        else:
            if not flags.imageInstall:
                msg = _(" The system will reboot automatically when you exit "
                        "from the shell.")
            else:
                msg = ""
            ButtonChoiceWindow(intf.screen, _("Rescue Mode"),
                               _("You don't have any Linux partitions. Press "
                                 "return to get a shell.%s") % msg,
                               [_("OK")], width=50)

    msgStr = ""

    if rootmounted and not readOnly:
        sto.makeMtab()
        try:
            makeResolvConf(iutil.getSysroot())
        except (OSError, IOError) as e:
            log.error("error making a resolv.conf: %s", e)
        msgStr = _("Your system is mounted under the %s directory.") % (iutil.getSysroot(),)
        ButtonChoiceWindow(intf.screen, _("Rescue"), msgStr, [_("OK")])

    # we do not need ncurses anymore, shut them down
    intf.shutdown()

    #create /etc/fstab in ramdisk, so it is easier to work with RO mounted filesystems
    makeFStab()

    # run %post if we've mounted everything
    if rootmounted and not readOnly and flags.automatedInstall:
        runPostScripts(ksdata.scripts)

    # start shell if reboot wasn't requested
    if not flags.automatedInstall or not ksdata.reboot.action in [KS_REBOOT, KS_SHUTDOWN]:
        runShell(msg=msgStr)

    sys.exit(0)
Пример #14
0
def doRescue(intf, rescue_mount, ksdata):
    import blivet

    # XXX: hook the exception handler wrapper that turns off snack first
    orig_hook = sys.excepthook
    sys.excepthook = lambda ty, val, tb: _exception_handler_wrapper(orig_hook,
                                                                    intf.screen,
                                                                    ty, val, tb)

    for f in ["services", "protocols", "group", "joe", "man.config",
              "nsswitch.conf", "selinux", "mke2fs.conf"]:
        try:
            os.symlink('/mnt/runtime/etc/' + f, '/etc/' + f)
        except OSError:
            pass

    # Early shell access with no disk access attempts
    if not rescue_mount:
        # the %post should be responsible for mounting all needed file systems
        # NOTE: 1st script must be bash or simple python as nothing else might be available in the rescue image
        if flags.automatedInstall and ksdata.scripts:
            runPostScripts(ksdata.scripts)
        else:
            runShell()

        sys.exit(0)

    if flags.automatedInstall:
        readOnly = ksdata.rescue.romount
    else:
        # prompt to see if we should try and find root filesystem and mount
        # everything in /etc/fstab on that root
        while True:
            rc = ButtonChoiceWindow(intf.screen, _("Rescue"),
                _("The rescue environment will now attempt to find your "
                  "Linux installation and mount it under the directory "
                  "%s.  You can then make any changes required to your "
                  "system.  If you want to proceed with this step choose "
                  "'Continue'.  You can also choose to mount your file systems "
                  "read-only instead of read-write by choosing 'Read-Only'.  "
                  "\n\n"
                  "If for some reason this process fails you can choose 'Skip' "
                  "and this step will be skipped and you will go directly to a "
                  "command shell.\n\n") % (iutil.getSysroot(),),
                  [_("Continue"), _("Read-Only"), _("Skip")])

            if rc == _("Skip").lower():
                runShell(intf.screen)
                sys.exit(0)
            else:
                readOnly = rc == _("Read-Only").lower()

            break

    sto = blivet.Blivet(ksdata=ksdata)
    storageInitialize(sto, ksdata, [])
    _unlock_devices(intf, sto)
    roots = osinstall.findExistingInstallations(sto.devicetree)

    if not roots:
        root = None
    elif len(roots) == 1:
        root = roots[0]
    else:
        height = min(len(roots), 12)
        if height == 12:
            scroll = 1
        else:
            scroll = 0

        lst = []
        for root in roots:
            lst.append("%s" % root.name)

        (button, choice) = \
            ListboxChoiceWindow(intf.screen, _("System to Rescue"),
                                _("Which device holds the root partition "
                                  "of your installation?"), lst,
                                [_("OK"), _("Exit")], width=30,
                                scroll=scroll, height=height,
                                help="multipleroot")

        if button == _("Exit").lower():
            root = None
        else:
            root = roots[choice]

    rootmounted = False

    if root:
        try:
            if not flags.imageInstall:
                msg = _("The system will reboot automatically when you exit "
                        "from the shell.")
            else:
                msg = _("Run %s to unmount the system "
                        "when you are finished.") % ANACONDA_CLEANUP

            mountExistingSystem(sto.fsset, root.device, readOnly=readOnly)

            if flags.automatedInstall:
                log.info("System has been mounted under: %s", iutil.getSysroot())
            else:
                ButtonChoiceWindow(intf.screen, _("Rescue"),
                   _("Your system has been mounted under %(rootPath)s.\n\n"
                     "Press <return> to get a shell. If you would like to "
                     "make your system the root environment, run the command:\n\n"
                     "\tchroot %(rootPath)s\n\n%(msg)s") %
                                   {'rootPath': iutil.getSysroot(),
                                    'msg': msg},
                                   [_("OK")])
            rootmounted = True

            # now turn on swap
            if not readOnly:
                try:
                    sto.turnOnSwap()
                except StorageError:
                    log.error("Error enabling swap")

            # and selinux too
            if flags.selinux:
                # we have to catch the possible exception
                # because we support read-only mounting
                try:
                    fd = open("%s/.autorelabel" % iutil.getSysroot(), "w+")
                    fd.close()
                except IOError:
                    log.warning("cannot touch /.autorelabel")

            # set a library path to use mounted fs
            libdirs = os.environ.get("LD_LIBRARY_PATH", "").split(":")
            mounted = ["/mnt/sysimage%s" % mdir for mdir in libdirs]
            iutil.setenv("LD_LIBRARY_PATH", ":".join(libdirs + mounted))

            # find groff data dir
            gversion = None
            try:
                glst = os.listdir("/mnt/sysimage/usr/share/groff")
            except OSError:
                pass
            else:
                # find a directory which is a numeral, its where
                # data files are
                for gdir in glst:
                    if re.match(r'\d[.\d]+\d$', gdir):
                        gversion = gdir
                        break

            if gversion is not None:
                gpath = "/mnt/sysimage/usr/share/groff/"+gversion
                iutil.setenv("GROFF_FONT_PATH", gpath + '/font')
                iutil.setenv("GROFF_TMAC_PATH", "%s:/mnt/sysimage/usr/share/groff/site-tmac" % (gpath + '/tmac',))

            # do we have bash?
            try:
                if os.access("/usr/bin/bash", os.R_OK):
                    os.symlink("/usr/bin/bash", "/bin/bash")
            except OSError:
                pass
        except (ValueError, LookupError, SyntaxError, NameError):
            raise
        except Exception as e:    # pylint: disable=broad-except
            log.error("doRescue caught exception: %s", e)
            if flags.automatedInstall:
                log.error("An error occurred trying to mount some or all of your system")
            else:
                if not flags.imageInstall:
                    msg = _("The system will reboot automatically when you "
                            "exit from the shell.")
                else:
                    msg = _("Run %s to unmount the system "
                            "when you are finished.") % ANACONDA_CLEANUP

                ButtonChoiceWindow(intf.screen, _("Rescue"),
                    _("An error occurred trying to mount some or all of your "
                      "system. Some of it may be mounted under %s.\n\n"
                      "Press <return> to get a shell.") % iutil.getSysroot() + msg,
                      [_("OK")])
    else:
        if flags.automatedInstall and ksdata.reboot.action in [KS_REBOOT, KS_SHUTDOWN]:
            log.info("No Linux partitions found")
            intf.screen.finish()
            print(_("You don't have any Linux partitions.  Rebooting.\n"))
            sys.exit(0)
        else:
            if not flags.imageInstall:
                msg = _(" The system will reboot automatically when you exit "
                        "from the shell.")
            else:
                msg = ""
            ButtonChoiceWindow(intf.screen, _("Rescue Mode"),
                               _("You don't have any Linux partitions. Press "
                                 "return to get a shell.%s") % msg,
                               [_("OK")], width=50)

    msgStr = ""

    if rootmounted and not readOnly:
        sto.makeMtab()
        try:
            makeResolvConf(iutil.getSysroot())
        except (OSError, IOError) as e:
            log.error("error making a resolv.conf: %s", e)
        msgStr = _("Your system is mounted under the %s directory.") % (iutil.getSysroot(),)
        ButtonChoiceWindow(intf.screen, _("Rescue"), msgStr, [_("OK")])

    # we do not need ncurses anymore, shut them down
    intf.shutdown()

    #create /etc/fstab in ramdisk, so it is easier to work with RO mounted filesystems
    makeFStab()

    # run %post if we've mounted everything
    if rootmounted and not readOnly and flags.automatedInstall:
        runPostScripts(ksdata.scripts)

    # start shell if reboot wasn't requested
    if not flags.automatedInstall or not ksdata.reboot.action in [KS_REBOOT, KS_SHUTDOWN]:
        runShell(msg=msgStr)

    sys.exit(0)
Пример #15
0
def setup_locale(locale, lang=None, text_mode=False):
    """
    Procedure setting the system to use the given locale and store it in to the
    ksdata.lang object (if given). DOES NOT PERFORM ANY CHECKS OF THE GIVEN
    LOCALE.

    $LANG must be set by the caller in order to set the language used by gettext.
    Doing this in a thread-safe way is up to the caller.

    We also try to set a proper console font for the locale in text mode.
    If the font for the locale can't be displayed in the Linux console,
    we fall back to the English locale.

    :param str locale: locale to setup
    :param lang: ksdata.lang object or None
    :param bool text_mode: if the locale is being setup for text mode
    :return: None
    :rtype: None

    """

    if lang:
        lang.lang = locale

    # not all locales might be displayable in text mode
    if text_mode:
        # check if the script corresponding to the locale/language
        # can be displayed by the Linux console
        # * all scripts for the given locale/language need to be
        #   supported by the linux console
        # * otherwise users might get a screen full of white rectangles
        #   (also known as "tofu") in text mode
        # then we also need to check if we have information about what
        # font to use for correctly displaying the given language/locale

        script_supported = locale_supported_in_console(locale)
        log.debug("scripts found for locale %s: %s", locale, get_locale_scripts(locale))

        console_fonts = get_locale_console_fonts(locale)
        log.debug("console fonts found for locale %s: %s", locale, console_fonts)

        font_set = False
        if script_supported and console_fonts:
            # try to set console font
            for font in console_fonts:
                if set_console_font(font):
                    # console font set successfully, skip the rest
                    font_set = True
                    break

        if not font_set:
            log.warning("can't set console font for locale %s", locale)
            # report what exactly went wrong
            if not(script_supported):
                log.warning("script not supported by console for locale %s", locale)
            if not(console_fonts):  # no fonts known for locale
                log.warning("no console font found for locale %s", locale)
            if script_supported and console_fonts:
                log.warning("none of the suggested fonts can be set for locale %s", locale)
            log.warning("falling back to the English locale")
            locale = constants.DEFAULT_LANG
            os.environ["LANG"] = locale  # pylint: disable=environment-modify

    # set the locale to the value we have selected
    log.debug("setting locale to: %s", locale)
    setenv("LANG", locale)
    locale_mod.setlocale(locale_mod.LC_ALL, locale)
Пример #16
0
def setup_locale(locale, lang=None, text_mode=False):
    """
    Procedure setting the system to use the given locale and store it in to the
    ksdata.lang object (if given). DOES NOT PERFORM ANY CHECKS OF THE GIVEN
    LOCALE.

    $LANG must be set by the caller in order to set the language used by gettext.
    Doing this in a thread-safe way is up to the caller.

    We also try to set a proper console font for the locale in text mode.
    If the font for the locale can't be displayed in the Linux console,
    we fall back to the English locale.

    :param str locale: locale to setup
    :param lang: ksdata.lang object or None
    :param bool text_mode: if the locale is being setup for text mode
    :return: None
    :rtype: None

    """

    if lang:
        lang.lang = locale

    # not all locales might be displayable in text mode
    if text_mode:
        # check if the script corresponding to the locale/language
        # can be displayed by the Linux console
        # * all scripts for the given locale/language need to be
        #   supported by the linux console
        # * otherwise users might get a screen full of white rectangles
        #   (also known as "tofu") in text mode
        # then we also need to check if we have information about what
        # font to use for correctly displaying the given language/locale

        script_supported = locale_supported_in_console(locale)
        log.debug("scripts found for locale %s: %s", locale, get_locale_scripts(locale))

        console_fonts = get_locale_console_fonts(locale)
        log.debug("console fonts found for locale %s: %s", locale, console_fonts)

        font_set = False
        if script_supported and console_fonts:
            # try to set console font
            for font in console_fonts:
                if set_console_font(font):
                    # console font set successfully, skip the rest
                    font_set = True
                    break

        if not font_set:
            log.warning("can't set console font for locale %s", locale)
            # report what exactly went wrong
            if not(script_supported):
                log.warning("script not supported by console for locale %s", locale)
            if not(console_fonts):  # no fonts known for locale
                log.warning("no console font found for locale %s", locale)
            if script_supported and console_fonts:
                log.warning("none of the suggested fonts can be set for locale %s", locale)
            log.warning("falling back to the English locale")
            locale = constants.DEFAULT_LANG
            os.environ["LANG"] = locale  # pylint: disable=environment-modify

    # set the locale to the value we have selected
    log.debug("setting locale to: %s", locale)
    setenv("LANG", locale)
    locale_mod.setlocale(locale_mod.LC_ALL, locale)