class VirtualPort(XMLBuilderDomain.XMLBuilderDomain):

    def __init__(self, conn, parsexml=None, parsexmlnode=None, caps=None):
        XMLBuilderDomain.XMLBuilderDomain.__init__(self, conn, parsexml,
                                                   parsexmlnode, caps=caps)
        self._type = None
        self._managerid = None
        self._typeid = None
        self._typeidversion = None
        self._instanceid = None

    def get_type(self):
        return self._type
    def set_type(self, val):
        self._type = val
    type = _xml_property(get_type, set_type,
                                  xpath="./virtualport/@type")

    def get_managerid(self):
        return self._managerid
    def set_managerid(self, val):
        self._managerid = val
    managerid = _xml_property(get_managerid, set_managerid,
                                  xpath="./virtualport/parameters/@managerid")

    def get_typeid(self):
        return self._typeid
    def set_typeid(self, val):
        self._typeid = val
    typeid = _xml_property(get_typeid, set_typeid,
                               xpath="./virtualport/parameters/@typeid")

    def get_typeidversion(self):
        return self._typeidversion
    def set_typeidversion(self, val):
        self._typeidversion = val
    typeidversion = _xml_property(get_typeidversion, set_typeidversion,
                               xpath="./virtualport/parameters/@typeidversion")

    def get_instanceid(self):
        return self._instanceid
    def set_instanceid(self, val):
        self._instanceid = val
    instanceid = _xml_property(get_instanceid, set_instanceid,
                               xpath="./virtualport/parameters/@instanceid")

    def _get_xml_config(self):
        # FIXME: This should be implemented, currently we can only parse
        return ""
Esempio n. 2
0
class CPUFeature(XMLBuilderDomain.XMLBuilderDomain):
    """
    Class for generating <cpu> child <feature> XML
    """

    POLICIES = ["force", "require", "optional", "disable", "forbid"]

    def __init__(self, conn, parsexml=None, parsexmlnode=None, caps=None):
        XMLBuilderDomain.XMLBuilderDomain.__init__(self, conn, parsexml,
                                                   parsexmlnode, caps)

        self._name = None
        self._policy = None

        if self._is_parse():
            return

    def _get_name(self):
        return self._name

    def _set_name(self, val):
        self._name = val

    name = _xml_property(_get_name, _set_name, xpath="./@name")

    def _get_policy(self):
        return self._policy

    def _set_policy(self, val):
        self._policy = val

    policy = _xml_property(_get_policy, _set_policy, xpath="./@policy")

    def _get_xml_config(self):
        if not self.name:
            return ""

        xml = "    <feature"
        if self.policy:
            xml += " policy='%s'" % self.policy
        xml += " name='%s'/>" % self.name

        return xml
Esempio n. 3
0
class Clock(XMLBuilderDomain.XMLBuilderDomain):
    """
    Class for generating <clock> XML
    """

    _dumpxml_xpath = "/domain/clock"
    def __init__(self, conn, parsexml=None, parsexmlnode=None, caps=None):
        XMLBuilderDomain.XMLBuilderDomain.__init__(self, conn, parsexml,
                                                   parsexmlnode, caps)

        self._offset = None

    def get_offset(self):
        return self._offset
    def set_offset(self, val):
        self._offset = val
    offset = _xml_property(get_offset, set_offset,
                           xpath="./clock/@offset")

    def _get_xml_config(self):
        if not self.offset:
            return ""

        return """  <clock offset="%s"/>""" % self.offset
Esempio n. 4
0
class DomainFeatures(XMLBuilderDomain.XMLBuilderDomain):
    """
    Class for generating <features> XML
    """

    _dumpxml_xpath = "/domain/features"

    def __init__(self, conn, parsexml=None, parsexmlnode=None, caps=None):
        XMLBuilderDomain.XMLBuilderDomain.__init__(self, conn, parsexml,
                                                   parsexmlnode, caps)

        self._acpi = None
        self._apic = None
        self._pae = None

    def get_acpi(self):
        return self._acpi

    def set_acpi(self, val):
        self._acpi = _none_or_bool(val)

    acpi = _xml_property(get_acpi,
                         set_acpi,
                         xpath="./features/acpi",
                         is_bool=True)

    def get_apic(self):
        return self._apic

    def set_apic(self, val):
        self._apic = _none_or_bool(val)

    apic = _xml_property(get_apic,
                         set_apic,
                         xpath="./features/apic",
                         is_bool=True)

    def get_pae(self):
        return self._pae

    def set_pae(self, val):
        self._pae = _none_or_bool(val)

    pae = _xml_property(get_pae, set_pae, xpath="./features/pae", is_bool=True)

    def __setitem__(self, attr, val):
        return setattr(self, attr, val)

    def __getitem__(self, attr):
        return getattr(self, attr)

    def __delitem__(self, attr):
        return setattr(self, attr, None)

    def _get_xml_config(self, defaults=None):
        # pylint: disable=W0221
        # Argument number differs from overridden method

        if not defaults:
            defaults = {}
        ret = ""

        feature_xml = ""
        if self.acpi or (self.acpi is None and defaults.get("acpi")):
            feature_xml += "<acpi/>"
        if self.apic or (self.apic is None and defaults.get("apic")):
            feature_xml += "<apic/>"
        if self.pae or (self.pae is None and defaults.get("pae")):
            feature_xml += "<pae/>"

        if feature_xml:
            ret += "  <features>\n"
            ret += "    %s\n" % feature_xml
            ret += "  </features>"

        return ret
