Example #1
0
def write_vdsm_config(engineHost, enginePort):
    if not os.path.exists(VDSM_CONFIG):
        system("touch " + VDSM_CONFIG)
    if os.path.getsize(VDSM_CONFIG) == 0:
        set_defaults()
        ovirt_store_config(VDSM_CONFIG)
        log("@ENGINENAME@ agent configuration files created.")
    else:
        log("@ENGINENAME@ agent configuration files already exist.")

    if system("ping -c 1 " + engineHost):
        sed_cmd = "sed -i --copy \"s/\(^vdc_host_name=\)\(..*$\)/vdc_host_name=" + engineHost + "/\" " + VDSM_REG_CONFIG
        if system(sed_cmd):
            log("The @ENGINENAME@'s address is set: %s\n" % engineHost)
        if enginePort != "":
            sed_cmd = "sed -i --copy \"s/\(^vdc_host_port=\)\(..*$\)/vdc_host_port=" + str(
                enginePort) + "/\" " + VDSM_REG_CONFIG
            if system(sed_cmd):
                log("The @ENGINENAME@'s port set: %s\n" % enginePort)
            fWriteConfig = 1
    else:
        log("Either " + engineHost +
            " is an invalid address or the @ENGINENAME@ unresponsive.\n")
        return False

    if fWriteConfig == 1:
        log("Saving vdsm-reg.conf\n")
        if ovirt_store_config(VDSM_REG_CONFIG):
            log("vdsm-reg.conf Saved\n")
            return True
Example #2
0
def write_vdsm_config(engineHost, enginePort):
    if not os.path.exists(VDSM_CONFIG):
        system("touch " + VDSM_CONFIG)
    if os.path.getsize(VDSM_CONFIG) == 0:
        set_defaults()
        ovirt_store_config(VDSM_CONFIG)
        log("@ENGINENAME@ agent configuration files created.")
    else:
        log("@ENGINENAME@ agent configuration files already exist.")

    if system("ping -c 1 " + engineHost):
        sed_cmd = "sed -i --copy \"s/\(^vdc_host_name=\)\(..*$\)/vdc_host_name\
                =" + engineHost + "/\" " + VDSM_REG_CONFIG
        if system(sed_cmd):
            log("The @ENGINENAME@'s address is set: %s\n" % engineHost)
        if enginePort != "":
            sed_cmd = "sed -i --copy \"s/\(^vdc_host_port=\)\(..*$\)/vdc\
                _host_port=" + str(enginePort) + "/\" " + VDSM_REG_CONFIG
            if system(sed_cmd):
                log("The @ENGINENAME@'s port set: %s\n" % enginePort)
            fWriteConfig = 1
    else:
        log("Either " + engineHost + " is an invalid address \
            or the IMVP unresponsive.\n")
        return False

    if fWriteConfig == 1:
        log("Saving vdsm-reg.conf\n")
        if ovirt_store_config(VDSM_REG_CONFIG):
            log("vdsm-reg.conf Saved\n")
            return True
 def reread_partitions(self, drive):
     logger.debug("Rereading pt")
     _functions.system("sync")
     if "dev/mapper" in drive:
         # kpartx -a -p p "$drive"
         # XXX fails with spaces in device names (TBI)
         # ioctl(3, DM_TABLE_LOAD, 0x966980) = -1 EINVAL (Invalid argument)
         # create/reload failed on 0QEMU   QEMU HARDDISK  drive-scsi0-0-0p1
         _functions.system("kpartx -a '%s'" % drive)
         _functions.system("partprobe")
         # partprobe fails on cdrom:
         # Error: Invalid partition table - recursive partition on /dev/sr0.
         _functions.system("service multipathd reload")
         _functions.system("multipath -r &>/dev/null")
         # wait for device to exit
         i = 0
         timeout = 15
         while not os.path.exists(drive):
             logger.error(drive + " is not available, waiting %s more " +
                          "secs") % (timeout - i)
             i = i + i
             time.sleep(1)
             if i == timeout:
                 logger.error("Timed out waiting for: %s" % drive)
                 return False
     else:
         _functions.passthrough("blockdev --rereadpt \"%s\"" % drive, \
                                logger.debug)
Example #4
0
 def kdump_apply(self, obj):
     try:
         from ocsetup import ocs
     except ImportError:
         pass
     else:
         page = ocs.page_kernel_dump
         buttons = page.nfs_ssh_restore_custom.btns
         val = None
         for i in range(3):
             # i == 0 is NFS, i == 1 is SSH, i == 2 is RESTORE
             if buttons[i].get_active() and i == 0:
                 val = page.nfs_location_custom.entry.get_text()
             elif buttons[i].get_active() and i == 1:
                 val = page.ssh_location_custom.entry.get_text()
             elif buttons[i].get_active() and i == 2:
                 restore_kdump_config()
         if val:
             write_kdump_config(val)
             pb = ProgressBar()
             pb.make_progress(0.1)
             if '@' in val:
                 if os.path.exists("/usr/bin/kdumpctl"):
                     kdump_prop_cmd = "kdumpctl propagate"
                 else:
                     kdump_prop_cmd = "service kdump propagate"
                 from sshcmd import runcmd
                 runcmd(kdump_prop_cmd)
                 pb.make_progress(0.2)
                 if runcmd:
                     # SSH LOGIN SUCCESS.
                     ovirt_store_config("/root/.ssh/kdump_id_rsa.pub")
                     ovirt_store_config("/root/.ssh/kdump_id_rsa")
                     ovirt_store_config("/root/.ssh/known_hosts")
                     ovirt_store_config("/root/.ssh/config")
             pb.make_progress(0.5)
             system('servic kdump restart &')
             while True:
                 res = check_output('service kdump status')
                 if 'starting' not in res:
                     break
                 pb.make_progress(0.5)
                 time.sleep(3)
             pb.make_progress(0.8)
             if 'Kdump is not operational' in res:
                 # restart kdump Failed.
                 unmount_config("/etc/kdump.conf")
                 if os.path.exists("/etc/kdump.conf"):
                     os.remove("/etc/kdump.conf")
                 pb.make_progress(0, 'FAILED!')
                 pb.progress_label.set_label('FAILED!')
             elif 'Kdump is operational' in res:
                 ovirt_store_config("/etc/kdump.conf")
                 pb.make_progress(1, 'successful!')
             else:
                 log('kdump start Failed:' + res)
                 pb.make_progress(0, 'FAILED!')
                 pb.progress_label.set_label('FAILED!')
Example #5
0
 def kdump_apply(self, obj):
     try:
         from ocsetup import ocs
     except ImportError:
         pass
     else:
         page = ocs.page_kernel_dump
         buttons = page.nfs_ssh_restore_custom.btns
         val = None
         for i in range(3):
             # i == 0 is NFS, i == 1 is SSH, i == 2 is RESTORE
             if buttons[i].get_active() and i == 0:
                 val = page.nfs_location_custom.entry.get_text()
             elif buttons[i].get_active() and i == 1:
                 val = page.ssh_location_custom.entry.get_text()
             elif buttons[i].get_active() and i == 2:
                 restore_kdump_config()
         if val:
             write_kdump_config(val)
             pb = ProgressBar()
             pb.make_progress(0.1)
             if '@' in val:
                 if os.path.exists("/usr/bin/kdumpctl"):
                     kdump_prop_cmd = "kdumpctl propagate"
                 else:
                     kdump_prop_cmd = "service kdump propagate"
                 from sshcmd import runcmd
                 runcmd(kdump_prop_cmd)
                 pb.make_progress(0.2)
                 if runcmd:
                     # SSH LOGIN SUCCESS.
                     ovirt_store_config("/root/.ssh/kdump_id_rsa.pub")
                     ovirt_store_config("/root/.ssh/kdump_id_rsa")
                     ovirt_store_config("/root/.ssh/known_hosts")
                     ovirt_store_config("/root/.ssh/config")
             pb.make_progress(0.5)
             system('servic kdump restart &')
             while True:
                 res = check_output('service kdump status')
                 if 'starting' not in res:
                     break
                 pb.make_progress(0.5)
                 time.sleep(3)
             pb.make_progress(0.8)
             if 'Kdump is not operational' in res:
                 # restart kdump Failed.
                 unmount_config("/etc/kdump.conf")
                 if os.path.exists("/etc/kdump.conf"):
                     os.remove("/etc/kdump.conf")
                 pb.make_progress(0, 'FAILED!')
                 pb.progress_label.set_label('FAILED!')
             elif 'Kdump is operational' in res:
                 ovirt_store_config("/etc/kdump.conf")
                 pb.make_progress(1, 'successful!')
             else:
                 log('kdump start Failed:' + res)
                 pb.make_progress(0, 'FAILED!')
                 pb.progress_label.set_label('FAILED!')
Example #6
0
def enable_snmpd(password):
    _functions.system("service snmpd stop")
    # get old password #
    if os.path.exists("/tmp/snmpd.conf"):
        conf = "/tmp/snmpd.conf"
    else:
        conf = snmp_conf
    cmd = "cat %s|grep createUser|awk '{print $4}'" % conf
    oldpwd = _functions.subprocess_closefds(cmd, shell=True,
                                            stdout=subprocess.PIPE,
                                            stderr=subprocess.STDOUT)
    oldpwd = oldpwd.stdout.read().strip()
    _functions.system("sed -c -ie '/^createUser root/d' %s" % snmp_conf)
    f = open(snmp_conf, "a")
    # create user account
    f.write("createUser root SHA %s AES\n" % password)
    f.close()
    _functions.system("service snmpd start")
    # change existing password
    if len(oldpwd) > 0:
        pwd_change_cmd = ("snmpusm -v 3 -u root -n \"\" -l authNoPriv -a " +
        "SHA -A %s localhost passwd %s %s -x AES") % (oldpwd, oldpwd, password)
        if _functions.system(pwd_change_cmd):
            _functions.system("rm -rf /tmp/snmpd.conf")
    _functions.ovirt_store_config(snmp_conf)
Example #7
0
def enable_snmpd(password):
    _functions.system("service snmpd stop")
    # get old password #
    if os.path.exists("/tmp/snmpd.conf"):
        conf = "/tmp/snmpd.conf"
    else:
        conf = snmp_conf
    cmd = "cat %s|grep createUser|awk '{print $4}'" % conf
    oldpwd = _functions.subprocess_closefds(cmd,
                                            shell=True,
                                            stdout=subprocess.PIPE,
                                            stderr=subprocess.STDOUT)
    oldpwd = oldpwd.stdout.read().strip()
    _functions.system("sed -c -ie '/^createUser root/d' %s" % snmp_conf)
    f = open(snmp_conf, "a")
    # create user account
    f.write("createUser root SHA %s AES\n" % password)
    f.close()
    _functions.system("service snmpd start")
    # change existing password
    if len(oldpwd) > 0:
        pwd_change_cmd = ("snmpusm -v 3 -u root -n \"\" -l authNoPriv -a " +
                          "SHA -A %s localhost passwd %s %s -x AES") % (
                              oldpwd, oldpwd, password)
        if _functions.system(pwd_change_cmd):
            _functions.system("rm -rf /tmp/snmpd.conf")
    _functions.ovirt_store_config(snmp_conf)
Example #8
0
def convert_to_biosdevname():
    if not "BIOSDEVNAMES_CONVERSION" in OVIRT_VARS:
        # check for appropriate bios version
        cmd = "dmidecode|grep SMBIOS|awk {'print $2'}"
        proc = _functions.passthrough(cmd, log_func=logger.debug)
        ver = proc.stdout.split()[0]
        if not float(ver) >= 2.6:
            logger.debug("Skipping biosdevname conversion, SMBIOS too old")
            _functions.augtool(
                "set", "/files/etc/default/ovirt/BIOSDEVNAMES_CONVERSION", "y")
            return
        nics = {}
        cmd = "biosdevname -d"
        biosdevname, err = subprocess.Popen(
            cmd, shell=True, stdout=subprocess.PIPE).communicate()
        biosdevname_output = biosdevname.splitlines()

        for line in biosdevname_output:
            if line is not None:
                if "BIOS device:" in line:
                    nic = line.split()[2]
                if "Permanent" in line:
                    mac = line.split()[2]
                    nics[mac.upper()] = nic
        logger.debug(nics)
        scripts_path = "/etc/sysconfig/network-scripts"
        logger.debug(glob(scripts_path + "/ifcfg-*"))
        for file in glob(scripts_path + "/ifcfg-*"):
            logger.debug("Processing %s" % file)
            # get mac for matching
            existing_mac = _functions.augtool_get("/files/" + file + "/HWADDR")
            # check dictionary for mac
            if not existing_mac is None and existing_mac.upper() in nics:
                old_nic_script = os.path.basename(file)
                new_nic_name = nics[existing_mac.upper()]
                logger.debug("Found %s in %s" % (existing_mac, file))
                # change device name within script file
                logger.debug("Setting to new device name: %s" % new_nic_name)
                _functions.augtool("set", \
                                   "/files" + file + "/DEVICE", new_nic_name)
                new_nic_file = "%s/ifcfg-%s" % (scripts_path, new_nic_name)
                cmd = "cp %s %s" % (file, new_nic_file)
                _functions.remove_config(file)
                if _functions.system(cmd):
                    logging.debug("Conversion on %s to %s succeed" %
                                  (file, new_nic_file))
                    _functions.ovirt_store_config(new_nic_file)
                else:
                    return False
        _functions.system("service network restart")
        _functions.augtool("set", \
                       "/files/etc/default/ovirt/BIOSDEVNAMES_CONVERSION", "y")
        _functions.ovirt_store_config("/etc/default/ovirt")
    return True
Example #9
0
def convert_to_biosdevname():
    if not "BIOSDEVNAMES_CONVERSION" in OVIRT_VARS:
        # check for appropriate bios version
        cmd="dmidecode|grep SMBIOS|awk {'print $2'}"
        proc = _functions.passthrough(cmd, log_func=logger.debug)
        ver = proc.stdout.split()[0]
        if not float(ver) >= 2.6:
            logger.debug("Skipping biosdevname conversion, SMBIOS too old")
            _functions.augtool("set", "/files/etc/default/ovirt/BIOSDEVNAMES_CONVERSION", "y")
            return
        nics = {}
        cmd = "biosdevname -d"
        biosdevname, err = subprocess.Popen(cmd, shell=True,
                                          stdout=subprocess.PIPE).communicate()
        biosdevname_output = biosdevname.splitlines()

        for line in biosdevname_output:
            if line is not None:
                if "BIOS device:" in line:
                    nic = line.split()[2]
                if "Permanent" in line:
                    mac = line.split()[2]
                    nics[mac.upper()] = nic
        logger.debug(nics)
        scripts_path = "/etc/sysconfig/network-scripts"
        logger.debug(glob(scripts_path + "/ifcfg-*"))
        for file in glob(scripts_path + "/ifcfg-*"):
            logger.debug("Processing %s" % file)
            # get mac for matching
            existing_mac = _functions.augtool_get("/files/" + file + "/HWADDR")
            # check dictionary for mac
            if not existing_mac is None and existing_mac.upper() in nics:
                old_nic_script = os.path.basename(file)
                new_nic_name = nics[existing_mac.upper()]
                logger.debug("Found %s in %s" % (existing_mac, file))
                # change device name within script file
                logger.debug("Setting to new device name: %s" % new_nic_name)
                _functions.augtool("set", \
                                   "/files" + file + "/DEVICE", new_nic_name)
                new_nic_file = "%s/ifcfg-%s" % (scripts_path, new_nic_name)
                cmd = "cp %s %s" % (file, new_nic_file)
                _functions.remove_config(file)
                if _functions.system(cmd):
                    logging.debug("Conversion on %s to %s succeed" % (file,
                                  new_nic_file))
                    _functions.ovirt_store_config(new_nic_file)
                else:
                    return False
        _functions.system("service network restart")
        _functions.augtool("set", \
                       "/files/etc/default/ovirt/BIOSDEVNAMES_CONVERSION", "y")
        _functions.ovirt_store_config("/etc/default/ovirt")
    return True
 def wipe_lvm_on_disk(self, _devs):
     devs = set(_devs.split(","))
     logger.debug("Considering to wipe LVM on: %s / %s" % (_devs, devs))
     for dev in devs:
         logger.debug("Considering device '%s'" % dev)
         if not os.path.exists(dev):
             logger.info("'%s' is no device, let's try the next one." % dev)
             continue
         part_delim = "p"
         # FIXME this should be more intelligent
         if "/dev/sd" in dev or "dev/vd" in dev:
             part_delim = ""
         vg_cmd = ("pvs -o vg_uuid --noheadings \"%s\" \"%s%s\"[0-9]* " +
                   "2>/dev/null | sort -u") % (dev, dev, part_delim)
         vg_proc = _functions.passthrough(vg_cmd, log_func=logger.debug)
         vgs_on_dev = vg_proc.stdout.split()
         for vg in vgs_on_dev:
             name = self._lvm_name_for_disk(dev)
             pvs_cmd = ("pvs -o pv_name,vg_uuid --noheadings | " +
                        "grep \"%s\" | egrep -v -q \"%s" % (vg, name))
             for fdev in devs:
                 pvs_cmd += "|%s%s[0-9]+|%s" % (fdev, part_delim, fdev)
                 name = self._lvm_name_for_disk(fdev)
                 pvs_cmd += "|%s%s[0-9]+|%s" % (name, part_delim, name)
             pvs_cmd += "\""
             remaining_pvs = _functions.system(pvs_cmd)
             if remaining_pvs:
                 logger.error("The volume group \"%s\" spans multiple " +
                              "disks.") % vg
                 logger.error("This operation cannot complete.  " +
                              "Please manually cleanup the storage using " +
                              "standard disk tools.")
                 return False
             _functions.wipe_volume_group(vg)
     return True
Example #11
0
def set_nfsv4_domain(domain):
    idmap_conf = "/etc/idmapd.conf"
    current_domain = get_current_nfsv4_domain()
    _functions.unmount_config(idmap_conf)
    if current_domain.startswith("#"):
        current_domain = "#Domain = %s" % current_domain.replace("# ","")
        _functions.system("sed -i 's/%s/Domain = %s/g' %s" \
            % (current_domain, domain, idmap_conf))
    else:
        _functions.system("sed -i '/^Domain/ s/%s/%s/g' %s" \
            % (current_domain, domain, idmap_conf))
    if _functions.ovirt_store_config(idmap_conf):
        logger.info("NFSv4 domain set as: " + domain)
    else:
        logger.warning("Setting nfsv4 domain failed")
    _functions.system_closefds("service rpcidmapd restart")
    _functions.system_closefds("nfsidmap -c &>/dev/null")
Example #12
0
def set_nfsv4_domain(domain):
    idmap_conf = "/etc/idmapd.conf"
    current_domain = get_current_nfsv4_domain()
    _functions.unmount_config(idmap_conf)
    if current_domain.startswith("#"):
        current_domain = "#Domain = %s" % current_domain.replace("# ", "")
        _functions.system("sed -i 's/%s/Domain = %s/g' %s" \
            % (current_domain, domain, idmap_conf))
    else:
        _functions.system("sed -i 's/%s/%s/g' %s" \
            % (current_domain, domain, idmap_conf))
    if _functions.ovirt_store_config(idmap_conf):
        logger.info("NFSv4 domain set as: " + domain)
    else:
        logger.warning("Setting nfsv4 domain failed")
    _functions.system_closefds("service rpcidmapd restart")
    _functions.system_closefds("nfsidmap -c &>/dev/null")
Example #13
0
 def kernel_image_copy(self):
     if (not _functions.system("cp -p /live/" + self.syslinux + \
                              "/vmlinuz0 " + self.initrd_dest)):
         logger.error("kernel image copy failed.")
         return False
     if (not _functions.system("cp -p /live/" + self.syslinux + \
                              "/initrd0.img " + self.initrd_dest)):
         logger.error("initrd image copy failed.")
         return False
     if (not _functions.system("cp -p /live/" + self.syslinux + \
                              "/version /liveos")):
         logger.error("version details copy failed.")
         return False
     if (not _functions.system("cp -p /live/LiveOS/squashfs.img " + \
                               "/liveos/LiveOS")):
         logger.error("squashfs image copy failed.")
         return False
     return True
Example #14
0
 def kernel_image_copy(self):
     if (not _functions.system("cp -p /live/" + self.syslinux + \
                              "/vmlinuz0 " + self.initrd_dest)):
         logger.error("kernel image copy failed.")
         return False
     if (not _functions.system("cp -p /live/" + self.syslinux + \
                              "/initrd0.img " + self.initrd_dest)):
         logger.error("initrd image copy failed.")
         return False
     if (not _functions.system("cp -p /live/" + self.syslinux + \
                              "/version /liveos")):
         logger.error("version details copy failed.")
         return False
     if (not _functions.system("cp -p /live/LiveOS/squashfs.img " + \
                               "/liveos/LiveOS")):
         logger.error("squashfs image copy failed.")
         return False
     return True
Example #15
0
 def kernel_image_copy(self):
     if (not _functions.system("cp -p %s/vmlinuz0 %s" % \
                              (self.live_path, self.initrd_dest))):
         logger.error("kernel image copy failed.")
         return False
     if (not _functions.system("cp -p %s/initrd0.img %s" % \
                              (self.live_path, self.initrd_dest))):
         logger.error("initrd image copy failed.")
         return False
     if (not _functions.system("cp -p %s/version /liveos" \
                               % self.live_path)):
         logger.error("version details copy failed.")
         return False
     if (not _functions.system("cp %s/LiveOS/squashfs.img /liveos/LiveOS" \
                               % os.path.split(self.live_path)[0])):
         logger.error("squashfs image copy failed.")
         return False
     return True
Example #16
0
 def kernel_image_copy(self):
     if (not _functions.system("cp -p %s/vmlinuz0 %s" % \
                              (self.live_path, self.initrd_dest))):
         logger.error("kernel image copy failed.")
         return False
     if (not _functions.system("cp -p %s/initrd0.img %s" % \
                              (self.live_path, self.initrd_dest))):
         logger.error("initrd image copy failed.")
         return False
     if (not _functions.system("cp -p %s/version /liveos" \
                               % self.live_path)):
         logger.error("version details copy failed.")
         return False
     if (not _functions.system("cp %s/LiveOS/squashfs.img /liveos/LiveOS" \
                               % os.path.split(self.live_path)[0])):
         logger.error("squashfs image copy failed.")
         return False
     return True
Example #17
0
 def create_efi_partition(self):
     if _functions.is_iscsi_install():
         disk = self.BOOTDRIVE
     else:
         disk = self.ROOTDRIVE
     parted_cmd = ("parted \"" + disk + "\" -s \"mkpart EFI 1M " +
                   str(self.EFI_SIZE) + "M\"")
     _functions.system(parted_cmd)
     partefi = disk + "1"
     if not os.path.exists(partefi):
         partefi = disk + "p1"
         _functions.system("ln -snf \"" + partefi + \
                           "\" /dev/disk/by-label/EFI")
         _functions.system("mkfs.vfat \"" + partefi + "\"")
