ROOT_PATH = "/mnt/sysimage" THREAD_PAYLOAD = "AnaPayloadThread" def writeBootLoader(storage, payload, instClass, ksdata):
    """ Write bootloader configuration to disk.

        When we get here, the bootloader will already have a default linux
        image. We only have to add images for the non-default kernels and
        adjust the default to reflect whatever the default variant is.
    """
    from pyanaconda.errors import errorHandler, ERROR_RAISE

    if not storage.bootloader.skip_bootloader:
        stage1_device = storage.bootloader.stage1_device
        log.info("bootloader stage1 target device is %s" % stage1_device.name)
        stage2_device = storage.bootloader.stage2_device
        log.info("bootloader stage2 target device is %s" % stage2_device.name)

    if payload.handlesBootloaderConfiguration:
        if storage.bootloader.skip_bootloader:
            log.info("skipping bootloader install per user request")
            return
        writeBootLoaderFinal(storage, payload, instClass, ksdata)
        return

    # get a list of installed kernel packages
    kernel_versions = payload.kernelVersionList
    if not kernel_versions:
        log.warning("no kernel was installed -- bootloader config unchanged")
        return

    # all the linux images' labels are based on the default image's
    base_label = productName
    base_short_label = "linux"

    # The first one is the default kernel. Update the bootloader's default
    # entry to reflect the details of the default kernel.
    version = kernel_versions.pop(0)
    default_image = LinuxBootLoaderImage(device=storage.rootDevice,
                                         version=version,
                                         label=base_label,
                                         short=base_short_label)
    storage.bootloader.add_image(default_image)
    storage.bootloader.default = default_image
    if hasattr(storage.bootloader, 'efi_dir'):
        storage.bootloader.efi_dir = instClass.efi_dir

    # write out /etc/sysconfig/kernel
    writeSysconfigKernel(storage, version)

    if storage.bootloader.skip_bootloader:
        log.info("skipping bootloader install per user request")
        return

    # now add an image for each of the other kernels
    for version in kernel_versions:
        label = "%s-%s" % (base_label, version)
        short = "%s-%s" % (base_short_label, version)
        if storage.bootloader.trusted_boot:
            image = TbootLinuxBootLoaderImage(
                                         device=storage.rootDevice,
                                         version=version,
                                         label=label, short=short)
        else:
            image = LinuxBootLoaderImage(device=storage.rootDevice,
                                         version=version,
                                         label=label, short=short)
        storage.bootloader.add_image(image)

    writeBootLoaderFinal(storage, payload, instClass, ksdata) def progress_report(message): def createLuserConf(instPath, algoname='sha512'):
    """ Writes a libuser.conf for instPath.

        This must be called before User() is instantiated the first time
        so that libuser.admin will use the temporary config file.
    """
    createTmp = False
    try:
        fn = os.environ["LIBUSER_CONF"]
        if os.access(fn, os.F_OK):
            log.info("removing libuser.conf at %s" % (os.getenv("LIBUSER_CONF")))
            os.unlink(fn)
        log.info("created new libuser.conf at %s with instPath=\"%s\"" % \
                (fn,instPath))
        fd = open(fn, 'w')
    except (OSError, IOError, KeyError):
        createTmp = True

    if createTmp:
        (fp, fn) = tempfile.mkstemp(prefix="libuser.")
        log.info("created new libuser.conf at %s with instPath=\"%s\"" % \
                (fn,instPath))
        fd = os.fdopen(fp, 'w')

    buf = """
[defaults]
skeleton = %(instPath)s/etc/skel
mailspooldir = %(instPath)s/var/mail
crypt_style = %(algo)s
modules = files shadow
create_modules = files shadow
[files]
directory = %(instPath)s/etc
[shadow]
directory = %(instPath)s/etc
""" % {"instPath": instPath, "algo": algoname}

    fd.write(buf)
    fd.close()
    os.environ["LIBUSER_CONF"] = fn

    return fn def getPassAlgo(authconfigStr):
    """ Reads the auth string and returns a string indicating our desired
        password encoding algorithm.
    """
    if authconfigStr.find("--enablemd5") != -1 or authconfigStr.find("--passalgo=md5") != -1:
        return 'md5'
    elif authconfigStr.find("--passalgo=sha256") != -1:
        return 'sha256'
    elif authconfigStr.find("--passalgo=sha512") != -1:
        return 'sha512'
    else:
        return None class Users:
    def __init__ (self):
        self.admin = libuser.admin()

    def createGroup (self, group_name, **kwargs):
        """Create a new user on the system with the given name.  Optional kwargs:

           gid       -- The GID for the new user.  If none is given, the next
                        available one is used.
           root      -- The directory of the system to create the new user
                        in.  homedir will be interpreted relative to this.
                        Defaults to /mnt/sysimage.
        """

        childpid = os.fork()
        root = kwargs.get("root", iutil.getSysroot())

        if not childpid:
            if not root in ["","/"]:
                os.chroot(root)
                os.chdir("/")
                del(os.environ["LIBUSER_CONF"])

            self.admin = libuser.admin()

            try:
                if self.admin.lookupGroupByName(group_name):
                    os._exit(1)

                groupEnt = self.admin.initGroup(group_name)

                if kwargs.get("gid", -1) >= 0:
                    groupEnt.set(libuser.GIDNUMBER, kwargs["gid"])

                self.admin.addGroup(groupEnt)
                os._exit(0)
            except Exception as e:
                log.critical("Error when creating new group: %s" % str(e))
                os._exit(1)

        try:
            (pid, status) = os.waitpid(childpid, 0)
        except OSError as e:
            log.critical("exception from waitpid while creating a group: %s %s" % (e.errno, e.strerror))
            return False

        if os.WIFEXITED(status) and (os.WEXITSTATUS(status) == 0):
            return True
        else:
            return False

    def createUser (self, user_name, *args, **kwargs):
        """Create a new user on the system with the given name.  Optional kwargs:

           algo      -- The password algorithm to use in case isCrypted=True.
                        If none is given, the cryptPassword default is used.
           gecos     -- The GECOS information (full name, office, phone, etc.).
                        Defaults to "".
           groups    -- A list of existing group names the user should be
                        added to.  Defaults to [].
           homedir   -- The home directory for the new user.  Defaults to
                        /home/<name>.
           isCrypted -- Is the password kwargs already encrypted?  Defaults
                        to False.
           lock      -- Is the new account locked by default?  Defaults to
                        False.
           password  -- The password.  See isCrypted for how this is interpreted.
                        If the password is "" then the account is created
                        with a blank password. If None or False the account will
                        be left in its initial state (locked)
           root      -- The directory of the system to create the new user
                        in.  homedir will be interpreted relative to this.
                        Defaults to /mnt/sysimage.
           shell     -- The shell for the new user.  If none is given, the
                        libuser default is used.
           uid       -- The UID for the new user.  If none is given, the next
                        available one is used.
           gid       -- The GID for the new user.  If none is given, the next
                        available one is used.
        """
        childpid = os.fork()
        root = kwargs.get("root", iutil.getSysroot())

        if not childpid:
            if not root in ["","/"]:
                os.chroot(root)
                os.chdir("/")
                del(os.environ["LIBUSER_CONF"])

            self.admin = libuser.admin()

            try:
                if self.admin.lookupUserByName(user_name):
                    os._exit(1)

                userEnt = self.admin.initUser(user_name)
                groupEnt = self.admin.initGroup(user_name)

                if kwargs.get("gid", -1) >= 0:
                    groupEnt.set(libuser.GIDNUMBER, kwargs["gid"])

                grpLst = filter(lambda grp: grp,
                                map(lambda name: self.admin.lookupGroupByName(name), kwargs.get("groups", [])))
                userEnt.set(libuser.GIDNUMBER, [groupEnt.get(libuser.GIDNUMBER)[0]] +
                            map(lambda grp: grp.get(libuser.GIDNUMBER)[0], grpLst))

                if kwargs.get("homedir", False):
                    userEnt.set(libuser.HOMEDIRECTORY, kwargs["homedir"])
                else:
                    iutil.mkdirChain('/home')
                    userEnt.set(libuser.HOMEDIRECTORY, "/home/" + user_name)

                if kwargs.get("shell", False):
                    userEnt.set(libuser.LOGINSHELL, kwargs["shell"])

                if kwargs.get("uid", -1) >= 0:
                    userEnt.set(libuser.UIDNUMBER, kwargs["uid"])

                if kwargs.get("gecos", False):
                    userEnt.set(libuser.GECOS, kwargs["gecos"])

                # need to create home directory for the user or does it already exist?
                # userEnt.get returns lists (usually with a single item)
                mk_homedir = not os.path.exists(userEnt.get(libuser.HOMEDIRECTORY)[0])

                self.admin.addUser(userEnt, mkmailspool=kwargs.get("mkmailspool", True),
                                   mkhomedir=mk_homedir)
                self.admin.addGroup(groupEnt)

                if not mk_homedir:
                    stats = os.stat(userEnt.get(libuser.HOMEDIRECTORY)[0])
                    orig_uid = stats.st_uid
                    orig_gid = stats.st_gid

                    log.info("Home directory for the user %s already existed, "
                             "fixing the owner." % user_name)
                    # home directory already existed, change owner of it properly
                    iutil.chown_dir_tree(userEnt.get(libuser.HOMEDIRECTORY)[0],
                                         userEnt.get(libuser.UIDNUMBER)[0],
                                         groupEnt.get(libuser.GIDNUMBER)[0],
                                         orig_uid, orig_gid)

                pw = kwargs.get("password", False)
                if pw:
                    if kwargs.get("isCrypted", False):
                        password = kwargs["password"]
                    else:
                        password = cryptPassword(kwargs["password"], algo=kwargs.get("algo", None))
                    self.admin.setpassUser(userEnt, password, True)
                elif pw == "":
                    # Setup the account with *NO* password
                    self.admin.unlockUser(userEnt)
                    log.info("user account %s setup with no password" % user_name)

                if kwargs.get("lock", False):
                    self.admin.lockUser(userEnt)
                    log.info("user account %s locked" % user_name)


                # Add the user to all the groups they should be part of.
                grpLst.append(self.admin.lookupGroupByName(user_name))
                for grp in grpLst:
                    grp.add(libuser.MEMBERNAME, user_name)
                    self.admin.modifyGroup(grp)

                os._exit(0)
            except Exception as e:
                log.critical("Error when creating new user: %s" % str(e))
                os._exit(1)

        try:
            (pid, status) = os.waitpid(childpid, 0)
        except OSError as e:
            log.critical("exception from waitpid while creating a user: %s %s" % (e.errno, e.strerror))
            return False

        if os.WIFEXITED(status) and (os.WEXITSTATUS(status) == 0):
            return True
        else:
            return False

    def checkUserExists(self, username, root=None):
        childpid = os.fork()
        if root is not None:
            rootval = root
        else:
            rootval = iutil.getSysroot()

        if not childpid:
            if not rootval in ["","/"]:
                os.chroot(rootval)
                os.chdir("/")
                del(os.environ["LIBUSER_CONF"])

            self.admin = libuser.admin()

            try:
                if self.admin.lookupUserByName(username):
                    os._exit(0)
            except Exception as e:
                log.critical("Error when searching for user: %s" % str(e))
            os._exit(1)

        try:
            (pid, status) = os.waitpid(childpid, 0)
        except OSError as e:
            log.critical("exception from waitpid while creating a user: %s %s" % (e.errno, e.strerror))
            return False

        if os.WIFEXITED(status) and (os.WEXITSTATUS(status) == 0):
            return True
        else:
            return False

    def setUserPassword(self, username, password, isCrypted, lock, algo=None, root=None):
        childpid = os.fork()
        if root is not None:
            rootval = root
        else:
            rootval = iutil.getSysroot()

        if not childpid:
            if not rootval in ["","/"]:
                os.chroot(rootval)
                os.chdir("/")
                del(os.environ["LIBUSER_CONF"])

            self.admin = libuser.admin()
            try:
                user = self.admin.lookupUserByName(username)

                if isCrypted:
                    self.admin.setpassUser(user, password, True)
                else:
                    self.admin.setpassUser(user, cryptPassword(password, algo=algo), True)

                if lock:
                    self.admin.lockUser(user)

                self.admin.modifyUser(user)
                os._exit(0)
            except Exception as e:
                log.critical("Error when setting user password: %s" % str(e))
                os._exit(1)

        try:
            (pid, status) = os.waitpid(childpid, 0)
        except OSError as e:
            log.critical("exception from waitpid while creating a user: %s %s" % (e.errno, e.strerror))
            return False

        if os.WIFEXITED(status) and (os.WEXITSTATUS(status) == 0):
            return True
        else:
            return False

    def setRootPassword(self, password, isCrypted=False, isLocked=False, algo=None, root=None):
        return self.setUserPassword("root", password, isCrypted, isLocked, algo, root) def augmentEnv():
