コード例 #1
0
 def __init__(self, iphost="127.0.0.1", port=11211, force=False, debug=True):
     self._iphost = iphost
     self._port = port
     self._force = force
     self._logpath = "/tmp/zabbix_memcached.log"
     self._cache_file = "/tmp/zabbix_memcached_cache_%s.txt" %(port)
     if not port:
         self._cache_file = "/tmp/zabbix_memcached_cache.txt"
         
     self._logger = Log(self._logpath,is_console=debug, mbs=5, count=5)
コード例 #2
0
ファイル: mdb_sstat.py プロジェクト: shell-develop/ops_doc
    def __init__(self,
                 iphost="127.0.0.1",
                 port=27017,
                 username=None,
                 password=None,
                 force=False,
                 debug=True):
        self._iphost = iphost
        self._port = port
        self._username = username
        self._password = password
        self._force = force

        self._logpath = "/tmp/zabbix_mongodb.log"
        self._cache_file = "/tmp/zabbix_mongodb_cache_%s.txt" % (port)
        if not port:
            self._cache_file = "/tmp/zabbix_mongodb_cache.txt"

        self._logger = Log(self._logpath, is_console=debug, mbs=5, count=5)
コード例 #3
0
ファイル: memcache.py プロジェクト: cybend/zabbix
 def __init__(self, iphost="127.0.0.1", port=11211, force=False, debug=True):
     self._iphost = iphost
     self._port = port
     self._force = force
     self._logpath = "/tmp/zabbix_memcached.log"
     self._cache_file = "/tmp/zabbix_memcached_cache_%s.txt" %(port)
     if not port:
         self._cache_file = "/tmp/zabbix_memcached_cache.txt"
         
     self._logger = Log(self._logpath,is_console=debug, mbs=5, count=5)
コード例 #4
0
ファイル: mdb_sstat.py プロジェクト: 361way/zabbix
 def __init__(self, iphost="127.0.0.1", port=27017, username=None, password=None, force=False, debug=True):
     self._iphost = iphost
     self._port = port
     self._username = username
     self._password = password
     self._force = force
     
     self._logpath = "/tmp/zabbix_mongodb.log"
     self._cache_file = "/tmp/zabbix_mongodb_cache_%s.txt" %(port)
     if not port:
         self._cache_file = "/tmp/zabbix_mongodb_cache.txt"
 
     self._logger = Log(self._logpath,is_console=debug, mbs=5, count=5)
コード例 #5
0
class MCache(object):
    
    
    def __init__(self, iphost="127.0.0.1", port=11211, force=False, debug=True):
        self._iphost = iphost
        self._port = port
        self._force = force
        self._logpath = "/tmp/zabbix_memcached.log"
        self._cache_file = "/tmp/zabbix_memcached_cache_%s.txt" %(port)
        if not port:
            self._cache_file = "/tmp/zabbix_memcached_cache.txt"
            
        self._logger = Log(self._logpath,is_console=debug, mbs=5, count=5)
        
    def get_logger(self):
        return self._logger

    def get_port_list(self):
        # sudo权限,必须授予
        # [root@localhost ~]# tail -n 2 /etc/sudoers
        # Defaults:zabbix   !requiretty 
        # zabbix ALL=(root) NOPASSWD:/bin/netstat

        cmdstr = "sudo netstat  -nlpt |grep 127.0.0.1| grep 'memcached' | awk '{print $4}'|awk -F: '{print $2}'"
        port_conf = None
        (stdo_list, stde_list, retcode) = docmd(cmdstr, timeout=3, raw = False)
        
        log_da = [{"cmdstr": cmdstr},{"ret": retcode},{"stdo": "".join(stdo_list)}, {"stde": "".join(stde_list)}]
        logstr = get_logstr(log_da, max_key_len=10)
        
        if retcode !=0:
                self._logger.error(logstr)
                return port_conf
        else:
            self._logger.info(logstr)
            
        data = list()
            
        for port in stdo_list:
            if not port:continue
            port = int(str(port).strip())
            data.append({"{#MEMCACHED_PORT}": port})
        import json
        return json.dumps({'data': data}, sort_keys=True, indent=7, separators=(",",":"))
    
    def get_result_dict_from_cache(self, seconds=60):
        """
        cache文件的内容,第一行是时间戳,第二行是内容
        """
        if os.path.exists(self._cache_file) == False:
            return None
        resobj = None
        with open(self._cache_file, "r") as fd:
            alllines = fd.readlines()
            fd.close()
            if alllines and len(alllines)>1:
                old_unixtime = int(str(alllines[0]).strip())
                now_unixtime = int(time.time())
                if (now_unixtime - old_unixtime) <= seconds: ## 1min内
                    resobj = str(alllines[1]).strip()
                    resobj = json.loads(resobj)
        return resobj
    
    def write_result_dict_to_cache(self, res_dict):
            jsonstr = json.dumps(res_dict)
            now_unixtime = int(time.time())
            with open(self._cache_file, "w") as fd:
                fd.write(str(now_unixtime)+"\n")
                fd.write(jsonstr)
                fd.close()
    
    def _get_result(self, iphost=None, port=None):
        try:
            hostname= iphost if iphost else self._iphost
            port = port if port else self._port
            
            resobj = dict()
            if self._force == False:
                resobj = self.get_result_dict_from_cache()
                
            if resobj:
                log_da = [{"msg": "Get From Cache File"}, {"content": str(resobj)}]
                logstr = get_logstr(log_da, max_key_len=10)
                self._logger.info(logstr)
                return resobj
                
            command = "stats\n"
            tn = telnetlib.Telnet(hostname,port) 
            tn.read_very_eager() 
            tn.write(command)
            ret = tn.read_until('END')
            tn.close()
            
            resobj = dict()
            alllines = re.split("\n", ret)
            for line in alllines:
                line = str(line).strip()
                ln_ary = re.split("[ ,;]+", line)
                if len(ln_ary) < 3:continue
                key = ln_ary[1]
                val = ln_ary[2]
                resobj[key] = val

            log_da = [{"cmdstr": command},{"result": str(resobj)}]
            logstr = get_logstr(log_da, max_key_len=10)
            self._logger.info(logstr)
            
            self.write_result_dict_to_cache(resobj)
            return resobj
        except Exception as expt:
            import traceback
            tb = traceback.format_exc()
            self._logger.error(tb)

    def get_all_key_val(self):
        resobj = self._get_result()
        return json.dumps(resobj, indent=4)
    
    def get_item_val(self, item):
        resobj = self._get_result()
        if resobj and dict(resobj).has_key(item):
            return resobj[item]
        return 0
    
    def get_item_tval(self, item):
        val = self.get_item_val(item)
        if val == None:return 0
        val = str(val)
        try:
            val = int(val)
        except Exception:
            try:
                val = float(val)
                val = "%.2f" % (val)
            except Exception:
                val = str(val)
        return val
    
    def get_item_tval_bak(self, item, val_type="int"):
        val = self.get_item_val(item)
        if val == None:return 0
        if val_type == "int":
            return int(val)
        if val_type == "float":
            fval = "%.2f" % (val)
            return float(fval)
        if val_type == "str":
            return str(val)
        
        return int(val)
コード例 #6
0
ファイル: mdb_sstat.py プロジェクト: shell-develop/ops_doc
class MGdb(object):
    def __init__(self,
                 iphost="127.0.0.1",
                 port=27017,
                 username=None,
                 password=None,
                 force=False,
                 debug=True):
        self._iphost = iphost
        self._port = port
        self._username = username
        self._password = password
        self._force = force

        self._logpath = "/tmp/zabbix_mongodb.log"
        self._cache_file = "/tmp/zabbix_mongodb_cache_%s.txt" % (port)
        if not port:
            self._cache_file = "/tmp/zabbix_mongodb_cache.txt"

        self._logger = Log(self._logpath, is_console=debug, mbs=5, count=5)

    def get_logger(self):
        return self._logger

    def get_port_list(self):
        # sudo权限,必须授予
        # [root@localhost ~]# tail -n 2 /etc/sudoers
        # Defaults:zabbix   !requiretty
        # zabbix ALL=(root) NOPASSWD:/bin/netstat

        binname = "mongod"
        cmdstr = "sudo netstat  -nlpt | grep '%s' | awk '{print $4}'|awk -F: '{print $2}'" % (
            binname)
        disk_space_info = []
        (stdo_list, stde_list, retcode) = docmd(cmdstr, timeout=3, raw=False)

        log_da = [{
            "cmdstr": cmdstr
        }, {
            "ret": retcode
        }, {
            "stdo": "".join(stdo_list)
        }, {
            "stde": "".join(stde_list)
        }]
        logstr = get_logstr(log_da, max_key_len=10)

        if retcode != 0:
            self._logger.error(logstr)
            return {}
        else:
            self._logger.info(logstr)

        data = list()

        for port in stdo_list:
            port = int(str(port).strip())
            data.append({"{#MONGODB_PORT}": port})
        import json
        return json.dumps({'data': data},
                          sort_keys=True,
                          indent=7,
                          separators=(",", ":"))

    def _get_result(self,
                    iphost=None,
                    port=None,
                    username=None,
                    password=None):
        try:
            hostname = iphost if iphost else self._iphost
            port = port if port else self._port
            username = username if username else self._username
            password = password if password else self._password
            resobj = None

            if self._force == False:
                if os.path.exists(self._cache_file):
                    with open(self._cache_file, "r") as fd:
                        alllines = fd.readlines()
                        fd.close()
                        if alllines and len(alllines) > 1:
                            old_unixtime = int(str(alllines[0]).strip())
                            now_unixtime = int(time.time())
                            if (now_unixtime - old_unixtime) <= 60:  ## 1min内
                                resobj = str(alllines[1]).strip()
                                resobj = json.loads(resobj)

                if resobj:
                    log_da = [{
                        "msg": "Get From Cache File"
                    }, {
                        "content": str(resobj)
                    }]
                    logstr = get_logstr(log_da, max_key_len=10)
                    self._logger.info(logstr)
                    return resobj

            pbinpaths = [
                "/usr/local/mongodb/bin/mongo",
                "/home/qiueer/mongodb/mongodb/bin/mongo",
            ]
            cmdstr = None
            for bp in pbinpaths:
                if os.path.exists(bp):
                    cmdstr = "echo 'db.serverStatus()' | %s admin --host '%s'  --port %s --quiet" % (
                        bp, hostname, port)
                    if username and password:
                        cmdstr = "echo 'db.serverStatus()' | %s admin --host '%s'  --port %s -u %s -p %s --quiet" % (
                            bp, hostname, port, username, password)
                    break
            if not cmdstr:
                return None

            (stdo_list, stde_list, retcode) = docmd(cmdstr,
                                                    timeout=3,
                                                    raw=False)

            log_da = [{
                "cmdstr": cmdstr
            }, {
                "ret": retcode
            }, {
                "stdo": None if not stdo_list else "".join(stdo_list)
            }, {
                "stde": None if not stde_list else "".join(stde_list)
            }]
            logstr = get_logstr(log_da, max_key_len=10)

            if retcode != 0:
                self._logger.error(logstr)
                return None
            else:
                self._logger.info(logstr)

            stdo_str = "".join(stdo_list)
            stdo_str = stdo_str.replace("NumberLong(",
                                        "").replace(")", "").replace(
                                            "ISODate(", "")
            #print stdo_str
            resobj = json.loads(stdo_str)
            now_unixtime = int(time.time())
            with open(self._cache_file, "w") as fd:
                fd.write(str(now_unixtime) + "\n")
                fd.write(stdo_str)
                fd.close()

            return resobj
        except Exception as expt:
            import traceback
            tb = traceback.format_exc()
            self._logger.error(tb)

    def get_item_val(self, *items):
        resobj = self._get_result()
        src_res = resobj
        for item in items:
            if resobj and type(resobj) == types.DictType and resobj.has_key(
                    item):
                resobj = resobj[item]
        if resobj == None or resobj == src_res:
            resobj = 0
        return resobj

    def get_result(self):
        return self._get_result()

    def get_item_tval(self, items, val_type="int"):
        val = self.get_item_val(*items)
        if val == None: return None  #0也满足此条件
        if val_type == "int":
            return int(val)
        if val_type == "float":
            fval = "%.2f" % (val)
            return float(fval)
        if val_type == "str":
            return str(val)

        return int(val)

    def print_all_key_val(self):
        resobj = self._get_result()
        print json.dumps(resobj, indent=4)
コード例 #7
0
ファイル: memcache.py プロジェクト: cybend/zabbix
class MCache(object):
    
    
    def __init__(self, iphost="127.0.0.1", port=11211, force=False, debug=True):
        self._iphost = iphost
        self._port = port
        self._force = force
        self._logpath = "/tmp/zabbix_memcached.log"
        self._cache_file = "/tmp/zabbix_memcached_cache_%s.txt" %(port)
        if not port:
            self._cache_file = "/tmp/zabbix_memcached_cache.txt"
            
        self._logger = Log(self._logpath,is_console=debug, mbs=5, count=5)
        
    def get_logger(self):
        return self._logger

    def get_port_list(self):
        # sudo权限,必须授予
        # [root@localhost ~]# tail -n 2 /etc/sudoers
        # Defaults:zabbix   !requiretty 
        # zabbix ALL=(root) NOPASSWD:/bin/netstat

        cmdstr = "sudo netstat  -nlpt | grep 'memcached' | awk '{print $4}'|awk -F: '{print $2}'"
        port_conf = None
        (stdo_list, stde_list, retcode) = docmd(cmdstr, timeout=3, raw = False)
        
        log_da = [{"cmdstr": cmdstr},{"ret": retcode},{"stdo": "".join(stdo_list)}, {"stde": "".join(stde_list)}]
        logstr = get_logstr(log_da, max_key_len=10)
        
        if retcode !=0:
                self._logger.error(logstr)
                return port_conf
        else:
            self._logger.info(logstr)
            
        data = list()
            
        for port in stdo_list:
            if not port:continue
            port = int(str(port).strip())
            data.append({"{#MEMCACHED_PORT}": port})
        import json
        return json.dumps({'data': data}, sort_keys=True, indent=7, separators=(",",":"))
    
    def get_result_dict_from_cache(self, seconds=60):
        """
        cache文件的内容,第一行是时间戳,第二行是内容
        """
        if os.path.exists(self._cache_file) == False:
            return None
        resobj = None
        with open(self._cache_file, "r") as fd:
            alllines = fd.readlines()
            fd.close()
            if alllines and len(alllines)>1:
                old_unixtime = int(str(alllines[0]).strip())
                now_unixtime = int(time.time())
                if (now_unixtime - old_unixtime) <= seconds: ## 1min内
                    resobj = str(alllines[1]).strip()
                    resobj = json.loads(resobj)
        return resobj
    
    def write_result_dict_to_cache(self, res_dict):
            jsonstr = json.dumps(res_dict)
            now_unixtime = int(time.time())
            with open(self._cache_file, "w") as fd:
                fd.write(str(now_unixtime)+"\n")
                fd.write(jsonstr)
                fd.close()
    
    def _get_result(self, iphost=None, port=None):
        try:
            hostname= iphost if iphost else self._iphost
            port = port if port else self._port
            
            resobj = dict()
            if self._force == False:
                resobj = self.get_result_dict_from_cache()
                
            if resobj:
                log_da = [{"msg": "Get From Cache File"}, {"content": str(resobj)}]
                logstr = get_logstr(log_da, max_key_len=10)
                self._logger.info(logstr)
                return resobj
                
            command = "stats\n"
            tn = telnetlib.Telnet(hostname,port) 
            tn.read_very_eager() 
            tn.write(command)
            ret = tn.read_until('END')
            tn.close()
            
            resobj = dict()
            alllines = re.split("\n", ret)
            for line in alllines:
                line = str(line).strip()
                ln_ary = re.split("[ ,;]+", line)
                if len(ln_ary) < 3:continue
                key = ln_ary[1]
                val = ln_ary[2]
                resobj[key] = val

            log_da = [{"cmdstr": command},{"result": str(resobj)}]
            logstr = get_logstr(log_da, max_key_len=10)
            self._logger.info(logstr)
            
            self.write_result_dict_to_cache(resobj)
            return resobj
        except Exception as expt:
            import traceback
            tb = traceback.format_exc()
            self._logger.error(tb)

    def get_all_key_val(self):
        resobj = self._get_result()
        return json.dumps(resobj, indent=4)
    
    def get_item_val(self, item):
        resobj = self._get_result()
        if resobj and dict(resobj).has_key(item):
            return resobj[item]
        return 0
    
    def get_item_tval(self, item):
        val = self.get_item_val(item)
        if val == None:return 0
        val = str(val)
        try:
            val = int(val)
        except Exception:
            try:
                val = float(val)
                val = "%.2f" % (val)
            except Exception:
                val = str(val)
        return val
    
    def get_item_tval_bak(self, item, val_type="int"):
        val = self.get_item_val(item)
        if val == None:return 0
        if val_type == "int":
            return int(val)
        if val_type == "float":
            fval = "%.2f" % (val)
            return float(fval)
        if val_type == "str":
            return str(val)
        
        return int(val)
コード例 #8
0
ファイル: mdb_sstat.py プロジェクト: 361way/zabbix
class MGdb(object):

    
    def __init__(self, iphost="127.0.0.1", port=27017, username=None, password=None, force=False, debug=True):
        self._iphost = iphost
        self._port = port
        self._username = username
        self._password = password
        self._force = force
        
        self._logpath = "/tmp/zabbix_mongodb.log"
        self._cache_file = "/tmp/zabbix_mongodb_cache_%s.txt" %(port)
        if not port:
            self._cache_file = "/tmp/zabbix_mongodb_cache.txt"
    
        self._logger = Log(self._logpath,is_console=debug, mbs=5, count=5)
        
    def get_logger(self):
        return self._logger

    def get_port_list(self):
        # sudo权限,必须授予
        # [root@localhost ~]# tail -n 2 /etc/sudoers
        # Defaults:zabbix   !requiretty 
        # zabbix ALL=(root) NOPASSWD:/bin/netstat

        binname = "mongod"
        cmdstr = "sudo netstat  -nlpt | grep '%s' | awk '{print $4}'|awk -F: '{print $2}'" % (binname)
        disk_space_info = []
        (stdo_list, stde_list, retcode) = docmd(cmdstr, timeout=3, raw = False)
        
        log_da = [{"cmdstr": cmdstr},{"ret": retcode},{"stdo": "".join(stdo_list)}, {"stde": "".join(stde_list)}]
        logstr = get_logstr(log_da, max_key_len=10)
        
        if retcode !=0:
            self._logger.error(logstr)
            return {}
        else:
            self._logger.info(logstr)
            
        data = list()

        for port in stdo_list:
            port = int(str(port).strip())
            data.append({"{#MONGODB_PORT}": port})
        import json
        return json.dumps({'data': data}, sort_keys=True, indent=7, separators=(",",":"))
    
    def _get_result(self, iphost=None, port=None, username=None, password=None):
        try:
            hostname= iphost if iphost else self._iphost
            port = port if port else self._port
            username = username if username else self._username
            password = password if password else self._password
            resobj = None
            
            if self._force == False:
                if os.path.exists(self._cache_file):
                    with open(self._cache_file, "r") as fd:
                        alllines = fd.readlines()
                        fd.close()
                        if alllines and len(alllines)>1:
                            old_unixtime = int(str(alllines[0]).strip())
                            now_unixtime = int(time.time())
                            if (now_unixtime - old_unixtime) <= 60: ## 1min内
                                resobj = str(alllines[1]).strip()
                                resobj = json.loads(resobj)

                if resobj:
                    log_da = [{"msg": "Get From Cache File"}, {"content": str(resobj)}]
                    logstr = get_logstr(log_da, max_key_len=10)
                    self._logger.info(logstr)
                    return resobj
            
            pbinpaths = [
                         "/usr/local/mongodb/bin/mongo",
                         "/home/qiueer/mongodb/mongodb/bin/mongo",
            ]
            cmdstr = None
            for bp in pbinpaths:
                if os.path.exists(bp):
                    cmdstr = "echo 'db.serverStatus()' | %s admin --host '%s'  --port %s --quiet" % (bp, hostname, port)
                    if username and password:
                        cmdstr = "echo 'db.serverStatus()' | %s admin --host '%s'  --port %s -u %s -p %s --quiet" % (bp, hostname, port, username, password)
                    break
            if not cmdstr:
                return None

            (stdo_list, stde_list, retcode) = docmd(cmdstr, timeout=3, raw = False)
            
            log_da = [{"cmdstr": cmdstr},{"ret": retcode},{"stdo": None if not stdo_list else "".join(stdo_list)}, {"stde": None if not stde_list else"".join(stde_list)}]
            logstr = get_logstr(log_da, max_key_len=10)
        
            if retcode !=0:
                    self._logger.error(logstr)
                    return None
            else:
                self._logger.info(logstr)
            
            stdo_str = "".join(stdo_list)
            stdo_str = stdo_str.replace("NumberLong(", "").replace(")", "").replace("ISODate(", "")
            #print stdo_str
            resobj = json.loads(stdo_str)
            now_unixtime = int(time.time())
            with open(self._cache_file, "w") as fd:
                fd.write(str(now_unixtime)+"\n")
                fd.write(stdo_str)
                fd.close()

            return resobj
        except Exception as expt:
            import traceback
            tb = traceback.format_exc()
            self._logger.error(tb)

    def get_item_val(self, *items):
        resobj = self._get_result()
        src_res = resobj
        for item in items:
            if resobj and type(resobj) == types.DictType and resobj.has_key(item):
                resobj = resobj[item]
        if resobj == None or resobj == src_res:
            resobj = 0
        return resobj
    
    def get_result(self):
        return self._get_result()
    
    def get_item_tval(self,  items, val_type="int"):
        val = self.get_item_val(*items)
        if val == None:return None  #0也满足此条件
        if val_type == "int":
            return int(val)
        if val_type == "float":
            fval = "%.2f" % (val)
            return float(fval)
        if val_type == "str":
            return str(val)
        
        return int(val)
    
    def print_all_key_val(self):
        resobj = self._get_result()
        print json.dumps(resobj, indent=4)