Exemplo n.º 1
0
def run(test, params, env):
    """
    Test command: virsh nwfilter-define.

    1) Prepare parameters.
    2) Set options of virsh define.
    3) Run define command.
    4) Check result.
    5) Clean env
    """
    # Prepare parameters
    filter_name = params.get("filter_name", "testcase")
    filter_uuid = params.get("filter_uuid",
                             "11111111-b071-6127-b4ec-111111111111")
    exist_filter = params.get("exist_filter", "no-mac-spoofing")
    filter_xml = params.get("filter_create_xml_file")
    options_ref = params.get("options_ref", "")
    status_error = params.get("status_error", "no")
    boundary_test_skip = "yes" == params.get("boundary_test_skip")
    new_uuid = "yes" == params.get("new_uuid", 'no')
    bug_url = params.get("bug_url")

    # libvirt acl polkit related params
    uri = params.get("virsh_uri")
    unprivileged_user = params.get('unprivileged_user')
    if unprivileged_user:
        if unprivileged_user.count('EXAMPLE'):
            unprivileged_user = '******'

    if not libvirt_version.version_compare(1, 1, 1):
        if params.get('setup_libvirt_polkit') == 'yes':
            raise error.TestNAError("API acl test not supported in current"
                                    " libvirt version.")

    if exist_filter == filter_name and new_uuid:
        # Since commit 46a811d, update filter with new uuid will fail.
        if libvirt_version.version_compare(1, 2, 7):
            status_error = 'yes'
        else:
            status_error = 'no'

    try:
        if filter_xml == "invalid-filter-xml":
            tmp_xml = xml_utils.TempXMLFile()
            tmp_xml.write('"<filter><<<BAD>>><\'XML</name\>'
                          '!@#$%^&*)>(}>}{CORRUPTE|>!</filter>')
            tmp_xml.flush()
            filter_xml = tmp_xml.name
            logging.info("Test invalid xml is: %s" % filter_xml)
        elif filter_xml:
            # Create filter xml
            new_filter = libvirt_xml.NwfilterXML()
            filterxml_backup = new_filter.new_from_filter_dumpxml(exist_filter)
            # Backup xml if only update exist filter
            if exist_filter == filter_name and not new_uuid:
                filter_uuid = filterxml_backup.uuid
                params['filter_uuid'] = filter_uuid

            filterxml = utlv.create_nwfilter_xml(params)
            filterxml.xmltreefile.write(filter_xml)

        # Run command
        cmd_result = virsh.nwfilter_define(filter_xml,
                                           options=options_ref,
                                           unprivileged_user=unprivileged_user,
                                           uri=uri,
                                           ignore_status=True,
                                           debug=True)
        status = cmd_result.exit_status

        # Check result
        chk_result = check_list(filter_uuid, filter_name)
        xml_path = "%s/%s.xml" % (NWFILTER_ETC_DIR, filter_name)
        if status_error == "yes":
            if status == 0:
                if boundary_test_skip:
                    raise error.TestNAError("Boundary check commit 4f20943 not"
                                            " in this libvirt build yet.")
                else:
                    err_msg = "Run successfully with wrong command."
                    if bug_url:
                        err_msg += " Check more info in %s" % bug_url
                    raise error.TestFail(err_msg)
        elif status_error == "no":
            if status:
                err_msg = "Run failed with right command."
                if bug_url:
                    err_msg += " Check more info in %s" % bug_url
                raise error.TestFail(err_msg)
            if not chk_result:
                raise error.TestFail("Can't find filter in nwfilter-list" +
                                     " output")
            if not os.path.exists(xml_path):
                raise error.TestFail("Can't find filter xml under %s" %
                                     NWFILTER_ETC_DIR)
            logging.info("Dump the xml after define:")
            virsh.nwfilter_dumpxml(filter_name, ignore_status=True, debug=True)

    finally:
        # Clean env
        if exist_filter == filter_name:
            logging.info("Restore exist filter: %s" % exist_filter)
            virsh.nwfilter_undefine(filter_name, ignore_status=True)
            virsh.nwfilter_define(filterxml_backup.xml, ignore_status=True)
        else:
            if chk_result:
                virsh.nwfilter_undefine(filter_name, ignore_status=True)
        if os.path.exists(filter_xml):
            os.remove(filter_xml)