def _run_program(argv, root='/', stdin=None, stdout=None, env_prune=None, log_output=True, binary_output=False):
    def chroot():
def setSysroot(path):
def getSysroot():
def execInSysimageRoot(command, argv, **kwargs):
def execWithRedirect(command, argv, stdin=None, stdout=None,
                     stderr=None, root='/', env_prune=[], log_output=True, binary_output=False):
def execWithCapture(command, argv, stdin=None, stderr=None, root='/',
                    fatal=False, log_output=True):
def execReadlines(command, argv, stdin=None, root='/', env_prune=None):
    def queue_lines(out, queue):
    def chroot():
def execConsole():
def getDirSize(dir):
    def getSubdirSize(dir):
def mkdirChain(dir):
def get_active_console(dev="console"):
def isConsoleOnVirtualTerminal(dev="console"):
def strip_markup(text):
def reIPL(ipldev):
def resetRpmDb():
def parseNfsUrl(nfsurl):
def add_po_path(module, dir):
def setup_translations(module):
def fork_orphan():
def _run_systemctl(command, service):
def start_service(service):
def stop_service(service):
def restart_service(service):
def service_running(service):
def dracut_eject(device):
def vtActivate(num):
    def __init__(self, url=None, protocol="http://", host=None, port="3128",
                 username=None, password=None):
    def parse_url(self):
    def parse_components(self):
    def dict(self):
    def __str__(self):
