Exemplo n.º 1
0
def _make_guest(conn=None, os_variant=None):
    if not conn:
        conn = utils.URIs.open_testdriver_cached()

    g = virtinst.Guest(conn)
    g.name = "TestGuest"
    g.currentMemory = int(200 * 1024)
    g.memory = int(400 * 1024)

    if os_variant:
        g.set_os_name(os_variant)

    # File disk
    d = virtinst.DeviceDisk(conn)
    d.path = "/dev/default-pool/new-test-suite.img"
    if d.wants_storage_creation():
        parent_pool = d.get_parent_pool()
        vol_install = virtinst.DeviceDisk.build_vol_install(conn,
            os.path.basename(d.path), parent_pool, .0000001, True)
        d.set_vol_install(vol_install)
    d.validate()
    g.add_device(d)

    # Block disk
    d = virtinst.DeviceDisk(conn)
    d.path = "/dev/disk-pool/diskvol1"
    d.validate()
    g.add_device(d)

    # Network device
    dev = virtinst.DeviceInterface(conn)
    g.add_device(dev)

    return g
Exemplo n.º 2
0
    def test_disk_backend(self):
        # Test get_size() with vol_install
        disk = virtinst.DeviceDisk(self.conn)
        pool = self.conn.storagePoolLookupByName("default-pool")
        vol_install = disk.build_vol_install(self.conn, "newvol1.img", pool, 1,
                                             False)
        disk.set_vol_install(vol_install)
        assert disk.get_size() == 1.0

        # Test some blockdev inspecting
        conn = utils.URIs.openconn("test:///default")
        if os.path.exists("/dev/loop0"):
            disk = virtinst.DeviceDisk(conn)
            disk.path = "/dev/loop0"
            assert disk.type == "block"
            disk.get_size()

        # Test sparse cloning
        tmpinput = tempfile.NamedTemporaryFile()
        open(tmpinput.name, "wb").write(b'\0' * 10000)

        srcdisk = virtinst.DeviceDisk(conn)
        srcdisk.path = tmpinput.name

        newdisk = virtinst.DeviceDisk(conn)
        tmpoutput = tempfile.NamedTemporaryFile()
        os.unlink(tmpoutput.name)
        newdisk.path = tmpoutput.name
        newdisk.set_local_disk_to_clone(srcdisk, True)
        newdisk.build_storage(None)

        # Test cloning onto existing disk
        newdisk.path = newdisk.path
        newdisk.set_local_disk_to_clone(srcdisk, True)
        newdisk.build_storage(None)
Exemplo n.º 3
0
def testXMLBuilderCoverage():
    """
    Test XMLBuilder corner cases
    """
    conn = utils.URIs.open_testdefault_cached()

    with pytest.raises(RuntimeError, match=".*'foo'.*"):
        # Ensure we validate root element
        virtinst.DeviceDisk(conn, parsexml="<foo/>")

    with pytest.raises(Exception, match=".*xmlParseDoc.*"):
        # Ensure we validate root element
        virtinst.DeviceDisk(conn, parsexml=-1)

    with pytest.raises(virtinst.xmlutil.DevError):
        raise virtinst.xmlutil.DevError("for coverage")

    with pytest.raises(ValueError):
        virtinst.DeviceDisk.validate_generic_name("objtype", None)

    with pytest.raises(ValueError):
        virtinst.DeviceDisk.validate_generic_name("objtype", "foo bar")

    # Test property __repr__ for code coverage
    assert "DeviceAddress" in str(virtinst.DeviceDisk.address)
    assert "./driver/@cache" in str(virtinst.DeviceDisk.driver_cache)

    # Conversion of 0x value into int
    xml = """
        <controller type='scsi'>
          <address type='pci' bus='0x00' slot='0x04' function='0x7'/>
        </controller>
    """
    dev = virtinst.DeviceController(conn, parsexml=xml)
    assert dev.address.slot == 4

    # Some XML formatting and get_xml_* corner cases
    conn = utils.URIs.openconn(utils.URIs.test_suite)
    xml = conn.lookupByName("test-for-virtxml").XMLDesc(0)
    guest = virtinst.Guest(conn, parsexml=xml)

    assert guest.features.get_xml().startswith("<features")
    assert guest.clock.get_xml().startswith("<clock")
    assert guest.seclabels[0].get_xml().startswith("<seclabel")
    assert guest.cpu.get_xml().startswith("<cpu")
    assert guest.os.get_xml().startswith("<os")
    assert guest.cpu.get_xml_id() == "./cpu"
    assert guest.cpu.get_xml_idx() == 0
    assert guest.get_xml_id() == "."
    assert guest.get_xml_idx() == 0

    assert guest.devices.disk[1].get_xml_id() == "./devices/disk[2]"
    assert guest.devices.disk[1].get_xml_idx() == 1
