def get_device_name(devspec):

    devices = nm.nm_devices()
    devname = None

    if not devspec:
        if "ksdevice" in flags.cmdline:
            msg = "ksdevice boot parameter"
            devname = ks_spec_to_device_name(flags.cmdline["ksdevice"])
        elif nm.nm_is_connected():
            # device activated in stage 1 by network kickstart command
            msg = "first active device"
            try:
                devname = nm.nm_activated_devices()[0]
            except IndexError:
                log.debug("get_device_name: NM is connected but no activated devices found")
        else:
            msg = "first device found"
            devname = min(devices)
        log.info("unspecified network --device in kickstart, using %s (%s)", devname, msg)
    else:
        if iutil.lowerASCII(devspec) == "ibft":
            devname = ""
        if iutil.lowerASCII(devspec) == "link":
            for dev in sorted(devices):
                try:
                    link_up = nm.nm_device_carrier(dev)
                except ValueError as e:
                    log.debug("get_device_name: %s", e)
                    continue
                if link_up:
                    devname = dev
                    break
            else:
                log.error("Kickstart: No network device with link found")
        elif iutil.lowerASCII(devspec) == "bootif":
            if "BOOTIF" in flags.cmdline:
                # MAC address like 01-aa-bb-cc-dd-ee-ff
                devname = flags.cmdline["BOOTIF"][3:]
                devname = devname.replace("-", ":")
            else:
                log.error("Using --device=bootif without BOOTIF= boot option supplied")
        else:
            devname = devspec

    if devname and devname not in devices:
        for d in devices:
            try:
                hwaddr = nm.nm_device_hwaddress(d)
            except ValueError as e:
                log.debug("get_device_name: %s", e)
                continue
            if hwaddr.lower() == devname.lower():
                devname = d
                break
        else:
            return ""

    return devname
def validate_mountpoint(mountpoint, used_mountpoints, strict=True):
    if strict:
        fake_mountpoints = []
    else:
        fake_mountpoints = ["swap", "biosboot", "prepboot"]

    if mountpoint in used_mountpoints:
        return _("That mount point is already in use. Try something else?")
    elif not mountpoint:
        return _("Please enter a valid mount point.")
    elif mountpoint in system_mountpoints:
        return _("That mount point is invalid. Try something else?")
    elif (lowerASCII(mountpoint) not in fake_mountpoints and
          ((len(mountpoint) > 1 and mountpoint.endswith("/")) or
           not mountpoint.startswith("/") or
           " " in mountpoint or
           re.search(r'/\.*/', mountpoint) or
           re.search(r'/\.+$', mountpoint))):
        # - does not end with '/' unless mountpoint _is_ '/'
        # - starts with '/' except for "swap", &c
        # - does not contain spaces
        # - does not contain pairs of '/' enclosing zero or more '.'
        # - does not end with '/' followed by one or more '.'
        return _("That mount point is invalid. Try something else?")
    else:
        return ""
def validate_mountpoint(mountpoint, used_mountpoints, strict=True):
    if strict:
        fake_mountpoints = []
    else:
        fake_mountpoints = ["swap", "biosboot", "prepboot"]

    if mountpoint in used_mountpoints:
        return _("That mount point is already in use. Try something else?")
    elif not mountpoint:
        return _("Please enter a valid mount point.")
    elif mountpoint in system_mountpoints:
        return _("That mount point is invalid. Try something else?")
    elif (lowerASCII(mountpoint) not in fake_mountpoints
          and ((len(mountpoint) > 1 and mountpoint.endswith("/"))
               or not mountpoint.startswith("/") or " " in mountpoint
               or re.search(r'/\.*/', mountpoint)
               or re.search(r'/\.+$', mountpoint))):
        # - does not end with '/' unless mountpoint _is_ '/'
        # - starts with '/' except for "swap", &c
        # - does not contain spaces
        # - does not contain pairs of '/' enclosing zero or more '.'
        # - does not end with '/' followed by one or more '.'
        return _("That mount point is invalid. Try something else?")
    else:
        return ""
