Example #1
0
 def __type_check__(self, other):
     try:
         # Raise error if object isn't dict-like or doesn't have key
         device_tag = other['device_tag']
         # Check that we have support for this type
         librarian.get(device_tag)
     except (AttributeError, TypeError, xcepts.LibvirtXMLError):
         # Required to always raise TypeError for list API in VMXML class
         raise TypeError("Unsupported item type: %s" % str(type(other)))
Example #2
0
 def __type_check__(other):
     try:
         # Raise error if object isn't dict-like or doesn't have key
         device_tag = other['device_tag']
         # Check that we have support for this type
         librarian.get(device_tag)
     except (AttributeError, TypeError, xcepts.LibvirtXMLError):
         # Required to always raise TypeError for list API in VMXML class
         raise TypeError("Unsupported item type: %s" % str(type(other)))
Example #3
0
 def test_arbitrart_attributes(self):
     parallel = librarian.get('parallel')(virsh_instance=self.dummy_virsh)
     serial = librarian.get('serial')(virsh_instance=self.dummy_virsh)
     channel = librarian.get('channel')(virsh_instance=self.dummy_virsh)
     console = librarian.get('console')(virsh_instance=self.dummy_virsh)
     for chardev in (parallel, serial, channel, console):
         attribute1 = utils_misc.generate_random_string(10)
         value1 = utils_misc.generate_random_string(10)
         attribute2 = utils_misc.generate_random_string(10)
         value2 = utils_misc.generate_random_string(10)
         chardev.add_source(**{attribute1: value1, attribute2: value2})
         chardev.add_target(**{attribute1: value1, attribute2: value2})
         self.assertEqual(chardev.sources, chardev.targets)
Example #4
0
 def test_arbitrart_attributes(self):
     parallel = librarian.get('parallel')(virsh_instance = self.dummy_virsh)
     serial = librarian.get('serial')(virsh_instance = self.dummy_virsh)
     channel = librarian.get('channel')(virsh_instance = self.dummy_virsh)
     console = librarian.get('console')(virsh_instance = self.dummy_virsh)
     for chardev in (parallel, serial, channel, console):
         attribute1 = utils_misc.generate_random_string(10)
         value1 = utils_misc.generate_random_string(10)
         attribute2 = utils_misc.generate_random_string(10)
         value2 = utils_misc.generate_random_string(10)
         chardev.add_source(**{attribute1:value1, attribute2:value2})
         chardev.add_target(**{attribute1:value1, attribute2:value2})
         self.assertEqual(chardev.sources, chardev.targets)
Example #5
0
class Hub(base.TypedDeviceBase):
    __slots__ = ('address', )

    def __init__(self, type_name, virsh_instance=base.base.virsh):
        super(Hub, self).__init__(device_tag='hub',
                                  type_name=type_name,
                                  virsh_instance=virsh_instance)
        accessors.XMLElementNest('address',
                                 self,
                                 parent_xpath='/',
                                 tag_name='address',
                                 subclass=self.Address,
                                 subclass_dargs={
                                     'type_name': 'usb',
                                     'virsh_instance': virsh_instance
                                 })

    # For convenience
    Address = librarian.get('address')

    def new_hub_address(self, type_name='usb', **dargs):
        """
        Return a new hub Address instance and set properties from dargs
        """
        new_one = self.Address(type_name=type_name, virsh_instance=self.virsh)
        for key, value in list(dargs.items()):
            setattr(new_one, key, value)
        return new_one
Example #6
0
class Interface(base.TypedDeviceBase):

    __slots__ = ('source', 'mac_address', 'bandwidth_inbound',
                 'bandwidth_outbound', 'portgroup', 'model', 'driver',
                 'address')

    def __init__(self, type_name, virsh_instance=base.base.virsh):
        super(Interface, self).__init__(device_tag='interface',
                                        type_name=type_name,
                                        virsh_instance=virsh_instance)
        accessors.XMLElementDict(property_name="source",
                                 libvirtxml=self,
                                 forbidden=None,
                                 parent_xpath='/',
                                 tag_name='source')
        accessors.XMLElementDict(property_name="driver",
                                 libvirtxml=self,
                                 forbidden=None,
                                 parent_xpath='/',
                                 tag_name='driver')
        accessors.XMLAttribute(property_name="mac_address",
                               libvirtxml=self,
                               forbidden=None,
                               parent_xpath='/',
                               tag_name='mac',
                               attribute='address')
        accessors.XMLElementDict(property_name="bandwidth_inbound",
                                 libvirtxml=self,
                                 forbidden=None,
                                 parent_xpath='/bandwidth',
                                 tag_name='inbound')
        accessors.XMLElementDict(property_name="bandwidth_outbound",
                                 libvirtxml=self,
                                 forbidden=None,
                                 parent_xpath='/bandwidth',
                                 tag_name='outbound')
        accessors.XMLAttribute(property_name="portgroup",
                               libvirtxml=self,
                               forbidden=None,
                               parent_xpath='/',
                               tag_name='source',
                               attribute='portgroup')
        accessors.XMLAttribute(property_name="model",
                               libvirtxml=self,
                               forbidden=None,
                               parent_xpath='/',
                               tag_name='model',
                               attribute='type')
        accessors.XMLElementNest('address',
                                 self,
                                 parent_xpath='/',
                                 tag_name='address',
                                 subclass=self.Address,
                                 subclass_dargs={
                                     'type_name': 'drive',
                                     'virsh_instance': virsh_instance
                                 })

    # For convenience
    Address = librarian.get('address')
Example #7
0
class Input(base.TypedDeviceBase):
    __slots__ = ('input_bus', 'address')

    def __init__(self, type_name, virsh_instance=base.base.virsh):
        super(Input, self).__init__(device_tag='input',
                                    type_name=type_name,
                                    virsh_instance=virsh_instance)
        accessors.XMLAttribute(property_name="input_bus",
                               libvirtxml=self,
                               forbidden=None,
                               parent_xpath='/',
                               tag_name='input',
                               attribute='bus')
        accessors.XMLElementNest('address',
                                 self,
                                 parent_xpath='/',
                                 tag_name='address',
                                 subclass=self.Address,
                                 subclass_dargs={
                                     'type_name': 'usb',
                                     'virsh_instance': virsh_instance
                                 })

    # For convenience
    Address = librarian.get('address')

    def new_input_address(self, type_name='usb', **dargs):
        """
        Return a new input Address instance and set properties from dargs
        """
        new_one = self.Address(type_name=type_name, virsh_instance=self.virsh)
        for key, value in dargs.items():
            setattr(new_one, key, value)
        return new_one
Example #8
0
class Vsock(base.UntypedDeviceBase):

    __slots__ = ('model_type', 'cid', 'address', 'alias')

    def __init__(self, virsh_instance=base.base.virsh):
        accessors.XMLAttribute('model_type',
                               self,
                               parent_xpath='/',
                               tag_name='vsock',
                               attribute='model')
        accessors.XMLElementDict('cid', self, parent_xpath='/', tag_name='cid')
        accessors.XMLElementNest(
            'address',
            self,
            parent_xpath='/',
            tag_name='address',
            subclass=self.Address,
            subclass_dargs={'virsh_instance': virsh_instance})
        accessors.XMLElementDict('alias',
                                 self,
                                 parent_xpath='/',
                                 tag_name='alias')
        super(Vsock, self).__init__(device_tag='vsock',
                                    virsh_instance=virsh_instance)
        self.xml = '<vsock/>'

    Address = librarian.get('address')
Example #9
0
 def _from_scratch(self):
     serial = librarian.get('Serial')(virsh_instance=self.dummy_virsh)
     self.assertEqual(serial.device_tag, 'serial')
     self.assertEqual(serial.type_name, 'pty')
     self.assertEqual(serial.virsh, self.dummy_virsh)
     serial.add_source(path='/dev/null')
     serial.add_target(port="-1")
     return serial
Example #10
0
 def _from_scratch(self):
     serial = librarian.get('Serial')(virsh_instance = self.dummy_virsh)
     self.assertEqual(serial.device_tag, 'serial')
     self.assertEqual(serial.type_name, 'pty')
     self.assertEqual(serial.virsh, self.dummy_virsh)
     serial.add_source(path='/dev/null')
     serial.add_target(port="-1")
     return serial
Example #11
0
 def marshal_to_seclabel(tag, attr_dict, index, libvirtxml):
     """Convert a tag + attributes into a Seclabel instance"""
     del index           # not used
     if tag != 'seclabel':
         return None     # Don't convert this item
     Seclabel = librarian.get('seclabel')
     newone = Seclabel(virsh_instance=libvirtxml.virsh)
     newone.update(attr_dict)
     return newone
Example #12
0
 def marshal_to_seclabel(tag, attr_dict, index, libvirtxml):
     """Convert a tag + attributes into a Seclabel instance"""
     del index  # not used
     if tag != 'seclabel':
         return None  # Don't convert this item
     Seclabel = librarian.get('seclabel')
     newone = Seclabel(virsh_instance=libvirtxml.virsh)
     newone.update(attr_dict)
     return newone
Example #13
0
 def test_from_element(self):
     element = xml_utils.ElementTree.fromstring(self.XML)
     serial1 = self._from_scratch()
     serial2 = librarian.get('Serial').new_from_element(element)
     self.assertEqual(serial1, serial2)
     # Can't in-place modify the dictionary since it's virtual
     serial2.update_target(0, port="0")
     self.assertTrue(serial1 != serial2)
     serial1.targets = [{'port':'0'}]
     self.assertEqual(serial1, serial2)
Example #14
0
 def test_from_element(self):
     element = xml_utils.ElementTree.fromstring(self.XML)
     serial1 = self._from_scratch()
     serial2 = librarian.get('Serial').new_from_element(element)
     self.assertEqual(serial1, serial2)
     # Can't in-place modify the dictionary since it's virtual
     serial2.update_target(0, port="0")
     self.assertTrue(serial1 != serial2)
     serial1.targets = [{'port': '0'}]
     self.assertEqual(serial1, serial2)
Example #15
0
 def test_required(self):
     address = librarian.get('address')
     self.assertRaises(xcepts.LibvirtXMLError, address.new_from_dict, {},
                       self.dummy_virsh)
     # no type_name attribute
     element = xml_utils.ElementTree.Element('address', {'foo': 'bar'})
     self.assertRaises(xcepts.LibvirtXMLError, address.new_from_element,
                       element, self.dummy_virsh)
     element.set('type', 'foobar')
     new_address = address.new_from_element(element, self.dummy_virsh)
     the_dict = {'type_name': 'foobar', 'foo': 'bar'}
     another_address = address.new_from_dict(the_dict, self.dummy_virsh)
     self.assertEqual(str(new_address), str(another_address))
Example #16
0
    def prepare_serial_device():
        """
        Prepare a serial device XML according to parameters

        :return: the serial device xml object
        """
        serial = librarian.get('serial')(serial_type)

        serial.target_port = target_port
        serial.target_type = target_type
        serial.target_model = target_model
        serial.log_file = log_file

        return serial
Example #17
0
 def test_required(self):
     address = librarian.get('address')
     self.assertRaises(xcepts.LibvirtXMLError,
                       address.new_from_dict,
                       {}, self.dummy_virsh)
     # no type_name attribute
     element = xml_utils.ElementTree.Element('address', {'foo':'bar'})
     self.assertRaises(xcepts.LibvirtXMLError,
                       address.new_from_element,
                       element, self.dummy_virsh)
     element.set('type', 'foobar')
     new_address = address.new_from_element(element, self.dummy_virsh)
     the_dict = {'type_name':'foobar', 'foo':'bar'}
     another_address = address.new_from_dict(the_dict, self.dummy_virsh)
     self.assertEqual(str(new_address), str(another_address))
Example #18
0
 def get_devices(self, device_type=None):
     """
     Put all nodes of devices into a VMXMLDevices instance.
     """
     devices = VMXMLDevices()
     all_devices = self.xmltreefile.find('devices')
     if device_type is not None:
         device_nodes = all_devices.findall(device_type)
     else:
         device_nodes = all_devices
     for node in device_nodes:
         device_tag = node.tag
         device_class = librarian.get(device_tag)
         new_one = device_class.new_from_element(node)
         devices.append(new_one)
     return devices
Example #19
0
 def get_devices(self, device_type=None):
     """
     Put all nodes of devices into a VMXMLDevices instance.
     """
     devices = VMXMLDevices()
     all_devices = self.xmltreefile.find('devices')
     if device_type is not None:
         device_nodes = all_devices.findall(device_type)
     else:
         device_nodes = all_devices
     for node in device_nodes:
         device_tag = node.tag
         device_class = librarian.get(device_tag)
         new_one = device_class.new_from_element(node)
         devices.append(new_one)
     return devices
Example #20
0
    def prepare_console_device():
        """
        Prepare a serial device XML according to parameters
        """
        console = librarian.get('console')(serial_type)
        console.target_type = console_target_type

        sources = []
        logging.debug(sources_str)
        for source_str in sources_str.split():
            source_dict = {}
            for att in source_str.split(','):
                key, val = att.split(':')
                source_dict[key] = val
            sources.append(source_dict)
        console.sources = sources
        return console
Example #21
0
    def prepare_console_device():
        """
        Prepare a serial device XML according to parameters
        """
        console = librarian.get('console')(serial_type)
        console.target_type = console_target_type

        sources = []
        logging.debug(sources_str)
        for source_str in sources_str.split():
            source_dict = {}
            for att in source_str.split(','):
                key, val = att.split(':')
                source_dict[key] = val
            sources.append(source_dict)
        console.sources = sources
        return console
Example #22
0
    def prepare_serial_device():
        """
        Prepare a serial device XML according to parameters
        """
        serial = librarian.get('serial')(serial_type)

        serial.target_port = "0"

        sources = []
        logging.debug(sources_str)
        for source_str in sources_str.split():
            source_dict = {}
            for att in source_str.split(','):
                key, val = att.split(':')
                source_dict[key] = val
            sources.append(source_dict)
        serial.sources = sources
        return serial
Example #23
0
    def prepare_serial_device():
        """
        Prepare a serial device XML according to parameters
        """
        serial = librarian.get('serial')(serial_type)

        serial.target_port = "0"

        sources = []
        logging.debug(sources_str)
        for source_str in sources_str.split():
            source_dict = {}
            for att in source_str.split(','):
                key, val = att.split(':')
                source_dict[key] = val
            sources.append(source_dict)
        serial.sources = sources
        return serial
Example #24
0
class Controller(base.TypedDeviceBase):

    __slots__ = ('type', 'index', 'model', 'ports', 'vectors', 'driver',
                 'address', 'pcihole64', 'target', 'alias')

    def __init__(self, type_name, virsh_instance=base.base.virsh):
        super(Controller, self).__init__(device_tag='controller',
                                         type_name=type_name,
                                         virsh_instance=virsh_instance)
        accessors.XMLAttribute('type', self, parent_xpath='/',
                               tag_name='controller', attribute='type')
        accessors.XMLAttribute('index', self, parent_xpath='/',
                               tag_name='controller', attribute='index')
        accessors.XMLAttribute('model', self, parent_xpath='/',
                               tag_name='controller', attribute='model')
        accessors.XMLAttribute('ports', self, parent_xpath='/',
                               tag_name='controller', attribute='ports')
        accessors.XMLAttribute('vectors', self, parent_xpath='/',
                               tag_name='controller', attribute='vectors')
        accessors.XMLElementText('pcihole64', self, parent_xpath='/',
                                 tag_name='pcihole64')
        accessors.XMLElementDict('driver', self, parent_xpath='/',
                                 tag_name='driver')
        accessors.XMLElementNest('address', self, parent_xpath='/',
                                 tag_name='address', subclass=self.Address,
                                 subclass_dargs={'type_name': 'pci',
                                                 'virsh_instance': virsh_instance})
        accessors.XMLElementDict('target', self, parent_xpath='/',
                                 tag_name='target')
        accessors.XMLElementDict('alias', self, parent_xpath='/',
                                 tag_name='alias')

    Address = librarian.get('address')

    def new_controller_address(self, **dargs):
        """
        Return a new controller Address instance and set properties from dargs
        """
        new_one = self.Address("pci", virsh_instance=self.virsh)
        for key, value in dargs.items():
            setattr(new_one, key, value)
        return new_one
    def prepare_serial_device():
        """
        Prepare a serial device XML
        """
        local_serial_type = serial_type
        serial = librarian.get('serial')(local_serial_type)
        serial.target_port = "0"
        serial.alias = {'name': alias_name}

        set_targets(serial)

        sources = []
        logging.debug(sources_str)
        for source_str in sources_str.split():
            source_dict = {}
            for att in source_str.split(','):
                key, val = att.split(':')
                source_dict[key] = val
            sources.append(source_dict)
        serial.sources = sources
        return serial
Example #26
0
class Vsock(base.UntypedDeviceBase):

    __slots__ = ('model_type', 'cid', 'address', 'alias')

    def __init__(self, virsh_instance=base.base.virsh):
        accessors.XMLAttribute('model_type',
                               self,
                               parent_xpath='/',
                               tag_name='vsock',
                               attribute='model')
        accessors.XMLElementDict('cid', self, parent_xpath='/', tag_name='cid')
        accessors.XMLElementNest('address',
                                 self,
                                 parent_xpath='/',
                                 tag_name='address',
                                 subclass=self.Address,
                                 subclass_dargs={
                                     'type_name': 'pci',
                                     'virsh_instance': virsh_instance
                                 })
        accessors.XMLElementDict('alias',
                                 self,
                                 parent_xpath='/',
                                 tag_name='alias')
        super(Vsock, self).__init__(device_tag='vsock',
                                    virsh_instance=virsh_instance)
        self.xml = '<vsock/>'

    Address = librarian.get('address')

    def new_vsock_address(self, **dargs):
        """
        Return a new interface Address instance and set properties from dargs
        """
        new_one = self.Address("pci", virsh_instance=self.virsh)
        for key, value in list(dargs.items()):
            setattr(new_one, key, value)
        return new_one
Example #27
0
class Disk(base.TypedDeviceBase):
    """
    Disk device XML class

    Properties:
        device: string, how exposted to guest
        rawio: string (yes/no), disk needs rawio capability
        sgio: string, "filtered" or "unfiltered"
        snapshot: string, "yes", "no", "internal" or "external"
        driver: dict, keys: name, type, cache, error_policy, io, ioeventfd,
                            event_idx, copy_on_read, discard
        target: dict, keys: dev, bus, tray
        address: libvirt_xml.devices.Address instance
        boot: string, boot order number to use if not using boot in os element
        readonly: bool, True/False
        transient: bool, True/False
        share: bool, True/False
        mirror: bool, read-only, True if block copy started
        ready: bool, read-only, True if disk ready for pivot
        iotune: libvirt_xml.devices.Disk.IOTune instance
        source: libvirt_xml.devices.Disk.DiskSource instance
    """

    __slots__ = ('device', 'rawio', 'sgio', 'snapshot', 'driver', 'target',
                 'address', 'boot', 'readonly', 'transient', 'share', 'mirror',
                 'ready', 'iotune', 'source')

    def __init__(self, type_name='file', virsh_instance=base.base.virsh):
        accessors.XMLAttribute('device',
                               self,
                               parent_xpath='/',
                               tag_name='disk',
                               attribute='device')
        accessors.XMLAttribute('rawio',
                               self,
                               parent_xpath='/',
                               tag_name='disk',
                               attribute='rawio')
        accessors.XMLAttribute('sgio',
                               self,
                               parent_xpath='/',
                               tag_name='disk',
                               attribute='sgio')
        accessors.XMLAttribute('snapshot',
                               self,
                               parent_xpath='/',
                               tag_name='disk',
                               attribute='snapshot')
        accessors.XMLElementDict('driver',
                                 self,
                                 parent_xpath='/',
                                 tag_name='driver')
        accessors.XMLElementDict('target',
                                 self,
                                 parent_xpath='/',
                                 tag_name='target')
        accessors.XMLElementNest('address',
                                 self,
                                 parent_xpath='/',
                                 tag_name='address',
                                 subclass=self.Address,
                                 subclass_dargs={
                                     'type_name': 'drive',
                                     'virsh_instance': virsh_instance
                                 })
        accessors.XMLAttribute('boot',
                               self,
                               parent_xpath='/',
                               tag_name='boot',
                               attribute='order')
        accessors.XMLElementBool('readonly',
                                 self,
                                 parent_xpath='/',
                                 tag_name='readonly')
        accessors.XMLElementBool('transient',
                                 self,
                                 parent_xpath='/',
                                 tag_name='transient')
        accessors.XMLElementBool('share',
                                 self,
                                 parent_xpath='/',
                                 tag_name='shareable')
        accessors.XMLElementNest(
            'source',
            self,
            parent_xpath='/',
            tag_name='source',
            subclass=self.DiskSource,
            subclass_dargs={'virsh_instance': virsh_instance})
        ro = ['set', 'del']
        accessors.XMLElementBool('mirror',
                                 self,
                                 forbidden=ro,
                                 parent_xpath='/',
                                 tag_name='mirror')
        accessors.XMLElementBool('ready',
                                 self,
                                 forbidden=ro,
                                 parent_xpath='/',
                                 tag_name='ready')
        accessors.XMLElementNest(
            'iotune',
            self,
            parent_xpath='/',
            tag_name='iotune',
            subclass=self.IOTune,
            subclass_dargs={'virsh_instance': virsh_instance})
        super(Disk, self).__init__(device_tag='disk',
                                   type_name=type_name,
                                   virsh_instance=virsh_instance)

    def new_disk_source(self, **dargs):
        """
        Return a new disk source instance and set properties from dargs
        """
        new_one = self.DiskSource(virsh_instance=self.virsh)
        for key, value in dargs.items():
            setattr(new_one, key, value)
        return new_one

    def new_iotune(self, **dargs):
        """
        Return a new disk IOTune instance and set properties from dargs
        """
        new_one = self.IOTune(virsh_instance=self.virsh)
        for key, value in dargs.items():
            setattr(new_one, key, value)
        return new_one

    def new_disk_address(self, type_name='drive', **dargs):
        """
        Return a new disk Address instance and set properties from dargs
        """
        new_one = self.Address(type_name=type_name, virsh_instance=self.virsh)
        for key, value in dargs.items():
            setattr(new_one, key, value)
        return new_one

    # For convenience
    Address = librarian.get('address')

    class DiskSource(base.base.LibvirtXMLBase):
        """
        Disk source device XML class

        Properties:
            attrs: Dictionary of attributes, qualifying the disk type
            seclabels: list of libvirt_xml.devices.seclabel.Seclabel instances
            hosts: list of dictionaries describing network host properties
        """

        __slots__ = (
            'attrs',
            'seclabels',
            'hosts',
        )

        def __init__(self, virsh_instance=base.base.virsh):
            accessors.XMLElementDict('attrs',
                                     self,
                                     parent_xpath='/',
                                     tag_name='source')
            accessors.XMLElementList('seclabels',
                                     self,
                                     parent_xpath='/',
                                     marshal_from=self.marshal_from_seclabel,
                                     marshal_to=self.marshal_to_seclabel)
            accessors.XMLElementList('hosts',
                                     self,
                                     parent_xpath='/',
                                     marshal_from=self.marshal_from_host,
                                     marshal_to=self.marshal_to_host)
            super(self.__class__, self).__init__(virsh_instance=virsh_instance)
            self.xml = '<source/>'

        @staticmethod
        def marshal_from_seclabel(item, index, libvirtxml):
            """Convert a Seclabel instance into tag + attributes"""
            del index  # not used
            del libvirtxml  # not used
            root = item.xmltreefile.getroot()
            if root.tag == 'seclabel':
                return (root.tag, dict(root.items))
            else:
                raise xcepts.LibvirtXMLError("Expected a list of seclabel "
                                             "instances, not a %s" % str(item))

        @staticmethod
        def marshal_to_seclabel(tag, attr_dict, index, libvirtxml):
            """Convert a tag + attributes into a Seclabel instance"""
            del index  # not used
            if tag != 'seclabel':
                return None  # Don't convert this item
            Seclabel = librarian.get('seclabel')
            newone = Seclabel(virsh_instance=libvirtxml.virsh)
            newone.update(attr_dict)
            return newone

        @staticmethod
        def marshal_from_host(item, index, libvirtxml):
            """Convert a dictionary into a tag + attributes"""
            del index  # not used
            del libvirtxml  # not used
            if not isinstance(item, dict):
                raise xcepts.LibvirtXMLError("Expected a dictionary of host "
                                             "attributes, not a %s" %
                                             str(item))
            return ('host', dict(item))  # return copy of dict, not reference

        @staticmethod
        def marshal_to_host(tag, attr_dict, index, libvirtxml):
            """Convert a tag + attributes into a dictionary"""
            del index  # not used
            del libvirtxml  # not used
            if tag != 'host':
                return None  # skip this one
            return dict(attr_dict)  # return copy of dict, not reference

    class IOTune(base.base.LibvirtXMLBase):
        """
        IOTune device XML class

        Properties:
            total_bytes_sec: str(int)
            read_bytes_sec: str(int)
            write_bytes_sec: str(int)
            total_iops_sec: str(int)
            read_iops_sec: str(int)
            write_iops_sec: str(int)
        """

        __slots__ = ('total_bytes_sec', 'read_bytes_sec', 'write_bytes_sec',
                     'total_iops_sec', 'read_iops_sec', 'write_iops_sec')

        def __init__(self, virsh_instance=base.base.virsh):
            for slot in self.__all_slots__:
                if slot in base.base.LibvirtXMLBase.__all_slots__:
                    continue  # don't add these
                else:
                    accessors.XMLElementInt(slot,
                                            self,
                                            parent_xpath='/',
                                            tag_name=slot)
            super(Disk.IOTune, self).__init__(virsh_instance=virsh_instance)
            self.xml = '<iotune/>'
Example #28
0
 def get_device_class(type_name):
     """
     Return class that handles type_name devices, or raise exception.
     """
     return librarian.get(type_name)
Example #29
0
class Redirdev(base.TypedDeviceBase):

    __slots__ = ('type', 'bus', 'source', 'protocol', 'boot', 'alias',
                 'address')

    def __init__(self, type_name="redirdev", virsh_instance=base.base.virsh):
        super(Redirdev, self).__init__(device_tag='redirdev',
                                       type_name=type_name,
                                       virsh_instance=virsh_instance)
        accessors.XMLAttribute('type',
                               self,
                               parent_xpath='/',
                               tag_name='redirdev',
                               attribute='type')
        accessors.XMLAttribute('bus',
                               self,
                               parent_xpath='/',
                               tag_name='redirdev',
                               attribute='bus')
        accessors.XMLElementNest(
            'source',
            self,
            parent_xpath='/',
            tag_name='source',
            subclass=self.Source,
            subclass_dargs={'virsh_instance': virsh_instance})
        accessors.XMLElementDict('protocol',
                                 self,
                                 parent_xpath='/',
                                 tag_name='protocol')
        accessors.XMLElementDict('boot',
                                 self,
                                 parent_xpath='/',
                                 tag_name='boot')
        accessors.XMLElementDict('alias',
                                 self,
                                 parent_xpath='/',
                                 tag_name='alias')
        accessors.XMLElementNest('address',
                                 self,
                                 parent_xpath='/',
                                 tag_name='address',
                                 subclass=self.Address,
                                 subclass_dargs={
                                     'type_name': 'usb',
                                     'virsh_instance': virsh_instance
                                 })

    Address = librarian.get('address')

    def new_source(self, **dargs):
        """
        Return a new Redirdev Source instance and set properties from dargs
        """
        new_one = self.Source(virsh_instance=self.virsh)
        for k, v in dargs.items():
            if v:
                setattr(new_one, k, v)
        return new_one

    class Source(base.base.LibvirtXMLBase):

        __slots__ = ('mode', 'host', 'service', 'tls', 'path')

        def __init__(self, virsh_instance=base.base.virsh):
            accessors.XMLAttribute('mode',
                                   self,
                                   parent_xpath='/',
                                   tag_name='source',
                                   attribute='mode')
            accessors.XMLAttribute('host',
                                   self,
                                   parent_xpath='/',
                                   tag_name='source',
                                   attribute='host')
            accessors.XMLAttribute('service',
                                   self,
                                   parent_xpath='/',
                                   tag_name='source',
                                   attribute='service')
            accessors.XMLAttribute('tls',
                                   self,
                                   parent_xpath='/',
                                   tag_name='source',
                                   attribute='tls')
            accessors.XMLAttribute('path',
                                   self,
                                   parent_xpath='/',
                                   tag_name='source',
                                   attribute='path')
            super(self.__class__, self).__init__(virsh_instance=virsh_instance)
            self.xml = '<source/>'
Example #30
0
class Hostdev(base.TypedDeviceBase):

    __slots__ = ('type', 'mode', 'managed', 'sgio', 'rawio', 'source',
                 'boot_order', 'readonly', 'shareable', 'alias', 'model',
                 'teaming', 'rom', 'address')

    def __init__(self, type_name="hostdev", virsh_instance=base.base.virsh):
        accessors.XMLAttribute('type',
                               self,
                               parent_xpath='/',
                               tag_name='hostdev',
                               attribute='type')
        accessors.XMLAttribute('mode',
                               self,
                               parent_xpath='/',
                               tag_name='hostdev',
                               attribute='mode')
        accessors.XMLAttribute('model',
                               self,
                               parent_xpath='/',
                               tag_name='hostdev',
                               attribute='model')
        accessors.XMLAttribute('managed',
                               self,
                               parent_xpath='/',
                               tag_name='hostdev',
                               attribute='managed')
        accessors.XMLAttribute('sgio',
                               self,
                               parent_xpath='/',
                               tag_name='hostdev',
                               attribute='sgio')
        accessors.XMLAttribute('rawio',
                               self,
                               parent_xpath='/',
                               tag_name='hostdev',
                               attribute='rawio')
        accessors.XMLElementNest(
            'source',
            self,
            parent_xpath='/',
            tag_name='source',
            subclass=self.Source,
            subclass_dargs={'virsh_instance': virsh_instance})
        accessors.XMLAttribute('boot_order',
                               self,
                               parent_xpath='/',
                               tag_name='boot',
                               attribute='order')
        accessors.XMLElementBool('readonly',
                                 self,
                                 parent_xpath='/',
                                 tag_name='readonly')
        accessors.XMLElementBool('shareable',
                                 self,
                                 parent_xpath='/',
                                 tag_name='shareable')
        accessors.XMLElementDict('alias',
                                 self,
                                 parent_xpath='/',
                                 tag_name='alias')
        accessors.XMLElementDict('rom', self, parent_xpath='/', tag_name='rom')
        accessors.XMLElementNest('address',
                                 self,
                                 parent_xpath='/',
                                 tag_name='address',
                                 subclass=self.Address,
                                 subclass_dargs={
                                     'type_name': 'drive',
                                     'virsh_instance': virsh_instance
                                 })
        accessors.XMLElementDict("teaming",
                                 self,
                                 parent_xpath='/',
                                 tag_name='teaming')
        super(self.__class__, self).__init__(device_tag='hostdev',
                                             type_name=type_name,
                                             virsh_instance=virsh_instance)

    Address = librarian.get('address')

    def new_source(self, **dargs):
        new_one = self.Source(virsh_instance=self.virsh)
        if self.type == 'pci':
            pass
        elif self.type == 'usb':
            new_one.vendor_id = dargs.pop("vendor_id", None)
            new_one.product_id = dargs.pop("product_id", None)
            new_one.address_bus = dargs.pop("address_bus", None)
            new_one.address_device = dargs.pop("address_device", None)
        elif self.type == 'scsi':
            if dargs.get("adapter_name"):
                new_one.adapter_name = dargs.pop("adapter_name")
            if dargs.get("protocol"):
                new_one.protocol = dargs.pop("protocol")
            if dargs.get("source_name"):
                new_one.source_name = dargs.pop("source_name")
            if dargs.get("host_name"):
                new_one.host_name = dargs.pop("host_name")
            if dargs.get("host_port"):
                new_one.host_port = dargs.pop("host_port")
            auth_args = {
                'auth_user': dargs.pop('auth_user', None),
                'secret_type': dargs.pop('secret_type', None),
                'secret_uuid': dargs.pop('secret_uuid', None),
                'secret_usage': dargs.pop('secret_usage', None)
            }
            if auth_args['auth_user']:
                new_auth = new_one.new_auth(**auth_args)
                new_one.auth = new_auth
            initiator_args = {'iqn_id': dargs.pop('iqn_id', None)}
            if initiator_args['iqn_id']:
                new_initiator = new_one.new_initiator(**initiator_args)
                new_one.initiator = new_initiator
        if dargs:
            new_address = new_one.new_untyped_address(**dargs)
            new_one.untyped_address = new_address
        return new_one

    class Source(base.base.LibvirtXMLBase):

        __slots__ = ('untyped_address', 'vendor_id', 'product_id',
                     'adapter_name', 'protocol', 'source_name', 'host_name',
                     'host_port', 'auth', 'address_bus', 'address_device',
                     'initiator')

        def __init__(self, virsh_instance=base.base.virsh):
            accessors.XMLAttribute('vendor_id',
                                   self,
                                   parent_xpath='/',
                                   tag_name='vendor',
                                   attribute='id')
            accessors.XMLAttribute('product_id',
                                   self,
                                   parent_xpath='/',
                                   tag_name='product',
                                   attribute='id')
            accessors.XMLElementNest(
                'untyped_address',
                self,
                parent_xpath='/',
                tag_name='address',
                subclass=self.UntypedAddress,
                subclass_dargs={'virsh_instance': virsh_instance})
            accessors.XMLAttribute('adapter_name',
                                   self,
                                   parent_xpath='/',
                                   tag_name='adapter',
                                   attribute='name')
            accessors.XMLAttribute('protocol',
                                   self,
                                   parent_xpath='/',
                                   tag_name='source',
                                   attribute='protocol')
            accessors.XMLAttribute('source_name',
                                   self,
                                   parent_xpath='/',
                                   tag_name='source',
                                   attribute='name')
            accessors.XMLAttribute('host_name',
                                   self,
                                   parent_xpath='/',
                                   tag_name='host',
                                   attribute='name')
            accessors.XMLAttribute('host_port',
                                   self,
                                   parent_xpath='/',
                                   tag_name='host',
                                   attribute='port')
            accessors.XMLAttribute('address_bus',
                                   self,
                                   parent_xpath='/',
                                   tag_name='address',
                                   attribute='bus')
            accessors.XMLAttribute('address_device',
                                   self,
                                   parent_xpath='/',
                                   tag_name='address',
                                   attribute='device')
            accessors.XMLElementNest(
                'auth',
                self,
                parent_xpath='/',
                tag_name='auth',
                subclass=self.Auth,
                subclass_dargs={'virsh_instance': virsh_instance})
            accessors.XMLElementNest(
                'initiator',
                self,
                parent_xpath='/',
                tag_name='initiator',
                subclass=self.Initiator,
                subclass_dargs={'virsh_instance': virsh_instance})
            super(self.__class__, self).__init__(virsh_instance=virsh_instance)
            self.xml = '<source/>'

        def new_untyped_address(self, **dargs):
            new_one = self.UntypedAddress(virsh_instance=self.virsh)
            for key, value in list(dargs.items()):
                if value:
                    setattr(new_one, key, value)
            return new_one

        def new_auth(self, **dargs):
            new_one = self.Auth(virsh_instance=self.virsh)
            for key, value in list(dargs.items()):
                if value:
                    setattr(new_one, key, value)
            return new_one

        def new_initiator(self, **dargs):
            new_one = self.Initiator(virsh_instance=self.virsh)
            for key, value in list(dargs.items()):
                if value:
                    setattr(new_one, key, value)
            return new_one

        class UntypedAddress(base.UntypedDeviceBase):

            __slots__ = ('device', 'domain', 'bus', 'slot', 'function',
                         'target', 'unit', 'uuid')

            def __init__(self, virsh_instance=base.base.virsh):
                accessors.XMLAttribute('domain',
                                       self,
                                       parent_xpath='/',
                                       tag_name='address',
                                       attribute='domain')
                accessors.XMLAttribute('slot',
                                       self,
                                       parent_xpath='/',
                                       tag_name='address',
                                       attribute='slot')
                accessors.XMLAttribute('bus',
                                       self,
                                       parent_xpath='/',
                                       tag_name='address',
                                       attribute='bus')
                accessors.XMLAttribute('device',
                                       self,
                                       parent_xpath='/',
                                       tag_name='address',
                                       attribute='device')
                accessors.XMLAttribute('function',
                                       self,
                                       parent_xpath='/',
                                       tag_name='address',
                                       attribute='function')
                accessors.XMLAttribute('target',
                                       self,
                                       parent_xpath='/',
                                       tag_name='address',
                                       attribute='target')
                accessors.XMLAttribute('unit',
                                       self,
                                       parent_xpath='/',
                                       tag_name='address',
                                       attribute='unit')
                accessors.XMLAttribute('uuid',
                                       self,
                                       parent_xpath='/',
                                       tag_name='address',
                                       attribute='uuid')
                super(self.__class__,
                      self).__init__("address", virsh_instance=virsh_instance)
                self.xml = "<address/>"

        class Auth(base.base.LibvirtXMLBase):

            __slots__ = ('auth_user', 'secret_type', 'secret_uuid',
                         'secret_usage')

            def __init__(self, virsh_instance=base.base.virsh, auth_user=""):
                accessors.XMLAttribute('auth_user',
                                       self,
                                       parent_xpath='/',
                                       tag_name='auth',
                                       attribute='username')
                accessors.XMLAttribute('secret_type',
                                       self,
                                       parent_xpath='/',
                                       tag_name='secret',
                                       attribute='type')
                accessors.XMLAttribute('secret_uuid',
                                       self,
                                       parent_xpath='/',
                                       tag_name='secret',
                                       attribute='uuid')
                accessors.XMLAttribute('secret_usage',
                                       self,
                                       parent_xpath='/',
                                       tag_name='secret',
                                       attribute='usage')
                super(self.__class__,
                      self).__init__(virsh_instance=virsh_instance)
                self.xml = "<auth/>"

        class Initiator(base.base.LibvirtXMLBase):

            __slots__ = ('iqn_id', )

            def __init__(self, virsh_instance=base.base.virsh, auth_user=""):
                accessors.XMLAttribute('iqn_id',
                                       self,
                                       parent_xpath='/',
                                       tag_name='iqn',
                                       attribute='name')
                super(self.__class__,
                      self).__init__(virsh_instance=virsh_instance)
                self.xml = "<initiator/>"
Example #31
0
 def test_serial_class(self):
     Serial = librarian.get('serial')
     self.assertTrue(issubclass(Serial, devices_base.UntypedDeviceBase))
     self.assertTrue(issubclass(Serial, devices_base.TypedDeviceBase))
Example #32
0
class Interface(base.TypedDeviceBase):

    __slots__ = ('source', 'hostdev_address', 'managed', 'mac_address',
                 'bandwidth', 'model', 'coalesce', 'link_state', 'target',
                 'driver', 'address', 'boot', 'rom', 'mtu', 'filterref',
                 'backend', 'virtualport_type', 'alias')

    def __init__(self, type_name, virsh_instance=base.base.virsh):
        super(Interface, self).__init__(device_tag='interface',
                                        type_name=type_name,
                                        virsh_instance=virsh_instance)
        accessors.XMLElementDict(property_name="source",
                                 libvirtxml=self,
                                 forbidden=None,
                                 parent_xpath='/',
                                 tag_name='source')
        accessors.XMLElementNest('hostdev_address',
                                 self,
                                 parent_xpath='/source',
                                 tag_name='address',
                                 subclass=self.Address,
                                 subclass_dargs={
                                     'type_name': 'pci',
                                     'virsh_instance': virsh_instance
                                 })
        accessors.XMLAttribute(property_name="managed",
                               libvirtxml=self,
                               forbidden=None,
                               parent_xpath='/',
                               tag_name='interface',
                               attribute='managed')
        accessors.XMLElementDict(property_name="target",
                                 libvirtxml=self,
                                 forbidden=None,
                                 parent_xpath='/',
                                 tag_name='target')
        accessors.XMLElementDict(property_name="backend",
                                 libvirtxml=self,
                                 forbidden=None,
                                 parent_xpath='/',
                                 tag_name='backend')
        accessors.XMLAttribute(property_name="mac_address",
                               libvirtxml=self,
                               forbidden=None,
                               parent_xpath='/',
                               tag_name='mac',
                               attribute='address')
        accessors.XMLAttribute(property_name="link_state",
                               libvirtxml=self,
                               forbidden=None,
                               parent_xpath='/',
                               tag_name='link',
                               attribute='state')
        accessors.XMLAttribute(property_name="boot",
                               libvirtxml=self,
                               forbidden=None,
                               parent_xpath='/',
                               tag_name='boot',
                               attribute='order')
        accessors.XMLElementNest(
            "bandwidth",
            self,
            parent_xpath='/',
            tag_name='bandwidth',
            subclass=self.Bandwidth,
            subclass_dargs={'virsh_instance': virsh_instance})
        accessors.XMLElementNest(
            "driver",
            self,
            parent_xpath='/',
            tag_name='driver',
            subclass=self.Driver,
            subclass_dargs={'virsh_instance': virsh_instance})
        accessors.XMLElementNest(
            "filterref",
            self,
            parent_xpath='/',
            tag_name='filterref',
            subclass=Filterref,
            subclass_dargs={'virsh_instance': virsh_instance})
        accessors.XMLAttribute(property_name="model",
                               libvirtxml=self,
                               forbidden=None,
                               parent_xpath='/',
                               tag_name='model',
                               attribute='type')
        accessors.XMLElementDict(property_name="coalesce",
                                 libvirtxml=self,
                                 forbidden=None,
                                 parent_xpath='/coalesce/rx',
                                 tag_name='frames')
        accessors.XMLElementDict(property_name="rom",
                                 libvirtxml=self,
                                 forbidden=None,
                                 parent_xpath='/',
                                 tag_name='rom')
        accessors.XMLElementDict(property_name="mtu",
                                 libvirtxml=self,
                                 forbidden=None,
                                 parent_xpath='/',
                                 tag_name='mtu')
        accessors.XMLElementNest('address',
                                 self,
                                 parent_xpath='/',
                                 tag_name='address',
                                 subclass=self.Address,
                                 subclass_dargs={
                                     'type_name': 'pci',
                                     'virsh_instance': virsh_instance
                                 })
        accessors.XMLAttribute('virtualport_type',
                               self,
                               parent_xpath='/',
                               tag_name='virtualport',
                               attribute='type')
        accessors.XMLElementDict('alias',
                                 self,
                                 parent_xpath='/',
                                 tag_name='alias')

    # For convenience
    Address = librarian.get('address')

    def new_bandwidth(self, **dargs):
        """
        Return a new interafce banwidth instance from dargs
        """
        new_one = self.Bandwidth(virsh_instance=self.virsh)
        for key, value in list(dargs.items()):
            setattr(new_one, key, value)
        return new_one

    def new_driver(self, **dargs):
        """
        Return a new interafce driver instance from dargs
        """
        new_one = self.Driver(virsh_instance=self.virsh)
        for key, value in list(dargs.items()):
            setattr(new_one, key, value)
        return new_one

    def new_iface_address(self, **dargs):
        """
        Return a new interface Address instance and set properties from dargs
        """
        new_one = self.Address("pci", virsh_instance=self.virsh)
        for key, value in list(dargs.items()):
            setattr(new_one, key, value)
        return new_one

    def new_filterref(self, **dargs):
        """
        Return a new interafce filterref instance from dargs
        """
        new_one = Filterref(virsh_instance=self.virsh)
        for key, value in list(dargs.items()):
            setattr(new_one, key, value)
        return new_one

    class Bandwidth(base.base.LibvirtXMLBase):
        """
        Interface bandwidth xml class.

        Properties:

        inbound:
            dict. Keys: average, peak, floor, burst
        outbound:
            dict. Keys: average, peak, floor, burst
        """
        __slots__ = ("inbound", "outbound")

        def __init__(self, virsh_instance=base.base.virsh):
            accessors.XMLElementDict("inbound",
                                     self,
                                     parent_xpath="/",
                                     tag_name="inbound")
            accessors.XMLElementDict("outbound",
                                     self,
                                     parent_xpath="/",
                                     tag_name="outbound")
            super(self.__class__, self).__init__(virsh_instance=virsh_instance)
            self.xml = '<bandwidth/>'

    class Driver(base.base.LibvirtXMLBase):
        """
        Interface Driver xml class.

        Properties:

        driver:
            dict.
        host:
            dict. Keys: csum, gso, tso4, tso6, ecn, ufo
        guest:
            dict. Keys: csum, gso, tso4, tso6, ecn, ufo
        """
        __slots__ = ("driver_attr", "driver_host", "driver_guest")

        def __init__(self, virsh_instance=base.base.virsh):
            accessors.XMLElementDict("driver_attr",
                                     self,
                                     parent_xpath="/",
                                     tag_name="driver")
            accessors.XMLElementDict("driver_host",
                                     self,
                                     parent_xpath="/",
                                     tag_name="host")
            accessors.XMLElementDict("driver_guest",
                                     self,
                                     parent_xpath="/",
                                     tag_name="guest")
            super(self.__class__, self).__init__(virsh_instance=virsh_instance)
            self.xml = '<driver/>'
Example #33
0
class Rng(base.UntypedDeviceBase):

    __slots__ = ('rng_model', 'rate', 'backend', 'alias', 'address')

    def __init__(self, virsh_instance=base.base.virsh):
        accessors.XMLAttribute('rng_model', self,
                               parent_xpath='/',
                               tag_name='rng',
                               attribute='model')
        accessors.XMLElementDict('rate', self,
                                 parent_xpath='/',
                                 tag_name='rate')
        accessors.XMLElementNest('backend', self, parent_xpath='/',
                                 tag_name='backend', subclass=self.Backend,
                                 subclass_dargs={
                                     'virsh_instance': virsh_instance})
        accessors.XMLElementNest('address', self, parent_xpath='/',
                                 tag_name='address', subclass=self.Address,
                                 subclass_dargs={'type_name': 'pci',
                                                 'virsh_instance': virsh_instance})
        accessors.XMLElementDict('alias', self, parent_xpath='/',
                                 tag_name='alias')
        super(Rng, self).__init__(
            device_tag='rng', virsh_instance=virsh_instance)
        self.xml = '<rng/>'

    Address = librarian.get('address')

    def new_rng_address(self, **dargs):
        """
        Return a new interface Address instance and set properties from dargs
        """
        new_one = self.Address("pci", virsh_instance=self.virsh)
        for key, value in list(dargs.items()):
            setattr(new_one, key, value)
        return new_one

    class Backend(base.base.LibvirtXMLBase):

        """
        Rng backend xml class.

        Properties:

        model:
            string. backend model
        type:
            string. backend type
        """
        __slots__ = ('backend_model', 'backend_type', 'backend_dev',
                     'source', 'backend_protocol')

        def __init__(self, virsh_instance=base.base.virsh):
            accessors.XMLAttribute(property_name="backend_model",
                                   libvirtxml=self,
                                   forbidden=None,
                                   parent_xpath='/',
                                   tag_name='backend',
                                   attribute='model')
            accessors.XMLAttribute(property_name="backend_type",
                                   libvirtxml=self,
                                   forbidden=None,
                                   parent_xpath='/',
                                   tag_name='backend',
                                   attribute='type')
            accessors.XMLElementText('backend_dev',
                                     self, parent_xpath='/',
                                     tag_name='backend')

            accessors.XMLElementList(property_name='source',
                                     libvirtxml=self,
                                     parent_xpath='/',
                                     marshal_from=self.marshal_from_source,
                                     marshal_to=self.marshal_to_source)
            accessors.XMLAttribute(property_name="backend_protocol",
                                   libvirtxml=self,
                                   forbidden=None,
                                   parent_xpath='/',
                                   tag_name='protocol',
                                   attribute='type')
            super(self.__class__, self).__init__(virsh_instance=virsh_instance)
            self.xml = '<backend/>'

        @staticmethod
        def marshal_from_source(item, index, libvirtxml):
            """Convert a dictionary into a tag + attributes"""
            del index           # not used
            del libvirtxml      # not used
            if not isinstance(item, dict):
                raise xcepts.LibvirtXMLError("Expected a dictionary of host "
                                             "attributes, not a %s"
                                             % str(item))
            return ('source', dict(item))  # return copy of dict, not reference

        @staticmethod
        def marshal_to_source(tag, attr_dict, index, libvirtxml):
            """Convert a tag + attributes into a dictionary"""
            del index                    # not used
            del libvirtxml               # not used
            if tag != 'source':
                return None              # skip this one
            return dict(attr_dict)       # return copy of dict, not reference
Example #34
0
class Disk(base.TypedDeviceBase):
    """
    Disk device XML class

    Properties:
        device:
            string, how exposted to guest
        rawio:
            string (yes/no), disk needs rawio capability
        sgio:
            string, "filtered" or "unfiltered"
        snapshot:
            string, "yes", "no", "internal" or "external"
        wwn:
            string.
        serial:
            string.
        vendor:
            string.
        product:
            string.
        driver:
            dict, keys: name, type, cache, error_policy, io, ioeventfd,
            event_idx, copy_on_read, discard
        target:
            dict, keys: dev, bus, tray
        blockio:
            dict, keys: logical_block_size, physical_block_size
        geometry:
            dict, keys: cyls, heads, secs, trans
        address:
            libvirt_xml.devices.Address instance
        boot:
            string, boot order number to use if not using boot in os element
        readonly:
            bool, True/False
        transient:
            bool, True/False
        share:
            bool, True/False
        mirror:
            bool, read-only, True if block copy started
        ready:
            bool, read-only, True if disk ready for pivot
        iotune:
            libvirt_xml.devices.Disk.IOTune instance
        source:
            libvirt_xml.devices.Disk.DiskSource instance
        encryption:
            libvirt_xml.devices.Disk.Encryption instance.
    """

    __slots__ = ('device', 'rawio', 'sgio', 'snapshot', 'driver', 'target',
                 'address', 'boot', 'readonly', 'transient', 'share', 'mirror',
                 'ready', 'iotune', 'source', 'blockio', 'geometry', 'wwn',
                 'serial', 'vendor', 'product', 'encryption', 'auth')

    def __init__(self, type_name='file', virsh_instance=base.base.virsh):
        accessors.XMLAttribute('device',
                               self,
                               parent_xpath='/',
                               tag_name='disk',
                               attribute='device')
        accessors.XMLAttribute('rawio',
                               self,
                               parent_xpath='/',
                               tag_name='disk',
                               attribute='rawio')
        accessors.XMLAttribute('sgio',
                               self,
                               parent_xpath='/',
                               tag_name='disk',
                               attribute='sgio')
        accessors.XMLAttribute('snapshot',
                               self,
                               parent_xpath='/',
                               tag_name='disk',
                               attribute='snapshot')
        accessors.XMLElementText('wwn', self, parent_xpath='/', tag_name='wwn')
        accessors.XMLElementText('serial',
                                 self,
                                 parent_xpath='/',
                                 tag_name='serial')
        accessors.XMLElementText('vendor',
                                 self,
                                 parent_xpath='/',
                                 tag_name='vendor')
        accessors.XMLElementText('product',
                                 self,
                                 parent_xpath='/',
                                 tag_name='product')
        accessors.XMLElementDict('driver',
                                 self,
                                 parent_xpath='/',
                                 tag_name='driver')
        accessors.XMLElementDict('target',
                                 self,
                                 parent_xpath='/',
                                 tag_name='target')
        accessors.XMLElementDict('blockio',
                                 self,
                                 parent_xpath='/',
                                 tag_name='blockio')
        accessors.XMLElementDict('geometry',
                                 self,
                                 parent_xpath='/',
                                 tag_name='geometry')
        accessors.XMLElementNest('address',
                                 self,
                                 parent_xpath='/',
                                 tag_name='address',
                                 subclass=self.Address,
                                 subclass_dargs={
                                     'type_name': 'drive',
                                     'virsh_instance': virsh_instance
                                 })
        accessors.XMLAttribute('boot',
                               self,
                               parent_xpath='/',
                               tag_name='boot',
                               attribute='order')
        accessors.XMLElementBool('readonly',
                                 self,
                                 parent_xpath='/',
                                 tag_name='readonly')
        accessors.XMLElementBool('transient',
                                 self,
                                 parent_xpath='/',
                                 tag_name='transient')
        accessors.XMLElementBool('share',
                                 self,
                                 parent_xpath='/',
                                 tag_name='shareable')
        accessors.XMLElementNest(
            'source',
            self,
            parent_xpath='/',
            tag_name='source',
            subclass=self.DiskSource,
            subclass_dargs={'virsh_instance': virsh_instance})
        ro = ['set', 'del']
        accessors.XMLElementBool('mirror',
                                 self,
                                 forbidden=ro,
                                 parent_xpath='/',
                                 tag_name='mirror')
        accessors.XMLElementBool('ready',
                                 self,
                                 forbidden=ro,
                                 parent_xpath='/',
                                 tag_name='ready')
        accessors.XMLElementNest(
            'iotune',
            self,
            parent_xpath='/',
            tag_name='iotune',
            subclass=self.IOTune,
            subclass_dargs={'virsh_instance': virsh_instance})
        accessors.XMLElementNest(
            'encryption',
            self,
            parent_xpath='/',
            tag_name='encryption',
            subclass=self.Encryption,
            subclass_dargs={'virsh_instance': virsh_instance})
        accessors.XMLElementNest(
            'auth',
            self,
            parent_xpath='/',
            tag_name='auth',
            subclass=self.Auth,
            subclass_dargs={'virsh_instance': virsh_instance})
        super(Disk, self).__init__(device_tag='disk',
                                   type_name=type_name,
                                   virsh_instance=virsh_instance)

    def new_disk_source(self, **dargs):
        """
        Return a new disk source instance and set properties from dargs
        """
        new_one = self.DiskSource(virsh_instance=self.virsh)
        for key, value in dargs.items():
            setattr(new_one, key, value)
        return new_one

    def new_iotune(self, **dargs):
        """
        Return a new disk IOTune instance and set properties from dargs
        """
        new_one = self.IOTune(virsh_instance=self.virsh)
        for key, value in dargs.items():
            setattr(new_one, key, value)
        return new_one

    def new_encryption(self, **dargs):
        """
        Return a new disk encryption instance and set properties from dargs
        """
        new_one = self.Encryption(virsh_instance=self.virsh)
        for key, value in dargs.items():
            setattr(new_one, key, value)
        return new_one

    def new_disk_address(self, type_name='drive', **dargs):
        """
        Return a new disk Address instance and set properties from dargs
        """
        new_one = self.Address(type_name=type_name, virsh_instance=self.virsh)
        for key, value in dargs.items():
            setattr(new_one, key, value)
        return new_one

    def new_auth(self, **dargs):
        """
        Return a new disk auth instance and set properties from dargs
        """
        new_one = self.Auth(virsh_instance=self.virsh)
        for key, value in dargs.items():
            setattr(new_one, key, value)
        return new_one

    # For convenience
    Address = librarian.get('address')

    class DiskSource(base.base.LibvirtXMLBase):
        """
        Disk source device XML class

        Properties:

        attrs: Dictionary of attributes, qualifying the disk type
        seclabels: list of libvirt_xml.devices.seclabel.Seclabel instances
        hosts: list of dictionaries describing network host properties
        """

        __slots__ = (
            'attrs',
            'seclabels',
            'hosts',
            'encryption',
            'auth',
            'config_file',
            'snapshot_name',
        )

        def __init__(self, virsh_instance=base.base.virsh):
            accessors.XMLElementDict('attrs',
                                     self,
                                     parent_xpath='/',
                                     tag_name='source')
            accessors.XMLElementList('seclabels',
                                     self,
                                     parent_xpath='/',
                                     marshal_from=self.marshal_from_seclabel,
                                     marshal_to=self.marshal_to_seclabel)
            accessors.XMLElementList('hosts',
                                     self,
                                     parent_xpath='/',
                                     marshal_from=self.marshal_from_host,
                                     marshal_to=self.marshal_to_host)
            accessors.XMLElementNest(
                'encryption',
                self,
                parent_xpath='/',
                tag_name='encryption',
                subclass=Disk.Encryption,
                subclass_dargs={'virsh_instance': virsh_instance})
            accessors.XMLElementNest(
                'auth',
                self,
                parent_xpath='/',
                tag_name='auth',
                subclass=Disk.Auth,
                subclass_dargs={'virsh_instance': virsh_instance})
            accessors.XMLAttribute('config_file',
                                   self,
                                   parent_xpath='/',
                                   tag_name='config',
                                   attribute='file')
            accessors.XMLAttribute('snapshot_name',
                                   self,
                                   parent_xpath='/',
                                   tag_name='snapshot',
                                   attribute='name')
            super(self.__class__, self).__init__(virsh_instance=virsh_instance)
            self.xml = '<source/>'

        @staticmethod
        def marshal_from_seclabel(item, index, libvirtxml):
            """Convert a Seclabel instance into tag + attributes"""
            del index  # not used
            del libvirtxml  # not used
            root = item.xmltreefile.getroot()
            if root.tag == 'seclabel':
                new_dict = dict(root.items())
                text_dict = {}
                # Put element text into dict under key 'text'
                for key in ('label', 'baselabel'):
                    text_val = item.xmltreefile.findtext(key)
                    if text_val:
                        text_dict.update({key: text_val})
                if text_dict:
                    new_dict['text'] = text_dict
                return (root.tag, new_dict)
            else:
                raise xcepts.LibvirtXMLError("Expected a list of seclabel "
                                             "instances, not a %s" % str(item))

        @staticmethod
        def marshal_to_seclabel(tag, attr_dict, index, libvirtxml):
            """Convert a tag + attributes into a Seclabel instance"""
            del index  # not used
            if tag != 'seclabel':
                return None  # Don't convert this item
            Seclabel = librarian.get('seclabel')
            newone = Seclabel(virsh_instance=libvirtxml.virsh)
            newone.update(attr_dict)
            return newone

        @staticmethod
        def marshal_from_host(item, index, libvirtxml):
            """Convert a dictionary into a tag + attributes"""
            del index  # not used
            del libvirtxml  # not used
            if not isinstance(item, dict):
                raise xcepts.LibvirtXMLError("Expected a dictionary of host "
                                             "attributes, not a %s" %
                                             str(item))
            return ('host', dict(item))  # return copy of dict, not reference

        @staticmethod
        def marshal_to_host(tag, attr_dict, index, libvirtxml):
            """Convert a tag + attributes into a dictionary"""
            del index  # not used
            del libvirtxml  # not used
            if tag != 'host':
                return None  # skip this one
            return dict(attr_dict)  # return copy of dict, not reference

    class IOTune(base.base.LibvirtXMLBase):
        """
        IOTune device XML class

        Properties:

        total_bytes_sec: str(int)
        read_bytes_sec: str(int)
        write_bytes_sec: str(int)
        total_iops_sec: str(int)
        read_iops_sec: str(int)
        write_iops_sec: str(int)
        """

        __slots__ = ('total_bytes_sec', 'read_bytes_sec', 'write_bytes_sec',
                     'total_iops_sec', 'read_iops_sec', 'write_iops_sec')

        def __init__(self, virsh_instance=base.base.virsh):
            for slot in self.__all_slots__:
                if slot in base.base.LibvirtXMLBase.__all_slots__:
                    continue  # don't add these
                else:
                    accessors.XMLElementInt(slot,
                                            self,
                                            parent_xpath='/',
                                            tag_name=slot)
            super(self.__class__, self).__init__(virsh_instance=virsh_instance)
            self.xml = '<iotune/>'

    class Encryption(base.base.LibvirtXMLBase):
        """
        Encryption device XML class

        Properties:

        encryption:
            string.
        secret:
            dict, keys: type, uuid
        """

        __slots__ = ('encryption', 'secret')

        def __init__(self, virsh_instance=base.base.virsh):
            accessors.XMLAttribute('encryption',
                                   self,
                                   parent_xpath='/',
                                   tag_name='encryption',
                                   attribute='format')
            accessors.XMLElementDict('secret',
                                     self,
                                     parent_xpath='/',
                                     tag_name='secret')
            super(self.__class__, self).__init__(virsh_instance=virsh_instance)
            self.xml = '<encryption/>'

    class Auth(base.base.LibvirtXMLBase):
        """
        Auth device XML class

        Properties:

        auth_user:
            string, attribute of auth tag
        secret_type:
            string, attribute of secret tag, sub-tag of the auth tag
        secret_uuid:
            string, attribute of secret tag, sub-tag of the auth tag
        secret_usage:
            string, attribute of secret tag, sub-tag of the auth tag
        """

        __slots__ = ('auth_user', 'secret_type', 'secret_uuid', 'secret_usage')

        def __init__(self, virsh_instance=base.base.virsh, auth_user=""):
            accessors.XMLAttribute('auth_user',
                                   self,
                                   parent_xpath='/',
                                   tag_name='auth',
                                   attribute='username')
            accessors.XMLAttribute('secret_type',
                                   self,
                                   parent_xpath='/',
                                   tag_name='secret',
                                   attribute='type')
            accessors.XMLAttribute('secret_uuid',
                                   self,
                                   parent_xpath='/',
                                   tag_name='secret',
                                   attribute='uuid')
            accessors.XMLAttribute('secret_usage',
                                   self,
                                   parent_xpath='/',
                                   tag_name='secret',
                                   attribute='usage')
            super(self.__class__, self).__init__(virsh_instance=virsh_instance)
            self.xml = u"<auth/>"
Example #35
0
 def get_device_class(type_name):
     """
     Return class that handles type_name devices, or raise exception.
     """
     return librarian.get(type_name)
Example #36
0
class Interface(base.TypedDeviceBase):

    __slots__ = ('source', 'hostdev_address', 'managed', 'mac_address',
                 'bandwidth', 'model', 'coalesce', 'link_state', 'target',
                 'driver', 'address', 'boot', 'rom', 'mtu', 'filterref',
                 'backend', 'virtualport_type', 'alias', "ips")

    def __init__(self, type_name, virsh_instance=base.base.virsh):
        super(Interface, self).__init__(device_tag='interface',
                                        type_name=type_name,
                                        virsh_instance=virsh_instance)
        accessors.XMLElementDict(property_name="source",
                                 libvirtxml=self,
                                 forbidden=None,
                                 parent_xpath='/',
                                 tag_name='source')
        accessors.XMLElementNest('hostdev_address',
                                 self,
                                 parent_xpath='/source',
                                 tag_name='address',
                                 subclass=self.Address,
                                 subclass_dargs={
                                     'type_name': 'pci',
                                     'virsh_instance': virsh_instance
                                 })
        accessors.XMLAttribute(property_name="managed",
                               libvirtxml=self,
                               forbidden=None,
                               parent_xpath='/',
                               tag_name='interface',
                               attribute='managed')
        accessors.XMLElementDict(property_name="target",
                                 libvirtxml=self,
                                 forbidden=None,
                                 parent_xpath='/',
                                 tag_name='target')
        accessors.XMLElementDict(property_name="backend",
                                 libvirtxml=self,
                                 forbidden=None,
                                 parent_xpath='/',
                                 tag_name='backend')
        accessors.XMLAttribute(property_name="mac_address",
                               libvirtxml=self,
                               forbidden=None,
                               parent_xpath='/',
                               tag_name='mac',
                               attribute='address')
        accessors.XMLAttribute(property_name="link_state",
                               libvirtxml=self,
                               forbidden=None,
                               parent_xpath='/',
                               tag_name='link',
                               attribute='state')
        accessors.XMLAttribute(property_name="boot",
                               libvirtxml=self,
                               forbidden=None,
                               parent_xpath='/',
                               tag_name='boot',
                               attribute='order')
        accessors.XMLElementNest(
            "bandwidth",
            self,
            parent_xpath='/',
            tag_name='bandwidth',
            subclass=self.Bandwidth,
            subclass_dargs={'virsh_instance': virsh_instance})
        accessors.XMLElementNest(
            "driver",
            self,
            parent_xpath='/',
            tag_name='driver',
            subclass=self.Driver,
            subclass_dargs={'virsh_instance': virsh_instance})
        accessors.XMLElementNest(
            "filterref",
            self,
            parent_xpath='/',
            tag_name='filterref',
            subclass=self.Filterref,
            subclass_dargs={'virsh_instance': virsh_instance})
        accessors.XMLAttribute(property_name="model",
                               libvirtxml=self,
                               forbidden=None,
                               parent_xpath='/',
                               tag_name='model',
                               attribute='type')
        accessors.XMLElementDict(property_name="coalesce",
                                 libvirtxml=self,
                                 forbidden=None,
                                 parent_xpath='/coalesce/rx',
                                 tag_name='frames')
        accessors.XMLElementDict(property_name="rom",
                                 libvirtxml=self,
                                 forbidden=None,
                                 parent_xpath='/',
                                 tag_name='rom')
        accessors.XMLElementDict(property_name="mtu",
                                 libvirtxml=self,
                                 forbidden=None,
                                 parent_xpath='/',
                                 tag_name='mtu')
        accessors.XMLElementNest('address',
                                 self,
                                 parent_xpath='/',
                                 tag_name='address',
                                 subclass=self.Address,
                                 subclass_dargs={
                                     'type_name': 'pci',
                                     'virsh_instance': virsh_instance
                                 })
        accessors.XMLAttribute('virtualport_type',
                               self,
                               parent_xpath='/',
                               tag_name='virtualport',
                               attribute='type')
        accessors.XMLElementDict('alias',
                                 self,
                                 parent_xpath='/',
                                 tag_name='alias')
        accessors.XMLElementList(property_name='ips',
                                 libvirtxml=self,
                                 forbidden=None,
                                 parent_xpath='/',
                                 marshal_from=self.marshal_from_ips,
                                 marshal_to=self.marshal_to_ips)

    # For convenience
    Address = librarian.get('address')

    Filterref = librarian.get('filterref')

    @staticmethod
    def marshal_from_ips(item, index, libvirtxml):
        """Convert an Address instance into tag + attributes"""
        """Convert a dictionary into a tag + attributes"""
        del index  # not used
        del libvirtxml  # not used
        if not isinstance(item, dict):
            raise xcepts.LibvirtXMLError("Expected a dictionary of ip"
                                         "attributes, not a %s" % str(item))
        return ('ip', dict(item))  # return copy of dict, not reference

    @staticmethod
    def marshal_to_ips(tag, attr_dict, index, libvirtxml):
        """Convert a tag + attributes into an Address instance """
        del index  # not used
        del libvirtxml  # not used
        if not tag == 'ip':
            return None  # skip this one
        return dict(attr_dict)  # return copy of dict, not reference

    def new_bandwidth(self, **dargs):
        """
        Return a new interafce banwidth instance from dargs
        """
        new_one = self.Bandwidth(virsh_instance=self.virsh)
        for key, value in list(dargs.items()):
            setattr(new_one, key, value)
        return new_one

    def new_driver(self, **dargs):
        """
        Return a new interafce driver instance from dargs
        """
        new_one = self.Driver(virsh_instance=self.virsh)
        for key, value in list(dargs.items()):
            setattr(new_one, key, value)
        return new_one

    def new_iface_address(self, **dargs):
        """
        Return a new interface Address instance and set properties from dargs
        """
        new_one = self.Address("pci", virsh_instance=self.virsh)
        for key, value in list(dargs.items()):
            setattr(new_one, key, value)
        return new_one

    def new_filterref(self, **dargs):
        """
        Return a new interafce filterref instance from dargs
        """
        new_one = self.Filterref(virsh_instance=self.virsh)
        for key, value in list(dargs.items()):
            setattr(new_one, key, value)
        return new_one

    class Bandwidth(base.base.LibvirtXMLBase):
        """
        Interface bandwidth xml class.

        Properties:

        inbound:
            dict. Keys: average, peak, floor, burst
        outbound:
            dict. Keys: average, peak, floor, burst
        """
        __slots__ = ("inbound", "outbound")

        def __init__(self, virsh_instance=base.base.virsh):
            accessors.XMLElementDict("inbound",
                                     self,
                                     parent_xpath="/",
                                     tag_name="inbound")
            accessors.XMLElementDict("outbound",
                                     self,
                                     parent_xpath="/",
                                     tag_name="outbound")
            super(self.__class__, self).__init__(virsh_instance=virsh_instance)
            self.xml = '<bandwidth/>'

    class Driver(base.base.LibvirtXMLBase):
        """
        Interface Driver xml class.

        Properties:

        driver:
            dict.
        host:
            dict. Keys: csum, gso, tso4, tso6, ecn, ufo
        guest:
            dict. Keys: csum, gso, tso4, tso6, ecn, ufo
        """
        __slots__ = ("driver_attr", "driver_host", "driver_guest")

        def __init__(self, virsh_instance=base.base.virsh):
            accessors.XMLElementDict("driver_attr",
                                     self,
                                     parent_xpath="/",
                                     tag_name="driver")
            accessors.XMLElementDict("driver_host",
                                     self,
                                     parent_xpath="/",
                                     tag_name="host")
            accessors.XMLElementDict("driver_guest",
                                     self,
                                     parent_xpath="/",
                                     tag_name="guest")
            super(self.__class__, self).__init__(virsh_instance=virsh_instance)
            self.xml = '<driver/>'
Example #37
0
class Disk(base.TypedDeviceBase):

    """
    Disk device XML class

    Properties:
        device:
            string, how exposted to guest
        rawio:
            string (yes/no), disk needs rawio capability
        sgio:
            string, "filtered" or "unfiltered"
        snapshot:
            string, "yes", "no", "internal" or "external"
        wwn:
            string.
        serial:
            string.
        vendor:
            string.
        product:
            string.
        driver:
            dict, keys: name, type, cache, error_policy, io, ioeventfd,
            event_idx, copy_on_read, discard
        target:
            dict, keys: dev, bus, tray
        alias:
            dict, keys: name
        blockio:
            dict, keys: logical_block_size, physical_block_size
        geometry:
            dict, keys: cyls, heads, secs, trans
        address:
            libvirt_xml.devices.Address instance
        boot:
            string, boot order number to use if not using boot in os element
        loadparm:
            string, loadparm attribute on disk's boot element
        readonly:
            bool, True/False
        transient:
            bool, True/False
        share:
            bool, True/False
        mirror:
            bool, read-only, True if block copy started
        ready:
            bool, read-only, True if disk ready for pivot
        iotune:
            libvirt_xml.devices.Disk.IOTune instance
        source:
            libvirt_xml.devices.Disk.DiskSource instance
        encryption:
            libvirt_xml.devices.Disk.Encryption instance.
        auth:
            libvirt_xml.devices.Disk.Auth instance.
        reservations:
            libvirt_xml.devices.Disk.Reservations instance.
        drivermetadata:
            libvirt_xml.devices.Disk.DriverMetadata instance.
   """

    __slots__ = ('device', 'rawio', 'sgio', 'snapshot', 'driver', 'target', 'alias',
                 'address', 'boot', 'loadparm', 'readonly', 'transient', 'share', 'model',
                 'mirror', 'ready', 'iotune', 'source', 'blockio', 'geometry',
                 'wwn', 'serial', 'vendor', 'product', 'encryption', 'auth',
                 'reservations', 'backingstore', 'drivermetadata')

    def __init__(self, type_name='file', virsh_instance=base.base.virsh):
        accessors.XMLAttribute('device', self, parent_xpath='/',
                               tag_name='disk', attribute='device')
        accessors.XMLAttribute('model', self, parent_xpath='/',
                               tag_name='disk', attribute='model')
        accessors.XMLAttribute('rawio', self, parent_xpath='/',
                               tag_name='disk', attribute='rawio')
        accessors.XMLAttribute('sgio', self, parent_xpath='/',
                               tag_name='disk', attribute='sgio')
        accessors.XMLAttribute('snapshot', self, parent_xpath='/',
                               tag_name='disk', attribute='snapshot')
        accessors.XMLElementText('wwn', self, parent_xpath='/',
                                 tag_name='wwn')
        accessors.XMLElementText('serial', self, parent_xpath='/',
                                 tag_name='serial')
        accessors.XMLElementText('vendor', self, parent_xpath='/',
                                 tag_name='vendor')
        accessors.XMLElementText('product', self, parent_xpath='/',
                                 tag_name='product')
        accessors.XMLElementDict('driver', self, parent_xpath='/',
                                 tag_name='driver')
        accessors.XMLElementDict('target', self, parent_xpath='/',
                                 tag_name='target')
        accessors.XMLElementDict('alias', self, parent_xpath='/',
                                 tag_name='alias')
        accessors.XMLElementDict('blockio', self, parent_xpath='/',
                                 tag_name='blockio')
        accessors.XMLElementDict('geometry', self, parent_xpath='/',
                                 tag_name='geometry')
        accessors.XMLElementNest('address', self, parent_xpath='/',
                                 tag_name='address', subclass=self.Address,
                                 subclass_dargs={'type_name': 'drive',
                                                 'virsh_instance': virsh_instance})
        accessors.XMLAttribute('boot', self, parent_xpath='/',
                               tag_name='boot', attribute='order')
        accessors.XMLAttribute('loadparm', self, parent_xpath='/',
                               tag_name='boot', attribute='loadparm')
        accessors.XMLElementBool('readonly', self, parent_xpath='/',
                                 tag_name='readonly')
        accessors.XMLElementBool('transient', self, parent_xpath='/',
                                 tag_name='transient')
        accessors.XMLElementBool('share', self, parent_xpath='/',
                                 tag_name='shareable')
        accessors.XMLElementNest('source', self, parent_xpath='/',
                                 tag_name='source', subclass=self.DiskSource,
                                 subclass_dargs={
                                     'virsh_instance': virsh_instance})
        ro = ['set', 'del']
        accessors.XMLElementBool('mirror', self, forbidden=ro,
                                 parent_xpath='/', tag_name='mirror')
        accessors.XMLElementBool('ready', self, forbidden=ro,
                                 parent_xpath='/', tag_name='ready')
        accessors.XMLElementNest('iotune', self, parent_xpath='/',
                                 tag_name='iotune', subclass=self.IOTune,
                                 subclass_dargs={
                                     'virsh_instance': virsh_instance})
        accessors.XMLElementNest('encryption', self, parent_xpath='/',
                                 tag_name='encryption', subclass=self.Encryption,
                                 subclass_dargs={
                                     'virsh_instance': virsh_instance})
        accessors.XMLElementNest('auth', self, parent_xpath='/',
                                 tag_name='auth', subclass=self.Auth,
                                 subclass_dargs={
                                     'virsh_instance': virsh_instance})
        accessors.XMLElementNest('reservations', self, parent_xpath='/',
                                 tag_name='reservations',
                                 subclass=Disk.Reservations,
                                 subclass_dargs={
                                     'virsh_instance': virsh_instance})
        accessors.XMLElementNest('backingstore', self, parent_xpath='/',
                                 tag_name='backingStore',
                                 subclass=self.BackingStore,
                                 subclass_dargs={
                                     'virsh_instance': virsh_instance})
        accessors.XMLElementNest('drivermetadata', self, parent_xpath='/',
                                 tag_name='driver',
                                 subclass=self.DriverMetadata,
                                 subclass_dargs={
                                     'virsh_instance': virsh_instance})
        super(Disk, self).__init__(device_tag='disk', type_name=type_name,
                                   virsh_instance=virsh_instance)

    def new_disk_source(self, **dargs):
        """
        Return a new disk source instance and set properties from dargs
        """
        new_one = self.DiskSource(virsh_instance=self.virsh)
        for key, value in list(dargs.items()):
            setattr(new_one, key, value)
        return new_one

    def new_iotune(self, **dargs):
        """
        Return a new disk IOTune instance and set properties from dargs
        """
        new_one = self.IOTune(virsh_instance=self.virsh)
        for key, value in list(dargs.items()):
            setattr(new_one, key, value)
        return new_one

    def new_encryption(self, **dargs):
        """
        Return a new disk encryption instance and set properties from dargs
        """
        new_one = self.Encryption(virsh_instance=self.virsh)
        for key, value in list(dargs.items()):
            setattr(new_one, key, value)
        return new_one

    def new_disk_address(self, type_name='drive', **dargs):
        """
        Return a new disk Address instance and set properties from dargs
        """
        new_one = self.Address(type_name=type_name, virsh_instance=self.virsh)
        for key, value in list(dargs.items()):
            setattr(new_one, key, value)
        return new_one

    def new_auth(self, **dargs):
        """
        Return a new disk auth instance and set properties from dargs
        """
        new_one = self.Auth(virsh_instance=self.virsh)
        for key, value in list(dargs.items()):
            setattr(new_one, key, value)
        return new_one

    def new_reservations(self, **dargs):
        """
        Return a new disk reservations instance and set properties from dargs
        """
        new_one = self.Reservations(virsh_instance=self.virsh)
        for key, value in list(dargs.items()):
            setattr(new_one, key, value)
        return new_one

    def new_slices(self, **dargs):
        """
        Return a new disk slices instance and set properties from dargs
        """
        new_one = self.Slices(virsh_instance=self.virsh)
        for key, value in list(dargs.items()):
            setattr(new_one, key, value)
        return new_one

    def new_backingstore(self, **dargs):
        """
        Return a new disk backingstore instance and set properties from dargs
        """
        new_one = self.BackingStore(virsh_instance=self.virsh)
        for key, value in list(dargs.items()):
            setattr(new_one, key, value)
        return new_one

    def get_backingstore_list(self):
        """
        Usage: get source file attribute from backingStore
            test_disk = Disk()
            backingstore_list = test_disk.get_backingstore_list()
            source_file_list = [elem.find('source').get('file') or elem.find('source').get('name') for elem in backingstore_list]

        :return: a disk backingstore list where each element is primitive virttest.element_tree._ElementInterface object
        """
        backingstore_list = []
        for elem in self.xmltreefile.getiterator('backingStore'):
            backingstore_list.append(elem)
        return backingstore_list

    def new_drivermetadata(self, **dargs):
        """
        Return a new DriverMetadata instance and set properties from dargs
        """
        new_one = self.DriverMetadata(virsh_instance=self.virsh)
        for key, value in list(dargs.items()):
            setattr(new_one, key, value)
        return new_one

    def get_all_backingstore(self):
        """
        Get all backingstore of a Disk object

        :return: an ordered list of backingstore items
        """

        def _get_next_backingstore(elem):
            """
            Recursively get backingstore object

            :param elem: root element to get backingstore object
            """
            if elem.xmltreefile.find('/backingStore') is None:
                return
            bs = elem.backingstore
            backingstore_list.append(bs)
            _get_next_backingstore(bs)

        backingstore_list = []
        _get_next_backingstore(self)

        return backingstore_list

    # For convenience
    Address = librarian.get('address')

    class DiskSource(base.base.LibvirtXMLBase):

        """
        Disk source device XML class

        Properties:

        attrs: Dictionary of attributes, qualifying the disk type
        seclabels: list of libvirt_xml.devices.seclabel.Seclabel instances
        hosts: list of dictionaries describing network host properties
        """

        __slots__ = ('attrs', 'seclabels', 'hosts', 'encryption', 'auth',
                     'reservations', 'slices', 'config_file', 'snapshot_name')

        def __init__(self, virsh_instance=base.base.virsh):
            accessors.XMLElementDict('attrs', self, parent_xpath='/',
                                     tag_name='source')
            accessors.XMLElementList('seclabels', self, parent_xpath='/',
                                     marshal_from=self.marshal_from_seclabel,
                                     marshal_to=self.marshal_to_seclabel)
            accessors.XMLElementList('hosts', self, parent_xpath='/',
                                     marshal_from=self.marshal_from_host,
                                     marshal_to=self.marshal_to_host)
            accessors.XMLElementNest('encryption', self, parent_xpath='/',
                                     tag_name='encryption',
                                     subclass=Disk.Encryption,
                                     subclass_dargs={
                                         'virsh_instance': virsh_instance})
            accessors.XMLElementNest('auth', self, parent_xpath='/',
                                     tag_name='auth', subclass=Disk.Auth,
                                     subclass_dargs={
                                         'virsh_instance': virsh_instance})
            accessors.XMLElementNest('reservations', self, parent_xpath='/',
                                     tag_name='reservations',
                                     subclass=Disk.Reservations,
                                     subclass_dargs={
                                         'virsh_instance': virsh_instance})
            accessors.XMLElementNest('slices', self, parent_xpath='/',
                                     tag_name='slices',
                                     subclass=Disk.Slices,
                                     subclass_dargs={
                                         'virsh_instance': virsh_instance})
            accessors.XMLAttribute('config_file', self, parent_xpath='/',
                                   tag_name='config', attribute='file')
            accessors.XMLAttribute('snapshot_name', self, parent_xpath='/',
                                   tag_name='snapshot', attribute='name')
            super(self.__class__, self).__init__(virsh_instance=virsh_instance)
            self.xml = '<source/>'

        @staticmethod
        def marshal_from_seclabel(item, index, libvirtxml):
            """Convert a Seclabel instance into tag + attributes"""
            del index           # not used
            del libvirtxml      # not used
            root = item.xmltreefile.getroot()
            if root.tag == 'seclabel':
                new_dict = dict(list(root.items()))
                text_dict = {}
                # Put element text into dict under key 'text'
                for key in ('label', 'baselabel'):
                    text_val = item.xmltreefile.findtext(key)
                    if text_val:
                        text_dict.update({key: text_val})
                if text_dict:
                    new_dict['text'] = text_dict
                return (root.tag, new_dict)
            else:
                raise xcepts.LibvirtXMLError("Expected a list of seclabel "
                                             "instances, not a %s" % str(item))

        @staticmethod
        def marshal_to_seclabel(tag, attr_dict, index, libvirtxml):
            """Convert a tag + attributes into a Seclabel instance"""
            del index           # not used
            if tag != 'seclabel':
                return None     # Don't convert this item
            Seclabel = librarian.get('seclabel')
            newone = Seclabel(virsh_instance=libvirtxml.virsh)
            newone.update(attr_dict)
            return newone

        @staticmethod
        def marshal_from_host(item, index, libvirtxml):
            """Convert a dictionary into a tag + attributes"""
            del index           # not used
            del libvirtxml      # not used
            if not isinstance(item, dict):
                raise xcepts.LibvirtXMLError("Expected a dictionary of host "
                                             "attributes, not a %s"
                                             % str(item))
            return ('host', dict(item))  # return copy of dict, not reference

        @staticmethod
        def marshal_to_host(tag, attr_dict, index, libvirtxml):
            """Convert a tag + attributes into a dictionary"""
            del index                    # not used
            del libvirtxml               # not used
            if tag != 'host':
                return None              # skip this one
            return dict(attr_dict)       # return copy of dict, not reference

    class IOTune(base.base.LibvirtXMLBase):

        """
        IOTune device XML class

        Properties:

        total_bytes_sec: str(int)
        read_bytes_sec: str(int)
        write_bytes_sec: str(int)
        total_iops_sec: str(int)
        read_iops_sec: str(int)
        write_iops_sec: str(int)
        """

        __slots__ = ('total_bytes_sec', 'read_bytes_sec', 'write_bytes_sec',
                     'total_iops_sec', 'read_iops_sec', 'write_iops_sec')

        def __init__(self, virsh_instance=base.base.virsh):
            # pylint: disable=E1133,E1135
            for slot in self.__all_slots__:
                if slot in base.base.LibvirtXMLBase.__all_slots__:
                    continue    # don't add these
                else:
                    accessors.XMLElementInt(slot, self, parent_xpath='/',
                                            tag_name=slot)
            super(self.__class__, self).__init__(virsh_instance=virsh_instance)
            self.xml = '<iotune/>'

    class Encryption(base.base.LibvirtXMLBase):

        """
        Encryption device XML class

        Properties:

        encryption:
            string.
        secret:
            dict, keys: type, uuid
        """

        __slots__ = ('encryption', 'secret')

        def __init__(self, virsh_instance=base.base.virsh):
            accessors.XMLAttribute('encryption', self, parent_xpath='/',
                                   tag_name='encryption', attribute='format')
            accessors.XMLElementDict('secret', self, parent_xpath='/',
                                     tag_name='secret')
            super(self.__class__, self).__init__(
                virsh_instance=virsh_instance)
            self.xml = '<encryption/>'

    class Auth(base.base.LibvirtXMLBase):

        """
        Auth device XML class

        Properties:

        auth_user:
            string, attribute of auth tag
        secret_type:
            string, attribute of secret tag, sub-tag of the auth tag
        secret_uuid:
            string, attribute of secret tag, sub-tag of the auth tag
        secret_usage:
            string, attribute of secret tag, sub-tag of the auth tag
        """

        __slots__ = ('auth_user', 'secret_type', 'secret_uuid', 'secret_usage')

        def __init__(self, virsh_instance=base.base.virsh, auth_user=""):
            accessors.XMLAttribute('auth_user', self, parent_xpath='/',
                                   tag_name='auth', attribute='username')
            accessors.XMLAttribute('secret_type', self, parent_xpath='/',
                                   tag_name='secret', attribute='type')
            accessors.XMLAttribute('secret_uuid', self, parent_xpath='/',
                                   tag_name='secret', attribute='uuid')
            accessors.XMLAttribute('secret_usage', self, parent_xpath='/',
                                   tag_name='secret', attribute='usage')
            super(self.__class__, self).__init__(virsh_instance=virsh_instance)
            self.xml = '<auth/>'

    class Slices(base.base.LibvirtXMLBase):

        """
        slices device XML class
        Typical xml looks like:
        <slices>
          <slice type='storage' offset='12345' size='123'/>
        </slices>
        Properties:

        slice_type:
            string, type attribute of slice tag
        slice_offset:
            string, offset attribute of slice tag
        slice_size:
            string, size attribute of slice tag
        """

        __slots__ = ('slice_type', 'slice_offset', 'slice_size')

        def __init__(self, virsh_instance=base.base.virsh, auth_user=""):
            accessors.XMLAttribute('slice_type', self, parent_xpath='/',
                                   tag_name='slice', attribute='type')
            accessors.XMLAttribute('slice_offset', self, parent_xpath='/',
                                   tag_name='slice', attribute='offset')
            accessors.XMLAttribute('slice_size', self, parent_xpath='/',
                                   tag_name='slice', attribute='size')
            super(self.__class__, self).__init__(virsh_instance=virsh_instance)
            self.xml = '<slices/>'

    class Reservations(base.base.LibvirtXMLBase):

        """
        Reservations device XML class

        Properties:

        reservations_managed:
            string, attribute of reservations tag
        reservations_source_type:
            string, attribute of source tag, sub-tag of the reservations tag
        reservations_source_path:
            string, attribute of source tag, sub-tag of the reservations tag
        reservations_source_mode:
            string, attribute of source tag, sub-tag of the reservations tag
        """

        __slots__ = ('reservations_managed', 'reservations_source_type',
                     'reservations_source_path', 'reservations_source_mode')

        def __init__(self, virsh_instance=base.base.virsh, reservations_managed=""):
            accessors.XMLAttribute('reservations_managed', self, parent_xpath='/',
                                   tag_name='reservations', attribute='managed')
            accessors.XMLAttribute('reservations_source_type', self, parent_xpath='/',
                                   tag_name='source', attribute='type')
            accessors.XMLAttribute('reservations_source_path', self, parent_xpath='/',
                                   tag_name='source', attribute='path')
            accessors.XMLAttribute('reservations_source_mode', self, parent_xpath='/',
                                   tag_name='source', attribute='mode')
            super(self.__class__, self).__init__(virsh_instance=virsh_instance)
            self.xml = '<reservations/>'

    class BackingStore(base.base.LibvirtXMLBase):
        """
        BakingStore of disk device XML class

        type:
            string, attribute of backingStore tag
        index:
            string, attribute of backingStore tag
        format:
            dict, key-attribute of backingStore tag
        source:
            nested xml of backingStore tag
        """
        __slots__ = ('type', 'index', 'format', 'source', 'backingstore')

        def __init__(self, virsh_instance=base.base.virsh):
            accessors.XMLAttribute('type', self,
                                   parent_xpath='/',
                                   tag_name='backingStore',
                                   attribute='type')
            accessors.XMLAttribute('index', self,
                                   parent_xpath='/',
                                   tag_name='backingStore',
                                   attribute='index')
            accessors.XMLElementDict('format', self,
                                     parent_xpath='/',
                                     tag_name='format')
            accessors.XMLElementNest('source', self,
                                     parent_xpath='/',
                                     tag_name='source',
                                     subclass=self.Source,
                                     subclass_dargs={
                                         'virsh_instance': virsh_instance})
            accessors.XMLElementNest('backingstore', self, parent_xpath='/',
                                     tag_name='backingStore',
                                     subclass=Disk.BackingStore,
                                     subclass_dargs={
                                         'virsh_instance': virsh_instance})

            super(self.__class__, self).__init__(virsh_instance=virsh_instance)
            self.xml = '<backingStore/>'

        def new_source(self, **dargs):
            """
            Create new source for backingstore

            """
            new_one = self.Source(virsh_instance=self.virsh)
            for key, value in list(dargs.items()):
                setattr(new_one, key, value)
            return new_one

        class Source(base.base.LibvirtXMLBase):
            """
            Source of backingstore xml class

            dev:
                string, attribute of backingStore/source tag
            protocal:
                string, attribute of backingStore/source tag
            name:
                string, attribute of backingStore/source tag
            host:
                dict, nested xml of backingStore/source tag
            file:
                string, attribute of backingStore/source tag
            """

            __slots__ = ('attrs', 'dev', 'protocol', 'name', 'host', 'file', 'auth')

            def __init__(self, virsh_instance=base.base.virsh):
                accessors.XMLElementDict('attrs', self,
                                         parent_xpath='/',
                                         tag_name='source')
                accessors.XMLAttribute('dev', self,
                                       parent_xpath='/',
                                       tag_name='source',
                                       attribute='dev')
                accessors.XMLAttribute('protocol', self,
                                       parent_xpath='/',
                                       tag_name='source',
                                       attribute='protocol')
                accessors.XMLAttribute('name', self,
                                       parent_xpath='/',
                                       tag_name='source',
                                       attribute='name')
                accessors.XMLElementDict('host', self,
                                         parent_xpath='/',
                                         tag_name='host')
                accessors.XMLAttribute('file', self,
                                       parent_xpath='/',
                                       tag_name='source',
                                       attribute='file')
                accessors.XMLElementNest('auth', self,
                                         parent_xpath='/',
                                         tag_name='auth',
                                         subclass=Disk.Auth,
                                         subclass_dargs={
                                            'virsh_instance': virsh_instance})

                super(self.__class__, self).__init__(virsh_instance=virsh_instance)
                self.xml = '<source/>'

    class DriverMetadata(base.base.LibvirtXMLBase):

        """
        DriverMetaData XML class

        <driver name='qemu' type='qcow2'>
         <metadata_cache>
           <max_size unit='bytes'>10</max_size>
         </metadata_cache>
        </driver>

        Properties:

        attrs: Dictionary of attributes, qualifying the driver name and type,etc.
        metadata_cache: embedded class to describe metadata attributes
        usages:
            custom_disk = Disk(type_name='disk')
            driver_dict = {"name": "qemu","type": "qcow2"}
            new_one = custom_disk.new_drivermetadata(**{"attrs": driver_dict})

            metadata_cache_dict = {"max_size": "10", "max_size_unit": "bytes"}

            new_one.metadata_cache = custom_disk.DriverMetadata().new_metadatacache(**metadata_cache_dict)

            custom_disk.drivermetadata = new_one
        """

        __slots__ = ('attrs', 'metadata_cache')

        def __init__(self, virsh_instance=base.base.virsh):
            accessors.XMLElementDict('attrs', self, parent_xpath='/',
                                     tag_name='driver')
            accessors.XMLElementNest('metadata_cache', self, parent_xpath='/',
                                     tag_name='metadata_cache',
                                     subclass=self.MetadataCache,
                                     subclass_dargs={
                                         'virsh_instance': virsh_instance})
            super(self.__class__, self).__init__(virsh_instance=virsh_instance)
            self.xml = '<driver/>'

        def new_metadatacache(self, **dargs):
            """
            Create new MetadataCache for DriverMetadata

            """
            new_one = self.MetadataCache(virsh_instance=self.virsh)
            for key, value in list(dargs.items()):
                setattr(new_one, key, value)
            return new_one

        class MetadataCache(base.base.LibvirtXMLBase):
            """
            Source of MetadataCache xml class

            max_size:
                string, attribute of MetadataCache max size
            max_size_unit:
                string, attribute of MetadataCache max size unit
            """

            __slots__ = ('max_size', 'max_size_unit')

            def __init__(self, virsh_instance=base.base.virsh):
                accessors.XMLElementText(property_name='max_size',
                                         libvirtxml=self,
                                         parent_xpath='/',
                                         tag_name='max_size')
                accessors.XMLAttribute(property_name="max_size_unit",
                                       libvirtxml=self,
                                       parent_xpath='/',
                                       tag_name='max_size',
                                       attribute='unit')
                super(self.__class__, self).__init__(virsh_instance=virsh_instance)
                self.xml = '<metadata_cache/>'