Exemplo n.º 4
0
def testReplaceChildParse():
    conn = utils.URIs.open_testdefault_cached()
    buildfile = DATADIR + "replace-child-build.xml"
    parsefile = DATADIR + "replace-child-parse.xml"

    def mkdisk(target):
        disk = virtinst.DeviceDisk(conn)
        disk.device = "cdrom"
        disk.bus = "scsi"
        disk.target = target
        return disk

    guest = virtinst.Guest(conn)
    guest.add_device(mkdisk("sda"))
    guest.add_device(mkdisk("sdb"))
    guest.add_device(mkdisk("sdc"))
    guest.add_device(mkdisk("sdd"))
    guest.add_device(mkdisk("sde"))
    guest.add_device(mkdisk("sdf"))
    guest.devices.replace_child(guest.devices.disk[2], mkdisk("sdz"))
    guest.set_defaults(guest)
    utils.diff_compare(guest.get_xml(), buildfile)

    guest = virtinst.Guest(conn, parsexml=guest.get_xml())
    newdisk = virtinst.DeviceDisk(conn, parsexml=mkdisk("sdw").get_xml())
    guest.devices.replace_child(guest.devices.disk[4], newdisk)
    utils.diff_compare(guest.get_xml(), parsefile)
Exemplo n.º 5
0
def test_disk_numtotarget():
    # Various testing our target generation
    #
    # Note: using single quotes in strings to avoid
    # codespell flagging the 'ba' assert
    assert DeviceDisk.num_to_target(1) == 'a'
    assert DeviceDisk.num_to_target(2) == 'b'
    assert DeviceDisk.num_to_target(26) == 'z'
    assert DeviceDisk.num_to_target(27) == 'aa'
    assert DeviceDisk.num_to_target(28) == 'ab'
    assert DeviceDisk.num_to_target(52) == 'az'
    assert DeviceDisk.num_to_target(53) == 'ba'
    assert DeviceDisk.num_to_target(27 * 26) == 'zz'
    assert DeviceDisk.num_to_target(27 * 26 + 1) == 'aaa'

    assert DeviceDisk.target_to_num('hda') == 0
    assert DeviceDisk.target_to_num('hdb') == 1
    assert DeviceDisk.target_to_num('sdz') == 25
    assert DeviceDisk.target_to_num('sdaa') == 26
    assert DeviceDisk.target_to_num('vdab') == 27
    assert DeviceDisk.target_to_num('vdaz') == 51
    assert DeviceDisk.target_to_num('xvdba') == 52
    assert DeviceDisk.target_to_num('xvdzz') == 26 * (25 + 1) + 25
    assert DeviceDisk.target_to_num('xvdaaa') == 26 * 26 * 1 + 26 * 1 + 0

    conn = utils.URIs.open_testdefault_cached()
    disk = virtinst.DeviceDisk(conn)
    disk.bus = 'ide'

    assert disk.generate_target([]) == 'hda'
    assert disk.generate_target(['hda']) == 'hdb'
    assert disk.generate_target(['hdb', 'sda']) == 'hdc'
    assert disk.generate_target(['hda', 'hdd']) == 'hdb'