Exemplo n.º 2
0
def run(test, params, env):
    """
    Test command: virsh net-create.

    1) Gather test parameters
    2) Store current libvirt host network state
    3) Call virsh net create on possibly modified network XML
    4) Recover original network.
    5) Check result.
    """

    # Gather test parameters
    uri = libvirt_vm.normalize_connect_uri(params.get("connect_uri",
                                                      "default"))
    status_error = "yes" == params.get("status_error", "no")
    net_name = params.get("net_create_net_name", "")  # default is tested
    net_uuid = params.get("net_create_net_uuid", "")  # default is tested
    options_ref = params.get("net_create_options_ref", "")  # default is tested
    # extra cmd-line params.
    extra = params.get("net_create_options_extra", "")
    corrupt = "yes" == params.get("net_create_corrupt_xml", "no")
    remove_existing = "yes" == params.get("net_create_remove_existing", "yes")
    # Dictionary or None value
    bridge = eval(params.get("net_create_bridge", "None"),
                  {'__builtins__': None}, {})
    # make easy to maintain
    virsh_dargs = {'uri': uri, 'debug': False, 'ignore_status': False}
    vrsh = virsh.VirshPersistent(**virsh_dargs)

    # Prepare environment and record current net_state_dict
    backup = NetworkXML.new_all_networks_dict(vrsh)
    backup_state = vrsh.net_state_dict()
    logging.debug("Backed up network(s): %s", backup_state)

    # Make some XML to use for testing, for now we just copy 'default'
    test_xml = xml_utils.TempXMLFile()  # temporary file
    try:
        # LibvirtXMLBase.__str__ returns XML content
        test_xml.write(str(backup['default']))
        test_xml.flush()
    except (KeyError, AttributeError):
        raise error.TestNAError("Test requires default network to exist")
    if corrupt:
        # find file size
        test_xml.seek(0, 2)  # end
        # write garbage at middle of file
        test_xml.seek(test_xml.tell() / 2)
        test_xml.write('"<network><<<BAD>>><\'XML</network\>'
                       '!@#$%^&*)>(}>}{CORRUPTE|>!')
        test_xml.flush()
        # Assume next user might want to read
        test_xml.seek(0)

    if remove_existing:
        for netxml in backup.values():
            netxml.orbital_nuclear_strike()

    # Run test case

    # Be nice to user
    if status_error:
        logging.info("The following is expected to fail...")

    try:
        # Determine depth of test - if low-level calls are needed
        if (options_ref or extra or corrupt):
            logging.debug("Performing low-level net-create test")
            # vrsh will act like it's own virsh-dargs, i.e. it is dict-like
            test_passed = do_low_level_test(vrsh, test_xml, options_ref, extra)
        else:  # high-level test
            logging.debug("Performing high-level net-create test")
            # vrsh will act like it's own virsh-dargs, i.e. it is dict-like
            test_passed = do_high_level_test(vrsh, test_xml, net_name,
                                             net_uuid, bridge)
    finally:
        # Be nice to user
        if status_error:
            # In case test itself has errors, warn they are real.
            logging.info("The following is NOT expected to fail...")

        # Done with file, cleanup
        del test_xml

        # Recover environment
        leftovers = NetworkXML.new_all_networks_dict(vrsh)
        for netxml in leftovers.values():
            netxml.orbital_nuclear_strike()

        # Recover from backup
        for netxml in backup.values():
            netxml.sync(backup_state[netxml.name])

        # Close down persistent virsh session (including for all netxml copies)
        vrsh.close_session()

    # Check Result
    if status_error:  # An error was expected
        if test_passed:  # Error was not produced
            raise error.TestFail("Error test did not fail!")
    else:  # no error expected
        if not test_passed:
            raise error.TestFail("Normal test returned failure")