def dracutBootArguments(devname, ifcfg, storage_ipaddr, hostname=None):

    netargs = set()

    if ifcfg.get('BOOTPROTO') == 'ibft':
        netargs.add("ip=ibft")
    elif storage_ipaddr:
        if hostname is None:
            hostname = ""
        # if using ipv6
        if ':' in storage_ipaddr:
            if ifcfg.get('DHCPV6C') == "yes":
                # XXX combination with autoconf not yet clear,
                # support for dhcpv6 is not yet implemented in NM/ifcfg-rh
                netargs.add("ip=%s:dhcp6" % devname)
            elif ifcfg.get('IPV6_AUTOCONF') == "yes":
                netargs.add("ip=%s:auto6" % devname)
            elif ifcfg.get('IPV6ADDR'):
                ipaddr = "[%s]" % ifcfg.get('IPV6ADDR')
                if ifcfg.get('IPV6_DEFAULTGW'):
                    gateway = "[%s]" % ifcfg.get('IPV6_DEFAULTGW')
                else:
                    gateway = ""
                netargs.add(
                    "ip=%s::%s:%s:%s:%s:none" %
                    (ipaddr, gateway, ifcfg.get('PREFIX'), hostname, devname))
        else:
            if iutil.lowerASCII(ifcfg.get('bootproto')) == 'dhcp':
                netargs.add("ip=%s:dhcp" % devname)
            else:
                if ifcfg.get('GATEWAY'):
                    gateway = ifcfg.get('GATEWAY')
                else:
                    gateway = ""

                netmask = ifcfg.get('netmask')
                prefix = ifcfg.get('prefix')
                if not netmask and prefix:
                    netmask = prefix2netmask(int(prefix))

                netargs.add(
                    "ip=%s::%s:%s:%s:%s:none" %
                    (ifcfg.get('ipaddr'), gateway, netmask, hostname, devname))

        hwaddr = ifcfg.get("HWADDR")
        if hwaddr:
            netargs.add("ifname=%s:%s" % (devname, hwaddr.lower()))

    nettype = ifcfg.get("NETTYPE")
    subchannels = ifcfg.get("SUBCHANNELS")
    if blivet.arch.isS390() and nettype and subchannels:
        znet = "rd.znet=%s,%s" % (nettype, subchannels)
        options = ifcfg.get("OPTIONS").strip("'\"")
        if options:
            options = filter(lambda x: x != '', options.split(' '))
            znet += ",%s" % (','.join(options))
        netargs.add(znet)

    return netargs
Example #5
0
def dracutBootArguments(devname, ifcfg, storage_ipaddr, hostname=None):

    netargs = set()

    if ifcfg.get('BOOTPROTO') == 'ibft':
        netargs.add("ip=ibft")
    elif storage_ipaddr:
        if hostname is None:
            hostname = ""
        # if using ipv6
        if ':' in storage_ipaddr:
            if ifcfg.get('DHCPV6C') == "yes":
                # XXX combination with autoconf not yet clear,
                # support for dhcpv6 is not yet implemented in NM/ifcfg-rh
                netargs.add("ip=%s:dhcp6" % devname)
            elif ifcfg.get('IPV6_AUTOCONF') == "yes":
                netargs.add("ip=%s:auto6" % devname)
            elif ifcfg.get('IPV6ADDR'):
                ipaddr = "[%s]" % ifcfg.get('IPV6ADDR')
                if ifcfg.get('IPV6_DEFAULTGW'):
                    gateway = "[%s]" % ifcfg.get('IPV6_DEFAULTGW')
                else:
                    gateway = ""
                netargs.add("ip=%s::%s:%s:%s:%s:none" % (ipaddr, gateway,
                           ifcfg.get('PREFIX'), hostname, devname))
        else:
            if iutil.lowerASCII(ifcfg.get('bootproto')) == 'dhcp':
                netargs.add("ip=%s:dhcp" % devname)
            else:
                if ifcfg.get('GATEWAY'):
                    gateway = ifcfg.get('GATEWAY')
                else:
                    gateway = ""

                netmask = ifcfg.get('netmask')
                prefix  = ifcfg.get('prefix')
                if not netmask and prefix:
                    netmask = prefix2netmask(int(prefix))

                netargs.add("ip=%s::%s:%s:%s:%s:none" % (ifcfg.get('ipaddr'),
                           gateway, netmask, hostname, devname))

        hwaddr = ifcfg.get("HWADDR")
        if hwaddr:
            netargs.add("ifname=%s:%s" % (devname, hwaddr.lower()))

    nettype = ifcfg.get("NETTYPE")
    subchannels = ifcfg.get("SUBCHANNELS")
    if blivet.arch.isS390() and nettype and subchannels:
        znet = "rd.znet=%s,%s" % (nettype, subchannels)
        options = ifcfg.get("OPTIONS").strip("'\"")
        if options:
            options = filter(lambda x: x != '', options.split(' '))
            znet += ",%s" % (','.join(options))
        netargs.add(znet)

    return netargs
Example #6
0
 def lower_ascii_test(self):
     """Test lowerASCII."""
     self.assertEqual(iutil.lowerASCII(""), "")
     self.assertEqual(iutil.lowerASCII("A"), "a")
     self.assertEqual(iutil.lowerASCII("a"), "a")
     self.assertEqual(iutil.lowerASCII("aBc"), "abc")
     self.assertEqual(iutil.lowerASCII("_&*'@#$%^aBcžčŘ"), "_&*'@#$%^abczcr")
     _out = "heizolruckstoabdampfung"
     self.assertEqual(iutil.lowerASCII("Heizölrückstoßabdämpfung"), _out)
    def addMessage(self, name, argc):
        if name in self.__names:
            raise AttributeError("%s queue already has a message named %s" % (self.name, name))

        # Add a constant.
        const_name = upperASCII(self.name) + "_CODE_" + upperASCII(name)
        setattr(self, const_name, self.__counter)
        self.__counter += 1

        # Add a convenience method for putting things into the queue.
        method_name = "send_" + lowerASCII(name)
        method = self._makeMethod(getattr(self, const_name), method_name, argc)
        setattr(self, method_name, method)

        self.__names.append(name)