Exemplo n.º 6
0
    def testDiskNumbers(self):
        # Various testing our target generation
        self.assertEqual("a", DeviceDisk.num_to_target(1))
        self.assertEqual("b", DeviceDisk.num_to_target(2))
        self.assertEqual("z", DeviceDisk.num_to_target(26))
        self.assertEqual("aa", DeviceDisk.num_to_target(27))
        self.assertEqual("ab", DeviceDisk.num_to_target(28))
        self.assertEqual("az", DeviceDisk.num_to_target(52))
        self.assertEqual("ba", DeviceDisk.num_to_target(53))
        self.assertEqual("zz", DeviceDisk.num_to_target(27 * 26))
        self.assertEqual("aaa", DeviceDisk.num_to_target(27 * 26 + 1))

        self.assertEqual(DeviceDisk.target_to_num("hda"), 0)
        self.assertEqual(DeviceDisk.target_to_num("hdb"), 1)
        self.assertEqual(DeviceDisk.target_to_num("sdz"), 25)
        self.assertEqual(DeviceDisk.target_to_num("sdaa"), 26)
        self.assertEqual(DeviceDisk.target_to_num("vdab"), 27)
        self.assertEqual(DeviceDisk.target_to_num("vdaz"), 51)
        self.assertEqual(DeviceDisk.target_to_num("xvdba"), 52)
        self.assertEqual(DeviceDisk.target_to_num("xvdzz"), 26 * (25 + 1) + 25)
        self.assertEqual(DeviceDisk.target_to_num("xvdaaa"),
                         26 * 26 * 1 + 26 * 1 + 0)

        disk = virtinst.DeviceDisk(self.conn)
        disk.bus = "ide"

        self.assertEqual("hda", disk.generate_target([]))
        self.assertEqual("hdb", disk.generate_target(["hda"]))
        self.assertEqual("hdc", disk.generate_target(["hdb", "sda"]))
        self.assertEqual("hdb", disk.generate_target(["hda", "hdd"]))

        disk.bus = "virtio-scsi"
        self.assertEqual("sdb", disk.generate_target(["sda", "sdg", "sdi"], 0))
        self.assertEqual("sdh", disk.generate_target(["sda", "sdg"], 1))
Exemplo n.º 7
0
    def testDiskNumbers(self):
        # Various testing our target generation
        #
        # Note: using single quotes in strings to avoid
        # codespell flagging the 'ba' assert
        self.assertEqual('a', DeviceDisk.num_to_target(1))
        self.assertEqual('b', DeviceDisk.num_to_target(2))
        self.assertEqual('z', DeviceDisk.num_to_target(26))
        self.assertEqual('aa', DeviceDisk.num_to_target(27))
        self.assertEqual('ab', DeviceDisk.num_to_target(28))
        self.assertEqual('az', DeviceDisk.num_to_target(52))
        self.assertEqual('ba', DeviceDisk.num_to_target(53))
        self.assertEqual('zz', DeviceDisk.num_to_target(27 * 26))
        self.assertEqual('aaa', DeviceDisk.num_to_target(27 * 26 + 1))

        self.assertEqual(DeviceDisk.target_to_num('hda'), 0)
        self.assertEqual(DeviceDisk.target_to_num('hdb'), 1)
        self.assertEqual(DeviceDisk.target_to_num('sdz'), 25)
        self.assertEqual(DeviceDisk.target_to_num('sdaa'), 26)
        self.assertEqual(DeviceDisk.target_to_num('vdab'), 27)
        self.assertEqual(DeviceDisk.target_to_num('vdaz'), 51)
        self.assertEqual(DeviceDisk.target_to_num('xvdba'), 52)
        self.assertEqual(DeviceDisk.target_to_num('xvdzz'),
            26 * (25 + 1) + 25)
        self.assertEqual(DeviceDisk.target_to_num('xvdaaa'),
            26 * 26 * 1 + 26 * 1 + 0)

        disk = virtinst.DeviceDisk(self.conn)
        disk.bus = 'ide'

        self.assertEqual('hda', disk.generate_target([]))
        self.assertEqual('hdb', disk.generate_target(['hda']))
        self.assertEqual('hdc', disk.generate_target(['hdb', 'sda']))
        self.assertEqual('hdb', disk.generate_target(['hda', 'hdd']))
Exemplo n.º 8
0
    def build_device(self,
                     vmname,
                     path=None,
                     device="disk",
                     collideguest=None):
        if path is None:
            if self.is_default_storage():
                path = self.get_default_path(vmname, collideguest=collideguest)
            else:
                path = self.widget("storage-entry").get_text().strip()

        disk = virtinst.DeviceDisk(self.conn.get_backend())
        disk.path = path or None
        disk.device = device

        if disk.wants_storage_creation():
            pool = disk.get_parent_pool()
            size = uiutil.spin_get_helper(self.widget("storage-size"))
            sparse = False

            vol_install = virtinst.DeviceDisk.build_vol_install(
                disk.conn, os.path.basename(disk.path), pool, size, sparse)
            disk.set_vol_install(vol_install)

            fmt = self.conn.get_default_storage_format()
            if disk.get_vol_install().supports_format():
                log.debug("Using default prefs format=%s for path=%s", fmt,
                          disk.path)
                disk.get_vol_install().format = fmt
            else:
                log.debug(
                    "path=%s can not use default prefs format=%s, "
                    "not setting it", disk.path, fmt)

        return disk
Exemplo n.º 9
0
def testSingleDisk():
    conn = utils.URIs.open_testdefault_cached()
    xml = ("""<disk type="file" device="disk"><source file="/a.img"/>\n"""
           """<target dev="hda" bus="ide"/></disk>\n""")
    conn = utils.URIs.open_testdefault_cached()
    d = virtinst.DeviceDisk(conn, parsexml=xml)
    _set_and_check(d, "target", "hda", "hdb")
    assert xml.replace("hda", "hdb") == d.get_xml()
Exemplo n.º 10
0
def test_disk_diskbackend_parse():
    # Test that calling validate() on parsed disk XML doesn't attempt
    # to verify the path exists. Assume it's a working config
    conn = utils.URIs.open_testdriver_cached()
    xml = ("<disk type='file' device='disk'>"
           "<source file='/A/B/C/D/NOPE'/>"
           "</disk>")
    disk = virtinst.DeviceDisk(conn, parsexml=xml)
    disk.validate()
    disk.is_size_conflict()
    disk.build_storage(None)
    assert getattr(disk, "_storage_backend").is_stub() is True

    # Stub backend coverage testing
    backend = getattr(disk, "_storage_backend")
    assert disk.get_parent_pool() is None
    assert disk.get_vol_object() is None
    assert disk.get_vol_install() is None
    assert disk.get_size() == 0
    assert backend.get_vol_xml() is None
    assert backend.get_dev_type() == "file"
    assert backend.get_driver_type() is None
    assert backend.get_parent_pool() is None

    disk.set_backend_for_existing_path()
    assert getattr(disk, "_storage_backend").is_stub() is False

    with pytest.raises(ValueError):
        disk.validate()

    # Ensure set_backend_for_existing_path resolves a path
    # to its existing storage volume
    xml = ("<disk type='file' device='disk'>"
           "<source file='/dev/default-pool/default-vol'/>"
           "</disk>")
    disk = virtinst.DeviceDisk(conn, parsexml=xml)
    disk.set_backend_for_existing_path()
    assert disk.get_vol_object()

    # Verify set_backend_for_existing_path doesn't error
    # for a variety of disks
    dom = conn.lookupByName("test-many-devices")
    guest = virtinst.Guest(conn, parsexml=dom.XMLDesc(0))
    for disk in guest.devices.disk:
        disk.set_backend_for_existing_path()
Exemplo n.º 11
0
    def build_device(self,
                     vmname,
                     path=None,
                     device="disk",
                     collideguest=None):
        if path is None:
            if self.is_default_storage():
                path = self.get_default_path(vmname, collideguest=collideguest)
            else:
                path = self.widget("storage-entry").get_text().strip()

        disk = virtinst.DeviceDisk(self.conn.get_backend())
        disk.set_source_path(path or None)
        disk.device = device
        vals = self.get_values()

        if vals.get("cache") is not None:
            disk.driver_cache = vals.get("cache")
        if vals.get("discard") is not None:
            disk.driver_discard = vals.get("discard")
        if vals.get("detect_zeroes") is not None:
            disk.driver_detect_zeroes = vals.get("detect_zeroes")
        if vals.get("readonly") is not None:
            disk.read_only = vals.get("readonly")
        if vals.get("shareable") is not None:
            disk.shareable = vals.get("shareable")
        if vals.get("serial") is not None:
            disk.serial = vals.get("serial")
        if (vals.get("removable") is not None
                and self.widget("disk-removable").get_visible()):
            disk.removable = vals.get("removable")

        if disk.wants_storage_creation():
            path = disk.get_source_path()
            pool = disk.get_parent_pool()
            size = uiutil.spin_get_helper(self.widget("storage-size"))
            fmt = self.conn.get_default_storage_format()

            # If the user changed the default disk format to raw, assume
            # they want to maximize performance, so fully allocate the
            # disk image. Otherwise use sparse
            sparse = fmt != 'raw'

            vol_install = virtinst.DeviceDisk.build_vol_install(
                disk.conn, os.path.basename(path), pool, size, sparse)
            disk.set_vol_install(vol_install)

            if disk.get_vol_install().supports_format():
                log.debug("Using default prefs format=%s for path=%s", fmt,
                          path)
                disk.get_vol_install().format = fmt
            else:
                log.debug("path=%s can not use default prefs format=%s, "
                          "not setting it", path, fmt)  # pragma: no cover

        return disk