def getdeepattr(obj, name):
def setdeepattr(obj, name, value):
def strip_accents(s):
def cmp_obj_attrs(obj1, obj2, attr_list):
def dir_tree_map(root, func, files=True, dirs=True):
def chown_dir_tree(root, uid, gid, from_uid_only=None, from_gid_only=None):
    def conditional_chown(path, uid, gid, from_uid=None, from_gid=None):
def is_unsupported_hw():
def upcase_first_letter(text):
    def __init__(self, **kwargs):
    def __getattr__(self, attr):
    def __setattr__(self, attr, value):
    def copy(self):
def get_mount_paths(devnode):
class ProxyStringError(Exception):
class ProxyString(object):
class DataHolder(dict): class Flags(object):
class BootArgs(OrderedDict):
    def __setattr__(self, attr, val):
    def get(self, attr, val=None):
    def set_cmdline_bool(self, flag):
    def __init__(self, read_cmdline=True):
    def read_cmdline(self):
    def __init__(self, cmdline=None, files=cmdline_files):
    def read(self, filenames):
    def readstr(self, cmdline):
    def getbool(self, arg, default=False):
def can_touch_runtime_system(msg): ETC_ZONES = ['GMT+1', 'GMT+2', 'GMT+3', 'GMT+4', 'GMT+5', 'GMT+6', 'GMT+7',
             'GMT+8', 'GMT+9', 'GMT+10', 'GMT+11', 'GMT+12',
             'GMT-1', 'GMT-2', 'GMT-3', 'GMT-4', 'GMT-5', 'GMT-6', 'GMT-7',
             'GMT-8', 'GMT-9', 'GMT-10', 'GMT-11', 'GMT-12', 'GMT-13',
             'GMT-14', 'UTC', 'GMT']
NTP_PACKAGE = "chrony"
NTP_SERVICE = "chronyd"
class TimezoneConfigError(Exception):
def time_initialize(timezone, storage, bootloader):
def write_timezone_config(timezone, root):
def save_hw_clock(timezone):
def get_preferred_timezone(territory):
def get_all_regions_and_timezones():
def is_valid_timezone(timezone): class ThreadManager(object):
class AnacondaThread(threading.Thread):
    def __init__(self):
    def __call__(self):
    def add(self, obj):
    def remove(self, name):
    def exists(self, name):
    def get(self, name):
    def wait(self, name):
    def wait_all(self):
    def set_error(self, name, *exc_info):
    def get_error(self, name):
    def any_errors(self):
    def raise_if_error(self, name):
    def in_main_thread(self):
    def running(self):
    def names(self):
    def __init__(self, *args, **kwargs):
    def run(self, *args, **kwargs):
def initThreading():
from pyanaconda.constants import ROOT_PATH, THREAD_PAYLOAD
from blivet import turnOnFilesystems
from pyanaconda.bootloader import writeBootLoader
from pyanaconda.progress import progress_report, progressQ
from pyanaconda.users import createLuserConf, getPassAlgo, Users
from pyanaconda import iutil
from pyanaconda import flags
from pyanaconda import timezone
from pyanaconda.i18n import _
from pyanaconda.threads import threadMgr
    from pyanaconda.kickstart import runPostScripts
    from pyanaconda.kickstart import runPostScripts
import logging
import blivet
    import os
# install.py
# Do the hard work of performing an installation.
#
# Copyright (C) 2012  Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
# Public License for more details.  You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.  Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
# Red Hat Author(s): Chris Lumens <clumens@redhat.com>
#

log = logging.getLogger("anaconda")

def _writeKS(ksdata):

    roothome = os.path.join(iutil.getSysroot(), "root")
    if os.path.islink(roothome) and not os.path.isdir(roothome):
        # In the OSTree case, /root -> /var/roothome, but
        # it doesn't exist yet.  If we created it here,
        # we'd need to ensure it was labeled correctly.
        # Punt on that for now and just stick it in /var.
        roothome = os.path.join(iutil.getSysroot(), "var")
    path = os.path.join(roothome, "anaconda-ks.cfg")

    # Clear out certain sensitive information that kickstart doesn't have a
    # way of representing encrypted.
    for obj in [ksdata.autopart] + ksdata.logvol.dataList() + \
               ksdata.partition.dataList() + ksdata.raid.dataList():
        obj.passphrase = ""

    with open(path, "w") as f:
        f.write(str(ksdata))

    # Make it so only root can read - could have passwords
    os.chmod(path, 0600)

def doConfiguration(storage, payload, ksdata, instClass):

    step_count = 6
    # if a realm was discovered,
    # increment the counter as the
    # real joining step will be executed
    if ksdata.realm.discovered:
        step_count += 1
    progressQ.send_init(step_count)

    # Now run the execute methods of ksdata that require an installed system
    # to be present first.
    with progress_report(_("Configuring installed system")):
        ksdata.authconfig.execute(storage, ksdata, instClass)
        ksdata.selinux.execute(storage, ksdata, instClass)
        ksdata.firstboot.execute(storage, ksdata, instClass)
        ksdata.services.execute(storage, ksdata, instClass)
        ksdata.keyboard.execute(storage, ksdata, instClass)
        ksdata.timezone.execute(storage, ksdata, instClass)
        ksdata.lang.execute(storage, ksdata, instClass)
        ksdata.firewall.execute(storage, ksdata, instClass)
        ksdata.xconfig.execute(storage, ksdata, instClass)
        ksdata.skipx.execute(storage, ksdata, instClass)

    if not flags.flags.imageInstall and not flags.flags.dirInstall:
        with progress_report(_("Writing network configuration")):
            ksdata.network.execute(storage, ksdata, instClass)

    # Creating users and groups requires some pre-configuration.
    with progress_report(_("Creating users")):

        createLuserConf(ROOT_PATH, algoname=getPassAlgo(ksdata.authconfig.authconfig))