コード例 #1
0
ファイル: initiatormgr.py プロジェクト: OpenSight/StorLever
    def discovery(self, portal, iface_name=None):
        # delete the config for this dicovery
        try:
            check_output([ISCSIADM_CMD, "-m", "discoverydb", "-t", "st",
                          "-p", portal, "-o", "delete"])
        except StorLeverError:
            pass

        # discovery process
        cmd = [ISCSIADM_CMD, "-m", "discovery", "-t", "st", "-p", portal]
        if iface_name is not None:
            cmd.append("-I")
            cmd.append(iface_name)

        outlines = check_output(cmd, input_ret=[2, 6, 7, 21, 22]).splitlines()

        result = []
        for line in outlines:
            line_list = line.split()
            target = line_list[1]
            portal, sep, tag = line_list[0].partition(",")
            result.append({
                "portal": portal,
                "target": target
            })

        return result
コード例 #2
0
ファイル: scsimgr.py プロジェクト: linuxmap/StorLever
    def get_smart_info(self):
        if self.dev_file == "":
            raise StorLeverError(
                "scsi_id (%s) has not be recognized" % self.scsi_id, 400)
        output = check_output(
            [SMARTCTL_CMD, "-i", "-T", "verypermissive", self.dev_file])
        smart_enabled = False
        auto_offline_enabled = False
        if "SMART support is: Enabled" in output:
            smart_enabled = True
            output = check_output(
                [SMARTCTL_CMD, "-a", "-T", "verypermissive", self.dev_file])

            if "Auto Offline Data Collection: Enabled" in output:
                auto_offline_enabled = True

        # filter the copyright
        lines = output.splitlines()
        for index, line in enumerate(lines):
            if line == "":
                break
        else:
            index = 0
        detail = "\n".join(lines[index + 1:])

        info = {
            "smart_enabled": smart_enabled,
            "auto_offline_enabled": auto_offline_enabled,
            "detail": detail
        }
        return info
コード例 #3
0
ファイル: fs.py プロジェクト: linuxmap/StorLever
    def quota_group_set(self,
                        group,
                        block_softlimit=0,
                        block_hardlimit=0,
                        inode_softlimit=0,
                        inode_hardlimit=0,
                        operator="unknown"):
        if not self.is_available():
            raise StorLeverError("File system is unavailable", 500)
        setquota_agrs = [
            SETQUOTA_BIN, "-g", group,
            str(block_softlimit),
            str(block_hardlimit),
            str(inode_softlimit),
            str(inode_hardlimit), self.fs_conf["mount_point"]
        ]
        check_output(setquota_agrs)

        logger.log(
            logging.INFO, logger.LOG_TYPE_CONFIG,
            "File System(%s) quota for group(%s) is changed to "
            "(%d,%d,%d,%d)"
            " by user(%s)" %
            (self.name, group, block_softlimit, block_hardlimit,
             inode_softlimit, inode_hardlimit, operator))
コード例 #4
0
ファイル: nfs.py プロジェクト: OpenSight/StorLever
 def _is_nfs_service_available(ip, mount_options):
     proto = Nfs._get_nfs_transport_proto(mount_options)
     if proto == "":  # detect automatically
         cmd = [RPCINFO_CMD, "-s", ip]
         try:
             result = check_output(cmd)
             if "nfs" in result:
                 return True
         except StorLeverCmdError as e:
             if e.return_code == 1:
                 pass
             else:
                 raise
     else:
         if proto == "udp":
             cmd = [RPCINFO_CMD, "-u", ip, "nfs"]
         elif proto == "tcp":
             cmd = [RPCINFO_CMD, "-t", ip, "nfs"]
         try:
             result = check_output(cmd)
             return True
         except StorLeverCmdError as e:
             if e.return_code == 1:
                 pass
             else:
                 raise
     return False
コード例 #5
0
ファイル: servicemgr.py プロジェクト: linuxmap/StorLever
 def disable_auto_start(self, user="******"):
     check_output(
         [CHKCONFIG, "--level", SET_CHK_LEVEL, self.init_script, "off"])
     logger.log(
         logging.INFO, logger.LOG_TYPE_CONFIG,
         "Service %s auto start is disabled by user(%s)" %
         (self.name, user))
コード例 #6
0
ファイル: sysinfo.py プロジェクト: OpenSight/StorLever
    def set_selinux_state(self, state, user="******"):
        state_str_to_int = {
            "enforcing": 1,
            "permissive": 0,
            "disabled": 0
        }
        param = state_str_to_int.get(state)
        if param is not None:
            old_state = check_output(["/usr/sbin/getenforce"]).lower().strip()
            if old_state != "disabled":
                check_output(["/usr/sbin/setenforce", str(param)])

        if not os.path.exists(SELINUX_CONF_DIR):
            os.makedirs(SELINUX_CONF_DIR)
        conf_path = os.path.join(SELINUX_CONF_DIR, SELINUX_CONF_FILE)
        conf = properties()
        conf.delete("SELINUX")
        conf.apply_to(conf_path)
        with open(conf_path, "r") as f:
            content = f.read()
        if content.endswith("\n") or len(content) == 0:
            content += "SELINUX=%s\n" % state
        else:
            content += "\nSELINUX=%s\n" % state
        with open(conf_path, "w") as f:
            f.write(content)

        logger.log(logging.INFO, logger.LOG_TYPE_CONFIG,
                   "selinux state is set to %s by user(%s)" %
                   (state, user))
コード例 #7
0
ファイル: scsimgr.py プロジェクト: linuxmap/StorLever
    def set_smart_config(self, smart_enabled=None, auto_offline_enabled=None):

        if self.dev_file == "":
            raise StorLeverError(
                "scsi_id (%s) has not be recognized" % self.scsi_id, 400)

        if smart_enabled is not None:
            if smart_enabled:
                param = "on"
            else:
                param = "off"
            out = check_output([
                SMARTCTL_CMD, "-s", param, "-T", "verypermissive",
                self.dev_file
            ])

        if auto_offline_enabled is not None:
            if auto_offline_enabled:
                param = "on"
            else:
                param = "off"
            out = check_output([
                SMARTCTL_CMD, "-o", param, "-T", "verypermissive",
                self.dev_file
            ])
コード例 #8
0
ファイル: modulemgr.py プロジェクト: linuxmap/StorLever
    def get_module_info(self, module_name):
        """ get the specific module info/state in the storlever Manager layer
        """
        if module_name not in self.managed_modules:
            raise StorLeverError("Module(%s) Not Found" % (module_name), 404)
        module_conf = self.managed_modules[module_name]
        deps_info_list = []
        for rpm in module_conf["rpms"]:
            installed = True
            try:
                check_output([RPM_CMD, "-q", rpm])
            except StorLeverCmdError:
                installed = False
            deps_info_list.append({
                "name": rpm,
                "type": "rpm",
                "installed": installed
            })
        for file_path in module_conf["extra_files"]:
            deps_info_list.append({
                "name": file_path,
                "type": "file",
                "installed": os.path.exists(file_path)
            })

        module_info = {
            "module_name": module_conf["module_name"],
            "requires": deps_info_list,
            "comment": module_conf["comment"],
        }

        return module_info
コード例 #9
0
ファイル: smbmgr.py プロジェクト: linuxmap/StorLever
    def del_smb_account(self, username, operator="unkown"):
        check_output([PDBEDIT_CMD, '-x', '-u', username])

        logger.log(
            logging.INFO, logger.LOG_TYPE_CONFIG,
            "Samba user (%s) is delete from password DB by operator(%s)" %
            (username, operator))
コード例 #10
0
ファイル: md.py プロジェクト: OpenSight/StorLever
    def delete(self, md_name):
        """
        Destroy a RAID device.

        WARNING This will zero the superblock of all members of the RAID array..

        CLI Example:

        .. code-block:: bash

        salt '*' raid.destroy /dev/md0
        """
        md = MD(md_name, self._lock)

        md_device  = _md_name_to_dev_file(md_name)

        stop_cmd = '/sbin/mdadm --stop {0}'.format(md_device)
        zero_cmd = '/sbin/mdadm --zero-superblock {0}'

        with self._lock:
            check_output(stop_cmd.split())
            for _, member in md.members.iteritems():
                try:
                    check_output(zero_cmd.format(member['device']).split())
                except StorLeverError:
                    logger.log(logging.WARNING, logger.LOG_TYPE_ERROR,
                               "Failed zero superblock of device {0}".format(md_device),
                               exc_info=True)
            self._update_mdadm_conf()
            self.refresh()
        logger.log(logging.INFO, logger.LOG_TYPE_CONFIG,
                   "MD {0} removed successfully".format(md_device))
コード例 #11
0
ファイル: scsimgr.py プロジェクト: ntvis/StorLever
    def get_smart_info(self):
        if self.dev_file == "":
            raise StorLeverError("scsi_id (%s) has not be recognized" % self.scsi_id, 400)
        output = check_output([SMARTCTL_CMD, "-i", "-T", "verypermissive", self.dev_file])
        smart_enabled = False
        auto_offline_enabled = False
        if "SMART support is: Enabled" in output:
            smart_enabled = True
            output = check_output([SMARTCTL_CMD, "-a", "-T", "verypermissive", self.dev_file])

            if "Auto Offline Data Collection: Enabled" in output:
                auto_offline_enabled = True

        # filter the copyright
        lines = output.splitlines()
        for index, line in enumerate(lines):
            if line == "":
                break
        else:
            index = 0
        detail = "\n".join(lines[index + 1:])

        info = {
            "smart_enabled": smart_enabled,
            "auto_offline_enabled": auto_offline_enabled,
            "detail": detail
        }
        return info
コード例 #12
0
ファイル: md.py プロジェクト: OpenSight/StorLever
 def add_component(self, device):
     add_cmd = '/sbin/mdadm {0} --add {1}'.format(self.dev_file, device)
     with self._lock:
         check_output(add_cmd.split())
     self.refresh()
     logger.log(logging.INFO, logger.LOG_TYPE_CONFIG,
                "Block device {0} added to MD {1} successfully".format(device, self.dev_file))
コード例 #13
0
ファイル: md.py プロジェクト: OpenSight/StorLever
 def grow_raid(self, device):
     grow_cmd = '/sbin/mdadm --grow {0} --raid-device={1}'.format(self.dev_file, device)
     with self._lock:
         check_output(grow_cmd.split())
     self.refresh()
     logger.log(logging.INFO, logger.LOG_TYPE_CONFIG,
                "MD {0} grows successfully with block device {1}".format(self.dev_file, device))
コード例 #14
0
    def discovery(self, portal, iface_name=None):
        # delete the config for this dicovery
        try:
            check_output([
                ISCSIADM_CMD, "-m", "discoverydb", "-t", "st", "-p", portal,
                "-o", "delete"
            ])
        except StorLeverError:
            pass

        # discovery process
        cmd = [ISCSIADM_CMD, "-m", "discovery", "-t", "st", "-p", portal]
        if iface_name is not None:
            cmd.append("-I")
            cmd.append(iface_name)

        outlines = check_output(cmd, input_ret=[2, 6, 7, 21, 22]).splitlines()

        result = []
        for line in outlines:
            line_list = line.split()
            target = line_list[1]
            portal, sep, tag = line_list[0].partition(",")
            result.append({"portal": portal, "target": target})

        return result
コード例 #15
0
    def remove_target_by_iqn(self, iqn, operator="unkown"):
        with self.lock:
            tgt_conf = self._load_conf()
            delete_conf = None
            for target_conf in tgt_conf["target_list"]:
                if target_conf["iqn"] == iqn:
                    delete_conf = target_conf
            if delete_conf is None:
                raise StorLeverError("tgt target (iqn:%s) Not Found" % (iqn),
                                     404)
            else:
                tgt_conf["target_list"].remove(delete_conf)

            # save new conf
            self._save_conf(tgt_conf)
            self._sync_to_system_conf(tgt_conf)

        try:
            check_output([TGTADMIN_CMD, "-f", "--delete", iqn])
        except StorLeverError:
            pass

        logger.log(
            logging.INFO, logger.LOG_TYPE_CONFIG,
            "tgt target (iqn:%s) is deleted by operator(%s)" % (iqn, operator))
コード例 #16
0
    def create_target(self, iqn, operator="unkown"):

        target_conf = {
            "iqn": iqn,
            "initiator_addr_list": [],
            "initiator_name_list": [],
            "incominguser_list": [],
            "outgoinguser_list": [],
        }
        target_conf = self.target_conf_schema.validate(target_conf)
        with self.lock:
            tgt_conf = self._load_conf()
            # check duplicate
            for target_conf in tgt_conf["target_list"]:
                if target_conf["iqn"] == iqn:
                    raise StorLeverError("Target (iqn:%s) Already exist" % iqn,
                                         400)

            tgt_conf["target_list"].append(target_conf)

            # save new conf
            self._save_conf(tgt_conf)
            self._sync_to_system_conf(tgt_conf)

        try:
            check_output([TGTADMIN_CMD, "--execute"])
        except StorLeverError:
            pass

        logger.log(
            logging.INFO, logger.LOG_TYPE_CONFIG,
            "tgt target (iqn:%s) config is added by operator(%s)" %
            (iqn, operator))
コード例 #17
0
ファイル: tgtmgr.py プロジェクト: OpenSight/StorLever
    def create_target(self, iqn, operator="unkown"):

        target_conf ={
            "iqn": iqn,
            "initiator_addr_list": [],
            "initiator_name_list": [],
            "incominguser_list": [],
            "outgoinguser_list": [],
        }
        target_conf = self.target_conf_schema.validate(target_conf)
        with self.lock:
            tgt_conf = self._load_conf()
            # check duplicate
            for target_conf in tgt_conf["target_list"]:
                if target_conf["iqn"] == iqn:
                    raise StorLeverError("Target (iqn:%s) Already exist" % iqn, 400)

            tgt_conf["target_list"].append(target_conf)

            # save new conf
            self._save_conf(tgt_conf)
            self._sync_to_system_conf(tgt_conf)

        try:
            check_output([TGTADMIN_CMD, "--execute"])
        except StorLeverError:
            pass

        logger.log(logging.INFO, logger.LOG_TYPE_CONFIG,
                   "tgt target (iqn:%s) config is added by operator(%s)" %
                   (iqn, operator))
コード例 #18
0
    def set_ip_config(self,
                      ip=None,
                      netmask=None,
                      gateway=None,
                      user="******"):

        if ip is None:
            ip = self.conf.get("IPADDR", "")
        if netmask is None:
            netmask = self.conf.get("NETMASK", "")
        if gateway is None:
            gateway = self.conf.get("GATEWAY", "")

        self.conf["IPADDR"] = ip
        self.conf["NETMASK"] = netmask
        self.conf["GATEWAY"] = gateway
        self.conf["BOOTPROTO"] = "none"

        # write to config file
        self.conf.apply_to(self.conf_file_path)

        # restart this interface
        if self.ifconfig_interface.is_up():
            check_output([IFDOWN, self.name])
            check_output([IFUP, self.name])

        # log the operation
        logger.log(
            logging.INFO, logger.LOG_TYPE_CONFIG,
            "Network interface (%s) is configured with (IP:%s, Netmask:%s, \
                 Gateway:%s) by user(%s)" %
            (self.name, ip, netmask, gateway, user))
コード例 #19
0
 def set_state(self, state, operator="unkown"):
     if state == "offline":
         check_output([TGTADMIN_CMD, "--offline", self.iqn])
     elif state == "ready":
         check_output([TGTADMIN_CMD, "--ready", self.iqn])
     else:
         raise StorLeverError("state (%s) is  not supported" % (state), 400)
コード例 #20
0
 def _is_nfs_service_available(ip, mount_options):
     proto = Nfs._get_nfs_transport_proto(mount_options)
     if proto == "":  # detect automatically
         cmd = [RPCINFO_CMD, "-s", ip]
         try:
             result = check_output(cmd)
             if "nfs" in result:
                 return True
         except StorLeverCmdError as e:
             if e.return_code == 1:
                 pass
             else:
                 raise
     else:
         if proto == "udp":
             cmd = [RPCINFO_CMD, "-u", ip, "nfs"]
         elif proto == "tcp":
             cmd = [RPCINFO_CMD, "-t", ip, "nfs"]
         try:
             result = check_output(cmd)
             return True
         except StorLeverCmdError as e:
             if e.return_code == 1:
                 pass
             else:
                 raise
     return False
コード例 #21
0
ファイル: smbmgr.py プロジェクト: linuxmap/StorLever
    def get_connection_list(self):
        connections = []
        pids = {}

        try:
            ll = check_output([SMBSTATUS_CMD, '-p']).splitlines()
        except StorLeverCmdError:
            return connections

        if len(ll) >= 5 and "anonymous mode" in ll[4]:
            return connections
        for l in ll[4:]:
            s = l.split()
            if len(s) > 0:
                pids[s[0]] = (s[1], ' '.join(s[3:]))

        ll = check_output([SMBSTATUS_CMD, '-S']).splitlines()
        for l in ll[3:]:
            s = l.split()
            if len(s) > 0 and s[1] in pids:
                c = {
                    "share_name": s[0],
                    "pid": s[1],
                    "user": pids[s[1]][0],
                    "machine": pids[s[1]][1],
                    "when": ' '.join(s[3:])
                }
                connections.append(c)

        return connections
コード例 #22
0
ファイル: sysinfo.py プロジェクト: linuxmap/StorLever
    def set_hostname(self, hostname, user="******"):
        # get old hostname
        old_hostname = self.get_hostname()

        # change hostname in system
        check_output(["/bin/hostname", hostname])

        # change hostname in /etc/sysconfig/network
        network_propeties = properties(HOSTNAME=hostname)
        network_propeties.apply_to(ETC_NETWORK_FILE)

        # add ip for this hostname
        host_list = self.get_host_list()
        exist = False
        for host in host_list:
            if host["hostname"] == old_hostname:
                host["hostname"] = hostname
                exist = True
        if not exist:
            # ipv4
            host_list.append({
                "addr": "127.0.0.1",
                "hostname": hostname,
                "alias": ""
            })
            # ipv6
            host_list.append({
                "addr": "::1",
                "hostname": hostname,
                "alias": ""
            })
        self.set_host_list(host_list, user=user)

        logger.log(logging.INFO, logger.LOG_TYPE_CONFIG,
                   "hostname is changed to %s by user(%s)" % (hostname, user))
コード例 #23
0
ファイル: netif.py プロジェクト: OpenSight/StorLever
    def set_ip_config(self, ip=None, netmask=None, gateway=None, user="******"):

        if ip is None:
            ip = self.conf.get("IPADDR", "")
        if netmask is None:
            netmask = self.conf.get("NETMASK", "")
        if gateway is None:
            gateway = self.conf.get("GATEWAY", "")

        self.conf["IPADDR"] = ip
        self.conf["NETMASK"] = netmask
        self.conf["GATEWAY"] = gateway
        self.conf["BOOTPROTO"] = "none"

        # write to config file
        self.conf.apply_to(self.conf_file_path)

        # restart this interface
        if self.ifconfig_interface.is_up():
            check_output([IFDOWN, self.name])
            check_output([IFUP, self.name])

        # log the operation
        logger.log(logging.INFO, logger.LOG_TYPE_CONFIG,
                   "Network interface (%s) is configured with (IP:%s, Netmask:%s, \
                 Gateway:%s) by user(%s)" %
                   (self.name, ip, netmask, gateway, user))
コード例 #24
0
ファイル: sysinfo.py プロジェクト: linuxmap/StorLever
    def set_selinux_state(self, state, user="******"):
        state_str_to_int = {"enforcing": 1, "permissive": 0, "disabled": 0}
        param = state_str_to_int.get(state)
        if param is not None:
            old_state = check_output(["/usr/sbin/getenforce"]).lower().strip()
            if old_state != "disabled":
                check_output(["/usr/sbin/setenforce", str(param)])

        if not os.path.exists(SELINUX_CONF_DIR):
            os.makedirs(SELINUX_CONF_DIR)
        conf_path = os.path.join(SELINUX_CONF_DIR, SELINUX_CONF_FILE)
        conf = properties()
        conf.delete("SELINUX")
        conf.apply_to(conf_path)
        with open(conf_path, "r") as f:
            content = f.read()
        if content.endswith("\n") or len(content) == 0:
            content += "SELINUX=%s\n" % state
        else:
            content += "\nSELINUX=%s\n" % state
        with open(conf_path, "w") as f:
            f.write(content)

        logger.log(logging.INFO, logger.LOG_TYPE_CONFIG,
                   "selinux state is set to %s by user(%s)" % (state, user))
コード例 #25
0
ファイル: fs.py プロジェクト: OpenSight/StorLever
    def quota_group_set(self, group,
                        block_softlimit=0,
                        block_hardlimit=0,
                        inode_softlimit=0,
                        inode_hardlimit=0,
                        operator="unknown"):
        if not self.is_available():
            raise StorLeverError("File system is unavailable", 500)
        setquota_agrs = [
            SETQUOTA_BIN,
            "-g",
            group,
            str(block_softlimit),
            str(block_hardlimit),
            str(inode_softlimit),
            str(inode_hardlimit),
            self.fs_conf["mount_point"]
        ]
        check_output(setquota_agrs)

        logger.log(logging.INFO, logger.LOG_TYPE_CONFIG,
                   "File System(%s) quota for group(%s) is changed to "
                   "(%d,%d,%d,%d)"
                   " by user(%s)" %
                   (self.name, group,
                    block_softlimit, block_hardlimit,
                    inode_softlimit, inode_hardlimit,
                    operator))
コード例 #26
0
ファイル: md.py プロジェクト: linuxmap/StorLever
    def delete(self, md_name):
        """
        Destroy a RAID device.

        WARNING This will zero the superblock of all members of the RAID array..

        CLI Example:

        .. code-block:: bash

        salt '*' raid.destroy /dev/md0
        """
        md = MD(md_name, self._lock)

        md_device = _md_name_to_dev_file(md_name)

        stop_cmd = '/sbin/mdadm --stop {0}'.format(md_device)
        zero_cmd = '/sbin/mdadm --zero-superblock {0}'

        with self._lock:
            check_output(stop_cmd.split())
            for _, member in md.members.iteritems():
                try:
                    check_output(zero_cmd.format(member['device']).split())
                except StorLeverError:
                    logger.log(logging.WARNING,
                               logger.LOG_TYPE_ERROR,
                               "Failed zero superblock of device {0}".format(
                                   md_device),
                               exc_info=True)
            self._update_mdadm_conf()
            self.refresh()
        logger.log(logging.INFO, logger.LOG_TYPE_CONFIG,
                   "MD {0} removed successfully".format(md_device))
コード例 #27
0
ファイル: target.py プロジェクト: OpenSight/StorLever
 def set_state(self, state, operator="unkown"):
     if state == "offline":
         check_output([TGTADMIN_CMD, "--offline", self.iqn])
     elif state == "ready":
         check_output([TGTADMIN_CMD, "--ready", self.iqn])
     else:
         raise StorLeverError("state (%s) is  not supported" %
                                  (state), 400)
コード例 #28
0
ファイル: scsimgr.py プロジェクト: ntvis/StorLever
 def safe_delete(self):
     # flush dev's buf first
     try:
         if self.dev_file != "":
             check_output([BLOCKDEV_CMD, "--flushbufs", self.dev_file])
     except Exception:
         pass
     delete_path = os.path.join("/sys/class/scsi_device/", self.scsi_id, "device/delete")
     write_file_entry(delete_path, "1\n")
コード例 #29
0
 def group_del_by_name(self, name, user="******"):
     if name == "root":
         raise StorLeverError("cannot del group root", 400)
     cmds = ["/usr/sbin/groupdel"]
     cmds.append(name)
     check_output(cmds, input_ret=[2, 6, 8])
     logger.log(logging.INFO, logger.LOG_TYPE_CONFIG,
                "System group %s is deleted by user(%s)" %
                (name, user))
コード例 #30
0
ファイル: md.py プロジェクト: OpenSight/StorLever
 def remove_component(self, device):
     fail_cmd = '/sbin/mdadm {0} --fail {1}'.format(self.dev_file, device)
     remove_cmd = '/sbin/mdadm {0} --remove {1}'.format(self.dev_file, device)
     with self._lock:
         check_output(fail_cmd.split())
         check_output(remove_cmd.split())
     self.refresh()
     logger.log(logging.INFO, logger.LOG_TYPE_CONFIG,
                "Block device {0} detached from MD {1} created successfully".format(device, self.dev_file))
コード例 #31
0
ファイル: md.py プロジェクト: linuxmap/StorLever
 def add_component(self, device):
     add_cmd = '/sbin/mdadm {0} --add {1}'.format(self.dev_file, device)
     with self._lock:
         check_output(add_cmd.split())
     self.refresh()
     logger.log(
         logging.INFO, logger.LOG_TYPE_CONFIG,
         "Block device {0} added to MD {1} successfully".format(
             device, self.dev_file))
コード例 #32
0
ファイル: lvm.py プロジェクト: dulton/StorLever
 def move(self, dst_device=None, lv_name=None):
     cmd = ["pvmove", "-b"]
     if lv_name:
         cmd.append("-n")
         cmd.append(lv_name)
     cmd.append(self.dev_file)
     if dst_device:
         cmd.append(dst_device)
     check_output(cmd)
コード例 #33
0
ファイル: lvm.py プロジェクト: linuxmap/StorLever
 def move(self, dst_device=None, lv_name=None):
     cmd = ['pvmove', '-b']
     if lv_name:
         cmd.append('-n')
         cmd.append(lv_name)
     cmd.append(self.dev_file)
     if dst_device:
         cmd.append(dst_device)
     check_output(cmd)
コード例 #34
0
    def down(self, user="******"):

        self.conf["ONBOOT"] = "no"
        self.save_conf()
        check_output([IFDOWN, self.name])

        # log the operation
        logger.log(
            logging.INFO, logger.LOG_TYPE_CONFIG,
            "Network interface (%s) is up by user(%s)" % (self.name, user))
コード例 #35
0
 def group_add(self, name, gid=None, user="******"):
     cmds = ["/usr/sbin/groupadd"]
     if gid is not None:
         cmds.append("-g")
         cmds.append("%d" % int(gid))
     cmds.append(name)
     check_output(cmds, input_ret=[2, 3, 4, 9])
     logger.log(logging.INFO, logger.LOG_TYPE_CONFIG,
                "New system group %s is created by user(%s)" %
                (name, user))
コード例 #36
0
ファイル: nfs.py プロジェクト: OpenSight/StorLever
    def mount(self):
        # check nfs service available on the remote host
        ip, path = Nfs._parse_dev_file(self.fs_conf["dev_file"])
        if not Nfs._is_nfs_service_available(ip, self.mount_options):
            raise StorLeverError("NFS service on %s is not available" % ip, 400)

        check_output(["/bin/mount", "-t", self.fs_conf["type"],
                     "-o", self.mount_options,
                     self.fs_conf["dev_file"], self.fs_conf["mount_point"]],
                     input_ret=[32])
コード例 #37
0
ファイル: scsimgr.py プロジェクト: linuxmap/StorLever
 def safe_delete(self):
     # flush dev's buf first
     try:
         if self.dev_file != "":
             check_output([BLOCKDEV_CMD, "--flushbufs", self.dev_file])
     except Exception:
         pass
     delete_path = os.path.join("/sys/class/scsi_device/", self.scsi_id,
                                "device/delete")
     write_file_entry(delete_path, "1\n")
コード例 #38
0
ファイル: md.py プロジェクト: linuxmap/StorLever
 def grow_raid(self, device):
     grow_cmd = '/sbin/mdadm --grow {0} --raid-device={1}'.format(
         self.dev_file, device)
     with self._lock:
         check_output(grow_cmd.split())
     self.refresh()
     logger.log(
         logging.INFO, logger.LOG_TYPE_CONFIG,
         "MD {0} grows successfully with block device {1}".format(
             self.dev_file, device))
コード例 #39
0
ファイル: netif.py プロジェクト: OpenSight/StorLever
    def up(self, user="******"):

        self.conf["ONBOOT"] = "yes"
        self.save_conf()
        check_output([IFUP, self.name])

        # log the operation
        logger.log(logging.INFO, logger.LOG_TYPE_CONFIG,
                   "Network interface (%s) is up by user(%s)" %
                   (self.name, user))
コード例 #40
0
ファイル: iface.py プロジェクト: OpenSight/StorLever
    def set_conf(self, name, value, operator="unkown"):
        name = str(name).strip()
        value = str(value).strip()
        check_output([ISCSIADM_CMD, "-m", "iface", "-I", self.iscsi_ifacename, "-o", "update",
                      "-n", name, "-v", value], input_ret=[2, 6, 7, 21, 22])

        self._refresh_property()

        logger.log(logging.INFO, logger.LOG_TYPE_CONFIG,
                   "iscsi initiator iface (%s) conf (%s:%s) is updated by operator(%s)" %
                   (self.iscsi_ifacename, name, value, operator))
コード例 #41
0
ファイル: initiatormgr.py プロジェクト: OpenSight/StorLever
    def create_iface(self, iface_name, operator="unkown"):
        iface_list = self.get_iface_list()
        for iface in iface_list:
            if iface.iscsi_ifacename == iface_name:
                raise StorLeverError("iface (%s) already exists" % iface_name, 400)
        check_output([ISCSIADM_CMD, "-m", "iface", "-I", iface_name, "-o", "new"],
                                input_ret=[2, 6, 7, 21, 22])

        logger.log(logging.INFO, logger.LOG_TYPE_CONFIG,
                   "iscsi initiator iface (%s) is created by operator(%s)" %
                   (iface_name, operator))
コード例 #42
0
ファイル: sysinfo.py プロジェクト: OpenSight/StorLever
    def set_datetime(self, datetime_str, user="******"):
        """set system date time by datetime_string"""

        # because linux date command cannot recognize iso 8601 format string with timezone,
        # change it with a valid format

        set_string = datetime_str.replace("T", " ")
        check_output(["/bin/date", "-s%s" % set_string])
        check_output(["/sbin/hwclock", "-w"])  # sync the system time to hw time
        logger.log(logging.INFO, logger.LOG_TYPE_CONFIG,
                   "system date time is update to %s by user(%s)" %
                   (datetime_str, user))
コード例 #43
0
ファイル: md.py プロジェクト: linuxmap/StorLever
 def remove_component(self, device):
     fail_cmd = '/sbin/mdadm {0} --fail {1}'.format(self.dev_file, device)
     remove_cmd = '/sbin/mdadm {0} --remove {1}'.format(
         self.dev_file, device)
     with self._lock:
         check_output(fail_cmd.split())
         check_output(remove_cmd.split())
     self.refresh()
     logger.log(
         logging.INFO, logger.LOG_TYPE_CONFIG,
         "Block device {0} detached from MD {1} created successfully".
         format(device, self.dev_file))
コード例 #44
0
    def mount(self):
        # check nfs service available on the remote host
        ip, path = Nfs._parse_dev_file(self.fs_conf["dev_file"])
        if not Nfs._is_nfs_service_available(ip, self.mount_options):
            raise StorLeverError("NFS service on %s is not available" % ip,
                                 400)

        check_output([
            "/bin/mount", "-t", self.fs_conf["type"], "-o", self.mount_options,
            self.fs_conf["dev_file"], self.fs_conf["mount_point"]
        ],
                     input_ret=[32])
コード例 #45
0
ファイル: sysinfo.py プロジェクト: linuxmap/StorLever
    def set_datetime(self, datetime_str, user="******"):
        """set system date time by datetime_string"""

        # because linux date command cannot recognize iso 8601 format string with timezone,
        # change it with a valid format

        set_string = datetime_str.replace("T", " ")
        check_output(["/bin/date", "-s%s" % set_string])
        check_output(["/sbin/hwclock",
                      "-w"])  # sync the system time to hw time
        logger.log(
            logging.INFO, logger.LOG_TYPE_CONFIG,
            "system date time is update to %s by user(%s)" %
            (datetime_str, user))
コード例 #46
0
    def create_iface(self, iface_name, operator="unkown"):
        iface_list = self.get_iface_list()
        for iface in iface_list:
            if iface.iscsi_ifacename == iface_name:
                raise StorLeverError("iface (%s) already exists" % iface_name,
                                     400)
        check_output(
            [ISCSIADM_CMD, "-m", "iface", "-I", iface_name, "-o", "new"],
            input_ret=[2, 6, 7, 21, 22])

        logger.log(
            logging.INFO, logger.LOG_TYPE_CONFIG,
            "iscsi initiator iface (%s) is created by operator(%s)" %
            (iface_name, operator))
コード例 #47
0
    def set_conf(self, name, value, operator="unkown"):
        name = str(name).strip()
        value = str(value).strip()
        check_output([
            ISCSIADM_CMD, "-m", "iface", "-I", self.iscsi_ifacename, "-o",
            "update", "-n", name, "-v", value
        ],
                     input_ret=[2, 6, 7, 21, 22])

        self._refresh_property()

        logger.log(
            logging.INFO, logger.LOG_TYPE_CONFIG,
            "iscsi initiator iface (%s) conf (%s:%s) is updated by operator(%s)"
            % (self.iscsi_ifacename, name, value, operator))
コード例 #48
0
ファイル: blockmgr.py プロジェクト: linuxmap/StorLever
    def refresh_property(self):
        lines = check_output([
            LSBLK_CMD, "-ribn", "-o",
            "NAME,MAJ:MIN,TYPE,SIZE,RO,FSTYPE,MOUNTPOINT", self.dev_file
        ]).splitlines()
        if not lines:
            raise StorLeverError(
                "Device (%s) has been removed from system" % self.dev_file,
                404)

        line = lines[0]
        line_list = line.split(" ")
        maj_num, sep, min_num = line_list[1].partition(":")
        if int(line_list[4]) == 0:
            ro = False
        else:
            ro = True
        self.name = line_list[0]
        self.major = int(maj_num)
        self.minor = int(min_num)
        self.size = int(line_list[3])
        self.type = line_list[2]
        self.readonly = ro
        self.fs_type = line_list[5]
        self.mount_point = line_list[6]
コード例 #49
0
ファイル: node.py プロジェクト: OpenSight/StorLever
    def logout(self, operator="unkown"):
        cmd = [ISCSIADM_CMD, "-m", "node","--logout", "-T", self.target, "-p", self.portal]

        outlines = check_output(cmd, input_ret=[2, 6, 7, 21, 22]).splitlines()
        logger.log(logging.INFO, logger.LOG_TYPE_CONFIG,
                   "iscsi initiator node (%s, %s) is logout by operator(%s)" %
                   (self.target, self.portal, operator))
コード例 #50
0
ファイル: initiatormgr.py プロジェクト: OpenSight/StorLever
    def get_iface_by_name(self, iface_name):
        try:
           outlines = check_output([ISCSIADM_CMD, "-m", "iface"], input_ret=[2, 7, 22]).splitlines()
        except StorLeverCmdError as e:
            if e.return_code == 21:
                outlines = []
            else:
                raise
        for line in outlines:
            entry_iface_name, sep, params = line.partition(" ")
            params = params.strip().split(",")
            if len(params) < 5:
                continue # we don't recognize this output format

            if entry_iface_name == iface_name:
                for index, value in enumerate(params):
                    if value == "<empty>":
                        params[index] = ""
                iface_obj = Iface(
                    self, entry_iface_name,
                    params[0], params[1], params[2], params[3], params[4]
                )
                return iface_obj
        else:
            raise StorLeverError("iface (%s) Not Found" % iface_name, 404)
コード例 #51
0
ファイル: fs.py プロジェクト: OpenSight/StorLever
    def quota_group_report(self):
        if not self.is_available():
            raise StorLeverError("File system is unavailable", 500)
        gq_list = []
        gq_lines = check_output([REPQUOTA_BIN, "-gpv", self.fs_conf["mount_point"]]).splitlines()
        table_start = False
        start_pattern = re.compile(r"^(-)+$")
        entry_pattern = re.compile(r"^[-\+][-\+]$")
        for line in gq_lines:
            if table_start:
                if len(line) == 0:
                    break
                elements = line.split()
                if len(elements) < 10:
                    break
                if entry_pattern.match(elements[1]) is None:
                    break

                gq_list.append({
                    "name": elements[0],
                    "block_used": int(elements[2]),
                    "block_softlimit": int(elements[3]),
                    "block_hardlimit": int(elements[4]),
                    "inode_used": int(elements[6]),
                    "inode_softlimit":int(elements[7]),
                    "inode_hardlimit":int(elements[8])
                })

            elif start_pattern.match(line) is not None:
                table_start = True

        return gq_list
コード例 #52
0
ファイル: blockmgr.py プロジェクト: linuxmap/StorLever
    def get_block_dev_list(self):
        block_list = []
        block_name_list = []
        lines = check_output([
            LSBLK_CMD, "-ribn", "-o",
            "NAME,MAJ:MIN,TYPE,SIZE,RO,FSTYPE,MOUNTPOINT"
        ]).splitlines()
        for line in lines:
            line_list = line.split(" ")

            # remove duplication
            if line_list[0] in block_name_list:
                continue  # this block device already in the list
            else:
                block_name_list.append(line_list[0])

            maj_num, sep, min_num = line_list[1].partition(":")
            if int(line_list[4]) == 0:
                ro = False
            else:
                ro = True
            block_list.append(
                BlockDev(line_list[0], int(maj_num), int(min_num),
                         int(line_list[3]), line_list[2], ro, line_list[5],
                         line_list[6]))

        return block_list
コード例 #53
0
ファイル: ntpmgr.py プロジェクト: OpenSight/StorLever
    def get_peer_list(self):

        connections = []
        ll = check_output([NTPQ_CMD, '-pn']).splitlines()
        for l in ll[2:]:
            s = l[1:].split()
            if len(s) < 10:
                raise StorLeverError("ntpq output format cannot be regonized" ,
                                     500)
            try:
                when = int(s[4])
            except Exception:
                when = 0

            connections.append({
                "state": l[0],
                "remote": s[0],
                "refid": s[1],
                "stratum": int(s[2]),
                "type": s[3],
                "when": when,
                "poll": int(s[5]),
                "reach": int(s[6], 8),
                "delay": float(s[7]),
                "offset": float(s[8]),
                "jitter": float(s[9])
            })
        return connections
コード例 #54
0
ファイル: tgtadmparse.py プロジェクト: dulton/StorLever
 def _get_target_info(self, iqn):
     output_lines = check_output([TGTADMIN_CMD, "-s"]).split("\n")
     line_num, root = parse_lines(output_lines)
     for k, v in root.items():
         if v.value == iqn:
             return v
     raise StorLeverError("The target (%s) Not Found" % (iqn), 404)
コード例 #55
0
ファイル: initiatormgr.py プロジェクト: OpenSight/StorLever
    def del_iface(self, iface_name, operator="unkown"):
        if iface_name in ("default", "iser"):
            raise StorLeverError("iface (default, iser) cannot be deleted", 400)
        iface_list = self.get_iface_list()
        for iface in iface_list:
            if iface.iscsi_ifacename == iface_name:
                break;
        else:
            raise StorLeverError("iface (%s) Not Found" % iface_name, 404)


        check_output([ISCSIADM_CMD, "-m", "iface", "-I", iface_name, "-o", "delete"],
                                input_ret=[2, 6, 7, 21, 22])
        logger.log(logging.INFO, logger.LOG_TYPE_CONFIG,
                   "iscsi initiator iface (%s) is deleted by operator(%s)" %
                   (iface_name, operator))
コード例 #56
0
ファイル: initiatormgr.py プロジェクト: OpenSight/StorLever
    def create_node(self, target, portal, iface=None, operator="unkown"):

        node_list = self.get_node_list()
        for node in node_list:
            if node.target == target and node.portal == portal:
                raise StorLeverError("Node (%s, %s) already exists" % (target, portal), 400)

        cmd = [ISCSIADM_CMD, "-m", "node", "-o", "new", "-T", target, "-p", portal]
        if iface is not None:
            cmd.append("-I")
            cmd.append(iface)

        check_output(cmd, input_ret=[2, 6, 7, 21, 22])

        logger.log(logging.INFO, logger.LOG_TYPE_CONFIG,
                   "iscsi initiator node (%s, %s) is created by operator(%s)" %
                   (target, portal, operator))
コード例 #57
0
ファイル: scsimgr.py プロジェクト: ntvis/StorLever
    def smart_test(self, scsi_id, test_type):
        if test_type not in ("offline", "short", "long", "conveyance"):
            raise StorLeverError("test_type (%s) Not Support" % test_type, 400)

        if self.dev_file == "":
            raise StorLeverError("scsi_id (%s) has not be recognized" % self.scsi_id, 400)

        out = check_output([SMARTCTL_CMD, "-t", test_type, "-T", "verypermissive", self.dev_file])