Exemplo n.º 12
0
def parse_disk_entry(conn, disks, fullkey, value, topdir):
    """
    Parse a particular key/value for a disk.
    """
    # skip bus values, e.g. 'scsi0.present = "TRUE"'
    if re.match(r"^(scsi|ide)[0-9]+[^:]", fullkey):
        return

    ignore, bus, bus_nr, inst, key = re.split(
        r"^(scsi|ide)([0-9]+):([0-9]+)\.", fullkey)

    lvalue = value.lower()

    if key == "present" and lvalue == "false":
        return

    # Does anyone else think it's scary that we're still doing things
    # like this?
    if bus == "ide":
        inst = int(bus_nr) * 2 + (int(inst) % 2)
    elif bus == "scsi":
        inst = int(bus_nr) * 16 + (int(inst) % 16)

    disk = None
    for checkdisk in disks:
        if checkdisk.bus == bus and getattr(checkdisk, "vmx_inst") == inst:
            disk = checkdisk
            break
    if not disk:
        disk = virtinst.DeviceDisk(conn)
        disk.bus = bus
        setattr(disk, "vmx_inst", inst)
        disks.append(disk)

    if key == "devicetype":
        if (lvalue == "atapi-cdrom" or
            lvalue == "cdrom-raw" or
            lvalue == "cdrom-image"):
            disk.device = "cdrom"

    if key == "filename":
        disk.path = value
        fmt = "raw"
        if lvalue.endswith(".vmdk"):
            fmt = "vmdk"
            # See if the filename is actually a VMDK descriptor file
            newpath = parse_vmdk(os.path.join(topdir, disk.path))
            if newpath:
                logging.debug("VMDK file parsed path %s->%s",
                    disk.path, newpath)
                disk.path = newpath

        disk.driver_type = fmt
Exemplo n.º 13
0
def test_disk_rbd_path():
    conn = utils.URIs.open_testdriver_cached()
    diskxml1 = """
    <disk type="network" device="disk">
      <source protocol="rbd" name="rbd-sourcename/some-rbd-vol">
        <host name="ceph-mon-1.example.com" port="6789"/>
        <host name="ceph-mon-2.example.com" port="6789"/>
        <host name="ceph-mon-3.example.com" port="6789"/>
      </source>
      <target dev="vdag" bus="virtio"/>
    </disk>
    """

    disk1 = virtinst.DeviceDisk(conn, parsexml=diskxml1)
    disk1.set_backend_for_existing_path()
    assert disk1.get_vol_object().name() == "some-rbd-vol"
Exemplo n.º 14
0
def testDiskSourceAbspath():
    # If an existing disk doesn't have an abspath in the XML, make sure
    # we don't convert it just by parsing
    conn = utils.URIs.open_testdefault_cached()
    xml = "<disk type='file' device='disk'><source file='foobar'/></disk>"
    disk = virtinst.DeviceDisk(conn, parsexml=xml)
    assert disk.get_source_path() == "foobar"

    # But setting a relative path should convert it
    import os
    disk.set_source_path("foobar2")
    assert disk.get_source_path() == os.path.abspath("foobar2")

    # ...unless it's a URL
    disk.set_source_path("http://example.com/foobar3")
    assert disk.get_source_path() == "http://example.com/foobar3"
Exemplo n.º 15
0
def test_disk_diskbackend_misc():
    # Test get_size() with vol_install
    conn = utils.URIs.open_testdefault_cached()
    disk = virtinst.DeviceDisk(conn)
    pool = conn.storagePoolLookupByName("default-pool")
    vol_install = disk.build_vol_install(conn, "newvol1.img", pool, 1, False)
    disk.set_vol_install(vol_install)
    assert disk.get_size() == 1.0

    # Test some blockdev inspecting
    conn = utils.URIs.openconn("test:///default")
    if os.path.exists("/dev/loop0"):
        disk = virtinst.DeviceDisk(conn)
        disk.set_source_path("/dev/loop0")
        assert disk.type == "block"
        disk.get_size()

    # Test sparse cloning
    tmpinput = tempfile.NamedTemporaryFile()
    open(tmpinput.name, "wb").write(b'\0' * 10000)

    srcdisk = virtinst.DeviceDisk(conn)
    srcdisk.set_source_path(tmpinput.name)

    newdisk = virtinst.DeviceDisk(conn)
    tmpoutput = tempfile.NamedTemporaryFile()
    os.unlink(tmpoutput.name)
    newdisk.set_source_path(tmpoutput.name)
    newdisk.set_local_disk_to_clone(srcdisk, True)
    newdisk.build_storage(None)

    # Test cloning onto existing disk
    newdisk = virtinst.DeviceDisk(conn, parsexml=newdisk.get_xml())
    newdisk.set_source_path(newdisk.get_source_path())
    newdisk.set_local_disk_to_clone(srcdisk, True)
    newdisk.build_storage(None)

    newdisk = virtinst.DeviceDisk(conn)
    newdisk.type = "block"
    newdisk.set_source_path("/dev/foo/idontexist")
    assert newdisk.get_size() == 0

    conn = utils.URIs.open_testdriver_cached()
    volpath = "/dev/default-pool/test-clone-simple.img"
    assert virtinst.DeviceDisk.path_definitely_exists(conn, volpath)
    disk = virtinst.DeviceDisk(conn)
    disk.set_source_path(volpath)
    assert disk.get_size()
Exemplo n.º 16
0
    def validate_storage(self,
                         vmname,
                         path=None,
                         device="disk",
                         collidelist=None):
        if self.is_default_storage():
            # Make sure default pool is running
            ret = self._check_default_pool_active()
            if not ret:
                return False

        if path is None:
            if self.is_default_storage():
                path = self.get_default_path(vmname, collidelist or [])
            else:
                path = self.widget("storage-entry").get_text().strip()

        if not path and device in ["disk", "lun"]:
            return self.err.val_err(_("A storage path must be specified."))

        disk = virtinst.DeviceDisk(self.conn.get_backend())
        disk.path = path or None
        disk.device = device

        if disk.wants_storage_creation():
            pool = disk.get_parent_pool()
            size = uiutil.spin_get_helper(self.widget("storage-size"))
            sparse = False

            vol_install = virtinst.DeviceDisk.build_vol_install(
                disk.conn, os.path.basename(disk.path), pool, size, sparse)
            disk.set_vol_install(vol_install)

            fmt = self.conn.get_default_storage_format()
            if fmt in disk.get_vol_install().list_formats():
                logging.debug("Using default prefs format=%s for path=%s", fmt,
                              disk.path)
                disk.get_vol_install().format = fmt
            else:
                logging.debug(
                    "path=%s can not use default prefs format=%s, "
                    "not setting it", disk.path, fmt)

        disk.validate()
        return disk
Exemplo n.º 17
0
def _make_guest(conn=None, os_variant=None):
    if not conn:
        conn = utils.URIs.open_testdriver_cached()

    g = virtinst.Guest(conn)
    g.type = "kvm"
    g.name = "TestGuest"
    g.memory = int(200 * 1024)
    g.maxmemory = int(400 * 1024)
    g.uuid = "12345678-1234-1234-1234-123456789012"
    gdev = virtinst.DeviceGraphics(conn)
    gdev.type = "vnc"
    gdev.keymap = "ja"
    g.add_device(gdev)
    g.features.pae = False
    g.vcpus = 5

    g.emulator = "/usr/lib/xen/bin/qemu-dm"
    g.os.arch = "i686"
    g.os.os_type = "hvm"

    if os_variant:
        g.set_os_name(os_variant)

    # Floppy disk
    path = "/dev/default-pool/testvol1.img"
    d = DeviceDisk(conn)
    d.path = path
    d.device = d.DEVICE_FLOPPY
    d.validate()
    g.add_device(d)

    # File disk
    path = "/dev/default-pool/new-test-suite.img"
    d = virtinst.DeviceDisk(conn)
    d.path = path

    if d.wants_storage_creation():
        parent_pool = d.get_parent_pool()
        vol_install = virtinst.DeviceDisk.build_vol_install(conn,
            os.path.basename(path), parent_pool, .0000001, True)
        d.set_vol_install(vol_install)

    d.validate()
    g.add_device(d)

    # Block disk
    path = "/dev/disk-pool/diskvol1"
    d = virtinst.DeviceDisk(conn)
    d.path = path
    d.validate()
    g.add_device(d)

    # Network device
    dev = virtinst.DeviceInterface(conn)
    dev.macaddr = "22:22:33:44:55:66"
    dev.type = virtinst.DeviceInterface.TYPE_VIRTUAL
    dev.source = "default"
    g.add_device(dev)

    return g