Example #8
0
 def lower_ascii_test(self):
     """Test lowerASCII."""
     self.assertEqual(iutil.lowerASCII(""),"")
     self.assertEqual(iutil.lowerASCII("A"),"a")
     self.assertEqual(iutil.lowerASCII("a"),"a")
     self.assertEqual(iutil.lowerASCII("aBc"),"abc")
     self.assertEqual(iutil.lowerASCII("_&*'@#$%^aBcžčŘ"),
                                       "_&*'@#$%^abc\xc5\xbe\xc4\x8d\xc5\x98")
     _out = "heiz\xc3\xb6lr\xc3\xbccksto\xc3\x9fabd\xc3\xa4mpfung"
     self.assertEqual(iutil.lowerASCII("Heizölrückstoßabdämpfung"), _out)
Example #9
0
 def lower_ascii_test(self):
     """Test lowerASCII."""
     self.assertEqual(iutil.lowerASCII(""), "")
     self.assertEqual(iutil.lowerASCII("A"), "a")
     self.assertEqual(iutil.lowerASCII("a"), "a")
     self.assertEqual(iutil.lowerASCII("aBc"), "abc")
     self.assertEqual(iutil.lowerASCII("_&*'@#$%^aBcžčŘ"),
                      "_&*'@#$%^abczcr")
     _out = "heizolruckstoabdampfung"
     self.assertEqual(iutil.lowerASCII("Heizölrückstoßabdämpfung"), _out)
Example #10
0
 def lower_ascii_test(self):
     """Test lowerASCII."""
     self.assertEqual(iutil.lowerASCII(""),"")
     self.assertEqual(iutil.lowerASCII("A"),"a")
     self.assertEqual(iutil.lowerASCII("a"),"a")
     self.assertEqual(iutil.lowerASCII("aBc"),"abc")
     self.assertEqual(iutil.lowerASCII("_&*'@#$%^aBcžčŘ"),
                                       "_&*'@#$%^abc\xc5\xbe\xc4\x8d\xc5\x98")
     _out = "heiz\xc3\xb6lr\xc3\xbccksto\xc3\x9fabd\xc3\xa4mpfung"
     self.assertEqual(iutil.lowerASCII("Heizölrückstoßabdämpfung"), _out)
Example #11
0
    def addMessage(self, name, argc):
        if name in self.__names:
            raise AttributeError("%s queue already has a message named %s" %
                                 (self.name, name))

        # Add a constant.
        const_name = upperASCII(self.name) + "_CODE_" + upperASCII(name)
        setattr(self, const_name, self.__counter)
        self.__counter += 1

        # Add a convenience method for putting things into the queue.
        method_name = "send_" + lowerASCII(name)
        method = self._makeMethod(getattr(self, const_name), method_name, argc)
        setattr(self, method_name, method)

        self.__names.append(name)
Example #12
0
    def preInstall(self, *args, **kwargs):
        """ Get image and loopback mount it.

            This is called after partitioning is setup, we now have space to
            grab the image. If it is a network source Download it to sysroot
            and provide feedback during the download (using urlgrabber
            callback).

            If it is a file:// source then use the file directly.
        """
        error = None
        if self.data.method.url.startswith("file://"):
            self.image_path = self.data.method.url[7:]
        else:
            error = self._preInstall_url_image()

        if error:
            exn = PayloadInstallError(str(error))
            if errorHandler.cb(exn) == ERROR_RAISE:
                raise exn

        # Used to make install progress % look correct
        self._adj_size = os.stat(self.image_path)[stat.ST_SIZE]

        if self.data.method.checksum:
            progressQ.send_message(_("Checking image checksum"))
            sha256 = hashlib.sha256()
            with open(self.image_path, "rb") as f:
                while True:
                    data = f.read(1024 * 1024)
                    if not data:
                        break
                    sha256.update(data)
            filesum = sha256.hexdigest()
            log.debug("sha256 of %s is %s", self.data.method.url, filesum)

            if lowerASCII(self.data.method.checksum) != filesum:
                log.error("%s does not match checksum.",
                          self.data.method.checksum)
                exn = PayloadInstallError("Checksum of image does not match")
                if errorHandler.cb(exn) == ERROR_RAISE:
                    raise exn

        # If this looks like a tarfile, skip trying to mount it
        if self.is_tarfile:
            return

        # Mount the image and check to see if it is a LiveOS/*.img
        # style squashfs image. If so, move it to IMAGE_DIR and mount the real
        # root image on INSTALL_TREE
        rc = blivet.util.mount(self.image_path,
                               INSTALL_TREE,
                               fstype="auto",
                               options="ro")
        if rc != 0:
            log.error("mount error (%s) with %s", rc, self.image_path)
            exn = PayloadInstallError("mount error %s" % rc)
            if errorHandler.cb(exn) == ERROR_RAISE:
                raise exn

        # Nothing more to mount
        if not os.path.exists(INSTALL_TREE + "/LiveOS"):
            self._updateKernelVersionList()
            return

        # Mount the first .img in the directory on INSTALL_TREE
        img_files = glob.glob(INSTALL_TREE + "/LiveOS/*.img")
        if img_files:
            # move the mount to IMAGE_DIR
            os.makedirs(IMAGE_DIR, 0o755)
            # work around inability to move shared filesystems
            rc = iutil.execWithRedirect("mount", ["--make-rprivate", "/"])
            if rc == 0:
                rc = iutil.execWithRedirect(
                    "mount", ["--move", INSTALL_TREE, IMAGE_DIR])
            if rc != 0:
                log.error("error %s moving mount", rc)
                exn = PayloadInstallError("mount error %s" % rc)
                if errorHandler.cb(exn) == ERROR_RAISE:
                    raise exn

            img_file = IMAGE_DIR + "/LiveOS/" + os.path.basename(
                sorted(img_files)[0])
            rc = blivet.util.mount(img_file,
                                   INSTALL_TREE,
                                   fstype="auto",
                                   options="ro")
            if rc != 0:
                log.error("mount error (%s) with %s", rc, img_file)
                exn = PayloadInstallError("mount error %s with %s" %
                                          (rc, img_file))
                if errorHandler.cb(exn) == ERROR_RAISE:
                    raise exn

            self._updateKernelVersionList()

            source = os.statvfs(INSTALL_TREE)
            self.source_size = source.f_frsize * (source.f_blocks -
                                                  source.f_bfree)
Example #13
0
def ifcfg_to_ksdata(ifcfg, devname):

    from pyanaconda.kickstart import AnacondaKSHandler
    handler = AnacondaKSHandler()
    kwargs = {}

    # no network command for bond slaves
    if ifcfg.get("MASTER"):
        return None

    # ipv4 and ipv6
    if ifcfg.get("ONBOOT") and ifcfg.get("ONBOOT" ) == "no":
        kwargs["onboot"] = False
    if ifcfg.get('MTU') and ifcfg.get('MTU') != "0":
        kwargs["mtu"] = ifcfg.get('MTU')
    # ipv4
    if not ifcfg.get('BOOTPROTO'):
        kwargs["noipv4"] = True
    else:
        if iutil.lowerASCII(ifcfg.get('BOOTPROTO')) == 'dhcp':
            kwargs["bootProto"] = "dhcp"
            if ifcfg.get('DHCPCLASS'):
                kwargs["dhcpclass"] = ifcfg.get('DHCPCLASS')
        elif ifcfg.get('IPADDR'):
            kwargs["bootProto"] = "static"
            kwargs["ip"] = ifcfg.get('IPADDR')
            netmask = ifcfg.get('NETMASK')
            prefix  = ifcfg.get('PREFIX')
            if not netmask and prefix:
                netmask = prefix2netmask(int(prefix))
            if netmask:
                kwargs["netmask"] = netmask
            # note that --gateway is common for ipv4 and ipv6
            if ifcfg.get('GATEWAY'):
                kwargs["gateway"] = ifcfg.get('GATEWAY')
        elif ifcfg.get('IPADDR0'):
            kwargs["bootProto"] = "static"
            kwargs["ip"] = ifcfg.get('IPADDR0')
            prefix  = ifcfg.get('PREFIX0')
            if prefix:
                netmask = prefix2netmask(int(prefix))
                kwargs["netmask"] = netmask
            # note that --gateway is common for ipv4 and ipv6
            if ifcfg.get('GATEWAY0'):
                kwargs["gateway"] = ifcfg.get('GATEWAY0')


    # ipv6
    if (not ifcfg.get('IPV6INIT') or
        ifcfg.get('IPV6INIT') == "no"):
        kwargs["noipv6"] = True
    else:
        if ifcfg.get('IPV6_AUTOCONF') in ("yes", ""):
            kwargs["ipv6"] = "auto"
        else:
            if ifcfg.get('IPV6ADDR'):
                kwargs["ipv6"] = ifcfg.get('IPV6ADDR')
                if ifcfg.get('IPV6_DEFAULTGW') \
                   and ifcfg.get('IPV6_DEFAULTGW') != "::":
                    kwargs["ipv6gateway"] = ifcfg.get('IPV6_DEFAULTGW')
            if ifcfg.get('DHCPV6C') == "yes":
                kwargs["ipv6"] = "dhcp"

    # ipv4 and ipv6
    dnsline = ''
    for key in ifcfg.info.keys():
        if iutil.upperASCII(key).startswith('DNS'):
            if dnsline == '':
                dnsline = ifcfg.get(key)
            else:
                dnsline += "," + ifcfg.get(key)
    if dnsline:
        kwargs["nameserver"] = dnsline

    if ifcfg.get("ETHTOOL_OPTS"):
        kwargs["ethtool"] = ifcfg.get("ETHTOOL_OPTS")

    if ifcfg.get("ESSID"):
        kwargs["essid"] = ifcfg.get("ESSID")

    # hostname
    if ifcfg.get("DHCP_HOSTNAME"):
        kwargs["hostname"] = ifcfg.get("DHCP_HOSTNAME")

    # bonding
    # FIXME: dracut has only BOND_OPTS
    if ifcfg.get("BONDING_MASTER") == "yes" or ifcfg.get("TYPE") == "Bond":
        slaves = get_bond_slaves_from_ifcfgs([devname, ifcfg.get("UUID")])
        if slaves:
            kwargs["bondslaves"] = ",".join(slaves)
        bondopts = ifcfg.get("BONDING_OPTS")
        if bondopts:
            sep = ","
            if sep in bondopts:
                sep = ";"
            kwargs["bondopts"] = sep.join(bondopts.split())

    # vlan
    if ifcfg.get("VLAN") == "yes" or ifcfg.get("TYPE") == "Vlan":
        kwargs["device"] = ifcfg.get("PHYSDEV")
        kwargs["vlanid"] = ifcfg.get("VLAN_ID")

    # pylint: disable-msg=E1101
    return handler.NetworkData(**kwargs)
Example #14
0
def ifcfg_to_ksdata(ifcfg, devname):

    from pyanaconda.kickstart import AnacondaKSHandler
    handler = AnacondaKSHandler()
    kwargs = {}

    # no network command for bond slaves
    if ifcfg.get("MASTER"):
        return None
    # no network command for team slaves
    if ifcfg.get("TEAM_MASTER"):
        return None

    # ipv4 and ipv6
    if ifcfg.get("ONBOOT") and ifcfg.get("ONBOOT") == "no":
        kwargs["onboot"] = False
    if ifcfg.get('MTU') and ifcfg.get('MTU') != "0":
        kwargs["mtu"] = ifcfg.get('MTU')
    # ipv4
    if not ifcfg.get('BOOTPROTO'):
        kwargs["noipv4"] = True
    else:
        if iutil.lowerASCII(ifcfg.get('BOOTPROTO')) == 'dhcp':
            kwargs["bootProto"] = "dhcp"
            if ifcfg.get('DHCPCLASS'):
                kwargs["dhcpclass"] = ifcfg.get('DHCPCLASS')
        elif ifcfg.get('IPADDR'):
            kwargs["bootProto"] = "static"
            kwargs["ip"] = ifcfg.get('IPADDR')
            netmask = ifcfg.get('NETMASK')
            prefix = ifcfg.get('PREFIX')
            if not netmask and prefix:
                netmask = prefix2netmask(int(prefix))
            if netmask:
                kwargs["netmask"] = netmask
            # note that --gateway is common for ipv4 and ipv6
            if ifcfg.get('GATEWAY'):
                kwargs["gateway"] = ifcfg.get('GATEWAY')
        elif ifcfg.get('IPADDR0'):
            kwargs["bootProto"] = "static"
            kwargs["ip"] = ifcfg.get('IPADDR0')
            prefix = ifcfg.get('PREFIX0')
            if prefix:
                netmask = prefix2netmask(int(prefix))
                kwargs["netmask"] = netmask
            # note that --gateway is common for ipv4 and ipv6
            if ifcfg.get('GATEWAY0'):
                kwargs["gateway"] = ifcfg.get('GATEWAY0')

    # ipv6
    if (not ifcfg.get('IPV6INIT') or ifcfg.get('IPV6INIT') == "no"):
        kwargs["noipv6"] = True
    else:
        if ifcfg.get('IPV6_AUTOCONF') in ("yes", ""):
            kwargs["ipv6"] = "auto"
        else:
            if ifcfg.get('IPV6ADDR'):
                kwargs["ipv6"] = ifcfg.get('IPV6ADDR')
                if ifcfg.get('IPV6_DEFAULTGW') \
                   and ifcfg.get('IPV6_DEFAULTGW') != "::":
                    kwargs["ipv6gateway"] = ifcfg.get('IPV6_DEFAULTGW')
            if ifcfg.get('DHCPV6C') == "yes":
                kwargs["ipv6"] = "dhcp"

    # ipv4 and ipv6
    dnsline = ''
    for key in ifcfg.info.keys():
        if iutil.upperASCII(key).startswith('DNS'):
            if dnsline == '':
                dnsline = ifcfg.get(key)
            else:
                dnsline += "," + ifcfg.get(key)
    if dnsline:
        kwargs["nameserver"] = dnsline

    if ifcfg.get("ETHTOOL_OPTS"):
        kwargs["ethtool"] = ifcfg.get("ETHTOOL_OPTS")

    if ifcfg.get("ESSID"):
        kwargs["essid"] = ifcfg.get("ESSID")

    # hostname
    if ifcfg.get("DHCP_HOSTNAME"):
        kwargs["hostname"] = ifcfg.get("DHCP_HOSTNAME")

    # bonding
    # FIXME: dracut has only BOND_OPTS
    if ifcfg.get("BONDING_MASTER") == "yes" or ifcfg.get("TYPE") == "Bond":
        slaves = get_bond_slaves_from_ifcfgs([devname, ifcfg.get("UUID")])
        if slaves:
            kwargs["bondslaves"] = ",".join(slaves)
        bondopts = ifcfg.get("BONDING_OPTS")
        if bondopts:
            sep = ","
            if sep in bondopts:
                sep = ";"
            kwargs["bondopts"] = sep.join(bondopts.split())

    # vlan
    if ifcfg.get("VLAN") == "yes" or ifcfg.get("TYPE") == "Vlan":
        kwargs["device"] = ifcfg.get("PHYSDEV")
        kwargs["vlanid"] = ifcfg.get("VLAN_ID")

    # pylint: disable-msg=E1101
    nd = handler.NetworkData(**kwargs)

    # teaming
    if ifcfg.get("TYPE") == "Team" or ifcfg.get("DEVICETYPE") == "Team":
        slaves = get_team_slaves([devname, ifcfg.get("UUID")])
        for dev, cfg in slaves:
            nd.teamslaves.append((dev, cfg))

        teamconfig = nm.nm_device_setting_value(devname, "team", "config")
        if teamconfig:
            nd.teamconfig = teamconfig

    return nd
Example #15
0
def ifcfg_to_ksdata(ifcfg, devname):

    from pyanaconda.kickstart import AnacondaKSHandler

    handler = AnacondaKSHandler()
    kwargs = {}

    # no network command for bond slaves
    if ifcfg.get("MASTER"):
        return None
    # no network command for team slaves
    if ifcfg.get("TEAM_MASTER"):
        return None

    # ipv4 and ipv6
    if ifcfg.get("ONBOOT") and ifcfg.get("ONBOOT") == "no":
        kwargs["onboot"] = False
    if ifcfg.get("MTU") and ifcfg.get("MTU") != "0":
        kwargs["mtu"] = ifcfg.get("MTU")
    # ipv4
    if not ifcfg.get("BOOTPROTO"):
        kwargs["noipv4"] = True
    else:
        if iutil.lowerASCII(ifcfg.get("BOOTPROTO")) == "dhcp":
            kwargs["bootProto"] = "dhcp"
            if ifcfg.get("DHCPCLASS"):
                kwargs["dhcpclass"] = ifcfg.get("DHCPCLASS")
        elif ifcfg.get("IPADDR"):
            kwargs["bootProto"] = "static"
            kwargs["ip"] = ifcfg.get("IPADDR")
            netmask = ifcfg.get("NETMASK")
            prefix = ifcfg.get("PREFIX")
            if not netmask and prefix:
                netmask = prefix2netmask(int(prefix))
            if netmask:
                kwargs["netmask"] = netmask
            # note that --gateway is common for ipv4 and ipv6
            if ifcfg.get("GATEWAY"):
                kwargs["gateway"] = ifcfg.get("GATEWAY")
        elif ifcfg.get("IPADDR0"):
            kwargs["bootProto"] = "static"
            kwargs["ip"] = ifcfg.get("IPADDR0")
            prefix = ifcfg.get("PREFIX0")
            if prefix:
                netmask = prefix2netmask(int(prefix))
                kwargs["netmask"] = netmask
            # note that --gateway is common for ipv4 and ipv6
            if ifcfg.get("GATEWAY0"):
                kwargs["gateway"] = ifcfg.get("GATEWAY0")

    # ipv6
    if not ifcfg.get("IPV6INIT") or ifcfg.get("IPV6INIT") == "no":
        kwargs["noipv6"] = True
    else:
        if ifcfg.get("IPV6_AUTOCONF") in ("yes", ""):
            kwargs["ipv6"] = "auto"
        else:
            if ifcfg.get("IPV6ADDR"):
                kwargs["ipv6"] = ifcfg.get("IPV6ADDR")
                if ifcfg.get("IPV6_DEFAULTGW") and ifcfg.get("IPV6_DEFAULTGW") != "::":
                    kwargs["ipv6gateway"] = ifcfg.get("IPV6_DEFAULTGW")
            if ifcfg.get("DHCPV6C") == "yes":
                kwargs["ipv6"] = "dhcp"

    # ipv4 and ipv6
    dnsline = ""
    for key in ifcfg.info.keys():
        if iutil.upperASCII(key).startswith("DNS"):
            if dnsline == "":
                dnsline = ifcfg.get(key)
            else:
                dnsline += "," + ifcfg.get(key)
    if dnsline:
        kwargs["nameserver"] = dnsline

    if ifcfg.get("ETHTOOL_OPTS"):
        kwargs["ethtool"] = ifcfg.get("ETHTOOL_OPTS")

    if ifcfg.get("ESSID"):
        kwargs["essid"] = ifcfg.get("ESSID")

    # hostname
    if ifcfg.get("DHCP_HOSTNAME"):
        kwargs["hostname"] = ifcfg.get("DHCP_HOSTNAME")

    # bonding
    # FIXME: dracut has only BOND_OPTS
    if ifcfg.get("BONDING_MASTER") == "yes" or ifcfg.get("TYPE") == "Bond":
        slaves = get_bond_slaves_from_ifcfgs([devname, ifcfg.get("UUID")])
        if slaves:
            kwargs["bondslaves"] = ",".join(slaves)
        bondopts = ifcfg.get("BONDING_OPTS")
        if bondopts:
            sep = ","
            if sep in bondopts:
                sep = ";"
            kwargs["bondopts"] = sep.join(bondopts.split())

    # vlan
    if ifcfg.get("VLAN") == "yes" or ifcfg.get("TYPE") == "Vlan":
        kwargs["device"] = ifcfg.get("PHYSDEV")
        kwargs["vlanid"] = ifcfg.get("VLAN_ID")

    # pylint: disable-msg=E1101
    nd = handler.NetworkData(**kwargs)

    # teaming
    if ifcfg.get("TYPE") == "Team" or ifcfg.get("DEVICETYPE") == "Team":
        slaves = get_team_slaves([devname, ifcfg.get("UUID")])
        for dev, cfg in slaves:
            nd.teamslaves.append((dev, cfg))

        teamconfig = nm.nm_device_setting_value(devname, "team", "config")
        if teamconfig:
            nd.teamconfig = teamconfig

    return nd
Example #16
0
def get_device_name(devspec):

    devices = nm.nm_devices()
    devname = None

    if not devspec:
        if "ksdevice" in flags.cmdline:
            msg = "ksdevice boot parameter"
            devname = ks_spec_to_device_name(flags.cmdline["ksdevice"])
        elif nm.nm_is_connected():
            # device activated in stage 1 by network kickstart command
            msg = "first active device"
            try:
                devname = nm.nm_activated_devices()[0]
            except IndexError:
                log.debug(
                    "get_device_name: NM is connected but no activated devices found"
                )
        else:
            msg = "first device found"
            devname = min(devices)
        log.info("unspecified network --device in kickstart, using %s (%s)",
                 devname, msg)
    else:
        if iutil.lowerASCII(devspec) == "ibft":
            devname = ""
        if iutil.lowerASCII(devspec) == "link":
            for dev in sorted(devices):
                try:
                    link_up = nm.nm_device_carrier(dev)
                except ValueError as e:
                    log.debug("get_device_name: %s", e)
                    continue
                if link_up:
                    devname = dev
                    break
            else:
                log.error("Kickstart: No network device with link found")
        elif iutil.lowerASCII(devspec) == "bootif":
            if "BOOTIF" in flags.cmdline:
                # MAC address like 01-aa-bb-cc-dd-ee-ff
                devname = flags.cmdline["BOOTIF"][3:]
                devname = devname.replace("-", ":")
            else:
                log.error(
                    "Using --device=bootif without BOOTIF= boot option supplied"
                )
        else:
            devname = devspec

    if devname and devname not in devices:
        for d in devices:
            try:
                hwaddr = nm.nm_device_hwaddress(d)
            except ValueError as e:
                log.debug("get_device_name: %s", e)
                continue
            if hwaddr.lower() == devname.lower():
                devname = d
                break
        else:
            return ""

    return devname
    def preInstall(self, *args, **kwargs):
        """ Get image and loopback mount it.

            This is called after partitioning is setup, we now have space to
            grab the image. If it is a network source Download it to sysroot
            and provide feedback during the download (using urlgrabber
            callback).

            If it is a file:// source then use the file directly.
        """
        error = None
        if self.data.method.url.startswith("file://"):
            self.image_path = self.data.method.url[7:]
        else:
            error = self._preInstall_url_image()

        if error:
            exn = PayloadInstallError(str(error))
            if errorHandler.cb(exn) == ERROR_RAISE:
                raise exn

        # Used to make install progress % look correct
        self._adj_size = os.stat(self.image_path)[stat.ST_SIZE]

        if self.data.method.checksum:
            progressQ.send_message(_("Checking image checksum"))
            sha256 = hashlib.sha256()
            with open(self.image_path, "rb") as f:
                while True:
                    data = f.read(1024*1024)
                    if not data:
                        break
                    sha256.update(data)
            filesum = sha256.hexdigest()
            log.debug("sha256 of %s is %s", self.data.method.url, filesum)

            if lowerASCII(self.data.method.checksum) != filesum:
                log.error("%s does not match checksum.", self.data.method.checksum)
                exn = PayloadInstallError("Checksum of image does not match")
                if errorHandler.cb(exn) == ERROR_RAISE:
                    raise exn

        # If this looks like a tarfile, skip trying to mount it
        if self.is_tarfile:
            return

        # Mount the image and check to see if it is a LiveOS/*.img
        # style squashfs image. If so, move it to IMAGE_DIR and mount the real
        # root image on INSTALL_TREE
        rc = blivet.util.mount(self.image_path, INSTALL_TREE, fstype="auto", options="ro")
        if rc != 0:
            log.error("mount error (%s) with %s", rc, self.image_path)
            exn = PayloadInstallError("mount error %s" % rc)
            if errorHandler.cb(exn) == ERROR_RAISE:
                raise exn

        # Nothing more to mount
        if not os.path.exists(INSTALL_TREE+"/LiveOS"):
            self._updateKernelVersionList()
            return

        # Mount the first .img in the directory on INSTALL_TREE
        img_files = glob.glob(INSTALL_TREE+"/LiveOS/*.img")
        if img_files:
            # move the mount to IMAGE_DIR
            os.makedirs(IMAGE_DIR, 0o755)
            # work around inability to move shared filesystems
            rc = iutil.execWithRedirect("mount",
                                        ["--make-rprivate", "/"])
            if rc == 0:
                rc = iutil.execWithRedirect("mount",
                                            ["--move", INSTALL_TREE, IMAGE_DIR])
            if rc != 0:
                log.error("error %s moving mount", rc)
                exn = PayloadInstallError("mount error %s" % rc)
                if errorHandler.cb(exn) == ERROR_RAISE:
                    raise exn

            img_file = IMAGE_DIR+"/LiveOS/"+os.path.basename(sorted(img_files)[0])
            rc = blivet.util.mount(img_file, INSTALL_TREE, fstype="auto", options="ro")
            if rc != 0:
                log.error("mount error (%s) with %s", rc, img_file)
                exn = PayloadInstallError("mount error %s with %s" % (rc, img_file))
                if errorHandler.cb(exn) == ERROR_RAISE:
                    raise exn

            self._updateKernelVersionList()

            source = iutil.eintr_retry_call(os.statvfs, INSTALL_TREE)
            self.source_size = source.f_frsize * (source.f_blocks - source.f_bfree)
Example #18
0
    def preInstall(self, *args, **kwargs):
        """ Download image and loopback mount it.

            This is called after partitioning is setup, we now have space
            to grab the image. Download it to ROOT_PATH and provide feedback
            during the download (using urlgrabber callback).
        """
        # Setup urlgrabber and call back to download image to ROOT_PATH
        progress = URLGrabberProgress()
        ugopts = {"ssl_verify_peer": not self.data.method.noverifyssl,
                  "ssl_verify_host": not self.data.method.noverifyssl,
                  "proxies" : self._proxies,
                  "progress_obj" : progress,
                  "copy_local" : True}

        error = None
        try:
            ug = URLGrabber()
            ug.urlgrab(self.data.method.url, self.image_path, **ugopts)
        except URLGrabError as e:
            log.error("Error downloading liveimg: %s", e)
            error = e
        else:
            if not os.path.exists(self.image_path):
                error = "Failed to download %s, file doesn't exist" % self.data.method.url
                log.error(error)

        if error:
            exn = PayloadInstallError(str(error))
            if errorHandler.cb(exn) == ERROR_RAISE:
                raise exn

        # Used to make install progress % look correct
        self._adj_size = os.stat(self.image_path)[stat.ST_SIZE]

        if self.data.method.checksum:
            progressQ.send_message(_("Checking image checksum"))
            sha256 = hashlib.sha256()
            with open(self.image_path, "rb") as f:
                while True:
                    data = f.read(1024*1024)
                    if not data:
                        break
                    sha256.update(data)
            filesum = sha256.hexdigest()
            log.debug("sha256 of %s is %s", self.data.method.url, filesum)

            if lowerASCII(self.data.method.checksum) != filesum:
                log.error("%s does not match checksum.", self.data.method.checksum)
                exn = PayloadInstallError("Checksum of image does not match")
                if errorHandler.cb(exn) == ERROR_RAISE:
                    raise exn

        # Mount the image and check to see if it is a LiveOS/*.img
        # style squashfs image. If so, move it to IMAGE_DIR and mount the real
        # root image on INSTALL_TREE
        blivet.util.mount(self.image_path, INSTALL_TREE, fstype="auto", options="ro")
        if os.path.exists(INSTALL_TREE+"/LiveOS"):
            # Find the first .img in the directory and mount that on INSTALL_TREE
            img_files = glob.glob(INSTALL_TREE+"/LiveOS/*.img")
            if img_files:
                img_file = os.path.basename(sorted(img_files)[0])

                # move the mount to IMAGE_DIR
                os.makedirs(IMAGE_DIR, 0755)
                # work around inability to move shared filesystems
                iutil.execWithRedirect("mount",
                                       ["--make-rprivate", "/"])
                iutil.execWithRedirect("mount",
                                       ["--move", INSTALL_TREE, IMAGE_DIR])
                blivet.util.mount(IMAGE_DIR+"/LiveOS/"+img_file, INSTALL_TREE,
                                  fstype="auto", options="ro")