Example #18
0
 def create_efi_partition(self):
     if _functions.is_iscsi_install():
         disk = self.BOOTDRIVE
     else:
         disk = self.ROOTDRIVE
     parted_cmd = ("parted \"" + disk +
                  "\" -s \"mkpart EFI 1M " +
                  str(self.EFI_SIZE) + "M\"")
     _functions.system(parted_cmd)
     partefi = disk + "1"
     if not os.path.exists(partefi):
         partefi = disk + "p1"
         _functions.system("ln -snf \"" + partefi + \
                           "\" /dev/disk/by-label/EFI")
         _functions.system("mkfs.vfat \"" + partefi + "\"")
Example #19
0
 def reread_partitions(self, drive):
     logger.debug("Rereading pt")
     _functions.system("sync")
     if "dev/mapper" in drive:
         _functions.system("service multipathd reload")
         _functions.system("multipath -r &>/dev/null")
         # wait for device to exit
         i = 0
         timeout = 15
         while not os.path.exists(drive):
             logger.error(drive + " is not available, waiting %s more " +
                          "secs") % (timeout - i)
             i = i + i
             time.sleep(1)
             if i == timeout:
                 logger.error("Timed out waiting for: %s" % drive)
                 return False
     else:
         _functions.passthrough("blockdev --rereadpt \"%s\"" % drive, \
                                logger.debug)
Example #20
0
    def ovirt_boot_setup(self, reboot="N"):
        self.generate_paths()
        logger.info("Installing the image.")
        # copy grub.efi to safe location
        if _functions.is_efi_boot():
            if "OVIRT_ISCSI_INSTALL" in OVIRT_VARS:
                _functions.system("umount /boot")
            if os.path.isfile("/boot/efi/%s/grubx64.efi" % self.efi_path):
                shutil.copy("/boot/efi/%s/grubx64.efi" % self.efi_path, "/tmp")
            else:
                shutil.copy("/boot/efi/%s/grub.efi" % self.efi_path, "/tmp")
            _functions.mount_boot()
        if "OVIRT_ROOT_INSTALL" in OVIRT_VARS:
            if OVIRT_VARS["OVIRT_ROOT_INSTALL"] == "n":
                logger.info("Root Installation Not Required, Finished.")
                return True
        self.oldtitle=None
        grub_config_file = None
        if _functions.findfs("Boot") and _functions.is_upgrade():
            grub_config_file = "/boot/grub/grub.conf"
            if not _functions.connect_iscsi_root():
                return False
        _functions.mount_liveos()
        if os.path.ismount("/liveos"):
            if os.path.exists("/liveos/vmlinuz0") \
                              and os.path.exists("/liveos/initrd0.img"):
                grub_config_file = self.grub_config_file
        elif not _functions.is_firstboot():
            # find existing iscsi install
            if _functions.findfs("Boot"):
                grub_config_file = "/boot/grub/grub.conf"
            elif os.path.ismount("/dev/.initramfs/live"):
                if not _functions.grub2_available():
                    grub_config_file = "/dev/.initramfs/live/grub/grub.conf"
                else:
                    grub_config_file = "/dev/.initramfs/live/grub2/grub.cfg"
            elif os.path.ismount("/run/initramfs/live"):
                grub_config_file = "/run/initramfs/live/grub/grub.conf"
            if _functions.is_upgrade() and not _functions.is_iscsi_install():
                _functions.mount_liveos()
                grub_config_file = "/liveos/grub/grub.conf"
        if _functions.is_iscsi_install() or _functions.findfs("Boot") \
            and not _functions.is_efi_boot():
            grub_config_file = "/boot/grub/grub.conf"
        if _functions.is_efi_boot():
            logger.debug(str(os.listdir("/liveos")))
            _functions.system("umount /liveos")
            _functions.mount_efi(target="/liveos")
            if self.efi_name == "fedora":
                grub_config_file = "/liveos/EFI/fedora/grub.cfg"
            else:
                grub_config_file = "/liveos/%s/grub.conf" % self.efi_path
        grub_config_file_exists = grub_config_file is not None \
            and os.path.exists(grub_config_file)
        logger.debug("Grub config file is: %s" % grub_config_file)
        logger.debug("Grub config file exists: %s" % grub_config_file_exists)
        if not grub_config_file is None and os.path.exists(grub_config_file):
            f=open(grub_config_file)
            oldgrub=f.read()
            f.close()
            if _functions.grub2_available():
                m=re.search("^menuentry (.*)$", oldgrub, re.MULTILINE)
            else:
                m=re.search("^title (.*)$", oldgrub, re.MULTILINE)
            if m is not None:
                self.oldtitle=m.group(1)
                # strip off extra title characters
                if _functions.grub2_available():
                    self.oldtitle = self.oldtitle.replace('"','').strip(" {")
        _functions.system("umount /liveos/efi")
        _functions.system("umount /liveos")
        if _functions.is_iscsi_install() or _functions.findfs("Boot"):
            self.boot_candidate = None
            boot_candidate_names = ["BootBackup", "BootUpdate", "BootNew"]
            for trial in range(1, 3):
                time.sleep(1)
                for candidate_name in boot_candidate_names:
                    logger.debug(os.listdir("/dev/disk/by-label"))
                    if _functions.findfs(candidate_name):
                        self.boot_candidate = candidate_name
                        break
                logger.debug("Trial %s to find candidate (%s)" % \
                             (trial, candidate_name))
                if self.boot_candidate:
                    logger.debug("Found candidate: %s" % self.boot_candidate)
                    break

            if not self.boot_candidate:
                logger.error("Unable to find boot partition")
                label_debug = ''
                for label in os.listdir("/dev/disk/by-label"):
                    label_debug += "%s\n" % label
                label_debug += _functions.subprocess_closefds("blkid", \
                                          shell=True, stdout=subprocess.PIPE,
                                          stderr=subprocess.STDOUT).stdout.read()
                logger.debug(label_debug)
                return False
            else:
                boot_candidate_dev = _functions.findfs(self.boot_candidate)
            # prepare Root partition update
            if self.boot_candidate != "BootNew":
                e2label_cmd = "e2label \"%s\" BootNew" % boot_candidate_dev
                logger.debug(e2label_cmd)
                if not _functions.system(e2label_cmd):
                    logger.error("Failed to label new Boot partition")
                    return False
            _functions.system("umount /boot")
            _functions.system("mount %s /boot &>/dev/null" \
                              % boot_candidate_dev)

        candidate = None
        candidate_dev = None
        candidate_names = ["RootBackup", "RootUpdate", "RootNew"]
        for trial in range(1, 3):
            time.sleep(1)
            for candidate_name in candidate_names:
                candidate_dev = _functions.findfs(candidate_name)
                logger.debug("Finding %s: '%s'" % (candidate_name, candidate_dev))
                if candidate_dev:
                    candidate = candidate_name
                    logger.debug("Found: %s" % candidate)
                    break
            logger.debug("Trial %s to find candidate (%s)" % (trial,
                                                              candidate_name))
            if candidate:
                logger.debug("Found candidate: '%s'" % candidate)
                break

        if not candidate:
            logger.error("Unable to find root partition")
            label_debug = ''
            for label in os.listdir("/dev/disk/by-label"):
                label_debug += "%s\n" % label
            label_debug += _functions.subprocess_closefds("blkid", shell=True,
                                      stdout=subprocess.PIPE,
                                      stderr=subprocess.STDOUT).stdout.read()
            logger.debug(label_debug)
            return False

        try:
            self.disk = candidate_dev
            logger.info("Candidate device: %s" % candidate_dev)
            logger.info("Candidate disk: %s" % self.disk)
            # grub2 starts at part 1
            self.partN = int(self.disk[-1:])
            if not _functions.grub2_available():
                self.partN = self.partN - 1
        except:
            logger.debug("Failed to get partition", exc_info=True)
            return False

        if self.disk is None or self.partN < 0:
            logger.error("Failed to determine Root partition number")
            return False
        # prepare Root partition update
        if candidate != "RootNew":
            e2label_cmd = "e2label \"%s\" RootNew" % candidate_dev
            logger.debug(e2label_cmd)
            if not _functions.system(e2label_cmd):
                logger.error("Failed to label new Root partition")
                return False
        mount_cmd = "mount \"%s\" /liveos" % candidate_dev
        if not _functions.system(mount_cmd):
            logger.error("Failed to mount %s on /liveos" % candidate_dev)
            _functions.system("lsof")
            _functions.system("dmsetup info -c")
            _functions.system("cat /proc/mounts")
            _functions.system("multipath -ll")
            _functions.system("lsblk")
            _functions.system("ls -l /dev/mapper")
        _functions.system("rm -rf /liveos/LiveOS")
        _functions.system("mkdir -p /liveos/LiveOS")
        _functions.mount_live()

        if os.path.isdir(self.grub_dir):
            shutil.rmtree(self.grub_dir)
        if not os.path.exists(self.grub_dir):
            os.makedirs(self.grub_dir)
            if _functions.is_efi_boot():
                logger.info("efi detected, installing efi configuration")
                _functions.system("mkdir /liveos/efi")
                _functions.mount_efi()
                _functions.system("mkdir -p /liveos/efi/%s" % self.efi_path)
                if _functions.is_iscsi_install() or _functions.is_efi_boot():
                    if os.path.isfile("/tmp/grubx64.efi"):
                        shutil.copy("/tmp/grubx64.efi",
                                    "/liveos/efi/%s/grubx64.efi" %
                                    self.efi_path)
                    else:
                        shutil.copy("/tmp/grub.efi",
                                    "/liveos/efi/%s/grub.efi" % self.efi_path)
                elif os.path.isfile("/boot/efi/%s/grubx64.efi" %
                        self.efi_path):
                    shutil.copy("/boot/efi/%s/grubx64.efi" % self.efi_path,
                          "/liveos/efi/%s/grubx64.efi" % self.efi_path)
                else:
                    shutil.copy("/boot/efi/%s/grub.efi" % self.efi_path,
                          "/liveos/efi/%s/grub.efi" % self.efi_path)
                if _functions.is_iscsi_install() or _functions.findfs("BootNew"):
                    self.disk = _functions.findfs("BootNew")
                if not "/dev/mapper/" in self.disk:
                    efi_disk = self.disk[:-1]
                else:
                    efi_disk = re.sub(r'p?[1,2,3]$', "", self.disk)
                # generate grub legacy config for efi partition
                #remove existing efi entries
                _functions.remove_efi_entry(_functions.PRODUCT_SHORT)
                if self.efi_name == "fedora":
                    _functions.add_efi_entry(_functions.PRODUCT_SHORT,
                                             ("\\EFI\\%s\\grubx64.efi" %
                                              self.efi_name),
                                             efi_disk)
                else:
                    if os.path.isfile("/liveos/efi/%s/grubx64.efi" %
                            self.efi_path):
                        _functions.add_efi_entry(_functions.PRODUCT_SHORT,
                                                 ("\\EFI\\%s\\grubx64.efi" %
                                                  self.efi_name),
                                                 efi_disk)
                    else:
                        _functions.add_efi_entry(_functions.PRODUCT_SHORT,
                                                 ("\\EFI\\%s\\grub.efi" %
                                                  self.efi_name),
                                                 efi_disk)
        self.kernel_image_copy()

        # reorder tty0 to allow both serial and phys console after installation
        if _functions.is_iscsi_install() or _functions.findfs("BootNew"):
            self.root_param = "root=live:LABEL=Root"
            if "OVIRT_NETWORK_LAYOUT" in OVIRT_VARS and \
                OVIRT_VARS["OVIRT_NETWORK_LAYOUT"] == "bridged":
                network_conf = "ip=br%s:dhcp bridge=br%s:%s" % \
                                (OVIRT_VARS["OVIRT_BOOTIF"],
                                 OVIRT_VARS["OVIRT_BOOTIF"],
                                 OVIRT_VARS["OVIRT_BOOTIF"])
            else:
                network_conf = "ip=%s:dhcp" % OVIRT_VARS["OVIRT_BOOTIF"]
            self.bootparams = "netroot=iscsi:%s::%s::%s %s " % (
                OVIRT_VARS["OVIRT_ISCSI_TARGET_HOST"],
                OVIRT_VARS["OVIRT_ISCSI_TARGET_PORT"],
                OVIRT_VARS["OVIRT_ISCSI_TARGET_NAME"],
                network_conf)
            if "OVIRT_ISCSI_NAME" in OVIRT_VARS:
                self.bootparams+= "iscsi_initiator=%s " % \
                    OVIRT_VARS["OVIRT_ISCSI_NAME"]
        else:
            self.root_param = "root=live:LABEL=Root"
            self.bootparams = "ro rootfstype=auto rootflags=ro "
        self.bootparams += OVIRT_VARS["OVIRT_BOOTPARAMS"].replace(
                                                            "console=tty0", ""
                                                            ).replace(
                                                            "rd_NO_MULTIPATH",
                                                            "")

        if " " in self.disk:
            # workaround for grub setup failing with spaces in dev.name:
            # use first active sd* device
            self.disk = re.sub("p[1,2,3]$", "", self.disk)
            grub_disk_cmd = ("multipath -l " +
                             "\"" + self.disk + "\" " +
                             "| egrep -o '[0-9]+:.*' " +
                             "| awk '/ active / {print $2}' " +
                             "| head -n1")
            logger.debug(grub_disk_cmd)
            grub_disk = _functions.subprocess_closefds(grub_disk_cmd,
                                            shell=True,
                                            stdout=subprocess.PIPE,
                                            stderr=subprocess.STDOUT)
            grub_disk_output, grub_disk_err = grub_disk.communicate()
            self.disk = grub_disk_output.strip()
            if "cciss" in self.disk:
                self.disk = self.disk.replace("!", "/")
            # flush to sync DM and blockdev, workaround from rhbz#623846#c14
            sysfs = open("/proc/sys/vm/drop_caches", "w")
            sysfs.write("3")
            sysfs.close()
        if not self.disk.startswith("/dev/"):
            self.disk = "/dev/" + self.disk
        try:
            if stat.S_ISBLK(os.stat(self.disk).st_mode):
                try:
                    if stat.S_ISBLK(os.stat(self.disk[:-1]).st_mode):
                        # e.g. /dev/sda2
                        self.disk = self.disk[:-1]
                except OSError:
                    pass
                try:
                    if stat.S_ISBLK(os.stat(self.disk[:-2]).st_mode):
                        # e.g. /dev/mapper/WWIDp2
                        self.disk = self.disk[:-2]
                except OSError:
                    pass
        except OSError:
            logger.error("Unable to determine disk for grub installation " +
                         traceback.format_exc())
            return False

        self.grub_dict = {
        "product": _functions.PRODUCT_SHORT,
        "version": _functions.PRODUCT_VERSION,
        "release": _functions.PRODUCT_RELEASE,
        "partN": self.partN,
        "root_param": self.root_param,
        "bootparams": self.bootparams,
        "disk": self.disk,
        "grub_dir": self.grub_dir,
        "grub_prefix": self.grub_prefix,
        "efi_hd": self.efi_hd,
        "linux": "linux",
        "initrd": "initrd",
    }
        if not _functions.is_firstboot():
            if os.path.ismount("/live"):
                with open("%s/version" % self.live_path) as version:
                    for line in version.readlines():
                        if "VERSION" in line:
                            key, value = line.split("=")
                            self.grub_dict["version"] = value.strip()
                        if "RELEASE" in line:
                            key, value = line.split("=")
                            self.grub_dict["release"] = value.strip()

        if _functions.grub2_available():
            if not self.grub2_install():
                logger.error("Grub2 Installation Failed ")
                return False
            else:
                 logger.info("Grub2 EFI Installation Completed ")
        else:
            if not self.grub_install():
                logger.error("Grub Installation Failed ")
                return False
            else:
                logger.info("Grub Installation Completed")

        if _functions.is_iscsi_install() or _functions.findfs("BootNew"):
            # copy default for when Root/HostVG is inaccessible(iscsi upgrade)
            shutil.copy(_functions.OVIRT_DEFAULTS, "/boot")
            # mark new Boot ready to go, reboot() in ovirt-function switches it
            # to active
            e2label_cmd = "e2label \"%s\" BootUpdate" % boot_candidate_dev

            if not _functions.system(e2label_cmd):
                logger.error("Unable to relabel " + boot_candidate_dev +
                             " to RootUpdate ")
                return False
        else:
            _functions.system("umount /liveos/efi")
        _functions.system("umount /liveos")
        # mark new Root ready to go, reboot() in ovirt-function switches it
        # to active
        e2label_cmd = "e2label \"%s\" RootUpdate" % candidate_dev
        if not _functions.system(e2label_cmd):
            logger.error("Unable to relabel " + candidate_dev +
                         " to RootUpdate ")
            return False
        _functions.system("udevadm settle --timeout=10")

        #
        # Rebuild the initramfs
        # A few hacks are needed to prep the chroot
        # The general issue is that we need to run dracut in the context fo the new iso
        # and that we need to put the initrd in the right place of the new iso.
        # These two things make the logic a bit more complicated.
        #
        mnts = []
        try:
            if not _functions.system("blkid -L RootUpdate"):
                raise RuntimeError("RootUpdate not found")

            # Let's mount the update fs, and use that kernel version and modules
            # We need this work to help dracut
            isomnt = tempfile.mkdtemp("RootUpdate")
            squashmnt = tempfile.mkdtemp("RootUpdate-LiveOS")
            updfs = tempfile.mkdtemp("RootUpdate-LiveOS-Img")
            mnts += [isomnt, squashmnt, updfs]

            # Unpack the iso
            def _call(args):
                logger.debug("Calling: %s" % args)
                try:
                    out = subprocess.check_output(args)
                    logger.debug("Out: %s" % out)
                except Exception as e:
                    logger.debug("Failed with: %s %s" % (e, e.output))
                    raise

            _call(["mount", "LABEL=RootUpdate", isomnt])
            _call(["mount", "%s/LiveOS/squashfs.img" % isomnt, squashmnt])
            _call(["mount", "%s/LiveOS/ext3fs.img" % squashmnt, updfs])

            # Now mount the update modules into place, and find the
            # correct kver
            def rbind(path, updfs=updfs):
                dst = updfs + "/" + path
                logger.debug("Binding %r to %r" % (path, dst))
                _call(["mount", "--make-rshared", "--rbind", "/" + path, dst])
                return dst

            for path in ["etc", "dev", "proc", "sys", "tmp", "run", "var/tmp"]:
                mnts += [rbind(path)]

            upd_kver = str(_functions.passthrough("ls -1 %s/lib/modules" % updfs)).strip()

            if len(upd_kver.splitlines()) != 1:
                # It would be very unusual to see more than one kver directory
                # in /lib/modules, because our images just contain one kernel
                raise RuntimeError("Found more than one kernel version")

            # Update initramfs to pickup multipath wwids
            # Let /boot point to the filesystem on the update candidate partition
            builder = _system.Initramfs(dracut_chroot=updfs, boot_source=isomnt)
            builder.rebuild(kver=upd_kver)

        except Exception as e:
            logger.debug("Failed to build initramfs: %s" % e, exc_info=True)
            output = getattr(e, "output", "")
            if output:
                logger.debug("Output: %s" % output)
            raise


        finally:
            # Clean up all eventual mounts
            pass
            # Disabled for now because akward things happen, we leave it to
            # systemd to unnmount on reboot
            # for mnt in reversed(mnts):
            #     d = _functions.passthrough("umount -fl %s" % mnt, logger.debug)
            #     logger.debug("Returned: %s" % d)

        _functions.disable_firstboot()
        if _functions.finish_install():
            if _functions.is_firstboot():
                _iscsi.iscsi_auto()
            logger.info("Installation of %s Completed" % \
                                                      _functions.PRODUCT_SHORT)
            if reboot is not None and reboot == "Y":
                _system.async_reboot()
            return True
        else:
            return False
    def perform_partitioning(self):
        if self.HOSTVGDRIVE is None and not _functions.is_iscsi_install():
            logger.error("\nNo storage device selected.")
            return False

        if self.BOOTDRIVE is None and _functions.is_iscsi_install():
            logger.error("No storage device selected.")
            return False

        if not self.cross_check_host_app():
            logger.error("Skip disk partitioning, AppVG overlaps with HostVG")
            return False

        if _functions.has_fakeraid(self.HOSTVGDRIVE):
            if not handle_fakeraid(self.HOSTVGDRIVE):
                return False
        if _functions.has_fakeraid(self.ROOTDRIVE):
            if not handle_fakeraid(self.ROOTDRIVE):
                return False

        logger.info("Saving parameters")
        _functions.unmount_config("/etc/default/ovirt")
        if not self.check_partition_sizes():
            return False

        # Check for still remaining HostVGs this can be the case when
        # Node was installed on a disk not given in storage_init
        # rhbz#872114
        existing_vgs = str(_functions.passthrough("vgs"))
        for vg in existing_vgs.split("\n"):
            vg = vg.strip()
            if "HostVG" in str(vg):
                logger.error("An existing installation was found or not " +
                     "all VGs could be removed.  " +
                     "Please manually cleanup the storage using " +
                     "standard disk tools.")
                return False

        logger.info("Removing old LVM partitions")
        # HostVG must not exist at this point
        # we wipe only foreign LVM here
        logger.info("Wiping LVM on HOSTVGDRIVE %s" % self.HOSTVGDRIVE)
        if not self.wipe_lvm_on_disk(self.HOSTVGDRIVE):
            logger.error("Wiping LVM on %s Failed" % self.HOSTVGDRIVE)
            return False
        logger.info("Wiping LVM on ROOTDRIVE %s" % self.ROOTDRIVE)
        if not self.wipe_lvm_on_disk(self.ROOTDRIVE):
            logger.error("Wiping LVM on %s Failed" % self.ROOTDRIVE)
            return False
        logger.info("Wiping LVM on BOOTDRIVE %s" % self.BOOTDRIVE)
        if not self.wipe_lvm_on_disk(self.BOOTDRIVE):
            logger.error("Wiping LVM on %s Failed" % self.BOOTDRIVE)
            return False
        logger.debug("Old LVM partitions should be gone.")
        logger.debug(_functions.passthrough("vgdisplay -v"))

        self.boot_size_si = self.BOOT_SIZE * (1024 * 1024) / (1000 * 1000)
        if _functions.is_iscsi_install():
            if "OVIRT_ISCSI_NAME" in _functions.OVIRT_VARS:
                iscsi_name = _functions.OVIRT_VARS["OVIRT_ISCSI_NAME"]
                set_iscsi_initiator(iscsi_name)
            # login to target and setup disk
            get_targets = ("iscsiadm -m discovery -p %s:%s -t sendtargets" %
                           (_functions.OVIRT_VARS["OVIRT_ISCSI_TARGET_HOST"],
                           _functions.OVIRT_VARS["OVIRT_ISCSI_TARGET_PORT"]))
            _functions.system(get_targets)
            before_login_drvs = self.get_dev_name()
            logger.debug(before_login_drvs)
            login_cmd = ("iscsiadm -m node -T %s -p %s:%s -l" %
                        (_functions.OVIRT_VARS["OVIRT_ISCSI_TARGET_NAME"],
                        _functions.OVIRT_VARS["OVIRT_ISCSI_TARGET_HOST"],
                        _functions.OVIRT_VARS["OVIRT_ISCSI_TARGET_PORT"]))
            _functions.system(login_cmd)
            _functions.system("multipath -r")
            after_login_drvs = self.get_dev_name()
            logger.debug(after_login_drvs)
            logger.info("iSCSI enabled, partitioning boot drive: %s" %
                        self.BOOTDRIVE)
            _functions.wipe_partitions(self.BOOTDRIVE)
            self.reread_partitions(self.BOOTDRIVE)
            logger.info("Creating boot partition")
            parted_cmd = "parted %s -s \"mklabel %s\"" % (self.BOOTDRIVE,
                                                          self.LABEL_TYPE)
            _functions.system(parted_cmd)
            self.create_efi_partition()
            boot_end_mb = self.EFI_SIZE + self.BOOT_SIZE
            parted_cmd = ("parted \"%s\" -s \"mkpart primary ext2 %sM %sM\"" %
                         (self.BOOTDRIVE, self.EFI_SIZE, boot_end_mb))
            _functions.system(parted_cmd)
            parted_cmd = ("parted \"%s\" -s \"mkpart primary ext2 %sM %sM\"" %
                         (self.BOOTDRIVE , boot_end_mb, boot_end_mb + self.BOOT_SIZE))
            _functions.system(parted_cmd)
            parted_cmd = ("parted \"" + self.BOOTDRIVE + "\" -s \"set 1 " +
                         "boot on\"")
            _functions.system(parted_cmd)
            self.reread_partitions(self.BOOTDRIVE)
            partboot = self.BOOTDRIVE + "2"
            partbootbackup = self.BOOTDRIVE + "3"

            if not os.path.exists(partboot):
                logger.debug("%s does not exist" % partboot)
                partboot = self.BOOTDRIVE + "p2"
                partbootbackup = self.BOOTDRIVE + "p3"

            # sleep to ensure filesystems are created before continuing
            _functions.system("udevadm settle")
            _functions.system("mke2fs \"" + str(partboot) + "\" -L Boot")
            _functions.system("tune2fs -c 0 -i 0 \"" + str(partboot) + "\"")
            _functions.system("ln -snf \"" + partboot + \
                              "\" /dev/disk/by-label/Boot")
            _functions.system("mke2fs \"" + str(partbootbackup) + \
                              "\" -L BootBackup")
            _functions.system("tune2fs -c 0 -i 0 \"" + \
                              str(partbootbackup) + "\"")
            _functions.system("ln -snf \"" + partbootbackup +
                   "\" /dev/disk/by-label/BootBackup")
            self.ISCSIDRIVE = _functions.translate_multipath_device(
                               _functions.OVIRT_VARS["OVIRT_ISCSI_INIT"])
            logger.debug(self.ISCSIDRIVE)
            if self.create_iscsiroot():
                logger.info("iSCSI Root Partitions Created")
                if self.create_hostvg():
                    if len(self.APPVGDRIVE) > 0:
                        self.create_appvg()
                    logger.info("Completed!")
                    return True

        if ("OVIRT_ROOT_INSTALL" in _functions.OVIRT_VARS and
                  _functions.OVIRT_VARS["OVIRT_ROOT_INSTALL"] == "y" and not \
                      _functions.is_iscsi_install()):
            logger.info("Partitioning root drive: " + self.ROOTDRIVE)
            _functions.wipe_partitions(self.ROOTDRIVE)
            self.reread_partitions(self.ROOTDRIVE)
            logger.info("Labeling Drive: " + self.ROOTDRIVE)
            parted_cmd = ("parted \"" + self.ROOTDRIVE + "\" -s \"mklabel " +
                         self.LABEL_TYPE + "\"")
            _functions.passthrough(parted_cmd, logger.debug)
            logger.debug("Creating Root and RootBackup Partitions")
            if _functions.is_efi_boot():
                self.create_efi_partition()
            else:
                # create partition labeled bios_grub
                parted_cmd = ("parted \"" + self.ROOTDRIVE +
                             "\" -s \"mkpart primary 1M " +
                             str(self.EFI_SIZE) + "M\"")
                _functions.passthrough(parted_cmd, logger.debug)
                parted_cmd = ("parted \"" + self.ROOTDRIVE +
                             "\" -s \"set 1 bios_grub on\"")
                _functions.passthrough(parted_cmd, logger.debug)
            parted_cmd = ("parted \"" + self.ROOTDRIVE +
                         "\" -s \"mkpart primary ext2 " + str(self.EFI_SIZE) +
                         "M " + str(self.Root_end) + "M\"")
            _functions.passthrough(parted_cmd, logger.debug)
            parted_cmd = ("parted \"" + self.ROOTDRIVE +
                         "\" -s \"mkpart primary ext2 " +
                         str(self.Root_end) + "M " +
                         str(self.RootBackup_end) + "M\"")
            logger.debug(parted_cmd)
            _functions.system(parted_cmd)
            _functions.system("sync ; udevadm settle ; partprobe")
            parted_cmd = ("parted \"" + self.ROOTDRIVE +
                         "\" -s \"set 2 boot on\"")
            logger.debug(parted_cmd)
            _functions.system(parted_cmd)
            # force reload some cciss devices will fail to mkfs
            _functions.system("multipath -r &>/dev/null")
            self.reread_partitions(self.ROOTDRIVE)
            partroot = self.ROOTDRIVE + "2"
            partrootbackup = self.ROOTDRIVE + "3"
            if not os.path.exists(partroot):
                partroot = self.ROOTDRIVE + "p2"
                partrootbackup = self.ROOTDRIVE + "p3"
            _functions.system("mke2fs \"" + partroot + "\" -L Root")
            _functions.system("tune2fs -c 0 -i 0 \"" + partroot + "\"")
            _functions.system("ln -snf \"" + partrootbackup +
                   "\" /dev/disk/by-label/RootBackup")
            _functions.system("mke2fs \"" + partrootbackup + \
                              "\" -L RootBackup")
            _functions.system("tune2fs -c 0 -i 0 \"" + partrootbackup + "\"")
        hostvg1 = self.HOSTVGDRIVE.split(",")[0]
        self.reread_partitions(self.ROOTDRIVE)
        if self.ROOTDRIVE != hostvg1:
            _functions.system("parted \"" + hostvg1 + "\" -s \"mklabel " +
                   self.LABEL_TYPE + "\"")
        if self.create_hostvg():
            if len(self.APPVGDRIVE) > 0:
                self.create_appvg()
        else:
            return False
        if ("OVIRT_CRYPT_SWAP2" in _functions.OVIRT_VARS or
            "OVIRT_CRYPT_SWAP" in _functions.OVIRT_VARS):
            _functions.ovirt_store_config("/etc/ovirt-crypttab")
        return True