Exemplo n.º 18
0
def _import_file(conn, input_file):
    """
    Parse the OVF file and generate a virtinst.Guest object from it
    """
    root = xml.etree.ElementTree.parse(input_file).getroot()
    vsnode = _find(root, "./ovf:VirtualSystem")
    vhnode = _find(vsnode, "./ovf:VirtualHardwareSection")

    # General info
    name = _text(vsnode.find("./ovf:Name", OVF_NAMESPACES))
    desc = _text(
        vsnode.find("./ovf:AnnotationSection/ovf:Annotation", OVF_NAMESPACES))
    if not desc:
        desc = _text(vsnode.find("./ovf:Description", OVF_NAMESPACES))

    vhxpath = "./ovf:Item[rasd:ResourceType='%s']"
    vcpus = _text(
        _find(vhnode, (vhxpath % DEVICE_CPU) + "/rasd:VirtualQuantity"))
    mem = _text(
        _find(vhnode, (vhxpath % DEVICE_MEMORY) + "/rasd:VirtualQuantity"))
    alloc_mem = _text(
        _find(vhnode, (vhxpath % DEVICE_MEMORY) + "/rasd:AllocationUnits"))

    # Sections that we handle
    # NetworkSection is ignored, since I don't have an example of
    # a valid section in the wild.
    parsed_sections = [
        "References", "DiskSection", "NetworkSection", "VirtualSystem"
    ]

    # Check for unhandled 'required' sections
    for env_node in root.findall("./"):
        if any([p for p in parsed_sections if p in env_node.tag]):
            continue

        logging.debug("Unhandled XML section '%s'", env_node.tag)

        if not _convert_bool_val(env_node.attrib.get("required")):
            continue
        raise Exception(
            _("OVF section '%s' is listed as "
              "required, but parser doesn't know "
              "how to handle it.") % env_node.name)

    disk_buses = {}
    for node in _findall(vhnode, vhxpath % DEVICE_IDE_BUS):
        instance_id = _text(_find(node, "rasd:InstanceID"))
        disk_buses[instance_id] = "ide"
    for node in _findall(vhnode, vhxpath % DEVICE_SCSI_BUS):
        instance_id = _text(_find(node, "rasd:InstanceID"))
        disk_buses[instance_id] = "scsi"

    ifaces = []
    for node in _findall(vhnode, vhxpath % DEVICE_ETHERNET):
        iface = virtinst.DeviceInterface(conn)
        # Just ignore 'source' info for now and choose the default
        net_model = _text(_find(node, "rasd:ResourceSubType"))
        if net_model and not net_model.isdigit():
            iface.model = net_model.lower()
        iface.set_default_source()
        ifaces.append(iface)

    disks = []
    for node in _findall(vhnode, vhxpath % DEVICE_DISK):
        bus_id = _text(_find(node, "rasd:Parent"))
        path = _text(_find(node, "rasd:HostResource"))

        bus = disk_buses.get(bus_id, "ide")
        fmt = "raw"

        if path:
            path = _lookup_disk_path(root, path)
            fmt = "vmdk"

        disk = virtinst.DeviceDisk(conn)
        disk.path = path
        disk.driver_type = fmt
        disk.bus = bus
        disk.device = "disk"
        disks.append(disk)

    # Generate the Guest
    guest = conn.caps.lookup_virtinst_guest()
    guest.installer = virtinst.ImportInstaller(conn)

    if not name:
        name = os.path.basename(input_file)

    guest.name = name.replace(" ", "_")
    guest.description = desc or None
    if vcpus:
        guest.vcpus = int(vcpus)

    if mem:
        guest.memory = _convert_alloc_val(alloc_mem, mem) * 1024

    for dev in ifaces + disks:
        guest.add_device(dev)

    return guest
Exemplo n.º 19
0
 def mkdisk(target):
     disk = virtinst.DeviceDisk(conn)
     disk.device = "cdrom"
     disk.bus = "scsi"
     disk.target = target
     return disk