Exemplo n.º 3
0
                try:
                    lv_utils.vg_create(vg_name, iscsi_device)
                except Exception, detail:
                    utils_test.libvirt.setup_or_cleanup_iscsi(False)
                    raise error.TestFail("vg_create failed: %s", detail)
                cleanup_logical = True

    # Prepare srcSpec xml
    if srcSpec:
        if srcSpec == "INVALID.XML":
            src_xml = "<invalid><host name='#@!'/><?source>"
        else:
            src_xml = srcSpec
    else:
        src_xml = "<source><host name='%s'/></source>" % source_host
    srcSpec = xml_utils.TempXMLFile()
    srcSpec.write(src_xml)
    srcSpec.flush()
    logging.debug("srcSpec file content:\n%s", file(srcSpec.name).read())

    if ro_flag:
        logging.debug("Readonly mode test")

    # Run virsh cmd
    try:
        cmd_result = virsh.find_storage_pool_sources(source_type,
                                                     srcSpec.name,
                                                     ignore_status=True,
                                                     debug=True,
                                                     readonly=ro_flag)
        output = cmd_result.stdout.strip()
Exemplo n.º 4
0
def run(test, params, env):
    """
    Test command: virsh net-define/net-undefine.

    1) Collect parameters&environment info before test
    2) Prepare options for command
    3) Execute command for test
    4) Check state of defined network
    5) Recover environment
    6) Check result
    """
    uri = libvirt_vm.normalize_connect_uri(params.get("connect_uri",
                                                      "default"))
    net_name = params.get("net_define_undefine_net_name", "default")
    net_uuid = params.get("net_define_undefine_net_uuid", "")
    options_ref = params.get("net_define_undefine_options_ref", "default")
    trans_ref = params.get("net_define_undefine_trans_ref", "trans")
    extra_args = params.get("net_define_undefine_extra", "")
    remove_existing = params.get("net_define_undefine_remove_existing", "yes")
    status_error = "yes" == params.get("status_error", "no")
    check_states = "yes" == params.get("check_states", "no")

    virsh_dargs = {'uri': uri, 'debug': False, 'ignore_status': True}
    virsh_instance = virsh.VirshPersistent(**virsh_dargs)

    # libvirt acl polkit related params
    if not libvirt_version.version_compare(1, 1, 1):
        if params.get('setup_libvirt_polkit') == 'yes':
            raise error.TestNAError("API acl test not supported in current"
                                    " libvirt version.")

    virsh_uri = params.get("virsh_uri")
    unprivileged_user = params.get('unprivileged_user')
    if unprivileged_user:
        if unprivileged_user.count('EXAMPLE'):
            unprivileged_user = '******'

    # Prepare environment and record current net_state_dict
    backup = network_xml.NetworkXML.new_all_networks_dict(virsh_instance)
    backup_state = virsh_instance.net_state_dict()
    logging.debug("Backed up network(s): %s", backup_state)

    # Make some XML to use for testing, for now we just copy 'default'
    test_xml = xml_utils.TempXMLFile()  # temporary file
    try:
        # LibvirtXMLBase.__str__ returns XML content
        test_xml.write(str(backup['default']))
        test_xml.flush()
    except (KeyError, AttributeError):
        raise error.TestNAError("Test requires default network to exist")

    testnet_xml = get_network_xml_instance(virsh_dargs,
                                           test_xml,
                                           net_name,
                                           net_uuid,
                                           bridge=None)

    if remove_existing:
        for netxml in backup.values():
            netxml.orbital_nuclear_strike()

    # Test both define and undefine, So collect info
    # both of them for result check.
    # When something wrong with network, set it to 1
    fail_flag = 0
    result_info = []

    if options_ref == "correct_arg":
        define_options = testnet_xml.xml
        undefine_options = net_name
    elif options_ref == "no_option":
        define_options = ""
        undefine_options = ""
    elif options_ref == "not_exist_option":
        define_options = "/not/exist/file"
        undefine_options = "NOT_EXIST_NETWORK"

    define_extra = undefine_extra = extra_args
    if trans_ref != "define":
        define_extra = ""

    if params.get('setup_libvirt_polkit') == 'yes':
        virsh_dargs = {
            'uri': virsh_uri,
            'unprivileged_user': unprivileged_user,
            'debug': False,
            'ignore_status': True
        }
        cmd = "chmod 666 %s" % testnet_xml.xml
        utils.system(cmd)

    try:
        # Run test case
        define_result = virsh.net_define(define_options, define_extra,
                                         **virsh_dargs)
        logging.debug(define_result)
        define_status = define_result.exit_status

        # Check network states
        if check_states and not define_status:
            net_state = virsh_instance.net_state_dict()
            if (net_state[net_name]['active']
                    or net_state[net_name]['autostart']
                    or not net_state[net_name]['persistent']):
                fail_flag = 1
                result_info.append("Found wrong network states for "
                                   "defined netowrk: %s" % str(net_state))

        # If defining network succeed, then trying to start it.
        if define_status == 0:
            start_result = virsh.net_start(net_name, extra="", **virsh_dargs)
            logging.debug(start_result)
            start_status = start_result.exit_status

        if trans_ref == "trans":
            if define_status:
                fail_flag = 1
                result_info.append("Define network with right command failed.")
            else:
                if start_status:
                    fail_flag = 1
                    result_info.append("Network is defined as expected, "
                                       "but failed to start it.")

        # Check network states for normal test
        if check_states and not status_error:
            net_state = virsh_instance.net_state_dict()
            if (not net_state[net_name]['active']
                    or net_state[net_name]['autostart']
                    or not net_state[net_name]['persistent']):
                fail_flag = 1
                result_info.append("Found wrong network states for "
                                   "started netowrk: %s" % str(net_state))
            # Try to set autostart
            virsh.net_autostart(net_name, **virsh_dargs)
            net_state = virsh_instance.net_state_dict()
            if not net_state[net_name]['autostart']:
                fail_flag = 1
                result_info.append("Failed to set autostart for network %s" %
                                   net_name)
            # Restart libvirtd and check state
            # Close down persistent virsh session before libvirtd restart
            if hasattr(virsh_instance, 'close_session'):
                virsh_instance.close_session()
            libvirtd = utils_libvirtd.Libvirtd()
            libvirtd.restart()
            # Need to redefine virsh_instance after libvirtd restart
            virsh_instance = virsh.VirshPersistent(**virsh_dargs)
            net_state = virsh_instance.net_state_dict()
            if (not net_state[net_name]['active']
                    or not net_state[net_name]['autostart']):
                fail_flag = 1
                result_info.append("Found wrong network state after restarting"
                                   " libvirtd: %s" % str(net_state))
            # Undefine an active network and check state
            undefine_status = virsh.net_undefine(undefine_options,
                                                 undefine_extra,
                                                 **virsh_dargs).exit_status
            if not undefine_status:
                net_state = virsh_instance.net_state_dict()
                if (not net_state[net_name]['active']
                        or net_state[net_name]['autostart']
                        or net_state[net_name]['persistent']):
                    fail_flag = 1
                    result_info.append("Found wrong network states for "
                                       "undefined netowrk: %s" %
                                       str(net_state))

        # Stop network for undefine test anyway
        destroy_result = virsh.net_destroy(net_name, extra="", **virsh_dargs)
        logging.debug(destroy_result)

        # Undefine network
        if not check_states:
            undefine_result = virsh.net_undefine(undefine_options,
                                                 undefine_extra, **virsh_dargs)
            if trans_ref != "define":
                logging.debug(undefine_result)
            undefine_status = undefine_result.exit_status

    finally:
        # Recover environment
        leftovers = network_xml.NetworkXML.new_all_networks_dict(
            virsh_instance)
        for netxml in leftovers.values():
            netxml.orbital_nuclear_strike()

        # Recover from backup
        for netxml in backup.values():
            netxml.sync(backup_state[netxml.name])

        # Close down persistent virsh session (including for all netxml copies)
        if hasattr(virsh_instance, 'close_session'):
            virsh_instance.close_session()

        # Done with file, cleanup
        del test_xml
        del testnet_xml

    # Check status_error
    # If fail_flag is set, it must be transaction test.
    if fail_flag:
        raise error.TestFail(
            "Define network for transaction test "
            "failed:%s", result_info)

    # The logic to check result:
    # status_error&only undefine:it is negative undefine test only
    # status_error&(no undefine):it is negative define test only
    # (not status_error)&(only undefine):it is positive transaction test.
    # (not status_error)&(no undefine):it is positive define test only
    if status_error:
        if trans_ref == "undefine":
            if undefine_status == 0:
                raise error.TestFail("Run successfully with wrong command.")
        else:
            if define_status == 0:
                if start_status == 0:
                    raise error.TestFail("Define an unexpected network, "
                                         "and start it successfully.")
                else:
                    raise error.TestFail("Define an unexpected network, "
                                         "but start it failed.")
    else:
        if trans_ref == "undefine":
            if undefine_status:
                raise error.TestFail("Define network for transaction "
                                     "successfully, but undefine failed.")
        else:
            if define_status != 0:
                raise error.TestFail("Run failed with right command")
            else:
                if start_status != 0:
                    raise error.TestFail("Network is defined as expected, "
                                         "but start it failed.")