class VirtualRNGDevice(VirtualDevice):

    _virtual_device_type = VirtualDevice.VIRTUAL_DEV_RNG

    TYPE_RANDOM = "random"
    TYPE_EGD = "egd"
    TYPES = [TYPE_RANDOM, TYPE_EGD]

    BACKEND_TYPE_UDP = "udp"
    BACKEND_TYPE_TCP = "tcp"
    BACKEND_TYPES = [BACKEND_TYPE_UDP, BACKEND_TYPE_TCP]

    BACKEND_MODE_BIND = "bind"
    BACKEND_MODE_CONNECT = "connect"
    BACKEND_MODES = [BACKEND_MODE_BIND, BACKEND_MODE_CONNECT]

    def __init__(self, conn=None, parsexml=None, parsexmlnode=None, caps=None):
        VirtualDevice.__init__(self, conn, parsexml, parsexmlnode, caps)
        self._type = None
        self._model = None
        self._backend_type = None
        self._bind_host = None
        self._bind_service = None
        self._connect_host = None
        self._connect_service = None
        self._rate_bytes = None
        self._rate_period = None

        self._device = None
        if self._is_parse():
            return

    @staticmethod
    def get_pretty_type(rng_type):
        if rng_type == VirtualRNGDevice.TYPE_RANDOM:
            return _("Random")
        if rng_type == VirtualRNGDevice.TYPE_EGD:
            return _("Entropy Gathering Daemon")
        return rng_type

    @staticmethod
    def get_pretty_backend_type(backend_type):
        return {"udp": "UDP", "tcp": "TCP"}.get(backend_type) or backend_type

    @staticmethod
    def get_pretty_mode(mode):
        return {"bind": "Bind", "connect": "Connect"}.get(mode) or mode

    def backend_mode(self):
        ret = []
        if self.bind_host or self.bind_service:
            ret.append(VirtualRNGDevice.BACKEND_MODE_BIND)
        if self.connect_host or self.connect_service:
            ret.append(VirtualRNGDevice.BACKEND_MODE_CONNECT)
        return ret

    def supports_property(self, propname):
        """
        Whether the rng dev type supports the passed property name
        """
        users = {
            "type": [self.TYPE_EGD, self.TYPE_RANDOM],
            "model": [self.TYPE_EGD, self.TYPE_RANDOM],
            "bind_host": [self.TYPE_EGD],
            "bind_service": [self.TYPE_EGD],
            "connect_host": [self.TYPE_EGD],
            "connect_service": [self.TYPE_EGD],
            "backend_type": [self.TYPE_EGD],
            "device": [self.TYPE_RANDOM],
            "rate_bytes": [self.TYPE_EGD, self.TYPE_RANDOM],
            "rate_period": [self.TYPE_EGD, self.TYPE_RANDOM],
        }
        if users.get(propname):
            return self.type in users[propname]

        return hasattr(self, propname)

    def _get_type(self):
        return self._type

    def _set_type(self, m):
        self._type = m

    type = _xml_property(_get_type, _set_type, xpath="./backend/@model")

    def _get_model(self):
        return self._model

    def _set_model(self, m):
        self._model = m

    model = _xml_property(_get_model, _set_model, xpath="./@model")

    def _get_backend_type(self):
        return self._backend_type

    def _set_backend_type(self, t):
        self._backend_type = t

    backend_type = _xml_property(_get_backend_type,
                                 _set_backend_type,
                                 xpath="./backend/@type")

    def _get_bind_host(self):
        return self._bind_host

    def _set_bind_host(self, m):
        self._bind_host = m

    bind_host = _xml_property(_get_bind_host,
                              _set_bind_host,
                              xpath="./backend/source[@mode='bind']/@host")

    def _get_connect_host(self):
        return self._connect_host

    def _set_connect_host(self, m):
        self._connect_host = m

    connect_host = _xml_property(
        _get_connect_host,
        _set_connect_host,
        xpath="./backend/source[@mode='connect']/@host")

    def _get_bind_service(self):
        return self._bind_service

    def _set_bind_service(self, m):
        self._bind_service = m

    bind_service = _xml_property(
        _get_bind_service,
        _set_bind_service,
        xpath="./backend/source[@mode='bind']/@service")

    def _get_connect_service(self):
        return self._connect_service

    def _set_connect_service(self, m):
        self._connect_service = m

    connect_service = _xml_property(
        _get_connect_service,
        _set_connect_service,
        xpath="./backend/source[@mode='connect']/@service")

    def _get_rate_bytes(self):
        return self._rate_bytes

    def _set_rate_bytes(self, b):
        self._rate_bytes = b

    rate_bytes = _xml_property(_get_rate_bytes,
                               _set_rate_bytes,
                               xpath="./rate/@bytes")

    def _get_rate_period(self):
        return self._rate_period

    def _set_rate_period(self, p):
        self._rate_period = p

    rate_period = _xml_property(_get_rate_period,
                                _set_rate_period,
                                xpath="./rate/@period")

    def _get_device(self):
        if self._type == self.TYPE_RANDOM:
            return self._device
        return None

    def _set_device(self, d):
        self._device = d

    device = _xml_property(_get_device, _set_device, xpath="./backend")

    def _get_xml_config(self):
        rng_model = self.model or "virtio"
        xml = ("    <rng model='%s'>\n" % rng_model)

        if self.rate_bytes or self.rate_period:
            xml += "      <rate"
            if self.rate_period:
                xml += " period='%s'" % self.rate_period
            if self.rate_bytes:
                xml += " bytes='%s'" % self.rate_bytes
            xml += "/>\n"

        if self.type == self.TYPE_RANDOM:
            xml += "      <backend model='random'>%s</backend>\n" % self.device
        else:
            model = "model='%s'" % self.type
            backend_type = "type='%s'" % (self.backend_type or "tcp")
            xml += "      <backend %s %s>\n" % (model, backend_type)

            def add_source(mode, host, service):
                ret = "        <source mode='%s'" % mode
                if host:
                    ret += " host='%s'" % host
                if service:
                    ret += " service='%s'" % service
                return ret + "/>\n"

            if self.bind_host or self.bind_service:
                xml += add_source("bind", self.bind_host, self.bind_service)
            if self.connect_host or self.connect_service:
                xml += add_source("connect", self.connect_host, \
                                  self.connect_service)
            xml += "      </backend>\n"

        xml += "    </rng>"
        return xml
Esempio n. 6
0
class Seclabel(XMLBuilderDomain.XMLBuilderDomain):
    """
    Class for generating <seclabel> XML
    """

    SECLABEL_TYPE_DYNAMIC = "dynamic"
    SECLABEL_TYPE_STATIC = "static"
    SECLABEL_TYPE_DEFAULT = "default"
    SECLABEL_TYPES = [SECLABEL_TYPE_DYNAMIC, SECLABEL_TYPE_STATIC]

    MODEL_DEFAULT = "default"

    SECLABEL_MODEL_TEST = "testSecurity"
    SECLABEL_MODEL_SELINUX = "selinux"
    SECLABEL_MODEL_DAC = "dac"
    SECLABEL_MODEL_NONE = "none"
    SECLABEL_MODELS = [SECLABEL_MODEL_SELINUX,
                        SECLABEL_MODEL_DAC,
                        SECLABEL_MODEL_NONE]

    _dumpxml_xpath = "/domain/seclabel"
    def __init__(self, conn, parsexml=None, parsexmlnode=None, caps=None):
        XMLBuilderDomain.XMLBuilderDomain.__init__(self, conn, parsexml,
                                                   parsexmlnode, caps)

        self._type = None
        self._model = None
        self._label = None
        self._imagelabel = None
        self._relabel = None

        if self._is_parse():
            return

        self.model = self.MODEL_DEFAULT
        self.type = self.SECLABEL_TYPE_DEFAULT

    def _get_default_model(self):
        caps = self._get_caps()
        if caps:
            if (self.SECLABEL_MODEL_TEST in
                [x.model for x in caps.host.secmodels]):
                return self.SECLABEL_MODEL_TEST

            for model in self.SECLABEL_MODELS:
                if model in [x.model for x in caps.host.secmodels]:
                    return model
        raise RuntimeError("No supported model found in capabilities")

    def _guess_secmodel(self, label, imagelabel):
        # We always want the testSecurity model when running tests
        caps = self._get_caps()
        if (caps and
            self.SECLABEL_MODEL_TEST in
            [x.model for x in caps.host.secmodels]):
            return self.SECLABEL_MODEL_TEST

        if not label and not imagelabel:
            return self._get_default_model()

        lab_len = imglab_len = None
        if label:
            lab_len = min(3, len(label.split(':')))
        if imagelabel:
            imglab_len = min(3, len(imagelabel.split(':')))
        if lab_len and imglab_len and lab_len != imglab_len:
            raise ValueError("Label and Imagelabel are incompatible")

        lab_len = lab_len or imglab_len
        if lab_len == 3:
            return self.SECLABEL_MODEL_SELINUX
        elif lab_len == 2:
            return self.SECLABEL_MODEL_DAC
        else:
            raise ValueError("Unknown model type for label '%s'" % self.label)

    def get_type(self):
        return self._type
    def set_type(self, val):
        if (val not in self.SECLABEL_TYPES and
            val != self.SECLABEL_TYPE_DEFAULT):
            raise ValueError("Unknown security type '%s'" % val)
        self._type = val
    type = _xml_property(get_type, set_type,
                         xpath="./seclabel/@type")

    def get_model(self):
        return self._model
    def set_model(self, val):
        self._model = val
    model = _xml_property(get_model, set_model,
                          xpath="./seclabel/@model",
                          default_converter=_get_default_model)

    def get_label(self):
        return self._label
    def set_label(self, val):
        self._label = val
    label = _xml_property(get_label, set_label,
                          xpath="./seclabel/label")

    def _get_relabel(self):
        return self._relabel
    def _set_relabel(self, val):
        self._relabel = val
    relabel = _xml_property(_get_relabel, _set_relabel,
                            xpath="./seclabel/@relabel")

    def get_imagelabel(self):
        return self._imagelabel
    def set_imagelabel(self, val):
        self._imagelabel = val
    imagelabel = _xml_property(get_imagelabel, set_imagelabel,
                               xpath="./seclabel/imagelabel")

    def _get_xml_config(self):
        if (self.model == self.MODEL_DEFAULT and
            self.type == self.SECLABEL_TYPE_DEFAULT):
            return ""

        model = self.model
        typ = self.type
        relabel = self.relabel

        if typ == self.SECLABEL_TYPE_DEFAULT:
            typ = self.SECLABEL_TYPE_DYNAMIC

        if not typ:
            raise RuntimeError("Security type and model must be specified")

        if typ == self.SECLABEL_TYPE_STATIC:
            if not self.label:
                raise RuntimeError("A label must be specified for static "
                                   "security type.")

        if model == self.MODEL_DEFAULT:
            model = self._guess_secmodel(self.label, self.imagelabel)

        label_xml = ""
        xml = "  <seclabel type='%s' model='%s'" % (typ, model)
        if relabel is not None:
            xml += " relabel='%s'" % (relabel and "yes" or "no")

        if self.label:
            label_xml += "    <label>%s</label>\n" % self.label
        if self.imagelabel:
            label_xml += "    <imagelabel>%s</imagelabel>\n" % self.imagelabel

        if label_xml:
            xml += ">\n"
            xml += label_xml
            xml += "  </seclabel>"
        else:
            xml += "/>"


        return xml
Esempio n. 7
0
class Installer(XMLBuilderDomain.XMLBuilderDomain):
    """
    Installer classes attempt to encapsulate all the parameters needed
    to 'install' a guest: essentially, booting the guest with the correct
    media for the OS install phase (if there is one), and setting up the
    guest to boot to the correct media for all subsequent runs.

    Some of the actual functionality:

        - Determining what type of install media has been requested, and
          representing it correctly to the Guest

        - Fetching install kernel/initrd or boot.iso from a URL

        - Setting the boot device as appropriate depending on whether we
          are booting into an OS install, or booting post-install

    Some of the information that the Installer needs to know to accomplish
    this:

        - Install media location (could be a URL, local path, ...)
        - Virtualization type (parameter 'os_type') ('xen', 'hvm', etc.)
        - Hypervisor name (parameter 'type') ('qemu', 'kvm', 'xen', etc.)
        - Guest architecture ('i686', 'x86_64')
    """
    _dumpxml_xpath = "/domain/os"
    _has_install_phase = True

    def __init__(self,
                 type="xen",
                 location=None,
                 extraargs=None,
                 os_type=None,
                 conn=None,
                 parsexml=None,
                 parsexmlnode=None,
                 caps=None):
        # pylint: disable=W0622
        # Redefining built-in 'type', but it matches the XML so keep it

        XMLBuilderDomain.XMLBuilderDomain.__init__(self,
                                                   conn,
                                                   parsexml,
                                                   parsexmlnode,
                                                   caps=caps)

        self._type = None
        self._location = None
        self._initrd_injections = []
        self._cdrom = False
        self._os_type = None
        self._scratchdir = None
        self._arch = None
        self._machine = None
        self._loader = None
        self._init = None
        self._install_bootconfig = Boot(self.conn)
        self._bootconfig = Boot(self.conn, parsexml, parsexmlnode)

        # Devices created/added during the prepare() stage
        self.install_devices = []

        if self._is_parse():
            return

        # FIXME: Better solution? Skip validating this since we may not be
        # able to install a VM of the host arch
        if self._get_caps():
            self._arch = self._get_caps().host.arch

        if type is None:
            type = "xen"
        self.type = type

        if not os_type is None:
            self.os_type = os_type
        else:
            self.os_type = "xen"
        if not location is None:
            self.location = location

        self.extraargs = extraargs

        self._tmpfiles = []
        self._tmpvols = []

    def get_conn(self):
        return self._conn

    conn = property(get_conn)

    def _get_bootconfig(self):
        return self._bootconfig

    bootconfig = property(_get_bootconfig)

    # Hypervisor name (qemu, kvm, xen, lxc, etc.)
    def get_type(self):
        return self._type

    def set_type(self, val):
        self._type = val

    type = _xml_property(get_type, set_type, xpath="./@type")

    # Virtualization type ('xen' == xen paravirt, or 'hvm)
    def get_os_type(self):
        return self._os_type

    def set_os_type(self, val):
        # Older libvirt back compat: if user specifies 'linux', convert
        # internally to newer equivalent value 'xen'
        if val == "linux":
            val = "xen"

        # XXX: Need to validate this: have some whitelist based on caps?
        self._os_type = val

    os_type = _xml_property(get_os_type, set_os_type, xpath="./os/type")

    def get_arch(self):
        return self._arch

    def set_arch(self, val):
        # XXX: Sanitize to a consisten value (i368 -> i686)
        # XXX: Validate against caps
        self._arch = val

    arch = _xml_property(get_arch, set_arch, xpath="./os/type/@arch")

    def _get_machine(self):
        return self._machine

    def _set_machine(self, val):
        self._machine = val

    machine = _xml_property(_get_machine,
                            _set_machine,
                            xpath="./os/type/@machine")

    def _get_loader(self):
        return self._loader

    def _set_loader(self, val):
        self._loader = val

    loader = _xml_property(_get_loader, _set_loader, xpath="./os/loader")

    def _get_init(self):
        return self._init

    def _set_init(self, val):
        self._init = val

    init = _xml_property(_get_init, _set_init, xpath="./os/init")

    def get_scratchdir(self):
        if not self.scratchdir_required():
            return None

        if not self._scratchdir:
            self._scratchdir = self._get_scratchdir()
            logging.debug("scratchdir=%s", self._scratchdir)
        return self._scratchdir

    scratchdir = property(get_scratchdir)

    def get_cdrom(self):
        return self._cdrom

    def set_cdrom(self, enable):
        if enable not in [True, False]:
            raise ValueError(_("Guest.cdrom must be a boolean type"))
        self._cdrom = enable

    cdrom = property(get_cdrom, set_cdrom)

    def get_location(self):
        return self._location

    def set_location(self, val):
        self._location = val

    location = property(get_location, set_location)

    def get_initrd_injections(self):
        return self._initrd_injections

    def set_initrd_injections(self, val):
        self._initrd_injections = val

    initrd_injections = property(get_initrd_injections, set_initrd_injections)

    # extra arguments to pass to the guest installer
    def get_extra_args(self):
        return self._install_bootconfig.kernel_args

    def set_extra_args(self, val):
        self._install_bootconfig.kernel_args = val

    extraargs = property(get_extra_args, set_extra_args)

    # Public helper methods
    def scratchdir_required(self):
        """
        Returns true if scratchdir is needed for the passed install parameters.
        Apps can use this to determine if they should attempt to ensure
        scratchdir permissions are adequate
        """
        return False

    def is_hvm(self):
        return self.os_type == "hvm"

    def is_xenpv(self):
        return self.os_type in ["xen", "linux"]

    def is_container(self):
        return self.os_type == "exe"

    # Private methods
    def _get_system_scratchdir(self):
        if platform.system() == "SunOS":
            return "/var/tmp"

        if self.type == "test":
            return "/tmp"
        elif self.type == "xen":
            return XEN_SCRATCH
        else:
            return LIBVIRT_SCRATCH

    def _get_scratchdir(self):
        scratch = None
        if not self.is_session_uri():
            scratch = self._get_system_scratchdir()

        if (not scratch or not os.path.exists(scratch)
                or not os.access(scratch, os.W_OK)):
            scratch = os.path.expanduser("~/.virtinst/boot")
            if not os.path.exists(scratch):
                os.makedirs(scratch, 0751)

        return scratch

    def _get_bootdev(self, isinstall, guest):
        raise NotImplementedError("Must be implemented in subclass")

    def _build_boot_order(self, isinstall, guest):
        bootorder = [self._get_bootdev(isinstall, guest)]

        # If guest has an attached disk, always have 'hd' in the boot
        # list, so disks are marked as bootable/installable (needed for
        # windows virtio installs, and booting local disk from PXE)
        for disk in guest.get_devices("disk"):
            if disk.device == disk.DEVICE_DISK:
                bootdev = self.bootconfig.BOOT_DEVICE_HARDDISK
                if bootdev not in bootorder:
                    bootorder.append(bootdev)
                break

        return bootorder

    def _get_default_init(self, guest):
        if not self.is_container():
            return

        for fs in guest.get_devices("filesystem"):
            if fs.target == "/":
                return "/sbin/init"
        return "/bin/sh"

    def _get_osblob_helper(self, guest, isinstall, bootconfig):
        conn = guest.conn
        arch = self.arch
        machine = self.machine
        hvtype = self.type
        loader = self.loader
        os_type = self.os_type
        init = self.init or self._get_default_init(guest)

        hvxen = (hvtype == "xen")

        if not loader and self.is_hvm() and hvxen:
            loader = "/usr/lib/xen/boot/hvmloader"

        # Use older libvirt 'linux' value for back compat
        if os_type == "xen" and hvxen:
            os_type = "linux"

        if (not isinstall and self.is_xenpv() and not self.bootconfig.kernel):
            return "<bootloader>%s</bootloader>" % _pygrub_path(conn)

        osblob = "<os>"

        typexml = "    <type"
        if arch:
            typexml += " arch='%s'" % arch
        if machine:
            typexml += " machine='%s'" % machine
        typexml += ">%s</type>" % os_type

        osblob = util.xml_append(osblob, typexml)

        if init:
            osblob = util.xml_append(
                osblob, "    <init>%s</init>" % util.xml_escape(init))
        if loader:
            osblob = util.xml_append(
                osblob, "    <loader>%s</loader>" % util.xml_escape(loader))

        if not self.is_container():
            osblob = util.xml_append(osblob, bootconfig.get_xml_config())
        osblob = util.xml_append(osblob, "  </os>")

        return osblob

    # Method definitions

    def _get_xml_config(self, guest, isinstall):
        """
        Generate the portion of the guest xml that determines boot devices
        and parameters. (typically the <os></os> block)

        @param guest: Guest instance we are installing
        @type guest: L{Guest}
        @param isinstall: Whether we want xml for the 'install' phase or the
                          'post-install' phase.
        @type isinstall: C{bool}
        """
        # pylint: disable=W0221
        # Argument number differs from overridden method

        if isinstall:
            bootconfig = self._install_bootconfig
        else:
            bootconfig = self.bootconfig

        if isinstall and not self.has_install_phase():
            return

        bootorder = self._build_boot_order(isinstall, guest)
        bootconfig = copy.copy(bootconfig)
        if not bootconfig.bootorder:
            bootconfig.bootorder = bootorder

        return self._get_osblob_helper(guest, isinstall, bootconfig)

    def has_install_phase(self):
        """
        Return True if the requested setup is actually installing an OS
        into the guest. Things like LiveCDs, Import, or a manually specified
        bootorder do not have an install phase.
        """
        return self._has_install_phase

    def cleanup(self):
        """
        Remove any temporary files retrieved during installation
        """
        for f in self._tmpfiles:
            logging.debug("Removing " + f)
            os.unlink(f)

        for vol in self._tmpvols:
            logging.debug("Removing volume '%s'", vol.name())
            vol.delete(0)

        self._tmpvols = []
        self._tmpfiles = []
        self.install_devices = []

    def prepare(self, guest, meter):
        """
        Fetch any files needed for installation.
        @param guest: guest instance being installed
        @type guest: L{Guest}
        @param meter: progress meter
        @type meter: Urlgrabber ProgressMeter
        """
        raise NotImplementedError("Must be implemented in subclass")

    def detect_distro(self):
        """
        Attempt to detect the distro for the Installer's 'location'. If
        an error is encountered in the detection process (or if detection
        is not relevant for the Installer type), (None, None) is returned

        @returns: (distro type, distro variant) tuple
        """
        return (None, None)

    def guest_from_installer(self):
        """
        Return a L{Guest} instance wrapping the current installer.

        If all the appropriate values are present in the installer
        (conn, type, os_type, arch, machine), we have everything we need
        to determine what L{Guest} class is expected and what default values
        to pass it. This is a convenience method to save the API user from
        having to enter all these known details twice.
        """

        if not self.conn:
            raise ValueError(_("A connection must be specified."))

        guest, domain = CapabilitiesParser.guest_lookup(conn=self.conn,
                                                        caps=self._get_caps(),
                                                        os_type=self.os_type,
                                                        typ=self.type,
                                                        arch=self.arch,
                                                        machine=self.machine)

        gobj = virtinst.Guest(installer=self, conn=self.conn)
        gobj.arch = guest.arch
        gobj.emulator = domain.emulator
        self.loader = domain.loader

        return gobj
Esempio n. 8
0
class Boot(XMLBuilderDomain.XMLBuilderDomain):
    """
    Class for generating boot device related XML
    """

    BOOT_DEVICE_HARDDISK = "hd"
    BOOT_DEVICE_CDROM = "cdrom"
    BOOT_DEVICE_FLOPPY = "fd"
    BOOT_DEVICE_NETWORK = "network"
    boot_devices = [BOOT_DEVICE_HARDDISK, BOOT_DEVICE_CDROM,
                    BOOT_DEVICE_FLOPPY, BOOT_DEVICE_NETWORK]

    _dumpxml_xpath = "/domain/os"
    def __init__(self, conn, parsexml=None, parsexmlnode=None, caps=None):
        XMLBuilderDomain.XMLBuilderDomain.__init__(self, conn, parsexml,
                                                   parsexmlnode, caps)

        self._bootorder = []
        self._enable_bootmenu = None
        self._kernel = None
        self._initrd = None
        self._kernel_args = None

    def _get_enable_bootmenu(self):
        return self._enable_bootmenu
    def _set_enable_bootmenu(self, val):
        self._enable_bootmenu = val
    def _get_menu_converter(self, val):
        ignore = self
        if val is None:
            return None
        return bool(val == "yes")
    enable_bootmenu = _xml_property(_get_enable_bootmenu, _set_enable_bootmenu,
                            get_converter=_get_menu_converter,
                            set_converter=lambda s, x: x and "yes" or "no",
                            xpath="./os/bootmenu/@enable")

    def _get_bootorder(self):
        return self._bootorder
    def _set_bootorder(self, val):
        self._bootorder = val
    def _bootorder_xpath_list(self):
        l = []
        for idx in range(len(self._get_bootorder())):
            l.append("./os/boot[%d]/@dev" % (idx + 1))
        return l
    bootorder = _xml_property(_get_bootorder, _set_bootorder,
                              is_multi=True,
                              xml_set_list=_bootorder_xpath_list,
                              xpath="./os/boot/@dev")

    def _get_kernel(self):
        return self._kernel
    def _set_kernel(self, val):
        self._kernel = val
    kernel = _xml_property(_get_kernel, _set_kernel,
                           xpath="./os/kernel")

    def _get_initrd(self):
        return self._initrd
    def _set_initrd(self, val):
        self._initrd = val
    initrd = _xml_property(_get_initrd, _set_initrd,
                           xpath="./os/initrd")

    def _get_kernel_args(self):
        return self._kernel_args
    def _set_kernel_args(self, val):
        self._kernel_args = val
    kernel_args = _xml_property(_get_kernel_args, _set_kernel_args,
                                xpath="./os/cmdline")

    def _get_xml_config(self):
        xml = ""

        if self.kernel:
            xml = util.xml_append(xml, "    <kernel>%s</kernel>" %
                                   util.xml_escape(self.kernel))
            if self.initrd:
                xml = util.xml_append(xml, "    <initrd>%s</initrd>" %
                                       util.xml_escape(self.initrd))
            if self.kernel_args:
                xml = util.xml_append(xml, "    <cmdline>%s</cmdline>" %
                                       util.xml_escape(self.kernel_args))

        else:
            for dev in self.bootorder:
                xml = util.xml_append(xml, "    <boot dev='%s'/>" % dev)

            if self.enable_bootmenu in [True, False]:
                val = self.enable_bootmenu and "yes" or "no"
                xml = util.xml_append(xml,
                                       "    <bootmenu enable='%s'/>" % val)

        return xml
Esempio n. 9
0
class DomainNumatune(XMLBuilderDomain.XMLBuilderDomain):
    """
    Class for generating <numatune> XML
    """

    @staticmethod
    def validate_cpuset(conn, val):
        if val is None or val == "":
            return

        if not isinstance(val, str) or len(val) == 0:
            raise ValueError(_("cpuset must be string"))
        if re.match("^[0-9,-^]*$", val) is None:
            raise ValueError(_("cpuset can only contain numeric, ',', '^', or "
                               "'-' characters"))

        pcpus = get_phy_cpus(conn)
        for c in val.split(','):
            # Redundant commas
            if not c:
                continue

            if "-" in c:
                (x, y) = c.split('-', 1)
                x = int(x)
                y = int(y)
                if x > y:
                    raise ValueError(_("cpuset contains invalid format."))
                if x >= pcpus or y >= pcpus:
                    raise ValueError(_("cpuset's pCPU numbers must be less "
                                       "than pCPUs."))
            else:
                if c.startswith("^"):
                    c = c[1:]
                c = int(c)

                if c >= pcpus:
                    raise ValueError(_("cpuset's pCPU numbers must be less "
                                       "than pCPUs."))

    @staticmethod
    def cpuset_str_to_tuple(conn, cpuset):
        DomainNumatune.validate_cpuset(conn, cpuset)
        pinlist = [False] * get_phy_cpus(conn)

        entries = cpuset.split(",")
        for e in entries:
            series = e.split("-", 1)

            if len(series) == 1:
                pinlist[int(series[0])] = True
                continue

            start = int(series[0])
            end = int(series[1])

            for i in range(start, end + 1):
                pinlist[i] = True

        return tuple(pinlist)

    _dumpxml_xpath = "/domain/numatune"

    MEMORY_MODES = ["interleave", "strict", "preferred"]

    def __init__(self, conn, parsexml=None, parsexmlnode=None, caps=None):
        self._memory_nodeset = None
        self._memory_mode = None

        XMLBuilderDomain.XMLBuilderDomain.__init__(self, conn, parsexml,
                                                   parsexmlnode, caps)
        if self._is_parse():
            return

    def _get_memory_nodeset(self):
        return self._memory_nodeset
    def _set_memory_nodeset(self, val):
        self._memory_nodeset = val
    memory_nodeset = _xml_property(_get_memory_nodeset,
                                   _set_memory_nodeset,
                                   xpath="./numatune/memory/@nodeset")

    def _get_memory_mode(self):
        return self._memory_mode
    def _set_memory_mode(self, val):
        self._memory_mode = val
    memory_mode = _xml_property(_get_memory_mode,
                                _set_memory_mode,
                                xpath="./numatune/memory/@mode")

    def _get_memory_xml(self):
        if not self.memory_nodeset:
            return ""

        xml = "    <memory"
        if self.memory_mode:
            xml += " mode='%s'" % self.memory_mode
        if self.memory_nodeset:
            xml += " nodeset='%s'" % self.memory_nodeset
        xml += "/>\n"
        return xml

    def _get_xml_config(self):
        mem_xml = self._get_memory_xml()
        if not mem_xml:
            return ""

        xml = "  <numatune>\n"
        xml += mem_xml
        xml += "  </numatune>"
        return xml
class VirtualNetworkInterface(VirtualDevice):

    _virtual_device_type = VirtualDevice.VIRTUAL_DEV_NET

    TYPE_BRIDGE     = "bridge"
    TYPE_VIRTUAL    = "network"
    TYPE_USER       = "******"
    TYPE_ETHERNET   = "ethernet"
    TYPE_DIRECT   = "direct"
    network_types = [TYPE_BRIDGE, TYPE_VIRTUAL, TYPE_USER, TYPE_ETHERNET,
                     TYPE_DIRECT]

    def get_network_type_desc(net_type):
        """
        Return human readable description for passed network type
        """
        desc = net_type.capitalize()

        if net_type == VirtualNetworkInterface.TYPE_BRIDGE:
            desc = _("Shared physical device")
        elif net_type == VirtualNetworkInterface.TYPE_VIRTUAL:
            desc = _("Virtual networking")
        elif net_type == VirtualNetworkInterface.TYPE_USER:
            desc = _("Usermode networking")

        return desc
    get_network_type_desc = staticmethod(get_network_type_desc)

    def __init__(self, macaddr=None, type=TYPE_BRIDGE, bridge=None,
                 network=None, model=None, conn=None,
                 parsexml=None, parsexmlnode=None, caps=None):
        # pylint: disable=W0622
        # Redefining built-in 'type', but it matches the XML so keep it

        VirtualDevice.__init__(self, conn, parsexml, parsexmlnode, caps)

        self._network = None
        self._bridge = None
        self._macaddr = None
        self._type = None
        self._model = None
        self._target_dev = None
        self._source_dev = None
        self._source_mode = "vepa"
        self._virtualport = VirtualPort(conn, parsexml, parsexmlnode, caps)

        # Generate _random_mac
        self._random_mac = None
        self._default_bridge = None

        if self._is_parse():
            return

        self.type = type
        self.macaddr = macaddr
        self.bridge = bridge
        self.source_dev = bridge
        self.network = network
        self.model = model

        if self.type == self.TYPE_VIRTUAL:
            if network is None:
                raise ValueError(_("A network name was not provided"))

    def _generate_default_bridge(self):
        ret = self._default_bridge
        if ret is None:
            ret = False
            default = util.default_bridge(self.conn)
            if default:
                ret = default[1]

        self._default_bridge = ret
        return ret or None

    def _generate_random_mac(self):
        if self.conn and not self._random_mac:
            found = False
            for ignore in range(256):
                self._random_mac = util.randomMAC(self.conn.getType().lower(),
                                                  conn=self.conn)
                ret = self.is_conflict_net(self.conn, self._random_mac)
                if ret[1] is not None:
                    continue
                found = True
                break

            if not found:
                logging.debug("Failed to generate non-conflicting MAC")
        return self._random_mac

    def get_source(self):
        """
        Convenince function, try to return the relevant <source> value
        per the network type.
        """
        if self.type == self.TYPE_VIRTUAL:
            return self.network
        if self.type == self.TYPE_BRIDGE:
            return self.bridge
        if self.type == self.TYPE_ETHERNET or self.type == self.TYPE_DIRECT:
            return self.source_dev
        if self.type == self.TYPE_USER:
            return None
        return self.network or self.bridge or self.source_dev

    def set_source(self, newsource):
        """
        Conveninece function, try to set the relevant <source> value
        per the network type
        """
        if self.type == self.TYPE_VIRTUAL:
            self.network = newsource
        elif self.type == self.TYPE_BRIDGE:
            self.bridge = newsource
        elif self.type == self.TYPE_ETHERNET or self.type == self.TYPE_DIRECT:
            self.source_dev = newsource
        return
    source = property(get_source, set_source)

    def _get_virtualport(self):
        return self._virtualport
    virtualport = property(_get_virtualport)

    def get_type(self):
        return self._type
    def set_type(self, val):
        if val not in self.network_types:
            raise ValueError(_("Unknown network type %s") % val)
        self._type = val
    type = _xml_property(get_type, set_type,
                         xpath="./@type")

    def get_macaddr(self):
        # Don't generate a random MAC if parsing XML, since it can be slow
        if not self._macaddr and not self._is_parse():
            return self._generate_random_mac()
        return self._macaddr
    def set_macaddr(self, val):
        util.validate_macaddr(val)
        self._macaddr = val
    macaddr = _xml_property(get_macaddr, set_macaddr,
                            xpath="./mac/@address")

    def get_network(self):
        return self._network
    def set_network(self, newnet):
        def _is_net_active(netobj):
            # Apparently the 'info' command was never hooked up for
            # libvirt virNetwork python apis.
            if not self.conn:
                return True
            return self.conn.listNetworks().count(netobj.name())

        if newnet is not None and self.conn:
            try:
                net = self.conn.networkLookupByName(newnet)
            except libvirt.libvirtError, e:
                raise ValueError(_("Virtual network '%s' does not exist: %s")
                                   % (newnet, str(e)))
            if not _is_net_active(net):
                raise ValueError(_("Virtual network '%s' has not been "
                                   "started.") % newnet)

        self._network = newnet
            if not self.conn:
                return True
            return self.conn.listNetworks().count(netobj.name())

        if newnet is not None and self.conn:
            try:
                net = self.conn.networkLookupByName(newnet)
            except libvirt.libvirtError, e:
                raise ValueError(_("Virtual network '%s' does not exist: %s")
                                   % (newnet, str(e)))
            if not _is_net_active(net):
                raise ValueError(_("Virtual network '%s' has not been "
                                   "started.") % newnet)

        self._network = newnet
    network = _xml_property(get_network, set_network,
                            xpath="./source/@network")

    def get_bridge(self):
        if (not self._is_parse() and
            not self._bridge and
            self.type == self.TYPE_BRIDGE):
            return self._generate_default_bridge()
        return self._bridge
    def set_bridge(self, val):
        self._bridge = val
    bridge = _xml_property(get_bridge, set_bridge,
                           xpath="./source/@bridge")

    def get_model(self):
        return self._model
    def set_model(self, val):
Esempio n. 12
0
class CPU(XMLBuilderDomain.XMLBuilderDomain):
    """
    Class for generating <cpu> XML
    """

    _dumpxml_xpath = "/domain/cpu"

    MATCHS = ["minimum", "exact", "strict"]

    def __init__(self, conn, parsexml=None, parsexmlnode=None, caps=None):
        self._model = None
        self._match = None
        self._vendor = None
        self._mode = None
        self._features = []

        self._sockets = None
        self._cores = None
        self._threads = None

        XMLBuilderDomain.XMLBuilderDomain.__init__(self, conn, parsexml,
                                                   parsexmlnode, caps)
        if self._is_parse():
            return

    def _parsexml(self, xml, node):
        XMLBuilderDomain.XMLBuilderDomain._parsexml(self, xml, node)

        for node in self._xml_node.children:
            if node.name != "feature":
                continue
            feature = CPUFeature(self.conn, parsexmlnode=node)
            self._features.append(feature)

    def _get_features(self):
        return self._features[:]

    features = _xml_property(_get_features)

    def add_feature(self, name, policy="require"):
        feature = CPUFeature(self.conn)
        feature.name = name
        feature.policy = policy

        if self._is_parse():
            xml = feature.get_xml_config()
            node = libxml2.parseDoc(xml).children
            feature.set_xml_node(node)
            self._add_child_node("./cpu", node)

        self._features.append(feature)

    def remove_feature(self, feature):
        if self._is_parse() and feature in self._features:
            xpath = feature.get_xml_node_path()
            if xpath:
                self._remove_child_xpath(xpath)

        self._features.remove(feature)

    def _get_model(self):
        return self._model

    def _set_model(self, val):
        if val:
            self.mode = "custom"
        if val and not self.match:
            self.match = "exact"
        self._model = val

    model = _xml_property(_get_model, _set_model, xpath="./cpu/model")

    def _get_match(self):
        return self._match

    def _set_match(self, val):
        self._match = val

    match = _xml_property(_get_match, _set_match, xpath="./cpu/@match")

    def _get_vendor(self):
        return self._vendor

    def _set_vendor(self, val):
        self._vendor = val

    vendor = _xml_property(_get_vendor, _set_vendor, xpath="./cpu/vendor")

    def _get_mode(self):
        return self._mode

    def _set_mode(self, val):
        self._mode = val

    mode = _xml_property(_get_mode, _set_mode, xpath="./cpu/@mode")

    # Topology properties
    def _get_sockets(self):
        return self._sockets

    def _set_sockets(self, val):
        self._sockets = _int_or_none(val)

    sockets = _xml_property(_get_sockets,
                            _set_sockets,
                            get_converter=lambda s, x: _int_or_none(x),
                            xpath="./cpu/topology/@sockets")

    def _get_cores(self):
        return self._cores

    def _set_cores(self, val):
        self._cores = _int_or_none(val)

    cores = _xml_property(_get_cores,
                          _set_cores,
                          get_converter=lambda s, x: _int_or_none(x),
                          xpath="./cpu/topology/@cores")

    def _get_threads(self):
        return self._threads

    def _set_threads(self, val):
        self._threads = _int_or_none(val)

    threads = _xml_property(_get_threads,
                            _set_threads,
                            get_converter=lambda s, x: _int_or_none(x),
                            xpath="./cpu/topology/@threads")

    def clear_attrs(self):
        self.match = None
        self.mode = None
        self.vendor = None
        self.model = None

        for feature in self.features:
            self.remove_feature(feature)

    def copy_host_cpu(self):
        """
        Enact the equivalent of qemu -cpu host, pulling all info
        from capabilities about the host CPU
        """
        cpu = self._get_caps().host.cpu
        if not cpu.model:
            raise ValueError(_("No host CPU reported in capabilities"))

        self.mode = "custom"
        self.match = "exact"
        self.model = cpu.model
        self.vendor = cpu.vendor

        for feature in self.features:
            self.remove_feature(feature)
        for name in cpu.features.names():
            self.add_feature(name)

    def vcpus_from_topology(self):
        """
        Determine the CPU count represented by topology, or 1 if
        no topology is set
        """
        self.set_topology_defaults()
        if self.sockets:
            return self.sockets * self.cores * self.threads
        return 1

    def set_topology_defaults(self, vcpus=None):
        """
        Fill in unset topology values, using the passed vcpus count if
        required
        """
        if (self.sockets is None and self.cores is None
                and self.threads is None):
            return

        if vcpus is None:
            if self.sockets is None:
                self.sockets = 1
            if self.threads is None:
                self.threads = 1
            if self.cores is None:
                self.cores = 1

        vcpus = int(vcpus or 0)
        if not self.sockets:
            if not self.cores:
                self.sockets = vcpus / self.threads
            else:
                self.sockets = vcpus / self.cores

        if not self.cores:
            if not self.threads:
                self.cores = vcpus / self.sockets
            else:
                self.cores = vcpus / (self.sockets * self.threads)

        if not self.threads:
            self.threads = vcpus / (self.sockets * self.cores)

        return

    def _get_topology_xml(self):
        xml = ""
        if self.sockets:
            xml += " sockets='%s'" % self.sockets
        if self.cores:
            xml += " cores='%s'" % self.cores
        if self.threads:
            xml += " threads='%s'" % self.threads

        if not xml:
            return ""
        return "    <topology%s/>\n" % xml

    def _get_feature_xml(self):
        xml = ""
        for feature in self._features:
            xml += feature.get_xml_config() + "\n"
        return xml

    def _get_xml_config(self):
        top_xml = self._get_topology_xml()
        feature_xml = self._get_feature_xml()
        mode_xml = ""
        match_xml = ""
        if self.match:
            match_xml = " match='%s'" % self.match
        xml = ""

        if self.model == "host-passthrough":
            self.mode = "host-passthrough"
            mode_xml = " mode='%s'" % self.mode
            xml += "  <cpu%s/>" % mode_xml
            return xml
        else:
            self.mode = "custom"
            mode_xml = " mode='%s'" % self.mode

        if not (self.model or top_xml or feature_xml):
            return ""

        # Simple topology XML mode
        xml += "  <cpu%s%s>\n" % (mode_xml, match_xml)
        if self.model:
            xml += "    <model>%s</model>\n" % self.model
        if self.vendor:
            xml += "    <vendor>%s</vendor>\n" % self.vendor
        if top_xml:
            xml += top_xml
        if feature_xml:
            xml += feature_xml

        xml += "  </cpu>"
        return xml