Esempio n. 1
0
def setup_or_cleanup_iscsi(is_setup, is_login=True,
                           emulated_image="emulated_iscsi", image_size="1G"):
    """
    Set up(and login iscsi target) or clean up iscsi service on localhost.

    :param is_setup: Boolean value, true for setup, false for cleanup
    :param is_login: Boolean value, true for login, false for not login
    :param emulated_image: name of iscsi device
    :param image_size: emulated image's size
    :return: iscsi device name or iscsi target
    """
    try:
        utils_misc.find_command("tgtadm")
        utils_misc.find_command("iscsiadm")
    except ValueError:
        raise error.TestNAError("Missing command 'tgtadm' and/or 'iscsiadm'.")

    tmpdir = os.path.join(data_dir.get_root_dir(), 'tmp')
    emulated_path = os.path.join(tmpdir, emulated_image)
    emulated_target = "iqn.2001-01.com.virttest:%s.target" % emulated_image
    iscsi_params = {"emulated_image": emulated_path, "target": emulated_target,
                    "image_size": image_size, "iscsi_thread_id": "virt"}
    _iscsi = iscsi.Iscsi(iscsi_params)
    if is_setup:
        sv_status = None
        if utils_selinux.is_enforcing():
            sv_status = utils_selinux.get_status()
            utils_selinux.set_status("permissive")
        _iscsi.export_target()
        if sv_status is not None:
            utils_selinux.set_status(sv_status)
        if is_login:
            _iscsi.login()
            # The device doesn't necessarily appear instantaneously, so give
            # about 5 seconds for it to appear before giving up
            iscsi_device = utils_misc.wait_for(_iscsi.get_device_name, 5, 0, 1,
                                               "Searching iscsi device name.")
            if iscsi_device:
                logging.debug("iscsi device: %s", iscsi_device)
                return iscsi_device
            if not iscsi_device:
                logging.error("Not find iscsi device.")
            # Cleanup and return "" - caller needs to handle that
            # _iscsi.export_target() will have set the emulated_id and
            # export_flag already on success...
            _iscsi.cleanup()
            utils.run("rm -f %s" % emulated_path)
        else:
            return emulated_target
    else:
        _iscsi.export_flag = True
        _iscsi.emulated_id = _iscsi.get_target_id()
        _iscsi.cleanup()
        utils.run("rm -f %s" % emulated_path)
    return ""
Esempio n. 2
0
    def __init__(self, test, params):
        self.vm_name = params.get("vm_name", "test-vm1")
        while virsh.domain_exists(self.vm_name):
            self.vm_name += ".test"
        params["main_vm"] = self.vm_name
        ios_file = os.path.join(data_dir.get_data_dir(),
                                params.get('cdrom_cd1'))
        if not os.path.exists(ios_file):
            raise error.TestNAError("Please prepare ios file:%s" % ios_file)
        self.env = params.get('env')
        self.vm = self.env.create_vm("libvirt", None, self.vm_name, params,
                                     test.bindir)
        self.env.register_vm(self.vm_name, self.vm)
        self.twice_execute = "yes" == params.get("twice_execute", "no")
        self.kill_first = "yes" == params.get("kill_first", "no")
        self.read_only = "yes" == params.get("read_only", "no")
        self.selinux_enforcing = utils_selinux.is_enforcing()
        if self.selinux_enforcing:
            utils_selinux.set_status("permissive")
        self.image_path = os.path.join(test.virtdir, "test_image")
        if not os.path.exists(self.image_path):
            os.mkdir(self.image_path)
        if self.read_only:
            os.chmod(self.image_path,
                     stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
        params["image_name"] = os.path.join(self.image_path, self.vm_name)
        params["image_format"] = "raw"
        params['force_create_image'] = "yes"
        params['remove_image'] = "yes"
        params['shutdown_cleanly'] = "yes"
        params['shutdown_cleanly_timeout'] = 120
        params['guest_port_unattended_install'] = 12323
        params['inactivity_watcher'] = "error"
        params['inactivity_treshold'] = 1800
        params['image_verify_bootable'] = "no"
        params['unattended_delivery_method'] = "cdrom"
        params['drive_index_unattended'] = 1
        params['drive_index_cd1'] = 2
        params['boot_once'] = "d"
        params['medium'] = "cdrom"
        params['wait_no_ack'] = "yes"
        params['image_raw_device'] = "yes"
        params['backup_image_before_testing'] = "no"
        params['kernel_params'] = ("ks=cdrom nicdelay=60 "
                                   "console=ttyS0,115200 console=tty0")
        params['cdroms'] += " unattended"
        params['redirs'] += " unattended_install"

        self.params = params
        self.test = test
    def __init__(self, test, params):
        self.vm_name = params.get("vm_name", "test-vm1")
        self.test = test
        while virsh.domain_exists(self.vm_name):
            self.vm_name += ".test"
        params["main_vm"] = self.vm_name
        ios_file = os.path.join(data_dir.get_data_dir(),
                                params.get('cdrom_cd1'))
        if not os.path.exists(ios_file):
            self.test.cancel("Please prepare ios file:%s" % ios_file)
        self.env = params.get('env')
        self.vm = self.env.create_vm("libvirt", None, self.vm_name, params,
                                     test.bindir)
        self.env.register_vm(self.vm_name, self.vm)
        self.twice_execute = "yes" == params.get("twice_execute", "no")
        self.kill_first = "yes" == params.get("kill_first", "no")
        self.read_only = "yes" == params.get("read_only", "no")
        self.selinux_enforcing = utils_selinux.is_enforcing()
        if self.selinux_enforcing:
            utils_selinux.set_status("permissive")
        self.image_path = os.path.join(test.virtdir, "test_image")
        if not os.path.exists(self.image_path):
            os.mkdir(self.image_path)
        if self.read_only:
            os.chmod(self.image_path,
                     stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
        params["image_name"] = os.path.join(self.image_path, self.vm_name)
        params["image_format"] = "raw"
        params['force_create_image'] = "yes"
        params['remove_image'] = "yes"
        params['shutdown_cleanly'] = "yes"
        params['shutdown_cleanly_timeout'] = 120
        params['guest_port_unattended_install'] = 12323
        params['inactivity_watcher'] = "error"
        params['inactivity_treshold'] = 1800
        params['image_verify_bootable'] = "no"
        params['unattended_delivery_method'] = "cdrom"
        params['drive_index_unattended'] = 1
        params['drive_index_cd1'] = 2
        params['boot_once'] = "d"
        params['medium'] = "cdrom"
        params['wait_no_ack'] = "yes"
        params['image_raw_device'] = "yes"
        params['backup_image_before_testing'] = "no"
        params['kernel_params'] = ("ks=cdrom nicdelay=60 "
                                   "console=ttyS0,115200 console=tty0")
        params['cdroms'] += " unattended"
        params['redirs'] += " unattended_install"

        self.params = params
 def __init__(self, test, params):
     self.td = None
     self.cpu_num = int(params.get("cpu_num", "1"))
     self.vm_name = params.get("main_vm")
     self.vm_new_name = params.get("vm_new_name")
     self.cgroup_name = params.get("cgroup_name")
     self.cgroup_dir = params.get("cgroup_dir")
     self.new_image_file = params.get("new_image_file")
     if self.new_image_file:
         self.new_image_file = os.path.join(test.virtdir,
                                            self.new_image_file)
     self.time_out = int(params.get("time_out", "600"))
     self.cpu_status = utils_misc.get_cpu_status(self.cpu_num)
     self.twice_execute = "yes" == params.get("twice_execute", "no")
     self.kill_first = "yes" == params.get("kill_first", "no")
     if params.get("abnormal_type") in ["disk_lack", ""]:
         self.selinux_enforcing = utils_selinux.is_enforcing()
         if self.selinux_enforcing:
             utils_selinux.set_status("permissive")
         self.fs_type = params.get("fs_type", "ext4")
         xml_file = vm_xml.VMXML.new_from_inactive_dumpxml(self.vm_name)
         disk_node = xml_file.get_disk_all()['vda']
         source_file = disk_node.find('source').get('file')
         self.image_size = utils_misc.get_image_info(source_file)['dsize']
         # Set the size to be image_size
         iscsi_size = "%sM" % (self.image_size / 1024 / 1024)
         params['image_size'] = iscsi_size
         self.iscsi_dev = qemu_storage.Iscsidev(params, test.virtdir,
                                                "iscsi")
         try:
             device_source = self.iscsi_dev.setup()
         except (exceptions.TestError, ValueError) as detail:
             self.iscsi_dev.cleanup()
             self.test.cancel("Cannot get iscsi device on this"
                              " host:%s\n" % detail)
         libvirt.mk_label(device_source)
         libvirt.mk_part(device_source, iscsi_size)
         self.mount_dir = os.path.join(test.virtdir,
                                       params.get('mount_dir'))
         if not os.path.exists(self.mount_dir):
             os.mkdir(self.mount_dir)
         params['mount_dir'] = self.mount_dir
         self.partition = device_source + "1"
         libvirt.mkfs(self.partition, self.fs_type)
         utils_misc.mount(self.partition, self.mount_dir, self.fs_type)
         self.new_image_file = os.path.join(self.mount_dir, "new_file")
Esempio n. 5
0
 def __init__(self, test, params):
     self.td = None
     self.cpu_num = int(params.get("cpu_num", "1"))
     self.vm_name = params.get("main_vm")
     self.vm_new_name = params.get("vm_new_name")
     self.cgroup_name = params.get("cgroup_name")
     self.cgroup_dir = params.get("cgroup_dir")
     self.new_image_file = params.get("new_image_file")
     if self.new_image_file:
         self.new_image_file = os.path.join(test.virtdir,
                                            self.new_image_file)
     self.time_out = int(params.get("time_out", "600"))
     self.cpu_status = utils_misc.get_cpu_status(self.cpu_num)
     self.twice_execute = "yes" == params.get("twice_execute", "no")
     self.kill_first = "yes" == params.get("kill_first", "no")
     if params.get("abnormal_type") in ["disk_lack", ""]:
         self.selinux_enforcing = utils_selinux.is_enforcing()
         if self.selinux_enforcing:
             utils_selinux.set_status("permissive")
         self.fs_type = params.get("fs_type", "ext4")
         xml_file = vm_xml.VMXML.new_from_inactive_dumpxml(self.vm_name)
         disk_node = xml_file.get_disk_all()['vda']
         source_file = disk_node.find('source').get('file')
         self.image_size = utils_misc.get_image_info(source_file)['dsize']
         # Set the size to be image_size
         iscsi_size = "%sM" % (self.image_size / 1024 / 1024)
         params['image_size'] = iscsi_size
         self.iscsi_dev = qemu_storage.Iscsidev(params, test.virtdir,
                                                "iscsi")
         try:
             device_source = self.iscsi_dev.setup()
         except (exceptions.TestError, ValueError) as detail:
             self.iscsi_dev.cleanup()
             self.test.cancel("Cannot get iscsi device on this"
                              " host:%s\n" % detail)
         libvirt.mk_label(device_source)
         libvirt.mk_part(device_source, iscsi_size)
         self.mount_dir = os.path.join(test.virtdir,
                                       params.get('mount_dir'))
         if not os.path.exists(self.mount_dir):
             os.mkdir(self.mount_dir)
         params['mount_dir'] = self.mount_dir
         self.partition = device_source + "1"
         libvirt.mkfs(self.partition, self.fs_type)
         utils_misc.mount(self.partition, self.mount_dir, self.fs_type)
         self.new_image_file = os.path.join(self.mount_dir, "new_file")
Esempio n. 6
0
def setup_or_cleanup_nfs(is_setup,
                         mount_dir="",
                         is_mount=False,
                         export_options="rw,no_root_squash",
                         mount_src="nfs-export"):
    """
    Set up or clean up nfs service on localhost.

    :param is_setup: Boolean value, true for setup, false for cleanup
    :param mount_dir: NFS mount point
    :param is_mount: Boolean value, true for mount, false for umount
    :param export_options: options for nfs dir
    :return: export nfs path or nothing
    """
    tmpdir = os.path.join(data_dir.get_root_dir(), 'tmp')
    if not os.path.isabs(mount_src):
        mount_src = os.path.join(tmpdir, mount_src)
    if not mount_dir:
        mount_dir = os.path.join(tmpdir, 'nfs-mount')

    nfs_params = {
        "nfs_mount_dir": mount_dir,
        "nfs_mount_options": "rw",
        "nfs_mount_src": mount_src,
        "setup_local_nfs": "yes",
        "export_options": "rw,no_root_squash"
    }
    _nfs = nfs.Nfs(nfs_params)
    # Set selinux to permissive that the file in nfs
    # can be used freely
    if utils_selinux.is_enforcing():
        sv_status = utils_selinux.get_status()
        utils_selinux.set_status("permissive")
    if is_setup:
        _nfs.setup()
        if not is_mount:
            _nfs.umount()
        return mount_src
    else:
        _nfs.unexportfs_in_clean = True
        _nfs.cleanup()
        return ""
Esempio n. 7
0
def setup_or_cleanup_nfs(is_setup, mount_dir="", is_mount=False,
                         export_options="rw,no_root_squash",
                         mount_src="nfs-export"):
    """
    Set up or clean up nfs service on localhost.

    :param is_setup: Boolean value, true for setup, false for cleanup
    :param mount_dir: NFS mount point
    :param is_mount: Boolean value, true for mount, false for umount
    :param export_options: options for nfs dir
    :return: export nfs path or nothing
    """
    tmpdir = os.path.join(data_dir.get_root_dir(), 'tmp')
    if not os.path.isabs(mount_src):
        mount_src = os.path.join(tmpdir, mount_src)
    if not mount_dir:
        mount_dir = os.path.join(tmpdir, 'nfs-mount')

    nfs_params = {"nfs_mount_dir": mount_dir, "nfs_mount_options": "rw",
                  "nfs_mount_src": mount_src, "setup_local_nfs": "yes",
                  "export_options": "rw,no_root_squash"}
    _nfs = nfs.Nfs(nfs_params)
    # Set selinux to permissive that the file in nfs
    # can be used freely
    if utils_selinux.is_enforcing():
        sv_status = utils_selinux.get_status()
        utils_selinux.set_status("permissive")
    if is_setup:
        _nfs.setup()
        if not is_mount:
            _nfs.umount()
        return mount_src
    else:
        _nfs.unexportfs_in_clean = True
        _nfs.cleanup()
        return ""
Esempio n. 8
0
    def export_target(self):
        """
        Export target in localhost for emulated iscsi
        """
        selinux_mode = None

        # create image disk
        if not os.path.isfile(self.emulated_image):
            process.system(self.create_cmd)
        else:
            emulated_image_size = os.path.getsize(self.emulated_image) // 1024
            if emulated_image_size != self.emulated_expect_size:
                # No need to remvoe, rebuild is fine
                process.system(self.create_cmd)

        # confirm if the target exists and create iSCSI target
        cmd = "targetcli ls /iscsi 1"
        output = decode_to_text(process.system_output(cmd))
        if not re.findall("%s$" % self.target, output, re.M):
            logging.debug("Need to export target in host")

            # Set selinux to permissive mode to make sure
            # iscsi target export successfully
            if utils_selinux.is_enforcing():
                selinux_mode = utils_selinux.get_status()
                utils_selinux.set_status("permissive")

            # In fact, We've got two options here
            #
            # 1) Create a block backstore that usually provides the best
            #    performance. We can use a block device like /dev/sdb or
            #    a logical volume previously created,
            #     (lvcreate -name lv_iscsi -size 1G vg)
            # 2) Create a fileio backstore,
            #    which enables the local file system cache.
            #
            # This class Only works for emulated iscsi device,
            # So fileio backstore is enough and safe.

            # Create a fileio backstore
            device_cmd = ("targetcli /backstores/fileio/ create %s %s" %
                          (self.device, self.emulated_image))
            output = decode_to_text(process.system_output(device_cmd))
            if "Created fileio" not in output:
                raise exceptions.TestFail("Failed to create fileio %s. (%s)" %
                                          (self.device, output))

            # Create an IQN with a target named target_name
            target_cmd = "targetcli /iscsi/ create %s" % self.target
            output = decode_to_text(process.system_output(target_cmd))
            if "Created target" not in output:
                raise exceptions.TestFail("Failed to create target %s. (%s)" %
                                          (self.target, output))

            check_portal = "targetcli /iscsi/%s/tpg1/portals ls" % self.target
            portal_info = decode_to_text(process.system_output(check_portal))
            if "0.0.0.0:3260" not in portal_info:
                # Create portal
                # 0.0.0.0 means binding to INADDR_ANY
                # and using default IP port 3260
                portal_cmd = ("targetcli /iscsi/%s/tpg1/portals/ create %s" %
                              (self.target, "0.0.0.0"))
                output = decode_to_text(process.system_output(portal_cmd))
                if "Created network portal" not in output:
                    raise exceptions.TestFail("Failed to create portal. (%s)" %
                                              output)
            if ("ipv6" == utils_net.IPAddress(self.portal_ip).version
                    and self.portal_ip not in portal_info):
                # Ipv6 portal address can't be created by default,
                # create ipv6 portal if needed.
                portal_cmd = ("targetcli /iscsi/%s/tpg1/portals/ create %s" %
                              (self.target, self.portal_ip))
                output = decode_to_text(process.system_output(portal_cmd))
                if "Created network portal" not in output:
                    raise exceptions.TestFail("Failed to create portal. (%s)" %
                                              output)
            # Create lun
            lun_cmd = "targetcli /iscsi/%s/tpg1/luns/ " % self.target
            dev_cmd = "create /backstores/fileio/%s" % self.device
            output = decode_to_text(process.system_output(lun_cmd + dev_cmd))
            luns = re.findall(r"Created LUN (\d+).", output)
            if not luns:
                raise exceptions.TestFail("Failed to create lun. (%s)" %
                                          output)
            self.luns = luns[0]

            # Set firewall if it's enabled
            output = decode_to_text(
                process.system_output("firewall-cmd --state",
                                      ignore_status=True))
            if re.findall("^running", output, re.M):
                # firewall is running
                process.system("firewall-cmd --permanent --add-port=3260/tcp")
                process.system("firewall-cmd --reload")

            # Restore selinux
            if selinux_mode is not None:
                utils_selinux.set_status(selinux_mode)

            self.export_flag = True
        else:
            logging.info("Target %s has already existed!" % self.target)

        if self.chap_flag:
            # Set CHAP authentication on the exported target
            self.set_chap_auth_target()
            # Set CHAP authentication for initiator to login target
            if self.portal_visible():
                self.set_chap_auth_initiator()
        else:
            # To enable that so-called "demo mode" TPG operation,
            # disable all authentication for the corresponding Endpoint.
            # which means grant access to all initiators,
            # so that they can access all LUNs in the TPG
            # without further authentication.
            auth_cmd = "targetcli /iscsi/%s/tpg1/ " % self.target
            attr_cmd = ("set attribute %s %s %s %s" %
                        ("authentication=0", "demo_mode_write_protect=0",
                         "generate_node_acls=1", "cache_dynamic_acls=1"))
            output = decode_to_text(process.system_output(auth_cmd + attr_cmd))
            logging.info("Define access rights: %s" % output)
            # Discovery the target
            self.portal_visible()

        # Save configuration
        process.system("targetcli / saveconfig")

        # Restart iSCSI service
        restart_iscsid()
Esempio n. 9
0
    def export_target(self):
        """
        Export target in localhost for emulated iscsi
        """
        selinux_mode = None

        if not os.path.isfile(self.emulated_image):
            process.system(self.create_cmd)
        else:
            emulated_image_size = os.path.getsize(self.emulated_image) // 1024
            if emulated_image_size != self.emulated_expect_size:
                # No need to remvoe, rebuild is fine
                process.system(self.create_cmd)
        cmd = "tgtadm --lld iscsi --mode target --op show"
        try:
            output = decode_to_text(process.system_output(cmd))
        except process.CmdError:
            restart_tgtd()
            output = decode_to_text(process.system_output(cmd))
        if not re.findall("%s$" % self.target, output, re.M):
            logging.debug("Need to export target in host")

            # Set selinux to permissive mode to make sure iscsi target
            # export successfully
            if utils_selinux.is_enforcing():
                selinux_mode = utils_selinux.get_status()
                utils_selinux.set_status("permissive")

            output = decode_to_text(process.system_output(cmd))
            used_id = re.findall("Target\s+(\d+)", output)
            emulated_id = 1
            while str(emulated_id) in used_id:
                emulated_id += 1
            self.emulated_id = str(emulated_id)
            cmd = "tgtadm --mode target --op new --tid %s" % self.emulated_id
            cmd += " --lld iscsi --targetname %s" % self.target
            process.system(cmd)
            cmd = "tgtadm --lld iscsi --op bind --mode target "
            cmd += "--tid %s -I ALL" % self.emulated_id
            process.system(cmd)
        else:
            target_strs = re.findall("Target\s+(\d+):\s+%s$" % self.target,
                                     output, re.M)
            self.emulated_id = target_strs[0].split(':')[0].split()[-1]

        cmd = "tgtadm --lld iscsi --mode target --op show"
        try:
            output = decode_to_text(process.system_output(cmd))
        except process.CmdError:  # In case service stopped
            restart_tgtd()
            output = decode_to_text(process.system_output(cmd))

        # Create a LUN with emulated image
        if re.findall(self.emulated_image, output, re.M):
            # Exist already
            logging.debug("Exported image already exists.")
            self.export_flag = True
        else:
            tgt_str = re.search(r'.*(Target\s+\d+:\s+%s\s*.*)$' % self.target,
                                output, re.DOTALL)
            if tgt_str:
                luns = len(re.findall("\s+LUN:\s(\d+)", tgt_str.group(1),
                                      re.M))
            else:
                luns = len(re.findall("\s+LUN:\s(\d+)", output, re.M))
            cmd = "tgtadm --mode logicalunit --op new "
            cmd += "--tid %s --lld iscsi " % self.emulated_id
            cmd += "--lun %s " % luns
            cmd += "--backing-store %s" % self.emulated_image
            process.system(cmd)
            self.export_flag = True
            self.luns = luns

        # Restore selinux
        if selinux_mode is not None:
            utils_selinux.set_status(selinux_mode)

        if self.chap_flag:
            # Set CHAP authentication on the exported target
            self.set_chap_auth_target()
            # Set CHAP authentication for initiator to login target
            if self.portal_visible():
                self.set_chap_auth_initiator()
Esempio n. 10
0
    def export_target(self):
        """
        Export target in localhost for emulated iscsi
        """
        selinux_mode = None

        if not os.path.isfile(self.emulated_image):
            utils.system(self.create_cmd)
        else:
            emulated_image_size = os.path.getsize(self.emulated_image) / 1024
            if emulated_image_size != self.emulated_expect_size:
                # No need to remvoe, rebuild is fine
                utils.system(self.create_cmd)
        cmd = "tgtadm --lld iscsi --mode target --op show"
        try:
            output = utils.system_output(cmd)
        except error.CmdError:
            utils.system("service tgtd restart")
            output = utils.system_output(cmd)
        if not re.findall("%s$" % self.target, output, re.M):
            logging.debug("Need to export target in host")

            # Set selinux to permissive mode to make sure iscsi target
            # export successfully
            if utils_selinux.is_enforcing():
                selinux_mode = utils_selinux.get_status()
                utils_selinux.set_status("permissive")

            output = utils.system_output(cmd)
            used_id = re.findall("Target\s+(\d+)", output)
            emulated_id = 1
            while str(emulated_id) in used_id:
                emulated_id += 1
            self.emulated_id = str(emulated_id)
            cmd = "tgtadm --mode target --op new --tid %s" % self.emulated_id
            cmd += " --lld iscsi --targetname %s" % self.target
            utils.system(cmd)
            cmd = "tgtadm --lld iscsi --op bind --mode target "
            cmd += "--tid %s -I ALL" % self.emulated_id
            utils.system(cmd)
        else:
            target_strs = re.findall("Target\s+(\d+):\s+%s$" %
                                     self.target, output, re.M)
            self.emulated_id = target_strs[0].split(':')[0].split()[-1]

        cmd = "tgtadm --lld iscsi --mode target --op show"
        try:
            output = utils.system_output(cmd)
        except error.CmdError:   # In case service stopped
            utils.system("service tgtd restart")
            output = utils.system_output(cmd)

        # Create a LUN with emulated image
        if re.findall(self.emulated_image, output, re.M):
            # Exist already
            logging.debug("Exported image already exists.")
            self.export_flag = True
        else:
            tgt_str = re.search(r'.*(Target\s+\d+:\s+%s\s*.*)$' % self.target,
                                output, re.DOTALL)
            if tgt_str:
                luns = len(re.findall("\s+LUN:\s(\d+)",
                                      tgt_str.group(1), re.M))
            else:
                luns = len(re.findall("\s+LUN:\s(\d+)", output, re.M))
            cmd = "tgtadm --mode logicalunit --op new "
            cmd += "--tid %s --lld iscsi " % self.emulated_id
            cmd += "--lun %s " % luns
            cmd += "--backing-store %s" % self.emulated_image
            utils.system(cmd)
            self.export_flag = True

        # Restore selinux
        if selinux_mode is not None:
            utils_selinux.set_status(selinux_mode)

        if self.chap_flag:
            # Set CHAP authentication on the exported target
            self.set_chap_auth_target()
            # Set CHAP authentication for initiator to login target
            if self.portal_visible():
                self.set_chap_auth_initiator()
Esempio n. 11
0
    def export_target(self):
        """
        Export target in localhost for emulated iscsi
        """
        selinux_mode = None

        # create image disk
        if not os.path.isfile(self.emulated_image):
            utils.system(self.create_cmd)
        else:
            emulated_image_size = os.path.getsize(self.emulated_image) / 1024
            if emulated_image_size != self.emulated_expect_size:
                # No need to remvoe, rebuild is fine
                utils.system(self.create_cmd)

        # confirm if the target exists and create iSCSI target
        cmd = "targetcli ls /iscsi 1"
        output = utils.system_output(cmd)
        if not re.findall("%s$" % self.target, output, re.M):
            logging.debug("Need to export target in host")

            # Set selinux to permissive mode to make sure
            # iscsi target export successfully
            if utils_selinux.is_enforcing():
                selinux_mode = utils_selinux.get_status()
                utils_selinux.set_status("permissive")

            # In fact, We've got two options here
            #
            # 1) Create a block backstore that usually provides the best
            #    performance. We can use a block device like /dev/sdb or
            #    a logical volume previously created,
            #     (lvcreate -name lv_iscsi -size 1G vg)
            # 2) Create a fileio backstore,
            #    which enables the local file system cache.
            #
            # This class Only works for emulated iscsi device,
            # So fileio backstore is enough and safe.

            # Create a fileio backstore
            device_cmd = ("targetcli /backstores/fileio/ create %s %s" %
                          (self.device, self.emulated_image))
            output = utils.system_output(device_cmd)
            if "Created fileio" not in output:
                raise error.TestFail("Failed to create fileio %s. (%s)",
                                     self.device, output)

            # Create an IQN with a target named target_name
            target_cmd = "targetcli /iscsi/ create %s" % self.target
            output = utils.system_output(target_cmd)
            if "Created target" not in output:
                raise error.TestFail("Failed to create target %s. (%s)",
                                     self.target, output)

            check_portal = "targetcli /iscsi/%s/tpg1/portals ls" % self.target
            if "0.0.0.0:3260" not in utils.system_output(check_portal):
                # Create portal
                # 0.0.0.0 means binding to INADDR_ANY
                # and using default IP port 3260
                portal_cmd = ("targetcli /iscsi/%s/tpg1/portals/ create %s"
                              % (self.target, "0.0.0.0"))
                output = utils.system_output(portal_cmd)
                if "Created network portal" not in output:
                    raise error.TestFail("Failed to create portal. (%s)",
                                         output)

            # Create lun
            lun_cmd = "targetcli /iscsi/%s/tpg1/luns/ " % self.target
            dev_cmd = "create /backstores/fileio/%s" % self.device
            output = utils.system_output(lun_cmd + dev_cmd)
            if "Created LUN" not in output:
                raise error.TestFail("Failed to create lun. (%s)",
                                     output)

            # Set firewall if it's enabled
            output = utils.system_output("firewall-cmd --state",
                                         ignore_status=True)
            if re.findall("^running", output, re.M):
                # firewall is running
                utils.system("firewall-cmd --permanent --add-port=3260/tcp")
                utils.system("firewall-cmd --reload")

            # Restore selinux
            if selinux_mode is not None:
                utils_selinux.set_status(selinux_mode)

            self.export_flag = True
        else:
            logging.info("Target %s has already existed!" % self.target)

        if self.chap_flag:
            # Set CHAP authentication on the exported target
            self.set_chap_auth_target()
            # Set CHAP authentication for initiator to login target
            if self.portal_visible():
                self.set_chap_auth_initiator()
        else:
            # To enable that so-called "demo mode" TPG operation,
            # disable all authentication for the corresponding Endpoint.
            # which means grant access to all initiators,
            # so that they can access all LUNs in the TPG
            # without further authentication.
            auth_cmd = "targetcli /iscsi/%s/tpg1/ " % self.target
            attr_cmd = ("set attribute %s %s %s %s" %
                        ("authentication=0",
                         "demo_mode_write_protect=0",
                         "generate_node_acls=1",
                         "cache_dynamic_acls=1"))
            output = utils.system_output(auth_cmd + attr_cmd)
            logging.info("Define access rights: %s" % output)

        # Save configuration
        utils.system("targetcli / saveconfig")
Esempio n. 12
0
def setup_or_cleanup_iscsi(is_setup,
                           is_login=True,
                           emulated_image="emulated_iscsi",
                           image_size="1G"):
    """
    Set up(and login iscsi target) or clean up iscsi service on localhost.

    :param is_setup: Boolean value, true for setup, false for cleanup
    :param is_login: Boolean value, true for login, false for not login
    :param emulated_image: name of iscsi device
    :param image_size: emulated image's size
    :return: iscsi device name or iscsi target
    """
    try:
        utils_misc.find_command("tgtadm")
        utils_misc.find_command("iscsiadm")
    except ValueError:
        raise error.TestNAError("Missing command 'tgtadm' and/or 'iscsiadm'.")

    tmpdir = os.path.join(data_dir.get_root_dir(), 'tmp')
    emulated_path = os.path.join(tmpdir, emulated_image)
    emulated_target = "iqn.2001-01.com.virttest:%s.target" % emulated_image
    iscsi_params = {
        "emulated_image": emulated_path,
        "target": emulated_target,
        "image_size": image_size,
        "iscsi_thread_id": "virt"
    }
    _iscsi = iscsi.Iscsi(iscsi_params)
    if is_setup:
        sv_status = None
        if utils_selinux.is_enforcing():
            sv_status = utils_selinux.get_status()
            utils_selinux.set_status("permissive")
        _iscsi.export_target()
        if sv_status is not None:
            utils_selinux.set_status(sv_status)
        if is_login:
            _iscsi.login()
            # The device doesn't necessarily appear instantaneously, so give
            # about 5 seconds for it to appear before giving up
            iscsi_device = utils_misc.wait_for(_iscsi.get_device_name, 5, 0, 1,
                                               "Searching iscsi device name.")
            if iscsi_device:
                logging.debug("iscsi device: %s", iscsi_device)
                return iscsi_device
            if not iscsi_device:
                logging.error("Not find iscsi device.")
            # Cleanup and return "" - caller needs to handle that
            # _iscsi.export_target() will have set the emulated_id and
            # export_flag already on success...
            _iscsi.cleanup()
            utils.run("rm -f %s" % emulated_path)
        else:
            return emulated_target
    else:
        _iscsi.export_flag = True
        _iscsi.emulated_id = _iscsi.get_target_id()
        _iscsi.cleanup()
        utils.run("rm -f %s" % emulated_path)
    return ""