Exemplo n.º 5
0
def run(test, params, env):
    """
    Test command: virsh pool-create.

    Create a libvirt pool from an XML file. The file could be given by tester or
    generated by dumpxml a pre-defined pool.
    """
    pool_xml_f = params.get("pool_create_xml_file", "")
    pool_name = params.get("pool_create_name", "virt_test_pool_tmp")
    option = params.get("pool_create_extra_option", "")
    readonly_mode = "yes" == params.get("pool_create_readonly_mode", "no")
    status_error = "yes" == params.get("status_error", "no")
    pre_def_pool = "yes" == params.get("pre_def_pool", "no")
    pool_type = params.get("pool_type", "dir")
    source_format = params.get("pool_src_format", "")
    source_name = params.get("pool_source_name", "")
    source_path = params.get("pool_source_path", "/")
    pool_target = params.get("pool_target", "pool_target")
    duplicate_element = params.get("pool_create_duplicate_element", "")
    new_pool_name = params.get("new_pool_create_name")
    no_disk_label = "yes" == params.get("no_disk_label", "no")

    if not libvirt_version.version_compare(1, 0, 0):
        if pool_type == "gluster":
            test.cancel("Gluster pool is not supported in current"
                        " libvirt version.")

    pool_ins = libvirt_storage.StoragePool()
    if pre_def_pool and pool_ins.pool_exists(pool_name):
        test.fail("Pool %s already exist" % pool_name)

    kwargs = {'image_size': '1G', 'source_path': source_path,
              'source_name': source_name, 'source_format': source_format,
              'emulated_image': "emulated-image", 'pool_target': pool_target,
              'pool_name': pool_name}
    params.update(kwargs)
    pvt = utlv.PoolVolumeTest(test, params)
    old_uuid = None
    new_device_name = None
    if pre_def_pool:
        try:
            pvt.pre_pool(**params)
            virsh.pool_dumpxml(pool_name, to_file=pool_xml_f)
            old_uuid = virsh.pool_uuid(pool_name).stdout.strip()
            if no_disk_label:
                # Update <device_path>
                logging.debug("Try to update device path")
                new_device_name = utlv.setup_or_cleanup_iscsi(True)
                p_xml = pool_xml.PoolXML.new_from_dumpxml(pool_name)
                s_xml = pool_xml.SourceXML()
                s_xml.device_path = new_device_name
                p_xml.set_source(s_xml)
                pool_xml_f = p_xml.xml
            if duplicate_element == "name":
                pass
            elif duplicate_element == "uuid":
                pass
            elif duplicate_element == "source":
                # Remove <uuid> and update <name>
                cmd = "sed -i '/<uuid>/d' %s" % pool_xml_f
                process.run(cmd, shell=True)
                cmd = "sed -i 's/<name>.*<\/name>/<name>%s<\/name>/g' %s" % (new_pool_name, pool_xml_f)
                process.run(cmd, shell=True)
            else:
                # The transient pool will gone after destroyed
                virsh.pool_destroy(pool_name)
            new_source_format = params.get("new_pool_src_format")
            if new_source_format:
                cmd = "sed -i s/type=\\\'%s\\\'/type=\\\'%s\\\'/g %s" % (
                    source_format, new_source_format, pool_xml_f)
                process.run(cmd, shell=True)
            # Remove uuid
            cmd = "sed -i '/<uuid>/d' %s" % pool_xml_f
            process.run(cmd, shell=True)
        except Exception as details:
            pvt.cleanup_pool(**params)
            if new_device_name:
                utlv.setup_or_cleanup_iscsi(False)
            test.error("Error occurred when prepare pool xml:\n %s"
                       % details)
    # Create an invalid pool xml file
    if pool_xml_f == "invalid-pool-xml":
        tmp_xml_f = xml_utils.TempXMLFile()
        tmp_xml_f.write('"<pool><<<BAD>>><\'XML</name\>'
                        '!@#$%^&*)>(}>}{CORRUPTE|>!</pool>')
        tmp_xml_f.flush()
        pool_xml_f = tmp_xml_f.name
    # Readonly mode
    ro_flag = False
    if readonly_mode:
        logging.debug("Readonly mode test")
        ro_flag = True
    # Run virsh test
    if os.path.exists(pool_xml_f):
        with open(pool_xml_f, 'r') as f:
            logging.debug("Create pool from file:\n %s", f.read())
    try:
        cmd_result = virsh.pool_create(pool_xml_f, option, ignore_status=True,
                                       debug=True, readonly=ro_flag)
        err = cmd_result.stderr.strip()
        status = cmd_result.exit_status
        if not status_error:
            if status:
                test.fail(err)
            utlv.check_actived_pool(pool_name)
            pool_detail = libvirt_xml.PoolXML.get_pool_details(pool_name)
            logging.debug("Pool detail: %s", pool_detail)
            if pool_detail['uuid'] == old_uuid:
                test.fail("New created pool still use the old UUID %s"
                          % old_uuid)
        else:
            if status == 0:
                test.fail("Expect fail, but run successfully.")
            else:
                logging.debug("Command fail as expected")
    finally:
        pvt.cleanup_pool(**params)
        if new_device_name:
            utlv.setup_or_cleanup_iscsi(False)
        if os.path.exists(pool_xml_f):
            os.remove(pool_xml_f)