Example #38
0
 def test_serial_class(self):
     Serial = librarian.get('serial')
     self.assertTrue(issubclass(Serial, devices_base.UntypedDeviceBase))
     self.assertTrue(issubclass(Serial, devices_base.TypedDeviceBase))
Example #39
0
class Memory(base.UntypedDeviceBase):

    __slots__ = ('mem_model', 'target', 'source', 'address', 'mem_discard',
                 'mem_access', 'alias')

    def __init__(self, virsh_instance=base.base.virsh):
        accessors.XMLAttribute('mem_model', self,
                               parent_xpath='/',
                               tag_name='memory',
                               attribute='model')
        accessors.XMLAttribute('mem_discard', self,
                               parent_xpath='/',
                               tag_name='memory',
                               attribute='discard')
        accessors.XMLAttribute('mem_access', self,
                               parent_xpath='/',
                               tag_name='memory',
                               attribute='access')
        accessors.XMLElementNest('target', self, parent_xpath='/',
                                 tag_name='target', subclass=self.Target,
                                 subclass_dargs={
                                     'virsh_instance': virsh_instance})
        accessors.XMLElementNest('source', self, parent_xpath='/',
                                 tag_name='source', subclass=self.Source,
                                 subclass_dargs={
                                     'virsh_instance': virsh_instance})
        accessors.XMLElementNest('address', self, parent_xpath='/',
                                 tag_name='address', subclass=self.Address,
                                 subclass_dargs={
                                     'type_name': 'dimm',
                                     'virsh_instance': virsh_instance})
        accessors.XMLElementDict('alias', self, parent_xpath='/',
                                 tag_name='alias')
        super(Memory, self).__init__(device_tag='memory',
                                     virsh_instance=virsh_instance)
        self.xml = '<memory/>'

    Address = librarian.get('address')

    class Target(base.base.LibvirtXMLBase):

        """
        Memory target xml class.

        Properties:

        size, node:
            int.
        size_unit:
            string.
        """
        __slots__ = ('size', 'size_unit', 'node', 'label')

        def __init__(self, virsh_instance=base.base.virsh):
            accessors.XMLElementInt('size',
                                    self, parent_xpath='/',
                                    tag_name='size')
            accessors.XMLAttribute(property_name="size_unit",
                                   libvirtxml=self,
                                   forbidden=None,
                                   parent_xpath='/',
                                   tag_name='size',
                                   attribute='unit')
            accessors.XMLElementInt('node',
                                    self, parent_xpath='/',
                                    tag_name='node')
            accessors.XMLElementNest('label', self, parent_xpath='/',
                                     tag_name='label', subclass=self.Label,
                                     subclass_dargs={
                                         'virsh_instance': virsh_instance})
            super(self.__class__, self).__init__(virsh_instance=virsh_instance)
            self.xml = '<target/>'

        class Label(base.base.LibvirtXMLBase):

            """
            Memory target label xml class.

            Properties:

            size:
                int.
            size_unit:
                string.
            """
            __slots__ = ('size', 'size_unit')

            def __init__(self, virsh_instance=base.base.virsh):
                accessors.XMLElementInt('size',
                                        self, parent_xpath='/',
                                        tag_name='size')
                accessors.XMLAttribute(property_name="size_unit",
                                       libvirtxml=self,
                                       forbidden=None,
                                       parent_xpath='/',
                                       tag_name='size',
                                       attribute='unit')
                super(self.__class__, self).__init__(virsh_instance=virsh_instance)
                self.xml = '<label/>'

    class Source(base.base.LibvirtXMLBase):

        """
        Memory source xml class.

        Properties:

        pagesize:
            int.
        pagesize_unit, nodemask:
            string.
        """
        __slots__ = ('pagesize', 'pagesize_unit', 'nodemask', 'path')

        def __init__(self, virsh_instance=base.base.virsh):
            accessors.XMLElementInt('pagesize',
                                    self, parent_xpath='/',
                                    tag_name='pagesize')
            accessors.XMLAttribute(property_name="pagesize_unit",
                                   libvirtxml=self,
                                   forbidden=None,
                                   parent_xpath='/',
                                   tag_name='pagesize',
                                   attribute='unit')
            accessors.XMLElementText('nodemask',
                                     self, parent_xpath='/',
                                     tag_name='nodemask')
            accessors.XMLElementText('path',
                                     self, parent_xpath='/',
                                     tag_name='path')
            super(self.__class__, self).__init__(virsh_instance=virsh_instance)
            self.xml = '<source/>'

    def new_mem_address(self, type_name='dimm', **dargs):
        """
        Return a new disk Address instance and set properties from dargs
        """
        new_one = self.Address(type_name=type_name, virsh_instance=self.virsh)
        for key, value in list(dargs.items()):
            setattr(new_one, key, value)
        return new_one
Example #40
0
    def check_xml():
        """
        Predict the result serial device and generated console device
        and check the result domain XML against expectation
        """
        console_cls = librarian.get('console')

        local_serial_type = serial_type

        if serial_type == 'tls':
            local_serial_type = 'tcp'
        # Predict expected serial and console XML
        expected_console = console_cls(local_serial_type)

        if local_serial_type == 'udp':
            sources = []
            for source in serial_dev.sources:
                if 'service' in source and 'mode' not in source:
                    source['mode'] = 'connect'
                sources.append(source)
        else:
            sources = serial_dev.sources

        expected_console.sources = sources

        if local_serial_type == 'tcp':
            if 'protocol_type' in local_serial_type:
                expected_console.protocol_type = serial_dev.protocol_type
            else:
                expected_console.protocol_type = "raw"

        expected_console.target_port = serial_dev.target_port
        if 'target_type' in serial_dev:
            expected_console.target_type = serial_dev.target_type
        expected_console.target_type = console_target_type
        logging.debug("Expected console XML is:\n%s", expected_console)

        # Get current serial and console XML
        current_xml = VMXML.new_from_dumpxml(vm_name)
        serial_elem = current_xml.xmltreefile.find('devices/serial')
        console_elem = current_xml.xmltreefile.find('devices/console')
        if console_elem is None:
            test.fail("Expect generate console automatically, "
                      "but found none.")
        if serial_elem and console_target_type != 'serial':
            test.fail("Don't Expect exist serial device, "
                      "but found:\n%s" % serial_elem)

        cur_console = console_cls.new_from_element(console_elem)
        logging.debug("Current console XML is:\n%s", cur_console)
        # Compare current serial and console with oracle.
        if not expected_console == cur_console:
            # "==" has been override
            test.fail("Expect generate console:\n%s\nBut got:\n%s" %
                      (expected_console, cur_console))

        if console_target_type == 'serial':
            serial_cls = librarian.get('serial')
            expected_serial = serial_cls(local_serial_type)
            expected_serial.sources = sources

            set_targets(expected_serial)

            if local_serial_type == 'tcp':
                if 'protocol_type' in local_serial_type:
                    expected_serial.protocol_type = serial_dev.protocol_type
                else:
                    expected_serial.protocol_type = "raw"
            expected_serial.target_port = serial_dev.target_port
            if serial_elem is None:
                test.fail("Expect exist serial device, " "but found none.")
            cur_serial = serial_cls.new_from_element(serial_elem)
            if target_type == 'pci-serial':
                if cur_serial.address is None:
                    test.fail("Expect serial device address is not assigned")
                else:
                    logging.debug("Serial address is: %s", cur_serial.address)

            logging.debug("Expected serial XML is:\n%s", expected_serial)
            logging.debug("Current serial XML is:\n%s", cur_serial)
            # Compare current serial and console with oracle.
            if (target_type != 'pci-serial' and machine_type != 'pseries'
                    and not expected_serial == cur_serial):
                # "==" has been override
                test.fail("Expect serial device:\n%s\nBut got:\n "
                          "%s" % (expected_serial, cur_serial))
Example #41
0
class NetworkXMLBase(base.LibvirtXMLBase):

    """
    Accessor methods for NetworkXML class.

    Properties:
        name:
            string, operates on XML name tag
        uuid:
            string, operates on uuid tag
        mac:
            string, operates on address attribute of mac tag
        ip:
            string operate on ip/dhcp ranges as IPXML instances
        forward:
            dict, operates on forward tag
        forward_interface:
            list, operates on forward/interface tag
        nat_port:
            dict, operates on nat tag
        bridge:
            dict, operates on bridge attributes
        routes:
            list, operates on route tag.
        virtualport_type:
            string, operates on 'type' attribute of virtualport tag.
        bandwidth_inbound:
            dict, operates on inbound under bandwidth.
        bandwidth_outbound:
            dict, operates on outbound under bandwidth.
        portgroup:
            PortgroupXML instance to access portgroup tag.
        domain_name:
            string, operates on name attribute of domain tag
        dns:
            DNSXML instance to access dns tag.

        defined:
            virtual boolean, callout to virsh methods
        get:
            True if libvirt knows network name
        set:
            True defines network, False undefines to libvirt
        del:
            Undefines network to libvirt

        active:
            virtual boolean, callout to virsh methods
        get:
            True if network is active to libvirt
        set:
            True activates network, False deactivates to libvirt
        del:
            Deactivates network to libvirt

        autostart:
            virtual boolean, callout to virsh methods
        get:
            True if libvirt autostarts network with same name
        set:
            True to set autostart, False to unset to libvirt
        del:
            Unset autostart to libvirt

        persistent:
            virtual boolean, callout to virsh methods
        get:
            True if network was defined, False if only created.
        set:
            Same as defined property
        del:
            Same as defined property
    """

    __slots__ = ('name', 'uuid', 'bridge', 'defined', 'active',
                 'autostart', 'persistent', 'forward', 'mac', 'ip',
                 'bandwidth_inbound', 'bandwidth_outbound', 'portgroup',
                 'dns', 'domain_name', 'nat_port', 'forward_interface',
                 'routes', 'virtualport_type', 'vf_list', 'driver', 'pf',
                 'mtu')

    __uncompareable__ = base.LibvirtXMLBase.__uncompareable__ + (
        'defined', 'active',
        'autostart', 'persistent')

    __schema_name__ = "network"

    def __init__(self, virsh_instance=base.virsh):
        accessors.XMLElementText('name', self, parent_xpath='/',
                                 tag_name='name')
        accessors.XMLElementText('uuid', self, parent_xpath='/',
                                 tag_name='uuid')
        accessors.XMLAttribute('mac', self, parent_xpath='/',
                               tag_name='mac', attribute='address')
        accessors.XMLElementDict('forward', self, parent_xpath='/',
                                 tag_name='forward')
        accessors.XMLElementList('forward_interface', self, parent_xpath='/forward',
                                 marshal_from=self.marshal_from_forward_iface,
                                 marshal_to=self.marshal_to_forward_iface)
        accessors.XMLElementList('vf_list', self,
                                 parent_xpath='/forward',
                                 marshal_from=self.marshal_from_address,
                                 marshal_to=self.marshal_to_address)
        accessors.XMLElementDict('driver', self, parent_xpath='/',
                                 tag_name='driver')
        accessors.XMLElementDict('pf', self, parent_xpath='/',
                                 tag_name='pf')
        accessors.XMLElementDict('nat_port', self, parent_xpath='/forward/nat',
                                 tag_name='port')
        accessors.XMLElementDict('bridge', self, parent_xpath='/',
                                 tag_name='bridge')
        accessors.XMLElementDict('bandwidth_inbound', self,
                                 parent_xpath='/bandwidth',
                                 tag_name='inbound')
        accessors.XMLElementDict('bandwidth_outbound', self,
                                 parent_xpath='/bandwidth',
                                 tag_name='outbound')
        accessors.XMLAttribute("mtu", self, parent_xpath='/',
                               tag_name='mtu',  attribute='size')
        accessors.XMLAttribute('domain_name', self, parent_xpath='/',
                               tag_name='domain', attribute='name')
        accessors.XMLElementNest('dns', self, parent_xpath='/',
                                 tag_name='dns', subclass=DNSXML,
                                 subclass_dargs={
                                     'virsh_instance': virsh_instance})
        accessors.XMLElementList('routes', self, parent_xpath='/',
                                 marshal_from=self.marshal_from_route,
                                 marshal_to=self.marshal_to_route)
        accessors.XMLAttribute('virtualport_type', self, parent_xpath='/',
                               tag_name='virtualport', attribute='type')
        super(NetworkXMLBase, self).__init__(virsh_instance=virsh_instance)

    Address = librarian.get('address')

    def new_vf_address(self, **dargs):
        """
        Return a new interface Address instance and set properties from dargs
        """
        new_one = self.Address("pci", virsh_instance=self.virsh)
        for key, value in dargs.items():
            setattr(new_one, key, value)
        return new_one

    @staticmethod
    def marshal_from_address(item, index, libvirtxml):
        """Convert an Address instance into tag + attributes"""
        root = item.xmltreefile.getroot()
        if root.tag == 'address':
            return (root.tag, dict(root.items()))
        else:
            raise xcepts.LibvirtXMLError("Expected a list of address "
                                         "instances, not a %s" % str(item))

    @staticmethod
    def marshal_to_address(self, tag, attr_dict, index, libvirtxml):
        """Convert a tag + attributes into an Address instance"""
        if not tag == 'address':
            return None
        newone = self.new_vf_address(attr_dict)
        return newone

    def __check_undefined__(self, errmsg):
        if not self.defined:
            raise xcepts.LibvirtXMLError(errmsg)

    def get_defined(self):
        """
        Accessor for 'define' property - does this name exist in network list
        """
        params = {'only_names': True, 'virsh_instance': self.virsh}
        return self.name in self.virsh.net_state_dict(**params)

    def set_defined(self, value):
        """Accessor method for 'define' property, set True to define."""
        if not self.__super_get__('INITIALIZED'):
            pass  # do nothing
        value = bool(value)
        if value:
            self.virsh.net_define(self.xml)  # send it the filename
        else:
            del self.defined

    def del_defined(self):
        """Accessor method for 'define' property, undefines network"""
        self.__check_undefined__("Cannot undefine non-existant network")
        self.virsh.net_undefine(self.name)

    def get_active(self):
        """Accessor method for 'active' property (True/False)"""
        self.__check_undefined__("Cannot determine activation for undefined "
                                 "network")
        state_dict = self.virsh.net_state_dict(virsh_instance=self.virsh)
        return state_dict[self.name]['active']

    def set_active(self, value):
        """Accessor method for 'active' property, sets network active"""
        if not self.__super_get__('INITIALIZED'):
            pass  # do nothing
        self.__check_undefined__("Cannot activate undefined network")
        value = bool(value)
        if value:
            if not self.active:
                self.virsh.net_start(self.name)
            else:
                pass  # don't activate twice
        else:
            if self.active:
                del self.active
            else:
                pass  # don't deactivate twice

    def del_active(self):
        """Accessor method for 'active' property, stops network"""
        self.__check_undefined__("Cannot deactivate undefined network")
        if self.active:
            self.virsh.net_destroy(self.name)
        else:
            pass  # don't destroy twice

    def get_autostart(self):
        """Accessor method for 'autostart' property, True if set"""
        self.__check_undefined__("Cannot determine autostart for undefined "
                                 "network")
        state_dict = self.virsh.net_state_dict(virsh_instance=self.virsh)
        return state_dict[self.name]['autostart']

    def set_autostart(self, value):
        """Accessor method for 'autostart' property, sets/unsets autostart"""
        if not self.__super_get__('INITIALIZED'):
            pass  # do nothing
        self.__check_undefined__("Cannot set autostart for undefined network")
        value = bool(value)
        if value:
            if not self.autostart:
                self.virsh.net_autostart(self.name)
            else:
                pass  # don't set autostart twice
        else:
            if self.autostart:
                del self.autostart
            else:
                pass  # don't unset autostart twice

    def del_autostart(self):
        """Accessor method for 'autostart' property, unsets autostart"""
        if not self.defined:
            raise xcepts.LibvirtXMLError("Can't autostart nonexistant network")
        self.virsh.net_autostart(self.name, "--disable")

    def get_persistent(self):
        """Accessor method for 'persistent' property"""
        state_dict = self.virsh.net_state_dict(virsh_instance=self.virsh)
        return state_dict[self.name]['persistent']

    # Copy behavior for consistency
    set_persistent = set_defined
    del_persistent = del_defined

    def get_ip(self):
        xmltreefile = self.__dict_get__('xml')
        try:
            ip_root = xmltreefile.reroot('/ip')
        except KeyError as detail:
            raise xcepts.LibvirtXMLError(detail)
        ipxml = IPXML(virsh_instance=self.__dict_get__('virsh'))
        ipxml.xmltreefile = ip_root
        return ipxml

    def set_ip(self, value):
        if not issubclass(type(value), IPXML):
            raise xcepts.LibvirtXMLError("value must be a IPXML or subclass")
        xmltreefile = self.__dict_get__('xml')
        # IPXML root element is whole IP element tree
        root = xmltreefile.getroot()
        root.append(value.xmltreefile.getroot())
        xmltreefile.write()

    def del_ip(self):
        xmltreefile = self.__dict_get__('xml')
        element = xmltreefile.find('/ip')
        if element is not None:
            xmltreefile.remove(element)
            xmltreefile.write()

    def get_portgroup(self):
        try:
            portgroup_root = self.xmltreefile.reroot('/portgroup')
        except KeyError as detail:
            raise xcepts.LibvirtXMLError(detail)
        portgroup_xml = PortgroupXML(virsh_instance=self.__dict_get__('virsh'))
        portgroup_xml.xmltreefile = portgroup_root
        return portgroup_xml

    def set_portgroup(self, value):
        if not issubclass(type(value), PortgroupXML):
            raise xcepts.LibvirtXMLError("value must be a PortgroupXML"
                                         "instance or subclass.")
        root = self.xmltreefile.getroot()
        root.append(value.xmltreefile.getroot())
        self.xmltreefile.write()

    def del_portgroup(self):
        element = self.xmltreefile.find("/portgroup")
        if element is not None:
            self.xmltreefile.remove(element)
            self.xmltreefile.write()

    def new_dns(self, **dargs):
        """
        Return a new dns instance and set properties from dargs
        """
        new_one = DNSXML(virsh_instance=self.virsh)
        for key, value in dargs.items():
            setattr(new_one, key, value)
        return new_one

    @staticmethod
    def marshal_from_forward_iface(item, index, libvirtxml):
        """Convert a dictionary into a tag + attributes"""
        del index           # not used
        del libvirtxml      # not used
        if not isinstance(item, dict):
            raise xcepts.LibvirtXMLError("Expected a dictionary of interface "
                                         "attributes, not a %s"
                                         % str(item))
        return ('interface', dict(item))  # return copy of dict, not reference

    @staticmethod
    def marshal_to_forward_iface(tag, attr_dict, index, libvirtxml):
        """Convert a tag + attributes into a dictionary"""
        del index                    # not used
        del libvirtxml               # not used
        if tag != 'interface':
            return None              # skip this one
        return dict(attr_dict)       # return copy of dict, not reference

    @staticmethod
    def marshal_from_route(item, index, libvirtxml):
        """Convert a dictionary into a tag + attributes"""
        del index           # not used
        del libvirtxml      # not used
        if not isinstance(item, dict):
            raise xcepts.LibvirtXMLError("Expected a dictionary of interface "
                                         "attributes, not a %s"
                                         % str(item))
        return ('route', dict(item))  # return copy of dict, not reference

    @staticmethod
    def marshal_to_route(tag, attr_dict, index, libvirtxml):
        """Convert a tag + attributes into a dictionary"""
        del index                    # not used
        del libvirtxml               # not used
        if tag != 'route':
            return None              # skip this one
        return dict(attr_dict)       # return copy of dict, not reference
    def check_xml():
        """
        Predict the result serial device and generated console device
        and check the result domain XML against expectation
        """
        console_cls = librarian.get('console')

        local_serial_type = serial_type

        if serial_type == 'tls':
            local_serial_type = 'tcp'
        # Predict expected serial and console XML
        expected_console = console_cls(local_serial_type)

        if local_serial_type == 'udp':
            sources = []
            for source in serial_dev.sources:
                if 'service' in source and 'mode' not in source:
                    source['mode'] = 'connect'
                sources.append(source)
        else:
            sources = serial_dev.sources

        expected_console.sources = sources

        if local_serial_type == 'tcp':
            if 'protocol_type' in local_serial_type:
                expected_console.protocol_type = serial_dev.protocol_type
            else:
                expected_console.protocol_type = "raw"

        expected_console.target_port = serial_dev.target_port
        if 'target_type' in serial_dev:
            expected_console.target_type = serial_dev.target_type
        expected_console.target_type = console_target_type
        logging.debug("Expected console XML is:\n%s", expected_console)

        # Get current serial and console XML
        current_xml = VMXML.new_from_dumpxml(vm_name)
        serial_elem = current_xml.xmltreefile.find('devices/serial')
        console_elem = current_xml.xmltreefile.find('devices/console')
        if console_elem is None:
            test.fail("Expect generate console automatically, "
                      "but found none.")
        if serial_elem and console_target_type != 'serial':
            test.fail("Don't Expect exist serial device, "
                      "but found:\n%s" % serial_elem)

        cur_console = console_cls.new_from_element(console_elem)
        logging.debug("Current console XML is:\n%s", cur_console)
        # Compare current serial and console with oracle.
        if not expected_console == cur_console:
            # "==" has been override
            test.fail("Expect generate console:\n%s\nBut got:\n%s" %
                      (expected_console, cur_console))

        if console_target_type == 'serial':
            serial_cls = librarian.get('serial')
            expected_serial = serial_cls(local_serial_type)
            expected_serial.sources = sources

            set_targets(expected_serial)

            if local_serial_type == 'tcp':
                if 'protocol_type' in local_serial_type:
                    expected_serial.protocol_type = serial_dev.protocol_type
                else:
                    expected_serial.protocol_type = "raw"
            expected_serial.target_port = serial_dev.target_port
            if serial_elem is None:
                test.fail("Expect exist serial device, "
                          "but found none.")
            cur_serial = serial_cls.new_from_element(serial_elem)
            if target_type == 'pci-serial':
                if cur_serial.address is None:
                    test.fail("Expect serial device address is not assigned")
                else:
                    logging.debug("Serial address is: %s", cur_serial.address)

            logging.debug("Expected serial XML is:\n%s", expected_serial)
            logging.debug("Current serial XML is:\n%s", cur_serial)
            # Compare current serial and console with oracle.
            if target_type != 'pci-serial' and not expected_serial == cur_serial:
                # "==" has been override
                test.fail("Expect serial device:\n%s\nBut got:\n "
                          "%s" % (expected_serial, cur_serial))