Example #22
0
    def perform_partitioning(self):
        if self.HOSTVGDRIVE is None and not _functions.is_iscsi_install():
            logger.error("\nNo storage device selected.")
            return False

        if self.BOOTDRIVE is None and _functions.is_iscsi_install():
            logger.error("No storage device selected.")
            return False

        if _functions.has_fakeraid(self.HOSTVGDRIVE):
            if not handle_fakeraid(self.HOSTVGDRIVE):
                return False
        if _functions.has_fakeraid(self.ROOTDRIVE):
            if not handle_fakeraid(self.ROOTDRIVE):
                return False

        logger.info("Saving parameters")
        _functions.unmount_config("/etc/default/ovirt")
        if not self.check_partition_sizes():
            return False
        logger.info("Removing old LVM partitions")
        # HostVG must not exist at this point
        # we wipe only foreign LVM here
        logger.info("Wiping LVM on HOSTVGDRIVE %s" % self.HOSTVGDRIVE)
        if not self.wipe_lvm_on_disk(self.HOSTVGDRIVE):
            logger.error("Wiping LVM on %s Failed" % self.HOSTVGDRIVE)
            return False
        logger.info("Wiping LVM on ROOTDRIVE %s" % self.ROOTDRIVE)
        if not self.wipe_lvm_on_disk(self.ROOTDRIVE):
            logger.error("Wiping LVM on %s Failed" % self.ROOTDRIVE)
            return False
        logger.info("Wiping LVM on BOOTDRIVE %s" % self.BOOTDRIVE)
        if not self.wipe_lvm_on_disk(self.BOOTDRIVE):
            logger.error("Wiping LVM on %s Failed" % self.BOOTDRIVE)
            return False
        logger.debug("Old LVM partitions should be gone.")
        logger.debug(_functions.passthrough("vgdisplay -v"))

        self.boot_size_si = self.BOOT_SIZE * (1024 * 1024) / (1000 * 1000)
        if _functions.is_iscsi_install():
            # login to target and setup disk"
            get_targets = ("iscsiadm -m discovery -p %s:%s -t sendtargets" %
                           (_functions.OVIRT_VARS["OVIRT_ISCSI_TARGET_HOST"],
                           _functions.OVIRT_VARS["OVIRT_ISCSI_TARGET_PORT"]))
            _functions.system(get_targets)
            before_login_drvs = self.get_dev_name()
            logger.debug(before_login_drvs)
            login_cmd = ("iscsiadm -m node -T %s -p %s:%s -l" %
                        (_functions.OVIRT_VARS["OVIRT_ISCSI_TARGET_NAME"],
                        _functions.OVIRT_VARS["OVIRT_ISCSI_TARGET_HOST"],
                        _functions.OVIRT_VARS["OVIRT_ISCSI_TARGET_PORT"]))
            _functions.system(login_cmd)
            _functions.system("multipath -r")
            after_login_drvs = self.get_dev_name()
            logger.debug(after_login_drvs)
            logger.info("iSCSI enabled, partitioning boot drive: %s" %
                        self.BOOTDRIVE)
            _functions.wipe_partitions(self.BOOTDRIVE)
            self.reread_partitions(self.BOOTDRIVE)
            logger.info("Creating boot partition")
            parted_cmd = "parted %s -s \"mklabel %s\"" % (self.BOOTDRIVE,
                                                          self.LABEL_TYPE)
            _functions.system(parted_cmd)
            parted_cmd = ("parted \"%s\" -s \"mkpart primary ext2 1M 256M\"" %
                       self.BOOTDRIVE)
            _functions.system(parted_cmd)
            parted_cmd = ("parted \"%s\" -s \"mkpart primary ext2 256M " +
                          "512M\"") % self.BOOTDRIVE
            _functions.system(parted_cmd)
            parted_cmd = ("parted \"" + self.BOOTDRIVE + "\" -s \"set 1 " +
                         "boot on\"")
            _functions.system(parted_cmd)
            self.reread_partitions(self.BOOTDRIVE)
            partboot = self.BOOTDRIVE + "1"
            if not os.path.exists(partboot):
                logger.debug("%s does not exist" % partboot)
                partboot = self.BOOTDRIVE + "p1"
            partbootbackup = self.BOOTDRIVE + "2"
            if not os.path.exists(partbootbackup):
                logger.debug("%s does not exist" % partbootbackup)
                partbootbackup = self.BOOTDRIVE + "p2"
            # sleep to ensure filesystems are created before continuing
            _functions.system("udevadm settle")
            time.sleep(10)
            _functions.system("mke2fs \"" + str(partboot) + "\" -L Boot")
            _functions.system("tune2fs -c 0 -i 0 \"" + str(partboot) + "\"")
            _functions.system("ln -snf \"" + partboot + \
                              "\" /dev/disk/by-label/Boot")
            _functions.system("mke2fs \"" + str(partbootbackup) + \
                              "\" -L BootBackup")
            _functions.system("tune2fs -c 0 -i 0 \"" + \
                              str(partbootbackup) + "\"")
            _functions.system("ln -snf \"" + partbootbackup +
                   "\" /dev/disk/by-label/BootBackup")
            self.ISCSIDRIVE = _functions.translate_multipath_device(
                               _functions.OVIRT_VARS["OVIRT_ISCSI_INIT"])
            logger.debug(self.ISCSIDRIVE)
            if self.create_iscsiroot():
                logger.info("iSCSI Root Partitions Created")
                if self.create_hostvg():
                    logger.info("Completed!")
                    return True

        if ("OVIRT_ROOT_INSTALL" in _functions.OVIRT_VARS and
                  _functions.OVIRT_VARS["OVIRT_ROOT_INSTALL"] == "y"):
            logger.info("Partitioning root drive: " + self.ROOTDRIVE)
            _functions.wipe_partitions(self.ROOTDRIVE)
            self.reread_partitions(self.ROOTDRIVE)
            logger.info("Labeling Drive: " + self.ROOTDRIVE)
            parted_cmd = ("parted \"" + self.ROOTDRIVE + "\" -s \"mklabel " +
                         self.LABEL_TYPE + "\"")
            _functions.passthrough(parted_cmd, logger.debug)
            logger.debug("Creating Root and RootBackup Partitions")
            # efi partition should at 0M
            if _functions.is_efi_boot():
                parted_cmd = ("parted \"" + self.ROOTDRIVE +
                             "\" -s \"mkpart EFI 1M " +
                             str(self.EFI_SIZE) + "M\"")
                _functions.passthrough(parted_cmd, logger.debug)
            else:
                # create partition labeled bios_grub
                parted_cmd = ("parted \"" + self.ROOTDRIVE +
                             "\" -s \"mkpart primary 1M " +
                             str(self.EFI_SIZE) + "M\"")
                _functions.passthrough(parted_cmd, logger.debug)
                parted_cmd = ("parted \"" + self.ROOTDRIVE +
                             "\" -s \"set 1 bios_grub on\"")
                _functions.passthrough(parted_cmd, logger.debug)
            parted_cmd = ("parted \"" + self.ROOTDRIVE +
                         "\" -s \"mkpart primary ext2 " + str(self.EFI_SIZE) +
                         "M " + str(self.Root_end) + "M\"")
            _functions.passthrough(parted_cmd, logger.debug)
            parted_cmd = ("parted \"" + self.ROOTDRIVE +
                         "\" -s \"mkpart primary ext2 " +
                         str(self.Root_end) + "M " +
                         str(self.RootBackup_end) + "M\"")
            logger.debug(parted_cmd)
            _functions.system(parted_cmd)
            parted_cmd = ("parted \"" + self.ROOTDRIVE +
                         "\" -s \"set 2 boot on\"")
            logger.debug(parted_cmd)
            _functions.system(parted_cmd)
            # sleep to ensure filesystems are created before continuing
            time.sleep(5)
            # force reload some cciss devices will fail to mkfs
            _functions.system("multipath -r &>/dev/null")
            self.reread_partitions(self.ROOTDRIVE)
            partefi = self.ROOTDRIVE + "1"
            partroot = self.ROOTDRIVE + "2"
            partrootbackup = self.ROOTDRIVE + "3"
            if not os.path.exists(partroot):
                partefi = self.ROOTDRIVE + "p1"
                partroot = self.ROOTDRIVE + "p2"
                partrootbackup = self.ROOTDRIVE + "p3"
            if _functions.is_efi_boot():
                _functions.system("ln -snf \"" + partefi + \
                                  "\" /dev/disk/by-label/EFI")
                _functions.system("mkfs.vfat \"" + partefi + "\"")
            _functions.system("ln -snf \"" + partroot + \
                              "\" /dev/disk/by-label/Root")
            _functions.system("mke2fs \"" + partroot + "\" -L Root")
            _functions.system("tune2fs -c 0 -i 0 \"" + partroot + "\"")
            _functions.system("ln -snf \"" + partrootbackup +
                   "\" /dev/disk/by-label/RootBackup")
            _functions.system("mke2fs \"" + partrootbackup + \
                              "\" -L RootBackup")
            _functions.system("tune2fs -c 0 -i 0 \"" + partrootbackup + "\"")
        hostvg1 = self.HOSTVGDRIVE.split(",")[0]
        self.reread_partitions(self.ROOTDRIVE)
        if self.ROOTDRIVE != hostvg1:
            _functions.system("parted \"" + hostvg1 + "\" -s \"mklabel " +
                   self.LABEL_TYPE + "\"")
        if self.create_hostvg():
            if len(self.APPVGDRIVE) > 0:
                self.create_appvg()
        else:
            return False
        if ("OVIRT_CRYPT_SWAP2" in _functions.OVIRT_VARS or
            "OVIRT_CRYPT_SWAP" in _functions.OVIRT_VARS):
            _functions.ovirt_store_config("/etc/ovirt-crypttab")
        return True
 def create_iscsiroot(self):
     logger.info("Partitioning iscsi root drive: " + self.ISCSIDRIVE)
     _functions.wipe_partitions(self.ISCSIDRIVE)
     self.reread_partitions(self.ISCSIDRIVE)
     logger.info("Labeling Drive: " + self.ISCSIDRIVE)
     parted_cmd = ("parted \"" + self.ISCSIDRIVE +
                  "\" -s \"mklabel " + self.LABEL_TYPE + "\"")
     logger.debug(parted_cmd)
     _functions.system(parted_cmd)
     logger.debug("Creating Root and RootBackup Partitions")
     parted_cmd = ("parted \"" + self.ISCSIDRIVE +
                   "\" -s \"mkpart primary 1M " +
                   str(self.ROOT_SIZE) + "M\"")
     logger.debug(parted_cmd)
     _functions.system(parted_cmd)
     parted_cmd = ("parted \"" + self.ISCSIDRIVE +
                  "\" -s \"mkpart primary ext2 " + str(self.ROOT_SIZE) +
                  "M " + str(self.ROOT_SIZE * 2) + "M\"")
     logger.debug(parted_cmd)
     _functions.system(parted_cmd)
     # sleep to ensure filesystems are created before continuing
     time.sleep(5)
     # force reload some cciss devices will fail to mkfs
     _functions.system("multipath -r")
     self.reread_partitions(self.ISCSIDRIVE)
     partroot = self.ISCSIDRIVE + "1"
     partrootbackup = self.ISCSIDRIVE + "2"
     if not os.path.exists(partroot):
         partroot = self.ISCSIDRIVE + "p1"
         partrootbackup = self.ISCSIDRIVE + "p2"
     _functions.system("ln -snf \"" + partroot + \
                       "\" /dev/disk/by-label/Root")
     _functions.system("mke2fs \"" + partroot + "\" -L Root")
     _functions.system("tune2fs -c 0 -i 0 \"" + partroot + "\"")
     _functions.system("ln -snf \"" + partrootbackup +
            "\" /dev/disk/by-label/RootBackup")
     _functions.system("mke2fs \"" + partrootbackup + "\" -L RootBackup")
     _functions.system("tune2fs -c 0 -i 0 \"" + partrootbackup + "\"")
     return True
    def create_appvg(self):
        logger.info("Creating LVM partition(s) for AppVG")
        physical_vols = []
        logger.debug("APPVGDRIVE: " + ' '.join(self.APPVGDRIVE))
        logger.debug("SWAP2_SIZE: " + str(self.SWAP2_SIZE))
        logger.debug("DATA2_SIZE: " + str(self.DATA2_SIZE))
        for drv in self.APPVGDRIVE:
            _functions.wipe_partitions(drv)
            self.reread_partitions(drv)
            logger.info("Labeling Drive: " + drv)
            appvgpart = "1"
            while True:
                parted_cmd = ("parted -s \"" + drv + "\" \"mklabel " +
                              self.LABEL_TYPE +
                              " mkpart primary ext2 2048s -1 set " +
                              appvgpart + " lvm on print\"")
                _functions.system(parted_cmd)
                self.reread_partitions(drv)
                if (os.path.exists(drv + appvgpart) or
                    os.path.exists(drv + "p" + appvgpart)):
                    break

            partpv = drv + appvgpart
            if not os.path.exists(partpv):
                # e.g. /dev/cciss/c0d0p2
                partpv = drv + "p" + appvgpart
            logger.info("Creating physical volume")
            if not os.path.exists(partpv):
                logger.error(partpv + " is not available!")
                return False
            dd_cmd = "dd if=/dev/zero of=\"" + partpv + "\" bs=1024k count=1"
            logger.info(dd_cmd)
            _functions.system(dd_cmd)
            _functions.system("pvcreate -ff -y \"" + partpv + "\"")
            physical_vols.append(partpv)

        logger.info("Creating volume group AppVG")
        is_first = True
        for drv in physical_vols:
            if is_first:
                _functions.system("vgcreate AppVG \"" + drv + "\"")
                is_first = False
            else:
                _functions.system("vgextend AppVG \"" + drv + "\"")

        if self.SWAP2_SIZE > 0:
            logger.info("Creating swap2 partition")
            lv_cmd = ("lvcreate --name Swap2 --size \"" +
                      str(self.SWAP2_SIZE) + "M\" /dev/AppVG")
            logger.debug(lv_cmd)
            _functions.system(lv_cmd)
            if "OVIRT_CRYPT_SWAP2" in _functions.OVIRT_VARS:
                _functions.system_closefds("echo \"SWAP2 /dev/AppVG/Swap2 " +
                                "/dev/mapper/ovirt-crypt-swap2 " +
                                _functions.OVIRT_VARS["OVIRT_CRYPT_SWAP2"] +
                                "\" >> /etc/ovirt-crypttab")
            else:
                _functions.system("mkswap -L \"SWAP2\" /dev/AppVG/Swap2")
                _functions.system_closefds("echo \"/dev/AppVG/Swap2 " + \
                                "swap swap defaults 0 0\" >> /etc/fstab")

        use_data = "1"
        if self.DATA2_SIZE == -1:
            logger.info("Creating data2 partition with remaining free space")
            _functions.system("lvcreate --name Data2 -l 100%FREE /dev/AppVG")
            use_data = 0
        elif self.DATA2_SIZE > 0:
            logger.info("Creating data2 partition")
            _functions.system("lvcreate --name Data2 --size " + \
                              str(self.DATA2_SIZE) +
                   "M /dev/AppVG")
            use_data = 0

        if use_data == 0:
            _functions.system("mke2fs -j -t ext4 /dev/AppVG/Data2 " + \
                              "-L \"DATA2\"")
            _functions.system("tune2fs -c 0 -i 0 /dev/AppVG/Data2")
            _functions.system_closefds("echo \"/dev/AppVG/Data2 /data2 ext4 " +
                            "defaults,noatime 0 0\" >> /etc/fstab")
            logger.info("Mounting data2 partition")
            _functions.mount_data2()
            logger.info("Completed AppVG!")
            return True
Example #25
0
def disable_snmpd():
    _functions.system("service snmpd stop")
    # copy to /tmp for enable/disable toggles w/o reboot
    _functions.system("cp /etc/snmp/snmpd.conf /tmp")
    _functions.system("sed -c -ie '/^createUser root/d' %s" % snmp_conf)
    _functions.remove_config(snmp_conf)
    def create_hostvg(self):
        logger.info("Creating LVM partition")
        self.physical_vols = []
        for drv in self.HOSTVGDRIVE.strip(",").split(","):
            drv = _functions.translate_multipath_device(drv)
            if drv != "":
                if self.ROOTDRIVE == drv and not _functions.is_iscsi_install():
                    self.reread_partitions(self.ROOTDRIVE)
                    parted_cmd = ("parted \"" + drv + "\" -s \"mkpart " +
                                  "primary ext2 " + str(self.RootBackup_end) +
                                  "M -1\"")
                    logger.debug(parted_cmd)
                    _functions.system(parted_cmd)
                    hostvgpart = "4"
                elif self.BOOTDRIVE == drv:
                    parted_cmd = ("parted \"" + drv + "\" -s \"mkpart " +
                                  "primary ext2 " + str(self.boot_size_si * 2) +
                                  " -1\"")
                    logger.debug(parted_cmd)
                    _functions.system(parted_cmd)
                    hostvgpart = "3"
                    self.ROOTDRIVE = self.BOOTDRIVE
                elif self.ISCSIDRIVE == drv:
                    parted_cmd = ("parted \"" + drv + "\" -s \"mkpart " +
                                  "primary ext2 " + str(self.ROOT_SIZE * 2) +
                                  " -1\"")
                    logger.debug(parted_cmd)
                    _functions.system(parted_cmd)
                    hostvgpart = "3"
                else:
                    _functions.system("parted \"" + drv + "\" -s \"mklabel " +
                            self.LABEL_TYPE + "\"")
                    parted_cmd = ("parted \"" + drv + "\" -s \"mkpart " +
                                  "primary ext2 1M -1 \"")
                    logger.debug(parted_cmd)
                    _functions.system(parted_cmd)
                    hostvgpart = "1"
                logger.info("Toggling LVM on")
                parted_cmd = ("parted \"" + drv + "\" -s \"set " +
                              str(hostvgpart) + " lvm on\"")
                logger.debug(parted_cmd)
                _functions.system(parted_cmd)
                _functions.system("parted \"" + self.ROOTDRIVE + \
                                  "\" -s \"print\"")
                _functions.system("udevadm settle 2> /dev/null || " + \
                                  "udevsettle &>/dev/null")
                # sync GPT to the legacy MBR partitions
                if ("OVIRT_INSTALL_ROOT" in _functions.OVIRT_VARS and
                     _functions.OVIRT_VARS["OVIRT_INSTALL_ROOT"] == "y"):
                    if self.LABEL_TYPE == "gpt":
                        logger.info("Running gptsync to create legacy mbr")
                        _functions.system("gptsync \"" + \
                                          self.ROOTDRIVE + "\"")

                self.physical_vols.append((drv, hostvgpart))
        drv_count = 0
        logger.debug(self.physical_vols)
        for drv, hostvgpart in self.physical_vols:
            partpv = None
            logger.info("Creating physical volume on (%s, %s)" % (drv,
                        hostvgpart))
            for _drv in self.HOSTVGDRIVE.strip(",").split(","):
                self.reread_partitions(_drv)
            i = 15
            while i > 0 and partpv is None:
                # e.g. /dev/cciss/c0d0p2
                for _partpv in [drv + hostvgpart, drv + "p" + hostvgpart]:
                    if os.path.exists(_partpv):
                        partpv = _partpv
                        break
                    logger.info(_partpv + " is not available!")
                i -= 1
                time.sleep(1)
            if i is 0:
                return False
            assert(partpv is not None)

            if not _functions.system("dd if=/dev/zero of=\"" + partpv +
                          "\" bs=1024k count=1"):
                logger.error("Failed to wipe lvm partition")
                return False
            if not _functions.system("pvcreate -ff -y \"" + partpv + "\""):
                logger.error("Failed to pvcreate on " + partpv)
                return False
            if drv_count < 1:
                logger.info("Creating volume group on " + partpv)
                if not _functions.system("vgcreate /dev/HostVG \"" + \
                                         partpv + "\""):
                    logger.error("Failed to vgcreate /dev/HostVG on " + partpv)
                    return False
            else:
                logger.info("Extending volume group on " + partpv)
                if not _functions.system("vgextend /dev/HostVG \"" + \
                                         partpv + "\""):
                    logger.error("Failed to vgextend /dev/HostVG on " + partpv)
                    return False
            drv_count = drv_count + 1
        if self.SWAP_SIZE > 0:
            logger.info("Creating swap partition")
            _functions.system("lvcreate --name Swap --size " + \
                              str(self.SWAP_SIZE) + "M /dev/HostVG")
            _functions.system("mkswap -L \"SWAP\" /dev/HostVG/Swap")
            _functions.system_closefds("echo \"/dev/HostVG/Swap swap swap " +
                            "defaults 0 0\" >> /etc/fstab")
            if "OVIRT_CRYPT_SWAP" in _functions.OVIRT_VARS:
                _functions.system_closefds("echo \"SWAP /dev/HostVG/Swap " +
                                "/dev/mapper/ovirt-crypt-swap " +
                                _functions.OVIRT_VARS["OVIRT_CRYPT_SWAP"] +
                                "\" >> /etc/ovirt-crypttab")
        if self.CONFIG_SIZE > 0:
            logger.info("Creating config partition")
            _functions.system("lvcreate --name Config --size " +
                    str(self.CONFIG_SIZE) + "M /dev/HostVG")
            _functions.system("mke2fs -j -t ext4 /dev/HostVG/Config " + \
                              "-L \"CONFIG\"")
            _functions.system("tune2fs -c 0 -i 0 /dev/HostVG/Config")
        if self.LOGGING_SIZE > 0:
            logger.info("Creating log partition")
            _functions.system("lvcreate --name Logging --size " +
                    str(self.LOGGING_SIZE) + "M /dev/HostVG")
            _functions.system("mke2fs -j -t ext4 /dev/HostVG/Logging " + \
                              "-L \"LOGGING\"")
            _functions.system("tune2fs -c 0 -i 0 /dev/HostVG/Logging")
            _functions.system_closefds("echo \"/dev/HostVG/Logging " + \
                            "/var/log ext4 defaults,noatime 0 0\" >> " + \
                            "/etc/fstab")
        use_data = 1
        if self.DATA_SIZE == -1:
            logger.info("Creating data partition with remaining free space")
            _functions.system("lvcreate --name Data -l 100%FREE /dev/HostVG")
            use_data = 0
        elif self.DATA_SIZE > 0:
            logger.info("Creating data partition")
            _functions.system("lvcreate --name Data --size " + \
                              str(self.DATA_SIZE) + "M /dev/HostVG")
            use_data = 0
        if use_data == 0:
            _functions.system("mke2fs -j -t ext4 /dev/HostVG/Data -L \"DATA\"")
            _functions.system("tune2fs -c 0 -i 0 /dev/HostVG/Data")
            _functions.system_closefds("echo \"/dev/HostVG/Data /data ext4 " +
                            "defaults,noatime 0 0\" >> /etc/fstab")
            _functions.system_closefds("echo \"/data/images " + \
                            "/var/lib/libvirt/images bind bind 0 0\" >> " + \
                            "/etc/fstab")
            _functions.system_closefds("echo \"/data/core " + \
                            "/var/log/core bind bind 0 0\" >> /etc/fstab")

        logger.info("Mounting config partition")
        _functions.mount_config()
        if os.path.ismount("/config"):
            _functions.ovirt_store_config("/etc/fstab")
        # remount /var/log from tmpfs to HostVG/Logging
        _functions.unmount_logging()
        _functions.mount_logging()
        if use_data == 0:
            logger.info("Mounting data partition")
            _functions.mount_data()
        logger.info("Completed HostVG Setup!")
        return True
Example #27
0
    def save_network_configuration(self):
        _functions.aug.load()
        net_configured = 0
        _functions.augtool_workdir_list = "ls %s/augtool-* >/dev/null"
        logger.info("Configuring network for NIC %s" % self.CONFIGURED_NIC)
        # Wee need to bring down all network stuff, with the current network
        # config, before we change the config. Otherwise the interfaces can
        # not be brought down correctly.
        logger.info("Stopping Network services")
        _functions.system("service network stop")
        # FIXME can't this be done further down were we remove the bridges?
        for vlan in get_system_vlans():
            # XXX wrong match e.g. eth10.1 with eth1
            if self.CONFIGURED_NIC in vlan:
                _functions.system_closefds("vconfig rem " + vlan + \
                                           "&> /dev/null")
                _functions.ovirt_safe_delete_config(self.IFSCRIPTS_PATH + vlan)
                _functions.system_closefds("rm -rf " + \
                                           self.IFSCRIPTS_PATH + vlan)

        # All old config files are gone, the new ones are created step by step

        logger.debug("Removing persisted network configs")
        # This should cover NICs, VLANs and bridges
        for script in glob("%s*" % (self.IFSCRIPTS_PATH)):
            #print script
            #print 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
            if not _functions.is_persisted(script):
                continue
            logger.debug("Removing Script: " + script)
            _functions.ovirt_safe_delete_config(script)
        _functions.aug.load()

        logger.debug("Updating interface config")
        for line in self.IF_CONFIG:
            logger.debug(line)
            try:
                oper, key, value = line.split()
                _functions.augtool(oper, key, value)
            except:
                oper, key = line.split()
                _functions.augtool(oper, key, "")

        logger.debug("Updating bridge config")
        if not self.disabled_nic == 1:
            for line in self.BR_CONFIG:
                logger.debug(line)
                try:
                    oper, key, value = line.split()
                    _functions.augtool(oper, key, value)
                except:
                    try:
                        oper, key = line.split()
                        _functions.augtool(oper, key, "")
                    except:
                        pass

            logger.debug("Updating VLAN config")
            for line in self.VL_CONFIG.split("\n"):
                logger.debug(line)
                try:
                    oper, key, value = line.split()
                    _functions.augtool(oper, key, value)
                except:
                    try:
                        oper, key = line.split()
                        _functions.augtool(oper, key, "")
                    except:
                        pass

        # preserve current MAC mappings for *all physical* network interfaces
        logger.error("Preserving current MAC mappings")
        for nicdev in glob('/sys/class/net/*/device'):
            nic = nicdev.split('/')[4]
            if nic != self.CONFIGURED_NIC:
                f = open('/sys/class/net/%s/address' % nic)
                mac = f.read().strip()
                f.close()
                if len(mac) > 0:
                    logger.debug("Mapping for %s" % nic)
                    self.CONFIGURED_NICS.append(nic)
                    nicroot = "%s%s" % (self.IFCONFIG_FILE_ROOT, nic)
                    # XXX _functions.augtool does save every time!
                    _functions.augtool("set", "%s/DEVICE" % nicroot, nic)
                    _functions.augtool("set", "%s/HWADDR" % nicroot, mac)
                    _functions.augtool("set", "%s/ONBOOT" % nicroot, "no")

        logger.debug("Storing configured NICs")
        net_configured = 1
        for nic in self.CONFIGURED_NICS:
            logger.debug("Storing %s" % nic)
            _functions.ovirt_store_config("%s%s" % (self.IFSCRIPTS_PATH, nic))
        _functions.ovirt_store_config(self.NTP_CONFIG_FILE)
        if self.disabled_nic == 1:
            _functions.augtool("set", \
                               "/files/etc/sysconfig/network/NETWORKING", "no")
        else:
            _functions.augtool("set", \
                               "/files/etc/sysconfig/network/NETWORKING", "yes")
        _functions.ovirt_store_config("/etc/sysconfig/network")
        _functions.ovirt_store_config("/etc/hosts")

        # Copy the initial net rules to a file that get's not
        # overwritten at each boot, rhbz#773495
        rulesfile = "/etc/udev/rules.d/70-persistent-net.rules"
        newrulesfile = "/etc/udev/rules.d/71-persistent-node-net.rules"
        if os.path.exists(rulesfile):
            _functions.system_closefds("cp %s %s >> /var/log/ovirt.log" %
                                       (rulesfile, newrulesfile))
            _functions.ovirt_store_config(newrulesfile)

            # Eventully it makes sense to rename the NICs
            #system_closefds("sed -ic 's/NAME=\"eth/NAME=\"eth00/' " +
            #                 "/etc/udev/rules.d/71-persistent-node-net.rules")

        logger.info("Network configured successfully")
        if net_configured == 1:
            logger.info("Stopping Network services")
            _functions.system_closefds("service network stop &> /dev/null")
            _functions.system_closefds("service ntpd stop &> /dev/null")
            # XXX eth assumed in breth
            brctl_cmd = "brctl show| awk 'NR>1 && /^br[ep]/ {print $1}'"
            brctl = _functions.subprocess_closefds(brctl_cmd,
                                                   shell=True,
                                                   stdout=subprocess.PIPE,
                                                   stderr=subprocess.STDOUT)
            brctl_output = brctl.stdout.read()
            for i in brctl_output.split():
                if_down_cmd = "ifconfig %s down &> /dev/null" % i
                _functions.system_closefds(if_down_cmd)
                del_br_cmd = "brctl delbr %s &> /dev/null" % i
                _functions.system_closefds(del_br_cmd)
            logger.info("Starting Network service")
            _functions.system_closefds("service network start &> /dev/null")
            _functions.system_closefds("service ntpdate start &> /dev/null")
            _functions.system_closefds("service ntpd start &> /dev/null")
            # rhbz#745541
            _functions.system_closefds("service rpcbind start &> /dev/null")
            _functions.system_closefds("service nfslock start &> /dev/null")
            _functions.system_closefds("service rpcidmapd start &> /dev/null")
            _functions.system_closefds("service rpcgssd start &> /dev/null")
            if "NTP" in OVIRT_VARS:
                logger.info("Testing NTP Configuration")
                _functions.test_ntp_configuration()
Example #28
0
    def ovirt_boot_setup(self, reboot="N"):
        self.generate_paths()
        logger.info("Installing the image.")
        # copy grub.efi to safe location
        if _functions.is_efi_boot():
            shutil.copy("/boot/efi/EFI/%s/grub.efi" % self.efi_dir_name,
                        "/tmp")
        if "OVIRT_ROOT_INSTALL" in OVIRT_VARS:
            if OVIRT_VARS["OVIRT_ROOT_INSTALL"] == "n":
                logger.info("Root Installation Not Required, Finished.")
                return True
        self.oldtitle = None
        grub_config_file = None
        if _functions.findfs("Boot") and _functions.is_upgrade():
            grub_config_file = "/boot/grub/grub.conf"
            if not _functions.connect_iscsi_root():
                return False
        _functions.mount_liveos()
        if os.path.ismount("/liveos"):
            if os.path.exists("/liveos/vmlinuz0") \
                              and os.path.exists("/liveos/initrd0.img"):
                grub_config_file = self.grub_config_file
        elif not _functions.is_firstboot():
            # find existing iscsi install
            if _functions.findfs("Boot"):
                grub_config_file = "/boot/grub/grub.conf"
            elif os.path.ismount("/dev/.initramfs/live"):
                if not _functions.grub2_available():
                    grub_config_file = "/dev/.initramfs/live/grub/grub.conf"
                else:
                    grub_config_file = "/dev/.initramfs/live/grub2/grub.cfg"
            elif os.path.ismount("/run/initramfs/live"):
                grub_config_file = "/run/initramfs/live/grub/grub.conf"
            if _functions.is_upgrade() and not _functions.is_iscsi_install():
                _functions.mount_liveos()
                grub_config_file = "/liveos/grub/grub.conf"
        if _functions.is_efi_boot():
            logger.debug(str(os.listdir("/liveos")))
            _functions.system("umount /liveos")
            _functions.mount_efi(target="/liveos")
            if self.efi_dir_name == "fedora":
                grub_config_file = "/liveos/EFI/fedora/grub.cfg"
            else:
                grub_config_file = "/liveos/EFI/redhat/grub.conf"
        if _functions.is_iscsi_install() or _functions.findfs("Boot"):
            grub_config_file = "/boot/grub/grub.conf"
        grub_config_file_exists = grub_config_file is not None \
            and os.path.exists(grub_config_file)
        logger.debug("Grub config file is: %s" % grub_config_file)
        logger.debug("Grub config file exists: %s" % grub_config_file_exists)
        if not grub_config_file is None and os.path.exists(grub_config_file):
            f = open(grub_config_file)
            oldgrub = f.read()
            f.close()
            if _functions.grub2_available():
                m = re.search("^menuentry (.*)$", oldgrub, re.MULTILINE)
            else:
                m = re.search("^title (.*)$", oldgrub, re.MULTILINE)
            if m is not None:
                self.oldtitle = m.group(1)
                # strip off extra title characters
                if _functions.grub2_available():
                    self.oldtitle = self.oldtitle.replace('"', '').strip(" {")
        _functions.system("umount /liveos/efi")
        _functions.system("umount /liveos")
        if _functions.is_iscsi_install() or _functions.findfs("Boot"):
            self.boot_candidate = None
            boot_candidate_names = ["BootBackup", "BootUpdate", "BootNew"]
            for trial in range(1, 3):
                time.sleep(1)
                _functions.system("partprobe")
                for candidate_name in boot_candidate_names:
                    logger.debug(os.listdir("/dev/disk/by-label"))
                    if _functions.findfs(candidate_name):
                        self.boot_candidate = candidate_name
                        break
                logger.debug("Trial %s to find candidate (%s)" % \
                             (trial, candidate_name))
                if self.boot_candidate:
                    logger.debug("Found candidate: %s" % self.boot_candidate)
                    break

            if not self.boot_candidate:
                logger.error("Unable to find boot partition")
                label_debug = ''
                for label in os.listdir("/dev/disk/by-label"):
                    label_debug += "%s\n" % label
                label_debug += _functions.subprocess_closefds("blkid", \
                                          shell=True, stdout=subprocess.PIPE,
                                          stderr=subprocess.STDOUT).stdout.read()
                logger.debug(label_debug)
                return False
            else:
                boot_candidate_dev = _functions.findfs(self.boot_candidate)
            # prepare Root partition update
            if self.boot_candidate != "BootNew":
                e2label_cmd = "e2label \"%s\" BootNew" % boot_candidate_dev
                logger.debug(e2label_cmd)
                if not _functions.system(e2label_cmd):
                    logger.error("Failed to label new Boot partition")
                    return False
            _functions.system("umount /boot")
            _functions.system("mount %s /boot &>/dev/null" \
                              % boot_candidate_dev)

        candidate = None
        candidate_names = ["RootBackup", "RootUpdate", "RootNew"]
        for trial in range(1, 3):
            time.sleep(1)
            _functions.system("partprobe")
            for candidate_name in candidate_names:
                if _functions.findfs(candidate_name):
                    candidate = candidate_name
                    break
            logger.debug("Trial %s to find candidate (%s)" %
                         (trial, candidate_name))
            if candidate:
                logger.debug("Found candidate: %s" % candidate)
                break

        if not candidate:
            logger.error("Unable to find root partition")
            label_debug = ''
            for label in os.listdir("/dev/disk/by-label"):
                label_debug += "%s\n" % label
            label_debug += _functions.subprocess_closefds(
                "blkid",
                shell=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT).stdout.read()
            logger.debug(label_debug)
            return False

        try:
            candidate_dev = self.disk = _functions.findfs(candidate)
            logger.info(candidate_dev)
            logger.info(self.disk)
            # grub2 starts at part 1
            self.partN = int(self.disk[-1:])
            if not _functions.grub2_available():
                self.partN = self.partN - 1
        except:
            logger.debug(traceback.format_exc())
            return False

        if self.disk is None or self.partN < 0:
            logger.error("Failed to determine Root partition number")
            return False
        # prepare Root partition update
        if candidate != "RootNew":
            e2label_cmd = "e2label \"%s\" RootNew" % candidate_dev
            logger.debug(e2label_cmd)
            if not _functions.system(e2label_cmd):
                logger.error("Failed to label new Root partition")
                return False
        mount_cmd = "mount \"%s\" /liveos" % candidate_dev
        _functions.system(mount_cmd)
        _functions.system("rm -rf /liveos/LiveOS")
        _functions.system("mkdir -p /liveos/LiveOS")
        _functions.mount_live()

        if os.path.isdir(self.grub_dir):
            shutil.rmtree(self.grub_dir)
        if not os.path.exists(self.grub_dir):
            os.makedirs(self.grub_dir)
            if _functions.is_efi_boot():
                logger.info("efi detected, installing efi configuration")
                _functions.system("mkdir /liveos/efi")
                _functions.mount_efi()
                _functions.system("mkdir -p /liveos/efi/EFI/redhat")
                if _functions.is_iscsi_install() or _functions.is_efi_boot():
                    shutil.copy("/tmp/grub.efi",
                                "/liveos/efi/EFI/redhat/grub.efi")
                else:
                    shutil.copy("/boot/efi/EFI/redhat/grub.efi",
                                "/liveos/efi/EFI/redhat/grub.efi")
                if _functions.is_iscsi_install() or _functions.findfs(
                        "BootNew"):
                    self.disk = _functions.findfs("BootNew")
                if not "/dev/mapper/" in self.disk:
                    efi_disk = self.disk[:-1]
                else:
                    efi_disk = re.sub("p[1,2,3]$", "", self.disk)
                # generate grub legacy config for efi partition
                #remove existing efi entries
                _functions.remove_efi_entry(_functions.PRODUCT_SHORT)
                if self.efi_dir_name == "fedora":
                    _functions.add_efi_entry(
                        _functions.PRODUCT_SHORT,
                        ("\\EFI\\%s\\grubx64.efi" % self.efi_dir_name),
                        efi_disk)
                else:
                    _functions.add_efi_entry(
                        _functions.PRODUCT_SHORT,
                        ("\\EFI\\%s\\grub.efi" % self.efi_dir_name), efi_disk)
        self.kernel_image_copy()

        # reorder tty0 to allow both serial and phys console after installation
        if _functions.is_iscsi_install() or _functions.findfs("BootNew"):
            self.root_param = "root=live:LABEL=Root"
            if "OVIRT_NETWORK_LAYOUT" in OVIRT_VARS and \
                OVIRT_VARS["OVIRT_NETWORK_LAYOUT"] == "bridged":
                network_conf = "ip=br%s:dhcp bridge=br%s:%s" % \
                                (OVIRT_VARS["OVIRT_BOOTIF"],
                                 OVIRT_VARS["OVIRT_BOOTIF"],
                                 OVIRT_VARS["OVIRT_BOOTIF"])
            else:
                network_conf = "ip=%s:dhcp" % OVIRT_VARS["OVIRT_BOOTIF"]
            self.bootparams = "netroot=iscsi:%s::%s::%s %s " % (
                OVIRT_VARS["OVIRT_ISCSI_TARGET_HOST"],
                OVIRT_VARS["OVIRT_ISCSI_TARGET_PORT"],
                OVIRT_VARS["OVIRT_ISCSI_TARGET_NAME"], network_conf)
            if "OVIRT_ISCSI_NAME" in OVIRT_VARS:
                self.bootparams+= "iscsi_initiator=%s " % \
                    OVIRT_VARS["OVIRT_ISCSI_NAME"]
        else:
            self.root_param = "root=live:LABEL=Root"
            self.bootparams = "ro rootfstype=auto rootflags=ro "
        self.bootparams += OVIRT_VARS["OVIRT_BOOTPARAMS"].replace(
            "console=tty0", "").replace("rd_NO_MULTIPATH", "")
        if " " in self.disk or os.path.exists("/dev/cciss"):
            # workaround for grub setup failing with spaces in dev.name:
            # use first active sd* device
            self.disk = re.sub("p[1,2,3]$", "", self.disk)
            grub_disk_cmd = ("multipath -l " + "\"" + self.disk + "\" " +
                             "| egrep -o '[0-9]+:.*' " +
                             "| awk '/ active / {print $2}' " + "| head -n1")
            logger.debug(grub_disk_cmd)
            grub_disk = _functions.subprocess_closefds(
                grub_disk_cmd,
                shell=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT)
            grub_disk_output, grub_disk_err = grub_disk.communicate()
            self.disk = grub_disk_output.strip()
            if "cciss" in self.disk:
                self.disk = self.disk.replace("!", "/")
            # flush to sync DM and blockdev, workaround from rhbz#623846#c14
            sysfs = open("/proc/sys/vm/drop_caches", "w")
            sysfs.write("3")
            sysfs.close()
            partprobe_cmd = "partprobe \"/dev/%s\"" % self.disk
            logger.debug(partprobe_cmd)
            _functions.system(partprobe_cmd)

        if not self.disk.startswith("/dev/"):
            self.disk = "/dev/" + self.disk
        try:
            if stat.S_ISBLK(os.stat(self.disk).st_mode):
                try:
                    if stat.S_ISBLK(os.stat(self.disk[:-1]).st_mode):
                        # e.g. /dev/sda2
                        self.disk = self.disk[:-1]
                except OSError:
                    pass
                try:
                    if stat.S_ISBLK(os.stat(self.disk[:-2]).st_mode):
                        # e.g. /dev/mapper/WWIDp2
                        self.disk = self.disk[:-2]
                except OSError:
                    pass
        except OSError:
            logger.error("Unable to determine disk for grub installation " +
                         traceback.format_exc())
            return False

        self.grub_dict = {
            "product": _functions.PRODUCT_SHORT,
            "version": _functions.PRODUCT_VERSION,
            "release": _functions.PRODUCT_RELEASE,
            "partN": self.partN,
            "root_param": self.root_param,
            "bootparams": self.bootparams,
            "disk": self.disk,
            "grub_dir": self.grub_dir,
            "grub_prefix": self.grub_prefix,
            "efi_hd": self.efi_hd
        }
        if not _functions.is_firstboot():
            if os.path.ismount("/live"):
                with open("%s/version" % self.live_path) as version:
                    for line in version.readlines():
                        if "VERSION" in line:
                            key, value = line.split("=")
                            self.grub_dict["version"] = value.strip()
                        if "RELEASE" in line:
                            key, value = line.split("=")
                            self.grub_dict["release"] = value.strip()

        if _functions.grub2_available():
            if not self.grub2_install():
                logger.error("Grub2 Installation Failed ")
                return False
            else:
                logger.info("Grub2 EFI Installation Completed ")
        else:
            if not self.grub_install():
                logger.error("Grub Installation Failed ")
                return False
            else:
                logger.info("Grub Installation Completed")

        if _functions.is_iscsi_install() or _functions.findfs("BootNew"):
            # copy default for when Root/HostVG is inaccessible(iscsi upgrade)
            shutil.copy(_functions.OVIRT_DEFAULTS, "/boot")
            # mark new Boot ready to go, reboot() in ovirt-function switches it
            # to active
            e2label_cmd = "e2label \"%s\" BootUpdate" % boot_candidate_dev

            if not _functions.system(e2label_cmd):
                logger.error("Unable to relabel " + boot_candidate_dev +
                             " to RootUpdate ")
                return False
        else:
            _functions.system("umount /liveos/efi")
        _functions.system("umount /liveos")
        # mark new Root ready to go, reboot() in ovirt-function switches it
        # to active
        e2label_cmd = "e2label \"%s\" RootUpdate" % candidate_dev
        if not _functions.system(e2label_cmd):
            logger.error("Unable to relabel " + candidate_dev +
                         " to RootUpdate ")
            return False
        _functions.disable_firstboot()
        if _functions.finish_install():
            if _functions.is_firstboot():
                _iscsi.iscsi_auto()
            logger.info("Installation of %s Completed" % \
                                                      _functions.PRODUCT_SHORT)
            if reboot is not None and reboot == "Y":
                _system.async_reboot()
            return True
        else:
            return False
Example #29
0
    def grub2_install(self):
        GRUB2_EFI_CONFIG_TEMPLATE = """
insmod efi_gop
insmod efi_uga
"""

        GRUB2_CONFIG_TEMPLATE = """
#default saved
set timeout=5
#hiddenmenu
menuentry "%(product)s %(version)s-%(release)s" {
set root=(hd0,%(partN)d)
search --no-floppy --label Root --set root
%(linux)s /vmlinuz0 %(root_param)s %(bootparams)s
%(initrd)s /initrd0.img
}"""

        GRUB2_BACKUP_TEMPLATE = """
menuentry "BACKUP %(oldtitle)s" {
set root=(hd0,%(partB)d)
search --no-floppy --label RootBackup --set root
%(linux)s /vmlinuz0 root=live:LABEL=RootBackup %(bootparams)s
%(initrd)s /initrd0.img
}    """
        if _functions.is_iscsi_install():
            disk = re.sub("p[1,2,3]$", "", \
                                    _functions.findfs("BootNew"))
            self.grub_dict["partN"] = int(_functions.findfs("BootNew")[-1:])
        else:
            disk = self.disk
        if _functions.is_efi_boot():
            boot_dir = self.initrd_dest + "/efi"
            self.grub_dict["linux"] = "linuxefi"
            self.grub_dict["initrd"] = "initrdefi"
        else:
            boot_dir = self.initrd_dest
        if not _functions.is_efi_boot():
            grub_setup_cmd = ("/sbin/grub2-install " + disk +
                              " --boot-directory=" + boot_dir +
                              " --root-directory=" + boot_dir +
                              " --efi-directory=" + boot_dir +
                              " --bootloader-id=" + self.efi_name + " --force")
            _functions.system("echo '%s' >> /liveos/efi/cmd" % grub_setup_cmd)
            logger.info(grub_setup_cmd)
            grub_setup = _functions.subprocess_closefds(grub_setup_cmd, \
                                             shell=True,
                                             stdout=subprocess.PIPE,
                                             stderr=subprocess.STDOUT)
            grub_results, grub_err = grub_setup.communicate()
            logger.info(grub_results)
            if grub_setup.wait() != 0 or "Error" in grub_results:
                logger.error("grub2-install Failed")
                return False
        else:
            efi_setup_cmd = (r'efibootmgr -c -L "RHEV-H" -l '
                             r'"\EFI\redhat\shim.efi" -d %s -p 1' % disk)
            _functions.system("echo '%s' >> /liveos/efi/cmd" % efi_setup_cmd)
            logger.info(efi_setup_cmd)
            efi_setup = _functions.subprocess_closefds(
                efi_setup_cmd,
                shell=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT)
            efi_results, efi_err = efi_setup.communicate()
            logger.info(efi_results)
            if efi_setup.wait() != 0:
                logger.error("efibootmgr setup failed")
                return False
            else:
                shutil.copy("/boot/efi/%s/shim.efi" % self.efi_path,
                            "/liveos/efi/%s/shim.efi" % self.efi_path)
        logger.debug("Generating Grub2 Templates")
        if _functions.is_efi_boot():
            if not os.path.exists("/liveos/efi/%s" % self.efi_path):
                os.makedirs("/liveos/efi/%s" % self.efi_path)
        grub_conf = open(self.grub_config_file, "w")
        grub_conf.write(GRUB2_CONFIG_TEMPLATE % self.grub_dict)
        if self.oldtitle is not None:
            partB = 0
            if self.partN == 0:
                partB = 1
            self.grub_dict['oldtitle'] = self.oldtitle
            self.grub_dict['partB'] = partB
            grub_conf.write(GRUB2_BACKUP_TEMPLATE % self.grub_dict)
        grub_conf.close()
        if os.path.exists("/liveos/efi/EFI"):
            efi_grub_conf = open("/liveos/efi/%s/grub.cfg" \
                    % self.efi_path, "w")
            # inject efi console output modules
            efi_grub_conf.write(GRUB2_EFI_CONFIG_TEMPLATE)
            efi_grub_conf.write(GRUB2_CONFIG_TEMPLATE % self.grub_dict)
            if self.oldtitle is not None:
                partB = 0
                if self.partN == 0:
                    partB = 1
                self.grub_dict['oldtitle'] = self.oldtitle
                self.grub_dict['partB'] = partB
                efi_grub_conf.write(GRUB2_BACKUP_TEMPLATE % self.grub_dict)
                efi_grub_conf.close()
            _functions.system("umount /liveos")
            _functions.remove_efi_entry(self.efi_name)
            logger.info("Grub2 Install Completed")
            return True
        return True
Example #30
0
    def ovirt_boot_setup(self, reboot="N"):
        self.generate_paths()
        logger.info("Installing the image.")
        # copy grub.efi to safe location
        if _functions.is_efi_boot():
            if "OVIRT_ISCSI_INSTALL" in OVIRT_VARS:
                _functions.system("umount /boot")
            if os.path.isfile("/boot/efi/%s/grubx64.efi" % self.efi_path):
                shutil.copy("/boot/efi/%s/grubx64.efi" % self.efi_path, "/tmp")
            else:
                shutil.copy("/boot/efi/%s/grub.efi" % self.efi_path, "/tmp")
            _functions.mount_boot()
        if "OVIRT_ROOT_INSTALL" in OVIRT_VARS:
            if OVIRT_VARS["OVIRT_ROOT_INSTALL"] == "n":
                logger.info("Root Installation Not Required, Finished.")
                return True
        self.oldtitle = None
        grub_config_file = None
        if _functions.findfs("Boot") and _functions.is_upgrade():
            grub_config_file = "/boot/grub/grub.conf"
            if not _functions.connect_iscsi_root():
                return False
        _functions.mount_liveos()
        if os.path.ismount("/liveos"):
            if os.path.exists("/liveos/vmlinuz0") \
                              and os.path.exists("/liveos/initrd0.img"):
                grub_config_file = self.grub_config_file
        elif not _functions.is_firstboot():
            # find existing iscsi install
            if _functions.findfs("Boot"):
                grub_config_file = "/boot/grub/grub.conf"
            elif os.path.ismount("/dev/.initramfs/live"):
                if not _functions.grub2_available():
                    grub_config_file = "/dev/.initramfs/live/grub/grub.conf"
                else:
                    grub_config_file = "/dev/.initramfs/live/grub2/grub.cfg"
            elif os.path.ismount("/run/initramfs/live"):
                grub_config_file = "/run/initramfs/live/grub/grub.conf"
            if _functions.is_upgrade() and not _functions.is_iscsi_install():
                _functions.mount_liveos()
                grub_config_file = "/liveos/grub/grub.conf"
        if _functions.is_iscsi_install() or _functions.findfs("Boot") \
            and not _functions.is_efi_boot():
            grub_config_file = "/boot/grub/grub.conf"
        if _functions.is_efi_boot():
            logger.debug(str(os.listdir("/liveos")))
            _functions.system("umount /liveos")
            _functions.mount_efi(target="/liveos")
            if self.efi_name == "fedora":
                grub_config_file = "/liveos/EFI/fedora/grub.cfg"
            else:
                grub_config_file = "/liveos/%s/grub.conf" % self.efi_path
        grub_config_file_exists = grub_config_file is not None \
            and os.path.exists(grub_config_file)
        logger.debug("Grub config file is: %s" % grub_config_file)
        logger.debug("Grub config file exists: %s" % grub_config_file_exists)
        if not grub_config_file is None and os.path.exists(grub_config_file):
            f = open(grub_config_file)
            oldgrub = f.read()
            f.close()
            if _functions.grub2_available():
                m = re.search("^menuentry (.*)$", oldgrub, re.MULTILINE)
            else:
                m = re.search("^title (.*)$", oldgrub, re.MULTILINE)
            if m is not None:
                self.oldtitle = m.group(1)
                # strip off extra title characters
                if _functions.grub2_available():
                    self.oldtitle = self.oldtitle.replace('"', '').strip(" {")
        _functions.system("umount /liveos/efi")
        _functions.system("umount /liveos")
        if _functions.is_iscsi_install() or _functions.findfs("Boot"):
            self.boot_candidate = None
            boot_candidate_names = ["BootBackup", "BootUpdate", "BootNew"]
            for trial in range(1, 3):
                time.sleep(1)
                for candidate_name in boot_candidate_names:
                    logger.debug(os.listdir("/dev/disk/by-label"))
                    if _functions.findfs(candidate_name):
                        self.boot_candidate = candidate_name
                        break
                logger.debug("Trial %s to find candidate (%s)" % \
                             (trial, candidate_name))
                if self.boot_candidate:
                    logger.debug("Found candidate: %s" % self.boot_candidate)
                    break

            if not self.boot_candidate:
                logger.error("Unable to find boot partition")
                label_debug = ''
                for label in os.listdir("/dev/disk/by-label"):
                    label_debug += "%s\n" % label
                label_debug += _functions.subprocess_closefds("blkid", \
                                          shell=True, stdout=subprocess.PIPE,
                                          stderr=subprocess.STDOUT).stdout.read()
                logger.debug(label_debug)
                return False
            else:
                boot_candidate_dev = _functions.findfs(self.boot_candidate)
            # prepare Root partition update
            if self.boot_candidate != "BootNew":
                e2label_cmd = "e2label \"%s\" BootNew" % boot_candidate_dev
                logger.debug(e2label_cmd)
                if not _functions.system(e2label_cmd):
                    logger.error("Failed to label new Boot partition")
                    return False
            _functions.system("umount /boot")
            _functions.system("mount %s /boot &>/dev/null" \
                              % boot_candidate_dev)

        candidate = None
        candidate_dev = None
        candidate_names = ["RootBackup", "RootUpdate", "RootNew"]
        for trial in range(1, 3):
            time.sleep(1)
            for candidate_name in candidate_names:
                candidate_dev = _functions.findfs(candidate_name)
                logger.debug("Finding %s: '%s'" %
                             (candidate_name, candidate_dev))
                if candidate_dev:
                    candidate = candidate_name
                    logger.debug("Found: %s" % candidate)
                    break
            logger.debug("Trial %s to find candidate (%s)" %
                         (trial, candidate_name))
            if candidate:
                logger.debug("Found candidate: '%s'" % candidate)
                break

        if not candidate:
            logger.error("Unable to find root partition")
            label_debug = ''
            for label in os.listdir("/dev/disk/by-label"):
                label_debug += "%s\n" % label
            label_debug += _functions.subprocess_closefds(
                "blkid",
                shell=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT).stdout.read()
            logger.debug(label_debug)
            return False

        try:
            self.disk = candidate_dev
            logger.info("Candidate device: %s" % candidate_dev)
            logger.info("Candidate disk: %s" % self.disk)
            # grub2 starts at part 1
            self.partN = int(self.disk[-1:])
            if not _functions.grub2_available():
                self.partN = self.partN - 1
        except:
            logger.debug("Failed to get partition", exc_info=True)
            return False

        if self.disk is None or self.partN < 0:
            logger.error("Failed to determine Root partition number")
            return False
        # prepare Root partition update
        if candidate != "RootNew":
            e2label_cmd = "e2label \"%s\" RootNew" % candidate_dev
            logger.debug(e2label_cmd)
            if not _functions.system(e2label_cmd):
                logger.error("Failed to label new Root partition")
                return False
        mount_cmd = "mount \"%s\" /liveos" % candidate_dev
        if not _functions.system(mount_cmd):
            logger.error("Failed to mount %s on /liveos" % candidate_dev)
            _functions.system("lsof")
            _functions.system("dmsetup info -c")
            _functions.system("cat /proc/mounts")
            _functions.system("multipath -ll")
            _functions.system("lsblk")
            _functions.system("ls -l /dev/mapper")
        _functions.system("rm -rf /liveos/LiveOS")
        _functions.system("mkdir -p /liveos/LiveOS")
        _functions.mount_live()

        if os.path.isdir(self.grub_dir):
            shutil.rmtree(self.grub_dir)
        if not os.path.exists(self.grub_dir):
            os.makedirs(self.grub_dir)
            if _functions.is_efi_boot():
                logger.info("efi detected, installing efi configuration")
                _functions.system("mkdir /liveos/efi")
                _functions.mount_efi()
                _functions.system("mkdir -p /liveos/efi/%s" % self.efi_path)
                if _functions.is_iscsi_install() or _functions.is_efi_boot():
                    if os.path.isfile("/tmp/grubx64.efi"):
                        shutil.copy(
                            "/tmp/grubx64.efi",
                            "/liveos/efi/%s/grubx64.efi" % self.efi_path)
                    else:
                        shutil.copy("/tmp/grub.efi",
                                    "/liveos/efi/%s/grub.efi" % self.efi_path)
                elif os.path.isfile("/boot/efi/%s/grubx64.efi" %
                                    self.efi_path):
                    shutil.copy("/boot/efi/%s/grubx64.efi" % self.efi_path,
                                "/liveos/efi/%s/grubx64.efi" % self.efi_path)
                else:
                    shutil.copy("/boot/efi/%s/grub.efi" % self.efi_path,
                                "/liveos/efi/%s/grub.efi" % self.efi_path)
                if _functions.is_iscsi_install() or _functions.findfs(
                        "BootNew"):
                    self.disk = _functions.findfs("BootNew")
                if not "/dev/mapper/" in self.disk:
                    efi_disk = self.disk[:-1]
                else:
                    efi_disk = re.sub(r'p?[1,2,3]$', "", self.disk)
                # generate grub legacy config for efi partition
                #remove existing efi entries
                _functions.remove_efi_entry(_functions.PRODUCT_SHORT)
                if self.efi_name == "fedora":
                    _functions.add_efi_entry(
                        _functions.PRODUCT_SHORT,
                        ("\\EFI\\%s\\grubx64.efi" % self.efi_name), efi_disk)
                else:
                    if os.path.isfile("/liveos/efi/%s/grubx64.efi" %
                                      self.efi_path):
                        _functions.add_efi_entry(
                            _functions.PRODUCT_SHORT,
                            ("\\EFI\\%s\\grubx64.efi" % self.efi_name),
                            efi_disk)
                    else:
                        _functions.add_efi_entry(
                            _functions.PRODUCT_SHORT,
                            ("\\EFI\\%s\\grub.efi" % self.efi_name), efi_disk)
        self.kernel_image_copy()

        # reorder tty0 to allow both serial and phys console after installation
        if _functions.is_iscsi_install() or _functions.findfs("BootNew"):
            self.root_param = "root=live:LABEL=Root"
            if "OVIRT_NETWORK_LAYOUT" in OVIRT_VARS and \
                OVIRT_VARS["OVIRT_NETWORK_LAYOUT"] == "bridged":
                network_conf = "ip=br%s:dhcp bridge=br%s:%s" % \
                                (OVIRT_VARS["OVIRT_BOOTIF"],
                                 OVIRT_VARS["OVIRT_BOOTIF"],
                                 OVIRT_VARS["OVIRT_BOOTIF"])
            else:
                network_conf = "ip=%s:dhcp" % OVIRT_VARS["OVIRT_BOOTIF"]
            self.bootparams = "netroot=iscsi:%s::%s::%s %s " % (
                OVIRT_VARS["OVIRT_ISCSI_TARGET_HOST"],
                OVIRT_VARS["OVIRT_ISCSI_TARGET_PORT"],
                OVIRT_VARS["OVIRT_ISCSI_TARGET_NAME"], network_conf)
            if "OVIRT_ISCSI_NAME" in OVIRT_VARS:
                self.bootparams+= "iscsi_initiator=%s " % \
                    OVIRT_VARS["OVIRT_ISCSI_NAME"]
        else:
            self.root_param = "root=live:LABEL=Root"
            self.bootparams = "ro rootfstype=auto rootflags=ro "
        self.bootparams += OVIRT_VARS["OVIRT_BOOTPARAMS"].replace(
            "console=tty0", "").replace("rd_NO_MULTIPATH", "")

        if " " in self.disk:
            # workaround for grub setup failing with spaces in dev.name:
            # use first active sd* device
            self.disk = re.sub("p[1,2,3]$", "", self.disk)
            grub_disk_cmd = ("multipath -l " + "\"" + self.disk + "\" " +
                             "| egrep -o '[0-9]+:.*' " +
                             "| awk '/ active / {print $2}' " + "| head -n1")
            logger.debug(grub_disk_cmd)
            grub_disk = _functions.subprocess_closefds(
                grub_disk_cmd,
                shell=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT)
            grub_disk_output, grub_disk_err = grub_disk.communicate()
            self.disk = grub_disk_output.strip()
            if "cciss" in self.disk:
                self.disk = self.disk.replace("!", "/")
            # flush to sync DM and blockdev, workaround from rhbz#623846#c14
            sysfs = open("/proc/sys/vm/drop_caches", "w")
            sysfs.write("3")
            sysfs.close()
        if not self.disk.startswith("/dev/"):
            self.disk = "/dev/" + self.disk
        try:
            if stat.S_ISBLK(os.stat(self.disk).st_mode):
                try:
                    if stat.S_ISBLK(os.stat(self.disk[:-1]).st_mode):
                        # e.g. /dev/sda2
                        self.disk = self.disk[:-1]
                except OSError:
                    pass
                try:
                    if stat.S_ISBLK(os.stat(self.disk[:-2]).st_mode):
                        # e.g. /dev/mapper/WWIDp2
                        self.disk = self.disk[:-2]
                except OSError:
                    pass
        except OSError:
            logger.error("Unable to determine disk for grub installation " +
                         traceback.format_exc())
            return False

        self.grub_dict = {
            "product": _functions.PRODUCT_SHORT,
            "version": _functions.PRODUCT_VERSION,
            "release": _functions.PRODUCT_RELEASE,
            "partN": self.partN,
            "root_param": self.root_param,
            "bootparams": self.bootparams,
            "disk": self.disk,
            "grub_dir": self.grub_dir,
            "grub_prefix": self.grub_prefix,
            "efi_hd": self.efi_hd,
            "linux": "linux",
            "initrd": "initrd",
        }
        if not _functions.is_firstboot():
            if os.path.ismount("/live"):
                with open("%s/version" % self.live_path) as version:
                    for line in version.readlines():
                        if "VERSION" in line:
                            key, value = line.split("=")
                            self.grub_dict["version"] = value.strip()
                        if "RELEASE" in line:
                            key, value = line.split("=")
                            self.grub_dict["release"] = value.strip()

        if _functions.grub2_available():
            if not self.grub2_install():
                logger.error("Grub2 Installation Failed ")
                return False
            else:
                logger.info("Grub2 EFI Installation Completed ")
        else:
            if not self.grub_install():
                logger.error("Grub Installation Failed ")
                return False
            else:
                logger.info("Grub Installation Completed")

        if _functions.is_iscsi_install() or _functions.findfs("BootNew"):
            # copy default for when Root/HostVG is inaccessible(iscsi upgrade)
            shutil.copy(_functions.OVIRT_DEFAULTS, "/boot")
            # mark new Boot ready to go, reboot() in ovirt-function switches it
            # to active
            e2label_cmd = "e2label \"%s\" BootUpdate" % boot_candidate_dev

            if not _functions.system(e2label_cmd):
                logger.error("Unable to relabel " + boot_candidate_dev +
                             " to RootUpdate ")
                return False
        else:
            _functions.system("umount /liveos/efi")
        _functions.system("umount /liveos")
        # mark new Root ready to go, reboot() in ovirt-function switches it
        # to active
        e2label_cmd = "e2label \"%s\" RootUpdate" % candidate_dev
        if not _functions.system(e2label_cmd):
            logger.error("Unable to relabel " + candidate_dev +
                         " to RootUpdate ")
            return False
        _functions.system("udevadm settle --timeout=10")

        #
        # Rebuild the initramfs
        # A few hacks are needed to prep the chroot
        # The general issue is that we need to run dracut in the context fo the new iso
        # and that we need to put the initrd in the right place of the new iso.
        # These two things make the logic a bit more complicated.
        #
        mnts = []
        try:
            if not _functions.system("blkid -L RootUpdate"):
                raise RuntimeError("RootUpdate not found")

            # Let's mount the update fs, and use that kernel version and modules
            # We need this work to help dracut
            isomnt = tempfile.mkdtemp("RootUpdate")
            squashmnt = tempfile.mkdtemp("RootUpdate-LiveOS")
            updfs = tempfile.mkdtemp("RootUpdate-LiveOS-Img")
            mnts += [isomnt, squashmnt, updfs]

            # Unpack the iso
            def _call(args):
                logger.debug("Calling: %s" % args)
                try:
                    out = subprocess.check_output(args)
                    logger.debug("Out: %s" % out)
                except Exception as e:
                    logger.debug("Failed with: %s %s" % (e, e.output))
                    raise

            _call(["mount", "LABEL=RootUpdate", isomnt])
            _call(["mount", "%s/LiveOS/squashfs.img" % isomnt, squashmnt])
            _call(["mount", "%s/LiveOS/ext3fs.img" % squashmnt, updfs])

            # Now mount the update modules into place, and find the
            # correct kver
            def rbind(path, updfs=updfs):
                dst = updfs + "/" + path
                logger.debug("Binding %r to %r" % (path, dst))
                _call(["mount", "--make-rshared", "--rbind", "/" + path, dst])
                return dst

            for path in ["etc", "dev", "proc", "sys", "tmp", "run", "var/tmp"]:
                mnts += [rbind(path)]

            upd_kver = str(
                _functions.passthrough("ls -1 %s/lib/modules" %
                                       updfs)).strip()

            if len(upd_kver.splitlines()) != 1:
                # It would be very unusual to see more than one kver directory
                # in /lib/modules but might happen when using edit-node.
                # Check via check_higher_kernel() the higher version available
                upd_kver = self.check_higher_kernel(updfs)
                if upd_kver is None:
                    raise RuntimeError("Unable to find the kernel version")

            # Update initramfs to pickup multipath wwids
            # Let /boot point to the filesystem on the update candidate partition
            builder = _system.Initramfs(dracut_chroot=updfs,
                                        boot_source=isomnt)
            builder.rebuild(kver=upd_kver)

        except Exception as e:
            logger.debug("Failed to build initramfs: %s" % e, exc_info=True)
            output = getattr(e, "output", "")
            if output:
                logger.debug("Output: %s" % output)
            raise

        finally:
            # Clean up all eventual mounts
            pass
            # Disabled for now because akward things happen, we leave it to
            # systemd to unnmount on reboot
            # for mnt in reversed(mnts):
            #     d = _functions.passthrough("umount -fl %s" % mnt, logger.debug)
            #     logger.debug("Returned: %s" % d)

        _functions.disable_firstboot()
        if _functions.finish_install():
            if _functions.is_firstboot():
                _iscsi.iscsi_auto()
            logger.info("Installation of %s Completed" % \
                                                      _functions.PRODUCT_SHORT)
            if reboot is not None and reboot == "Y":
                _system.async_reboot()
            return True
        else:
            return False
Example #31
0
    def grub_install(self):
        if _functions.is_iscsi_install() or _functions.findfs("BootNew"):
            self.disk = _functions.findfs("BootNew")
            self.grub_dict["partN"] = int(self.disk[-1:]) - 1
            if not "/dev/mapper/" in self.disk:
                self.disk = self.disk[:-1]
            else:
                self.disk = re.sub("p[1,2,3]$", "", self.disk)
        device_map = "(hd0) %s" % self.disk
        logger.debug(device_map)
        device_map_conf = open(self.grub_dir + "/device.map", "w")
        device_map_conf.write(device_map)
        device_map_conf.close()

        GRUB_CONFIG_TEMPLATE = """
default saved
timeout 5
hiddenmenu
%(splashscreen)s
title %(product)s %(version)s-%(release)s
    root (hd0,%(partN)d)
    kernel /vmlinuz0 %(root_param)s %(bootparams)s
    initrd /initrd0.img
    savedefault
    """
        GRUB_BACKUP_TEMPLATE = """
title BACKUP %(oldtitle)s
    root (hd0,%(partB)d)
    kernel /vmlinuz0 root=live:LABEL=RootBackup %(bootparams)s
    initrd /initrd0.img
    savedefault
    """
        GRUB_SETUP_TEMPLATE = """
    grub --device-map=%(grub_dir)s/device.map <<EOF
root (hd0,%(partN)d)
setup --prefix=%(grub_prefix)s (hd0)
EOF
"""

        if _functions.is_efi_boot():
            """ The EFI product path.
                eg: HD(1,800,64000,faacb4ef-e361-455e-bd97-ca33632550c3)
            """
            efi_cmd = "efibootmgr -v"
            efi = _functions.subprocess_closefds(efi_cmd,
                                                 shell=True,
                                                 stdout=subprocess.PIPE,
                                                 stderr=subprocess.STDOUT)
            efi_out, efi_err = efi.communicate()
            efi_out = efi_out.strip()
            matches = re.search(_functions.PRODUCT_SHORT + r'\s+(HD\(.+?\))', \
                                                                       efi_out)
            if matches and matches.groups():
                GRUB_EFIONLY_CONFIG = """%(efi_hd)s"""
                GRUB_CONFIG_TEMPLATE = GRUB_EFIONLY_CONFIG + \
                                       GRUB_CONFIG_TEMPLATE
                self.grub_dict['efi_hd'] = "device (hd0) " + matches.group(1)
        if os.path.exists("/live/EFI/BOOT/splash.xpm.gz"):
            if _functions.is_iscsi_install() or _functions.findfs("BootNew"):
                splashscreen = "splashimage=(hd0,%s)/grub/splash.xpm.gz" \
                    % self.grub_dict["partN"]
            else:
                splashscreen = "splashimage=(hd0,%s)/grub/splash.xpm.gz" \
                    % self.partN
        else:
            splashscreen = ""
        self.grub_dict["splashscreen"] = splashscreen
        GRUB_CONFIG_TEMPLATE % self.grub_dict
        grub_conf = open(self.grub_config_file, "w")
        grub_conf.write(GRUB_CONFIG_TEMPLATE % self.grub_dict)
        if self.oldtitle is not None:
            partB = 1
            if self.partN == 1:
                partB = 2
            if _functions.is_iscsi_install() or _functions.findfs("Boot"):
                partB = partB + 1
            self.grub_dict['oldtitle'] = self.oldtitle
            self.grub_dict['partB'] = partB
            grub_conf.write(GRUB_BACKUP_TEMPLATE % self.grub_dict)
        grub_conf.close()
        # splashscreen
        if _functions.is_iscsi_install() or _functions.findfs("BootNew"):
            _functions.system("cp /live/EFI/BOOT/splash.xpm.gz /boot/grub")
        else:
            _functions.system("cp /live/EFI/BOOT/splash.xpm.gz /liveos/grub")
        # usb devices requires default BOOTX64 entries
        if _functions.is_efi_boot():
            _functions.system("mkdir -p /liveos/efi/EFI/BOOT")
            if _functions.is_iscsi_install() or _functions.findfs("BootNew"):
                _functions.system("cp /tmp/grub.efi \
                                   /liveos/efi/EFI/BOOT/BOOTX64.efi")
            if os.path.isfile("/boot/efi/%s/grubx86.efi" % self.efi_path):
                _functions.system("cp /boot/efi/%s/grubx64.efi \
                                  /liveos/efi/EFI/BOOT/BOOTX64.efi" %
                                  self.efi_path)
            else:
                _functions.system("cp /boot/efi/%s/grub.efi \
                                  /liveos/efi/EFI/BOOT/BOOTX64.efi" %
                                  self.efi_path)
            _functions.system("cp %s /liveos/efi/EFI/BOOT/BOOTX64.conf" \
                              % self.grub_config_file)
            _functions.system("umount /liveos/efi")
        if not _functions.is_efi_boot():
            for f in ["stage1", "stage2", "e2fs_stage1_5"]:
                _functions.system("cp /usr/share/grub/x86_64-redhat/%s %s" % \
                                                            (f, self.grub_dir))
            grub_setup_out = GRUB_SETUP_TEMPLATE % self.grub_dict
            logger.debug(grub_setup_out)
            grub_setup = _functions.subprocess_closefds(
                grub_setup_out,
                shell=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT)
            grub_results, grub_err = grub_setup.communicate()
            logger.debug(grub_results)
            if grub_setup.wait() != 0 or "Error" in grub_results:
                logger.error("GRUB setup failed")
                return False
        return True
Example #32
0
    def ovirt_boot_setup(self, reboot="N"):
        self.generate_paths()
        logger.info("Installing the image.")

        if "OVIRT_ROOT_INSTALL" in OVIRT_VARS:
            if OVIRT_VARS["OVIRT_ROOT_INSTALL"] == "n":
                logger.info("Root Installation Not Required, Finished.")
                return True

        self.oldtitle = None
        if os.path.ismount("/liveos"):
            if (os.path.exists("/liveos/vmlinuz0") and
                os.path.exists("/liveos/initrd0.img")):
                f = open(self.grub_config_file)
                oldgrub = f.read()
                f.close()
                m = re.search("^title (.*)$", oldgrub, re.MULTILINE)
                if m is not None:
                    self.oldtitle = m.group(1)

            _functions.system("umount /liveos")

        if _functions.findfs("BootBackup"):
            self.boot_candidate = "BootBackup"
        elif _functions.findfs("Boot"):
            self.boot_candidate = "Boot"
            if not os.path.ismount("/boot"):
                logger.error("Boot partition not available, Install Failed")
                return False
            # Grab OVIRT_ISCSI VARIABLES from boot partition for upgrading
            # file created only if OVIRT_ISCSI_ENABLED=y
            if os.path.exists("/boot/ovirt"):
                try:
                    f = open("/boot/ovirt", 'r')
                    for line in f:
                        try:
                            line = line.strip()
                            key, value = line.split("\"", 1)
                            key = key.strip("=")
                            key = key.strip()
                            value = value.strip("\"")
                            OVIRT_VARS[key] = value
                        except:
                            pass
                    f.close()
                    iscsiadm_cmd = (("iscsiadm -p %s:%s -m discovery -t " +
                                     "sendtargets") % (
                                        OVIRT_VARS["OVIRT_ISCSI_TARGET_IP"],
                                        OVIRT_VARS["OVIRT_ISCSI_TARGET_PORT"]))
                    _functions.system(iscsiadm_cmd)
                    logger.info("Restarting iscsi service")
                    _functions.system("service iscsi restart")
                except:
                    pass
        if _functions.findfs("RootBackup"):
            candidate = "RootBackup"
        elif _functions.findfs("RootUpdate"):
            candidate = "RootUpdate"
        elif _functions.findfs("RootNew"):
            candidate = "RootNew"
        else:
            logger.error("Unable to find %s partition" % candidate)
            label_debug = ''
            for label in os.listdir("/dev/disk/by-label"):
                label_debug += "%s\n" % label
            label_debug += _functions.subprocess_closefds("blkid", shell=True,
                                      stdout=subprocess.PIPE,
                                      stderr=subprocess.STDOUT).stdout.read()
            logger.debug(label_debug)
            return False
        logger.debug("candidate: " + candidate)

        if _functions.is_iscsi_install():
            _functions.system("mount LABEL=%s /boot" % self.boot_candidate)
        try:
            candidate_dev = self.disk = _functions.findfs(candidate)
            logger.info(candidate_dev)
            logger.info(self.disk)
            # grub2 starts at part 1
            self.partN = int(self.disk[-1:])
            if (not os.path.exists("/sbin/grub2-install") \
                or _functions.is_efi_boot()):
                self.partN = self.partN - 1
        except:
            logger.debug(traceback.format_exc())
            return False

        if self.disk is None or self.partN < 0:
            logger.error("Failed to determine Root partition number")
            return False
        # prepare Root partition update
        if candidate != "RootNew":
            e2label_cmd = "e2label \"%s\" RootNew" % candidate_dev
            logger.debug(e2label_cmd)
            if not _functions.system(e2label_cmd):
                logger.error("Failed to label new Root partition")
                return False
        mount_cmd = "mount \"%s\" /liveos" % candidate_dev
        _functions.system(mount_cmd)
        _functions.system("rm -rf /liveos/LiveOS")
        _functions.system("mkdir -p /liveos/LiveOS")
        _functions.mount_live()

        if os.path.isdir(self.grub_dir):
            shutil.rmtree(self.grub_dir)
        if not os.path.exists(self.grub_dir):
            os.makedirs(self.grub_dir)

            if _functions.is_efi_boot():
                logger.info("efi detected, installing efi configuration")
                _functions.system("mkdir /liveos/efi")
                _functions.mount_efi()
                _functions.system("mkdir -p /liveos/efi/EFI/redhat")
                _functions.system("cp /boot/efi/EFI/redhat/grub.efi " +
                       "/liveos/efi/EFI/redhat/grub.efi")
                efi_disk = re.sub("p[1,2,3]$", "", self.disk)
                # generate grub legacy config for efi partition
                #remove existing efi entries
                efi_mgr_cmd = "efibootmgr|grep '%s'" % _functions.PRODUCT_SHORT
                efi_mgr = _functions.subprocess_closefds(efi_mgr_cmd, \
                                              shell=True, \
                                              stdout=subprocess.PIPE, \
                                              stderr=subprocess.STDOUT)
                efi_out = efi_mgr.stdout.read().strip()
                logger.debug(efi_mgr_cmd)
                logger.debug(efi_out)
                for line in efi_out.splitlines():
                    if not "Warning" in line:
                        num = line[4:8]  # grabs 4 digit hex id
                        cmd = "efibootmgr -B -b %s" % num
                        _functions.system(cmd)
                efi_mgr_cmd = ("efibootmgr -c -l '\\EFI\\redhat\\grub.efi' " +
                              "-L '%s' -d %s -v") % (_functions.PRODUCT_SHORT,
                                                     efi_disk)
                logger.info(efi_mgr_cmd)
                _functions.system(efi_mgr_cmd)
        self.kernel_image_copy()

        # reorder tty0 to allow both serial and phys console after installation
        if _functions.is_iscsi_install():
            self.root_param = "root=LABEL=Root"
            self.bootparams = "root=iscsi:%s::%s::%s ip=%s:dhcp" % (
                OVIRT_VARS["OVIRT_ISCSI_TARGET_HOST"],
                OVIRT_VARS["OVIRT_ISCSI_TARGET_PORT"],
                OVIRT_VARS["OVIRT_ISCSI_TARGET_NAME"],
                OVIRT_VARS["OVIRT_BOOTIF"])
        else:
            self.root_param = "root=live:LABEL=Root"
            self.bootparams = "ro rootfstype=auto rootflags=ro "
        self.bootparams += OVIRT_VARS["OVIRT_BOOTPARAMS"].replace(
                                                            "console=tty0", "")
        if " " in self.disk or os.path.exists("/dev/cciss"):
            # workaround for grub setup failing with spaces in dev.name:
            # use first active sd* device
            self.disk = re.sub("p[1,2,3]$", "", self.disk)
            grub_disk_cmd = "multipath -l \"" + os.path.basename(self.disk) + \
                            "\" | awk '/ active / {print $3}' | head -n1"
            logger.debug(grub_disk_cmd)
            grub_disk = _functions.subprocess_closefds(grub_disk_cmd,
                                            shell=True,
                                            stdout=subprocess.PIPE,
                                            stderr=subprocess.STDOUT)
            self.disk = grub_disk.stdout.read().strip()
            if "cciss" in self.disk:
                self.disk = self.disk.replace("!", "/")
            # flush to sync DM and blockdev, workaround from rhbz#623846#c14
            sysfs = open("/proc/sys/vm/drop_caches", "w")
            sysfs.write("3")
            sysfs.close()
            partprobe_cmd = "partprobe \"/dev/%s\"" % self.disk
            logger.debug(partprobe_cmd)
            _functions.system(partprobe_cmd)

        if not self.disk.startswith("/dev/"):
            self.disk = "/dev/" + self.disk
        try:
            if stat.S_ISBLK(os.stat(self.disk).st_mode):
                try:
                    if stat.S_ISBLK(os.stat(self.disk[:-1]).st_mode):
                        # e.g. /dev/sda2
                        self.disk = self.disk[:-1]
                except OSError:
                    pass
                try:
                    if stat.S_ISBLK(os.stat(self.disk[:-2]).st_mode):
                        # e.g. /dev/mapper/WWIDp2
                        self.disk = self.disk[:-2]
                except OSError:
                    pass
        except OSError:
            logger.error("Unable to determine disk for grub installation " +
                         traceback.format_exc())
            return False

        self.grub_dict = {
        "product": _functions.PRODUCT_SHORT,
        "version": _functions.PRODUCT_VERSION,
        "release": _functions.PRODUCT_RELEASE,
        "partN": self.partN,
        "root_param": self.root_param,
        "bootparams": self.bootparams,
        "disk": self.disk,
        "grub_dir": self.grub_dir,
        "grub_prefix": self.grub_prefix,
        "efi_hd": self.efi_hd
    }

        if os.path.exists("/sbin/grub2-install"):
            if not _functions.is_efi_boot():
                if not self.grub2_install():
                    logger.error("Grub2 Installation Failed ")
                    return False
            else:
                if not self.grub_install():
                    logger.error("Grub EFI Installation Failed ")
                    return False
                else:
                    logger.info("Grub EFI Installation Completed ")
        else:
            if not self.grub_install():
                logger.error("Grub Installation Failed ")
                return False
            else:
                logger.info("Grub Installation Completed")

        if _functions.is_iscsi_install():
            # copy default for when Root/HostVG is inaccessible(iscsi upgrade)
            shutil.copy(_functions.OVIRT_DEFAULTS, "/boot")
            _functions.system("umount /boot")
        else:
            _functions.system("umount /liveos/efi")
        _functions.system("umount /liveos")
        # mark new Root ready to go, reboot() in ovirt-function switches it
        # to active
        e2label_cmd = "e2label \"%s\" RootUpdate" % candidate_dev
        if not _functions.system(e2label_cmd):
            logger.error("Unable to relabel " + candidate_dev +
                         " to RootUpdate ")
            return False
        _functions.disable_firstboot()
        if _functions.finish_install():
            _iscsi.iscsi_auto()
            logger.info("Installation of %s Completed" % \
                                                      _functions.PRODUCT_SHORT)
            if reboot is not None and reboot == "Y":
                f = open('/var/spool/cron/root', 'w')
                f.write('* * * * * sleep 10 && /sbin/reboot')
                f.close()
                #ensure crond is started
                subprocess_closefds("crond", shell=True,
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.STDOUT)
            return True
        else:
            return False
Example #33
0
def disable_snmpd():
    _functions.system("service snmpd stop")
    # copy to /tmp for enable/disable toggles w/o reboot
    _functions.system("cp /etc/snmp/snmpd.conf /tmp")
    _functions.system("sed -c -ie '/^createUser root/d' %s" % snmp_conf)
    _functions.remove_config(snmp_conf)
Example #34
0
    def grub2_install(self):
        GRUB2_EFI_CONFIG_TEMPLATE = """
insmod efi_gop
insmod efi_uga
"""

        GRUB2_CONFIG_TEMPLATE = """
#default saved
set timeout=5
#hiddenmenu
menuentry "%(product)s %(version)s-%(release)s" {
set root=(hd0,%(partN)d)
search --no-floppy --label Root --set root
linux /vmlinuz0 %(root_param)s %(bootparams)s
initrd /initrd0.img
}"""

        GRUB2_BACKUP_TEMPLATE = """
menuentry "BACKUP %(oldtitle)s" {
set root (hd0,%(partB)d)
search --no-floppy --label RootBackup --set root
linux /vmlinuz0 root=live:LABEL=RootBackup %(bootparams)s
initrd /initrd0.img
}    """
        if _functions.is_iscsi_install():
            disk = re.sub("p[1,2,3]$", "", \
                                    _functions.findfs("BootNew"))
            self.grub_dict["partN"] = int(_functions.findfs("BootNew")[-1:])
        else:
            disk = self.disk
        if _functions.is_efi_boot():
            boot_dir = self.initrd_dest + "/efi"
        else:
            boot_dir = self.initrd_dest
        grub_setup_cmd = ("/sbin/grub2-install " + disk +
                          " --boot-directory=" + boot_dir +
                          " --root-directory=" + boot_dir +
                          " --efi-directory=" + boot_dir +
                          " --bootloader-id=" + self.efi_dir_name +
                          " --force")
        _functions.system("echo '%s' >> /liveos/efi/cmd" % grub_setup_cmd)
        logger.info(grub_setup_cmd)
        grub_setup = _functions.subprocess_closefds(grub_setup_cmd, \
                                         shell=True,
                                         stdout=subprocess.PIPE,
                                         stderr=subprocess.STDOUT)
        grub_results = grub_setup.stdout.read()
        logger.info(grub_results)
        if grub_setup.wait() != 0 or "Error" in grub_results:
            logger.error("grub2-install Failed")
            return False
        else:
            logger.debug("Generating Grub2 Templates")
            if _functions.is_efi_boot():
                if not os.path.exists("/liveos/efi/EFI/%s" % self.efi_dir_name):
                    os.makedirs("/liveos/efi/EFI/%s" % self.efi_dir_name)
            grub_conf = open(self.grub_config_file, "w")
            grub_conf.write(GRUB2_CONFIG_TEMPLATE % self.grub_dict)
        if self.oldtitle is not None:
            partB = 0
            if self.partN == 0:
                partB = 1
            self.grub_dict['oldtitle'] = self.oldtitle
            self.grub_dict['partB'] = partB
            grub_conf.write(GRUB2_BACKUP_TEMPLATE % self.grub_dict)
        grub_conf.close()
        if os.path.exists("/liveos/efi/EFI"):
            efi_grub_conf = open("/liveos/efi/EFI/%s/grub.cfg" \
                    % self.efi_dir_name, "w")
            # inject efi console output modules
            efi_grub_conf.write(GRUB2_EFI_CONFIG_TEMPLATE)
            efi_grub_conf.write(GRUB2_CONFIG_TEMPLATE % self.grub_dict)
            if self.oldtitle is not None:
                partB = 0
                if self.partN == 0:
                    partB = 1
                self.grub_dict['oldtitle'] = self.oldtitle
                self.grub_dict['partB'] = partB
                efi_grub_conf.write(GRUB2_BACKUP_TEMPLATE % self.grub_dict)
                efi_grub_conf.close()
            _functions.system("umount /liveos")
            _functions.remove_efi_entry(self.efi_dir_name)
            logger.info("Grub2 Install Completed")
            return True
        return True
Example #35
0
    def ovirt_boot_setup(self, reboot="N"):
        self.generate_paths()
        logger.info("Installing the image.")
        # copy grub.efi to safe location
        if _functions.is_efi_boot():
            if "OVIRT_ISCSI_INSTALL" in OVIRT_VARS:
                _functions.system("umount /boot")
            if os.path.isfile("/boot/efi/EFI/%s/grubx64.efi" %
                              self.efi_dir_name):
                shutil.copy("/boot/efi/EFI/%s/grubx64.efi" % self.efi_dir_name,
                            "/tmp")
            else:
                shutil.copy("/boot/efi/EFI/%s/grub.efi" % self.efi_dir_name,
                            "/tmp")
            _functions.mount_boot()
        if "OVIRT_ROOT_INSTALL" in OVIRT_VARS:
            if OVIRT_VARS["OVIRT_ROOT_INSTALL"] == "n":
                logger.info("Root Installation Not Required, Finished.")
                return True
        self.oldtitle=None
        grub_config_file = None
        if _functions.findfs("Boot") and _functions.is_upgrade():
            grub_config_file = "/boot/grub/grub.conf"
            if not _functions.connect_iscsi_root():
                return False
        _functions.mount_liveos()
        if os.path.ismount("/liveos"):
            if os.path.exists("/liveos/vmlinuz0") \
                              and os.path.exists("/liveos/initrd0.img"):
                grub_config_file = self.grub_config_file
        elif not _functions.is_firstboot():
            # find existing iscsi install
            if _functions.findfs("Boot"):
                grub_config_file = "/boot/grub/grub.conf"
            elif os.path.ismount("/dev/.initramfs/live"):
                if not _functions.grub2_available():
                    grub_config_file = "/dev/.initramfs/live/grub/grub.conf"
                else:
                    grub_config_file = "/dev/.initramfs/live/grub2/grub.cfg"
            elif os.path.ismount("/run/initramfs/live"):
                grub_config_file = "/run/initramfs/live/grub/grub.conf"
            if _functions.is_upgrade() and not _functions.is_iscsi_install():
                _functions.mount_liveos()
                grub_config_file = "/liveos/grub/grub.conf"
        if _functions.is_iscsi_install() or _functions.findfs("Boot") \
            and not _functions.is_efi_boot():
            grub_config_file = "/boot/grub/grub.conf"
        if _functions.is_efi_boot():
            logger.debug(str(os.listdir("/liveos")))
            _functions.system("umount /liveos")
            _functions.mount_efi(target="/liveos")
            if self.efi_dir_name == "fedora":
                grub_config_file = "/liveos/EFI/fedora/grub.cfg"
            else:
                grub_config_file = "/liveos/EFI/redhat/grub.conf"
        grub_config_file_exists = grub_config_file is not None \
            and os.path.exists(grub_config_file)
        logger.debug("Grub config file is: %s" % grub_config_file)
        logger.debug("Grub config file exists: %s" % grub_config_file_exists)
        if not grub_config_file is None and os.path.exists(grub_config_file):
            f=open(grub_config_file)
            oldgrub=f.read()
            f.close()
            if _functions.grub2_available():
                m=re.search("^menuentry (.*)$", oldgrub, re.MULTILINE)
            else:
                m=re.search("^title (.*)$", oldgrub, re.MULTILINE)
            if m is not None:
                self.oldtitle=m.group(1)
                # strip off extra title characters
                if _functions.grub2_available():
                    self.oldtitle = self.oldtitle.replace('"','').strip(" {")
        _functions.system("umount /liveos/efi")
        _functions.system("umount /liveos")
        if _functions.is_iscsi_install() or _functions.findfs("Boot"):
            self.boot_candidate = None
            boot_candidate_names = ["BootBackup", "BootUpdate", "BootNew"]
            for trial in range(1, 3):
                time.sleep(1)
                for candidate_name in boot_candidate_names:
                    logger.debug(os.listdir("/dev/disk/by-label"))
                    if _functions.findfs(candidate_name):
                        self.boot_candidate = candidate_name
                        break
                logger.debug("Trial %s to find candidate (%s)" % \
                             (trial, candidate_name))
                if self.boot_candidate:
                    logger.debug("Found candidate: %s" % self.boot_candidate)
                    break

            if not self.boot_candidate:
                logger.error("Unable to find boot partition")
                label_debug = ''
                for label in os.listdir("/dev/disk/by-label"):
                    label_debug += "%s\n" % label
                label_debug += _functions.subprocess_closefds("blkid", \
                                          shell=True, stdout=subprocess.PIPE,
                                          stderr=subprocess.STDOUT).stdout.read()
                logger.debug(label_debug)
                return False
            else:
                boot_candidate_dev = _functions.findfs(self.boot_candidate)
            # prepare Root partition update
            if self.boot_candidate != "BootNew":
                e2label_cmd = "e2label \"%s\" BootNew" % boot_candidate_dev
                logger.debug(e2label_cmd)
                if not _functions.system(e2label_cmd):
                    logger.error("Failed to label new Boot partition")
                    return False
            _functions.system("umount /boot")
            _functions.system("mount %s /boot &>/dev/null" \
                              % boot_candidate_dev)

        candidate = None
        candidate_dev = None
        candidate_names = ["RootBackup", "RootUpdate", "RootNew"]
        for trial in range(1, 3):
            time.sleep(1)
            for candidate_name in candidate_names:
                candidate_dev = _functions.findfs(candidate_name)
                logger.debug("Finding %s: '%s'" % (candidate_name, candidate_dev))
                if candidate_dev:
                    candidate = candidate_name
                    logger.debug("Found: %s" % candidate)
                    break
            logger.debug("Trial %s to find candidate (%s)" % (trial,
                                                              candidate_name))
            if candidate:
                logger.debug("Found candidate: '%s'" % candidate)
                break

        if not candidate:
            logger.error("Unable to find root partition")
            label_debug = ''
            for label in os.listdir("/dev/disk/by-label"):
                label_debug += "%s\n" % label
            label_debug += _functions.subprocess_closefds("blkid", shell=True,
                                      stdout=subprocess.PIPE,
                                      stderr=subprocess.STDOUT).stdout.read()
            logger.debug(label_debug)
            return False

        try:
            self.disk = candidate_dev
            logger.info("Candidate device: %s" % candidate_dev)
            logger.info("Candidate disk: %s" % self.disk)
            # grub2 starts at part 1
            self.partN = int(self.disk[-1:])
            if not _functions.grub2_available():
                self.partN = self.partN - 1
        except:
            logger.debug("Failed to get partition", exc_info=True)
            return False

        if self.disk is None or self.partN < 0:
            logger.error("Failed to determine Root partition number")
            return False
        # prepare Root partition update
        if candidate != "RootNew":
            e2label_cmd = "e2label \"%s\" RootNew" % candidate_dev
            logger.debug(e2label_cmd)
            if not _functions.system(e2label_cmd):
                logger.error("Failed to label new Root partition")
                return False
        mount_cmd = "mount \"%s\" /liveos" % candidate_dev
        if not _functions.system(mount_cmd):
            logger.error("Failed to mount %s on /liveos" % candidate_dev)
            _functions.system("lsof")
            _functions.system("dmsetup info -c")
            _functions.system("cat /proc/mounts")
            _functions.system("multipath -ll")
            _functions.system("lsblk")
            _functions.system("ls -l /dev/mapper")
        _functions.system("rm -rf /liveos/LiveOS")
        _functions.system("mkdir -p /liveos/LiveOS")
        _functions.mount_live()

        if os.path.isdir(self.grub_dir):
            shutil.rmtree(self.grub_dir)
        if not os.path.exists(self.grub_dir):
            os.makedirs(self.grub_dir)
            if _functions.is_efi_boot():
                logger.info("efi detected, installing efi configuration")
                _functions.system("mkdir /liveos/efi")
                _functions.mount_efi()
                _functions.system("mkdir -p /liveos/efi/EFI/redhat")
                if _functions.is_iscsi_install() or _functions.is_efi_boot():
                    if os.path.isfile("/tmp/grubx64.efi"):
                        shutil.copy("/tmp/grubx64.efi",
                                    "/liveos/efi/EFI/redhat/grubx64.efi")
                    else:
                        shutil.copy("/tmp/grub.efi",
                                    "/liveos/efi/EFI/redhat/grub.efi")
                elif os.path.isfile("/boot/efi/EFI/redhat/grubx64.efi"):
                    shutil.copy("/boot/efi/EFI/redhat/grubx64.efi",
                          "/liveos/efi/EFI/redhat/grubx64.efi")
                else:
                    shutil.copy("/boot/efi/EFI/redhat/grub.efi",
                          "/liveos/efi/EFI/redhat/grub.efi")
                if _functions.is_iscsi_install() or _functions.findfs("BootNew"):
                    self.disk = _functions.findfs("BootNew")
                if not "/dev/mapper/" in self.disk:
                    efi_disk = self.disk[:-1]
                else:
                    efi_disk = re.sub(r'p?[1,2,3]$', "", self.disk)
                # generate grub legacy config for efi partition
                #remove existing efi entries
                _functions.remove_efi_entry(_functions.PRODUCT_SHORT)
                if self.efi_dir_name == "fedora":
                    _functions.add_efi_entry(_functions.PRODUCT_SHORT,
                                             ("\\EFI\\%s\\grubx64.efi" %
                                              self.efi_dir_name),
                                             efi_disk)
                else:
                    if os.path.isfile("/liveos/efi/EFI/redhat/grubx64.efi"):
                        _functions.add_efi_entry(_functions.PRODUCT_SHORT,
                                                 ("\\EFI\\%s\\grubx64.efi" %
                                                  self.efi_dir_name),
                                                 efi_disk)
                    else:
                        _functions.add_efi_entry(_functions.PRODUCT_SHORT,
                                                 ("\\EFI\\%s\\grub.efi" %
                                                  self.efi_dir_name),
                                                 efi_disk)
        self.kernel_image_copy()

        # reorder tty0 to allow both serial and phys console after installation
        if _functions.is_iscsi_install() or _functions.findfs("BootNew"):
            self.root_param = "root=live:LABEL=Root"
            if "OVIRT_NETWORK_LAYOUT" in OVIRT_VARS and \
                OVIRT_VARS["OVIRT_NETWORK_LAYOUT"] == "bridged":
                network_conf = "ip=br%s:dhcp bridge=br%s:%s" % \
                                (OVIRT_VARS["OVIRT_BOOTIF"],
                                 OVIRT_VARS["OVIRT_BOOTIF"],
                                 OVIRT_VARS["OVIRT_BOOTIF"])
            else:
                network_conf = "ip=%s:dhcp" % OVIRT_VARS["OVIRT_BOOTIF"]
            self.bootparams = "netroot=iscsi:%s::%s::%s %s " % (
                OVIRT_VARS["OVIRT_ISCSI_TARGET_HOST"],
                OVIRT_VARS["OVIRT_ISCSI_TARGET_PORT"],
                OVIRT_VARS["OVIRT_ISCSI_TARGET_NAME"],
                network_conf)
            if "OVIRT_ISCSI_NAME" in OVIRT_VARS:
                self.bootparams+= "iscsi_initiator=%s " % \
                    OVIRT_VARS["OVIRT_ISCSI_NAME"]
        else:
            self.root_param = "root=live:LABEL=Root"
            self.bootparams = "ro rootfstype=auto rootflags=ro "
        self.bootparams += OVIRT_VARS["OVIRT_BOOTPARAMS"].replace(
                                                            "console=tty0", ""
                                                            ).replace(
                                                            "rd_NO_MULTIPATH",
                                                            "")

        is_mpath_root = self.disk and self.disk.startswith("/dev/mapper")
        has_mpath_wwid = "mpath.wwid=" in self.bootparams
        if is_mpath_root and not has_mpath_wwid:
            """We need to specify the wwid of the root device if it
            is using multiple paths to prevent races within dracut.
            Basically there are two options:
            1. bake wwid of root device into initrd
            2. pass wwid of root device on kernel cmdline
            I choose 2 because it seems to be less invasive.
            https://bugzilla.redhat.com/show_bug.cgi?id=1152948
            """
            lsblkcmd = "lsblk -inls %s | awk 'FNR==2 {print $1}'" % self.disk
            lsblkproc = _functions.subprocess_closefds(lsblkcmd, shell=True,
                                                       stdout=subprocess.PIPE,
                                                       stderr=subprocess.STDOUT)
            lsblkout, lsblkerr = lsblkproc.communicate()
            logger.debug("lsblk returned: %s -- %s" % (lsblkout, lsblkerr))
            if not lsblkout.strip():
                raise RuntimeError("Failed to determin parent of partition: %s" % self.disk)
            part_parent = "/dev/mapper/" + lsblkout.strip()
            logger.debug("lsblk found parent for partition %s: %s" % (self.disk, part_parent))

            wwidcmd = "multipath -ll %s | egrep -o '^.*dm-[0-9]' | cut -d' ' -f1" % part_parent
            logger.debug("Checking device for multipath: %s" % wwidcmd)
            wwidproc = _functions.subprocess_closefds(wwidcmd, shell=True,
                                                      stdout=subprocess.PIPE,
                                                      stderr=subprocess.STDOUT)
            wwidout, wwiderr = wwidproc.communicate()
            logger.debug("multipath returned: %s -- %s" % (wwidout, wwiderr))
            wwid = wwidout.strip()
            if wwid:
                logger.debug("Using multipath wwid: %s" % wwid)
                self.bootparams += " mpath.wwid=%s" % wwid
                logger.debug("Cmdline with mpath: %s" % self.bootparams)
            else:
                logger.debug("Got NO multipath wwid, not using any")

        if " " in self.disk:
            # workaround for grub setup failing with spaces in dev.name:
            # use first active sd* device
            self.disk = re.sub("p[1,2,3]$", "", self.disk)
            grub_disk_cmd = ("multipath -l " +
                             "\"" + self.disk + "\" " +
                             "| egrep -o '[0-9]+:.*' " +
                             "| awk '/ active / {print $2}' " +
                             "| head -n1")
            logger.debug(grub_disk_cmd)
            grub_disk = _functions.subprocess_closefds(grub_disk_cmd,
                                            shell=True,
                                            stdout=subprocess.PIPE,
                                            stderr=subprocess.STDOUT)
            grub_disk_output, grub_disk_err = grub_disk.communicate()
            self.disk = grub_disk_output.strip()
            if "cciss" in self.disk:
                self.disk = self.disk.replace("!", "/")
            # flush to sync DM and blockdev, workaround from rhbz#623846#c14
            sysfs = open("/proc/sys/vm/drop_caches", "w")
            sysfs.write("3")
            sysfs.close()
        if not self.disk.startswith("/dev/"):
            self.disk = "/dev/" + self.disk
        try:
            if stat.S_ISBLK(os.stat(self.disk).st_mode):
                try:
                    if stat.S_ISBLK(os.stat(self.disk[:-1]).st_mode):
                        # e.g. /dev/sda2
                        self.disk = self.disk[:-1]
                except OSError:
                    pass
                try:
                    if stat.S_ISBLK(os.stat(self.disk[:-2]).st_mode):
                        # e.g. /dev/mapper/WWIDp2
                        self.disk = self.disk[:-2]
                except OSError:
                    pass
        except OSError:
            logger.error("Unable to determine disk for grub installation " +
                         traceback.format_exc())
            return False

        self.grub_dict = {
        "product": _functions.PRODUCT_SHORT,
        "version": _functions.PRODUCT_VERSION,
        "release": _functions.PRODUCT_RELEASE,
        "partN": self.partN,
        "root_param": self.root_param,
        "bootparams": self.bootparams,
        "disk": self.disk,
        "grub_dir": self.grub_dir,
        "grub_prefix": self.grub_prefix,
        "efi_hd": self.efi_hd,
        "linux": "linux",
        "initrd": "initrd",
    }
        if not _functions.is_firstboot():
            if os.path.ismount("/live"):
                with open("%s/version" % self.live_path) as version:
                    for line in version.readlines():
                        if "VERSION" in line:
                            key, value = line.split("=")
                            self.grub_dict["version"] = value.strip()
                        if "RELEASE" in line:
                            key, value = line.split("=")
                            self.grub_dict["release"] = value.strip()

        if _functions.grub2_available():
            if not self.grub2_install():
                logger.error("Grub2 Installation Failed ")
                return False
            else:
                 logger.info("Grub2 EFI Installation Completed ")
        else:
            if not self.grub_install():
                logger.error("Grub Installation Failed ")
                return False
            else:
                logger.info("Grub Installation Completed")

        if _functions.is_iscsi_install() or _functions.findfs("BootNew"):
            # copy default for when Root/HostVG is inaccessible(iscsi upgrade)
            shutil.copy(_functions.OVIRT_DEFAULTS, "/boot")
            # mark new Boot ready to go, reboot() in ovirt-function switches it
            # to active
            e2label_cmd = "e2label \"%s\" BootUpdate" % boot_candidate_dev

            if not _functions.system(e2label_cmd):
                logger.error("Unable to relabel " + boot_candidate_dev +
                             " to RootUpdate ")
                return False
        else:
            _functions.system("umount /liveos/efi")
        _functions.system("umount /liveos")
        # mark new Root ready to go, reboot() in ovirt-function switches it
        # to active
        e2label_cmd = "e2label \"%s\" RootUpdate" % candidate_dev
        if not _functions.system(e2label_cmd):
            logger.error("Unable to relabel " + candidate_dev +
                         " to RootUpdate ")
            return False
        _functions.disable_firstboot()
        if _functions.finish_install():
            if _functions.is_firstboot():
                _iscsi.iscsi_auto()
            logger.info("Installation of %s Completed" % \
                                                      _functions.PRODUCT_SHORT)
            if reboot is not None and reboot == "Y":
                _system.async_reboot()
            return True
        else:
            return False
Example #36
0
    def ovirt_boot_setup(self, reboot="N"):
        self.generate_paths()
        logger.info("Installing the image.")

        if "OVIRT_ROOT_INSTALL" in OVIRT_VARS:
            if OVIRT_VARS["OVIRT_ROOT_INSTALL"] == "n":
                logger.info("Root Installation Not Required, Finished.")
                return True
        self.oldtitle=None
        grub_config_file = None
        _functions.mount_liveos()
        if os.path.ismount("/liveos"):
            if os.path.exists("/liveos/vmlinuz0") and os.path.exists("/liveos/initrd0.img"):
                grub_config_file = self.grub_config_file
        elif not _functions.is_firstboot():
            # find existing iscsi install
            if _functions.findfs("Boot"):
                grub_config_file = "/boot/grub/grub.conf"
            elif os.path.ismount("/dev/.initramfs/live"):
                if not _functions.grub2_available():
                    grub_config_file = "/dev/.initramfs/live/grub/grub.conf"
                else:
                    grub_config_file = "/dev/.initramfs/live/grub2/grub.cfg"
            elif os.path.ismount("/run/initramfs/live"):
                grub_config_file = "/run/initramfs/live/grub/grub.conf"
            if _functions.is_upgrade() and not _functions.is_iscsi_install():
                mount_liveos()
                grub_config_file = "/liveos/grub/grub.conf"
        if _functions.is_efi_boot():
            logger.debug(str(os.listdir("/liveos")))
            _functions.system("umount /liveos")
            _functions.mount_efi(target="/liveos")
            grub_config_file = "/liveos/EFI/%s/grub.cfg" % self.efi_dir_name
        if _functions.is_iscsi_install():
            grub_config_file = "/boot/grub/grub.conf"
        grub_config_file_exists = grub_config_file is not None and os.path.exists(grub_config_file)
        logger.debug("Grub config file is: %s" % grub_config_file)
        logger.debug("Grub config file exists: %s" % grub_config_file_exists)
        if not grub_config_file is None and os.path.exists(grub_config_file):
            f=open(grub_config_file)
            oldgrub=f.read()
            f.close()
            if _functions.grub2_available():
                m=re.search("^menuentry (.*)$", oldgrub, re.MULTILINE)
            else:
                m=re.search("^title (.*)$", oldgrub, re.MULTILINE)
            if m is not None:
                self.oldtitle=m.group(1)
                # strip off extra title characters
                if _functions.grub2_available():
                    self.oldtitle = self.oldtitle.replace('"','').strip(" {")
        _functions.system("umount /liveos/efi")
        _functions.system("umount /liveos")
        if _functions.is_iscsi_install():
            self.boot_candidate = None
            boot_candidate_names = ["BootBackup", "BootUpdate", "BootNew"]
            for trial in range(1, 3):
                time.sleep(1)
                _functions.system("partprobe")
                for candidate_name in boot_candidate_names:
                    if _functions.findfs(candidate_name):
                        self.boot_candidate = candidate_name
                        break
                logger.debug("Trial %s to find candidate (%s)" % \
                             (trial, self.boot_candidate))
                if self.boot_candidate:
                    logger.debug("Found candidate: %s" % self.boot_candidate)
                    break

            if not self.boot_candidate:
                logger.error("Unable to find boot partition")
                label_debug = ''
                for label in os.listdir("/dev/disk/by-label"):
                    label_debug += "%s\n" % label
                label_debug += _functions.subprocess_closefds("blkid", \
                                          shell=True, stdout=subprocess.PIPE,
                                          stderr=subprocess.STDOUT).stdout.read()
                logger.debug(label_debug)
                return False
            else:
                boot_candidate_dev = _functions.findfs(self.boot_candidate)
            # prepare Root partition update
            if self.boot_candidate != "BootNew":
                e2label_cmd = "e2label \"%s\" BootNew" % boot_candidate_dev
                logger.debug(e2label_cmd)
                if not _functions.system(e2label_cmd):
                    logger.error("Failed to label new Boot partition")
                    return False
            _functions.system("mount LABEL=%s /boot &>/dev/null" % self.boot_candidate)

            if os.path.exists("/boot/ovirt"):
                try:
                    f = open("/boot/ovirt", 'r')
                    for line in f:
                        try:
                            line = line.strip()
                            key, value = line.split("\"", 1)
                            key = key.strip("=")
                            key = key.strip()
                            value = value.strip("\"")
                            OVIRT_VARS[key] = value
                        except:
                            pass
                    f.close()
                    iscsiadm_cmd = (("iscsiadm -p %s:%s -m discovery -t " +
                                     "sendtargets") % (
                                        OVIRT_VARS["OVIRT_ISCSI_TARGET_IP"],
                                        OVIRT_VARS["OVIRT_ISCSI_TARGET_PORT"]))
                    _functions.system(iscsiadm_cmd)
                    logger.info("Restarting iscsi service")
                    _functions.system("service iscsi restart")
                except:
                    pass

        candidate = None
        candidate_names = ["RootBackup", "RootUpdate", "RootNew"]
        for trial in range(1, 3):
            time.sleep(1)
            _functions.system("partprobe")
            for candidate_name in candidate_names:
                if _functions.findfs(candidate_name):
                    candidate = candidate_name
                    break
            logger.debug("Trial %s to find candidate (%s)" % (trial,
                                                              candidate))
            if candidate:
                logger.debug("Found candidate: %s" % candidate)
                break

        if not candidate:
            logger.error("Unable to find root partition")
            label_debug = ''
            for label in os.listdir("/dev/disk/by-label"):
                label_debug += "%s\n" % label
            label_debug += _functions.subprocess_closefds("blkid", shell=True,
                                      stdout=subprocess.PIPE,
                                      stderr=subprocess.STDOUT).stdout.read()
            logger.debug(label_debug)
            return False

        try:
            candidate_dev = self.disk = _functions.findfs(candidate)
            logger.info(candidate_dev)
            logger.info(self.disk)
            # grub2 starts at part 1
            self.partN = int(self.disk[-1:])
            if not _functions.grub2_available():
                self.partN = self.partN - 1
        except:
            logger.debug(traceback.format_exc())
            return False

        if self.disk is None or self.partN < 0:
            logger.error("Failed to determine Root partition number")
            return False
        # prepare Root partition update
        if candidate != "RootNew":
            e2label_cmd = "e2label \"%s\" RootNew" % candidate_dev
            logger.debug(e2label_cmd)
            if not _functions.system(e2label_cmd):
                logger.error("Failed to label new Root partition")
                return False
        mount_cmd = "mount \"%s\" /liveos" % candidate_dev
        _functions.system(mount_cmd)
        _functions.system("rm -rf /liveos/LiveOS")
        _functions.system("mkdir -p /liveos/LiveOS")
        _functions.mount_live()

        if os.path.isdir(self.grub_dir):
            shutil.rmtree(self.grub_dir)
        if not os.path.exists(self.grub_dir):
            os.makedirs(self.grub_dir)
            if _functions.is_efi_boot():
                logger.info("efi detected, installing efi configuration")
                _functions.system("mkdir /liveos/efi")
                _functions.mount_efi()
                _functions.system("mkdir -p /liveos/efi/EFI/redhat")
                _functions.system("cp /boot/efi/EFI/redhat/grub.efi " +
                      "/liveos/efi/EFI/redhat/grub.efi")
                if not "/dev/mapper/" in self.disk:
                   efi_disk = self.disk[:-1]
                else:
                   efi_disk = re.sub("p[1,2,3]$", "", self.disk)
                # generate grub legacy config for efi partition
                #remove existing efi entries
                _functions.remove_efi_entry(self.efi_dir_name)
                efi_mgr_cmd = ("efibootmgr -c -l '\\EFI\\%s\\grubx64.efi' " +
                              "-L '%s' -d %s -v") % (self.efi_dir_name,  \
                                               _functions.PRODUCT_SHORT, \
                                               efi_disk)
                logger.info(efi_mgr_cmd)
                _functions.system(efi_mgr_cmd)
        self.kernel_image_copy()

        # reorder tty0 to allow both serial and phys console after installation
        if _functions.is_iscsi_install():
            self.root_param = "root=live:LABEL=Root"
            self.bootparams = "netroot=iscsi:%s::%s::%s ip=br%s:dhcp bridge=br%s:%s " % (
                OVIRT_VARS["OVIRT_ISCSI_TARGET_HOST"],
                OVIRT_VARS["OVIRT_ISCSI_TARGET_PORT"],
                OVIRT_VARS["OVIRT_ISCSI_TARGET_NAME"],
                OVIRT_VARS["OVIRT_BOOTIF"],
                OVIRT_VARS["OVIRT_BOOTIF"],
                OVIRT_VARS["OVIRT_BOOTIF"])
        else:
            self.root_param = "root=live:LABEL=Root"
            self.bootparams = "ro rootfstype=auto rootflags=ro "
        self.bootparams += OVIRT_VARS["OVIRT_BOOTPARAMS"].replace(
                                                            "console=tty0", "")
        if " " in self.disk or os.path.exists("/dev/cciss"):
            # workaround for grub setup failing with spaces in dev.name:
            # use first active sd* device
            self.disk = re.sub("p[1,2,3]$", "", self.disk)
            grub_disk_cmd = "multipath -l \"" + self.disk + \
                            "\" | awk '/ active / {print $3}' | head -n1"
            logger.debug(grub_disk_cmd)
            grub_disk = _functions.subprocess_closefds(grub_disk_cmd,
                                            shell=True,
                                            stdout=subprocess.PIPE,
                                            stderr=subprocess.STDOUT)
            self.disk = grub_disk.stdout.read().strip()
            if "cciss" in self.disk:
                self.disk = self.disk.replace("!", "/")
            # flush to sync DM and blockdev, workaround from rhbz#623846#c14
            sysfs = open("/proc/sys/vm/drop_caches", "w")
            sysfs.write("3")
            sysfs.close()
            partprobe_cmd = "partprobe \"/dev/%s\"" % self.disk
            logger.debug(partprobe_cmd)
            _functions.system(partprobe_cmd)

        if not self.disk.startswith("/dev/"):
            self.disk = "/dev/" + self.disk
        try:
            if stat.S_ISBLK(os.stat(self.disk).st_mode):
                try:
                    if stat.S_ISBLK(os.stat(self.disk[:-1]).st_mode):
                        # e.g. /dev/sda2
                        self.disk = self.disk[:-1]
                except OSError:
                    pass
                try:
                    if stat.S_ISBLK(os.stat(self.disk[:-2]).st_mode):
                        # e.g. /dev/mapper/WWIDp2
                        self.disk = self.disk[:-2]
                except OSError:
                    pass
        except OSError:
            logger.error("Unable to determine disk for grub installation " +
                         traceback.format_exc())
            return False

        self.grub_dict = {
        "product": _functions.PRODUCT_SHORT,
        "version": _functions.PRODUCT_VERSION,
        "release": _functions.PRODUCT_RELEASE,
        "partN": self.partN,
        "root_param": self.root_param,
        "bootparams": self.bootparams,
        "disk": self.disk,
        "grub_dir": self.grub_dir,
        "grub_prefix": self.grub_prefix,
        "efi_hd": self.efi_hd
    }
        if not _functions.is_firstboot():
            if os.path.ismount("/live"):
                with open("/live/%s/version" % self.syslinux) as version:
                    for line in version.readlines():
                        if "VERSION" in line:
                            key, value = line.split("=")
                            self.grub_dict["version"] = value.strip()
                        if "RELEASE" in line:
                            key, value = line.split("=")
                            self.grub_dict["release"] = value.strip()

        if _functions.grub2_available():
            if not self.grub2_install():
                logger.error("Grub2 Installation Failed ")
                return False
            else:
                 logger.info("Grub2 EFI Installation Completed ")
        else:
            if not self.grub_install():
                logger.error("Grub Installation Failed ")
                return False
            else:
                logger.info("Grub Installation Completed")

        if _functions.is_iscsi_install():
            # copy default for when Root/HostVG is inaccessible(iscsi upgrade)
            shutil.copy(_functions.OVIRT_DEFAULTS, "/boot")
            # mark new Root ready to go, reboot() in ovirt-function switches it
            # to active
            e2label_cmd = "e2label \"%s\" BootUpdate" % boot_candidate_dev

            if not _functions.system(e2label_cmd):
                logger.error("Unable to relabel " + boot_candidate_dev +
                             " to RootUpdate ")
                return False
        else:
            _functions.system("umount /liveos/efi")
        _functions.system("umount /liveos")
        # mark new Root ready to go, reboot() in ovirt-function switches it
        # to active
        e2label_cmd = "e2label \"%s\" RootUpdate" % candidate_dev
        if not _functions.system(e2label_cmd):
            logger.error("Unable to relabel " + candidate_dev +
                         " to RootUpdate ")
            return False
        _functions.disable_firstboot()
        if _functions.finish_install():
            if _functions.is_firstboot():
                _iscsi.iscsi_auto()
            logger.info("Installation of %s Completed" % \
                                                      _functions.PRODUCT_SHORT)
            if reboot is not None and reboot == "Y":
                _system.async_reboot()
            return True
        else:
            return False
Example #37
0
    def save_network_configuration(self):
        _functions.aug.load()
        net_configured = 0
        _functions.augtool_workdir_list = "ls %s/augtool-* >/dev/null"
        logger.info("Configuring network for NIC %s" % self.CONFIGURED_NIC)
        # Wee need to bring down all network stuff, with the current network
        # config, before we change the config. Otherwise the interfaces can
        # not be brought down correctly.
        logger.info("Stopping Network services")
        _functions.system("service network stop")
        # FIXME can't this be done further down were we remove the bridges?
        for vlan in get_system_vlans():
            # XXX wrong match e.g. eth10.1 with eth1
            if self.CONFIGURED_NIC in vlan:
                _functions.system_closefds("vconfig rem " + vlan + \
                                           "&> /dev/null")
                _functions.ovirt_safe_delete_config(self.IFSCRIPTS_PATH + vlan)
                _functions.system_closefds("rm -rf " + \
                                           self.IFSCRIPTS_PATH + vlan)

        # All old config files are gone, the new ones are created step by step

        logger.debug("Removing persisted network configs")
        # This should cover NICs, VLANs and bridges
        for script in glob("%s*" % (self.IFSCRIPTS_PATH)):
            if not _functions.is_persisted(script):
                continue
            logger.debug("Removing Script: " + script)
            _functions.ovirt_safe_delete_config(script)
        _functions.aug.load()

        logger.debug("Updating interface config")
        for line in self.IF_CONFIG:
            logger.debug(line)
            try:
                oper, key, value = line.split()
                _functions.augtool(oper, key, value)
            except:
                oper, key = line.split()
                _functions.augtool(oper, key, "")

        logger.debug("Updating bridge config")
        if not self.disabled_nic == 1:
            for line in self.BR_CONFIG:
                logger.debug(line)
                try:
                    oper, key, value = line.split()
                    _functions.augtool(oper, key, value)
                except:
                    try:
                        oper, key = line.split()
                        _functions.augtool(oper, key, "")
                    except:
                        pass

            logger.debug("Updating VLAN config")
            for line in self.VL_CONFIG.split("\n"):
                logger.debug(line)
                try:
                    oper, key, value = line.split()
                    _functions.augtool(oper, key, value)
                except:
                    try:
                        oper, key = line.split()
                        _functions.augtool(oper, key, "")
                    except:
                        pass

        # preserve current MAC mappings for *all physical* network interfaces
        logger.debug("Preserving current MAC mappings")
        for nicdev in glob('/sys/class/net/*/device'):
            nic = nicdev.split('/')[4]
            if nic != self.CONFIGURED_NIC:
                f = open('/sys/class/net/%s/address' % nic)
                mac = f.read().strip()
                f.close()
                if len(mac) > 0:
                    logger.debug("Mapping for %s" % nic)
                    self.CONFIGURED_NICS.append(nic)
                    nicroot = "%s%s" % (self.IFCONFIG_FILE_ROOT, nic)
                    # XXX _functions.augtool does save every time!
                    _functions.augtool("set", "%s/DEVICE" % nicroot, nic)
                    _functions.augtool("set", "%s/HWADDR" % nicroot, mac)
                    _functions.augtool("set", "%s/ONBOOT" % nicroot, "no")

        logger.debug("Storing configured NICs")
        net_configured = 1
        for nic in self.CONFIGURED_NICS:
            logger.debug("Storing %s" % nic)
            _functions.ovirt_store_config("%s%s" % (self.IFSCRIPTS_PATH, nic))
        _functions.ovirt_store_config(self.NTP_CONFIG_FILE)
        if self.disabled_nic == 1:
            _functions.augtool("set", \
                               "/files/etc/sysconfig/network/NETWORKING", "no")
        else:
            _functions.augtool("set", \
                               "/files/etc/sysconfig/network/NETWORKING", "yes")
        _functions.ovirt_store_config("/etc/sysconfig/network")
        _functions.ovirt_store_config("/etc/hosts")

        # Copy the initial net rules to a file that get's not
        # overwritten at each boot, rhbz#773495
        rulesfile = "/etc/udev/rules.d/70-persistent-net.rules"
        newrulesfile = "/etc/udev/rules.d/71-persistent-node-net.rules"
        if os.path.exists(rulesfile):
            _functions.system_closefds("cp %s %s >> /var/log/ovirt.log" % (
                                                                rulesfile,
                                                                newrulesfile))
            _functions.ovirt_store_config(newrulesfile)

            # Eventully it makes sense to rename the NICs
            #system_closefds("sed -ic 's/NAME=\"eth/NAME=\"eth00/' " +
            #                 "/etc/udev/rules.d/71-persistent-node-net.rules")



        logger.info("Network configured successfully")
        if net_configured == 1:
            logger.info("Stopping Network services")
            _functions.system_closefds("service network stop &> /dev/null")
            _functions.system_closefds("service ntpd stop &> /dev/null")
            # XXX eth assumed in breth
            brctl_cmd = "ip --details --oneline link " \
                "| awk -F':' '/^[0-9]: br[ep]/ {print $2}'"
            brctl = _functions.subprocess_closefds(brctl_cmd, shell=True,
                                                   stdout=subprocess.PIPE,
                                        stderr=subprocess.STDOUT)
            brctl_output = brctl.stdout.read()
            for i in brctl_output.split():
                if_down_cmd = "ifconfig %s down &> /dev/null" % i
                _functions.system_closefds(if_down_cmd)
                del_br_cmd = "ip link delete %s type bridge &> /dev/null" % i
                _functions.system_closefds(del_br_cmd)
            logger.info("Starting Network service")
            _functions.system_closefds("service network start &> /dev/null")
            _functions.system_closefds("service ntpdate start &> /dev/null")
            _functions.system_closefds("service ntpd start &> /dev/null")
            # rhbz#745541
            _functions.system_closefds("service rpcbind start &> /dev/null")
            _functions.system_closefds("service nfslock start &> /dev/null")
            _functions.system_closefds("service rpcidmapd start &> /dev/null")
            _functions.system_closefds("service rpcgssd start &> /dev/null")
            if "NTP" in OVIRT_VARS:
                logger.info("Testing NTP Configuration")
                _functions.test_ntp_configuration()
Example #38
0
    def grub_install(self):
        if _functions.is_iscsi_install():
            self.disk = re.sub("p[1,2,3]$", "", _functions.findfs(self.boot_candidate))
        device_map = "(hd0) %s" % self.disk
        logger.debug(device_map)
        device_map_conf = open(self.grub_dir + "/device.map", "w")
        device_map_conf.write(device_map)
        device_map_conf.close()

        GRUB_CONFIG_TEMPLATE = """
default saved
timeout 5
hiddenmenu
%(splashscreen)s
title %(product)s %(version)s-%(release)s
    root (hd0,%(partN)d)
    kernel /vmlinuz0 %(root_param)s %(bootparams)s
    initrd /initrd0.img
    """
        GRUB_BACKUP_TEMPLATE = """
title BACKUP %(oldtitle)s
    root (hd0,%(partB)d)
    kernel /vmlinuz0 root=live:LABEL=RootBackup %(bootparams)s
    initrd /initrd0.img
    savedefault
    """
        GRUB_SETUP_TEMPLATE = """
    grub --device-map=%(grub_dir)s/device.map <<EOF
root (hd0,%(partN)d)
setup --prefix=%(grub_prefix)s (hd0)
EOF
"""

        if _functions.is_efi_boot():
            """ The EFI product path.
                eg: HD(1,800,64000,faacb4ef-e361-455e-bd97-ca33632550c3)
            """
            efi_cmd = "efibootmgr -v"
            efi = _functions.subprocess_closefds(efi_cmd, shell=True,
                                                 stdout=subprocess.PIPE,
                                                 stderr=subprocess.STDOUT)
            efi_out = efi.stdout.read().strip()
            matches = re.search(_functions.PRODUCT_SHORT + r'\s+(HD\(.+?\))', \
                                                                       efi_out)
            if matches and matches.groups():
                GRUB_EFIONLY_CONFIG = """%(efi_hd)s"""
                GRUB_CONFIG_TEMPLATE = GRUB_EFIONLY_CONFIG + GRUB_CONFIG_TEMPLATE
                self.grub_dict['efi_hd'] = "device (hd0) " + matches.group(1)
        if os.path.exists("/live/EFI/BOOT/splash.xpm.gz"):
            splashscreen = "splashimage=(hd0,%s)/grub/splash.xpm.gz" \
                % self.partN
        else:
            splashscreen = ""
        self.grub_dict["splashscreen"] = splashscreen
        GRUB_CONFIG_TEMPLATE % self.grub_dict
        grub_conf = open(self.grub_config_file, "w")
        grub_conf.write(GRUB_CONFIG_TEMPLATE % self.grub_dict)
        if self.oldtitle is not None:
            partB = 1
            if self.partN == 1:
                partB = 2
            if _functions.is_iscsi_install():
                partB = 0
                if self.partN == 0:
                    partB = 1
            self.grub_dict['oldtitle'] = self.oldtitle
            self.grub_dict['partB'] = partB
            grub_conf.write(GRUB_BACKUP_TEMPLATE % self.grub_dict)
        grub_conf.close()
        # splashscreen
        _functions.system("cp /live/EFI/BOOT/splash.xpm.gz /liveos/grub")
        # usb devices requires default BOOTX64 entries
        if _functions.is_efi_boot():
            _functions.system("mkdir -p /liveos/efi/EFI/BOOT")
            _functions.system("cp /boot/efi/EFI/redhat/grub.efi /liveos/efi/EFI/BOOT/BOOTX64.efi")
            _functions.system("cp %s /liveos/efi/EFI/BOOT/BOOTX64.conf" % self.grub_config_file)
            _functions.system("umount /liveos/efi")
        if not _functions.is_efi_boot():
            for f in ["stage1", "stage2", "e2fs_stage1_5"]:
                _functions.system("cp /usr/share/grub/x86_64-redhat/%s %s" % \
                                                            (f, self.grub_dir))
            grub_setup_out = GRUB_SETUP_TEMPLATE % self.grub_dict
            logger.debug(grub_setup_out)
            grub_setup = _functions.subprocess_closefds(grub_setup_out,
                                             shell=True,
                                             stdout=subprocess.PIPE,
                                             stderr=subprocess.STDOUT)
            grub_results = grub_setup.stdout.read()
            logger.debug(grub_results)
            if grub_setup.wait() != 0 or "Error" in grub_results:
                logger.error("GRUB setup failed")
                return False
        return True
Example #39
0
    def grub2_install(self):

        GRUB2_EFI_CONFIG_TEMPLATE = """
insmod efi_gop
insmod efi_uga
"""

        GRUB2_CONFIG_TEMPLATE = """
#default saved
set timeout=5
#hiddenmenu
menuentry "%(product)s %(version)s-%(release)s" {
set root=(hd0,%(partN)d)
linux /vmlinuz0 %(root_param)s %(bootparams)s
initrd /initrd0.img
}"""

        GRUB2_BACKUP_TEMPLATE = """
menuentry "BACKUP %(oldtitle)s" {
set root (hd0,%(partB)d)
linux /vmlinuz0 root=live:LABEL=RootBackup %(bootparams)s
initrd /initrd0.img
    """
        # if efi is detected only install grub-efi
        if not _functions.is_efi_boot():
            logger.info("efi not detected, installing grub2 configuraton")
            if _functions.is_iscsi_install():
                disk = re.sub("p[1,2,3]$", "", \
                                        _functions.findfs(self.boot_candidate))
            else:
                disk = self.disk
            grub_setup_cmd = ("/sbin/grub2-install " + disk +
                              " --boot-directory=" + self.initrd_dest +
                              " --force")
            logger.info(grub_setup_cmd)
            grub_setup = _functions.subprocess_closefds(grub_setup_cmd, \
                                             shell=True,
                                             stdout=subprocess.PIPE,
                                             stderr=subprocess.STDOUT)
            grub_results = grub_setup.stdout.read()
            logger.info(grub_results)
            if grub_setup.wait() != 0 or "Error" in grub_results:
                logger.error("GRUB efi setup failed")
                return False
            else:
                logger.debug("Generating Grub2 Templates")
                grub_conf = open(self.grub_config_file, "w")
                grub_conf.write(GRUB2_CONFIG_TEMPLATE % self.grub_dict)
            if self.oldtitle is not None:
                partB = 0
                if self.partN == 0:
                    partB = 1
                self.grub_dict['oldtitle'] = self.oldtitle
                self.grub_dict['partB'] = partB
                grub_conf.write(GRUB2_BACKUP_TEMPLATE % self.grub_dict)
            grub_conf.close()
            if os.path.exists("/liveos/efi"):
                efi_grub_conf = open("/liveos/grub2-efi/grub.cfg", "w")
                # inject efi console output modules
                efi_grub_conf.write(GRUB2_EFI_CONFIG_TEMPLATE)
                efi_grub_conf.write(GRUB2_CONFIG_TEMPLATE % self.grub_dict)
                if self.oldtitle is not None:
                    partB = 0
                    if self.partN == 0:
                        partB = 1
                    self.grub_dict['oldtitle'] = self.oldtitle
                    self.grub_dict['partB'] = partB
                    efi_grub_conf.write(GRUB2_BACKUP_TEMPLATE % self.grub_dict)
                efi_grub_conf.close()
                _functions.system("umount /liveos/efi")
            logger.info("Grub2 Install Completed")
            return True