Exemplo n.º 6
0
            else:
                # The transient pool will gone after destroyed
                virsh.pool_destroy(pool_name)
            new_source_format = params.get("new_pool_src_format")
            if new_source_format:
                cmd = "sed -i s/type=\\\'%s\\\'/type=\\\'%s\\\'/g %s" % (
                    source_format, new_source_format, pool_xml_f)
                utils.run(cmd)
        except Exception, e:
            pvt.cleanup_pool(pool_name, pool_type, pool_target,
                             emulated_image, **kwargs)
            raise error.TestError("Error occurred when prepare pool xml:\n %s"
                                  % e)
    # Create an invalid pool xml file
    if pool_xml_f == "invalid-pool-xml":
        tmp_xml_f = xml_utils.TempXMLFile()
        tmp_xml_f.write('"<pool><<<BAD>>><\'XML</name\>'
                        '!@#$%^&*)>(}>}{CORRUPTE|>!</pool>')
        tmp_xml_f.flush()
        pool_xml_f = tmp_xml_f.name

    # Readonly mode
    ro_flag = False
    if readonly_mode:
        logging.debug("Readonly mode test")
        ro_flag = True

    # Run virsh test
    if os.path.exists(pool_xml_f):
        f = open(pool_xml_f, 'r')
        try: