设为首页 收藏本站
查看: 611|回复: 0

[经验分享] ansible 1.7.2 api 获取有某些应用的ip

[复制链接]

尚未签到

发表于 2018-7-30 08:34:58 | 显示全部楼层 |阅读模式
#!/usr/bin/python  

  

  
""" Check Zookeeper Cluster
  

  
zookeeper version should be newer than 3.4.x
  

  
# echo mntr|nc 127.0.0.1 2181
  
zk_version  3.4.6-1569965, built on 02/20/2014 09:09 GMT
  
zk_avg_latency  0
  
zk_max_latency  4
  
zk_min_latency  0
  
zk_packets_received 84467
  
zk_packets_sent 84466
  
zk_num_alive_connections    3
  
zk_outstanding_requests 0
  
zk_server_state follower
  
zk_znode_count  17159
  
zk_watch_count  2
  
zk_ephemerals_count 1
  
zk_approximate_data_size    6666471
  
zk_open_file_descriptor_count   29
  
zk_max_file_descriptor_count    102400
  

  
# echo ruok|nc 127.0.0.1 2181
  
imok
  

  
"""
  

  
import sys
  
import socket
  
import re
  
import subprocess
  
from StringIO import StringIO
  
import os
  

  

  
zabbix_sender = '/opt/app/zabbix/sbin/zabbix_sender'
  
zabbix_conf = '/opt/app/zabbix/conf/zabbix_agentd.conf'
  
send_to_zabbix = 1
  

  

  

  
############# get zookeeper server status
  
class ZooKeeperServer(object):
  

  
    def __init__(self, host='localhost', port='2181', timeout=1):
  
        self._address = (host, int(port))
  
        self._timeout = timeout
  
        self._result  = {}
  

  
    def _create_socket(self):
  
        return socket.socket()
  

  

  
    def _send_cmd(self, cmd):
  
        """ Send a 4letter word command to the server """
  
        s = self._create_socket()
  
        s.settimeout(self._timeout)
  

  
        s.connect(self._address)
  
        s.send(cmd)
  

  
        data = s.recv(2048)
  
        s.close()
  

  
        return data
  

  
    def get_stats(self):
  
        """ Get ZooKeeper server stats as a map """
  
        data_mntr = self._send_cmd('mntr')
  
        data_ruok = self._send_cmd('ruok')
  
        if data_mntr:
  
            result_mntr = self._parse(data_mntr)
  
        if data_ruok:
  
            result_ruok = self._parse_ruok(data_ruok)
  

  
        self._result = dict(result_mntr.items() + result_ruok.items())
  

  
        if not self._result.has_key('zk_followers') and not self._result.has_key('zk_synced_followers') and not self._result.has_key('zk_pending_syncs'):
  

  
           ##### the tree metrics only exposed on leader role zookeeper server, we just set the followers' to 0
  
           leader_only = {'zk_followers':0,'zk_synced_followers':0,'zk_pending_syncs':0}
  
           self._result = dict(result_mntr.items() + result_ruok.items() + leader_only.items() )
  

  
        return self._result
  

  

  

  
    def _parse(self, data):
  
        """ Parse the output from the 'mntr' 4letter word command """
  
        h = StringIO(data)
  

  
        result = {}
  
        for line in h.readlines():
  
            try:
  
                key, value = self._parse_line(line)
  
                result[key] = value
  
            except ValueError:
  
                pass # ignore broken lines
  

  
        return result
  

  
    def _parse_ruok(self, data):
  
        """ Parse the output from the 'ruok' 4letter word command """
  

  
        h = StringIO(data)
  

  
        result = {}
  

  
        ruok = h.readline()
  
        if ruok:
  
           result['zk_server_ruok'] = ruok
  

  
        return result
  

  

  

  
    def _parse_line(self, line):
  
        try:
  
            key, value = map(str.strip, line.split('\t'))
  
        except ValueError:
  
            raise ValueError('Found invalid line: %s' % line)
  

  
        if not key:
  
            raise ValueError('The key is mandatory and should not be empty')
  

  
        try:
  
            value = int(value)
  
        except (TypeError, ValueError):
  
            pass
  

  
        return key, value
  

  

  

  
    def get_pid(self):
  
#  ps -ef|grep java|grep zookeeper|awk '{print $2}'
  
         pidarg = '''ps -ef|grep java|grep zookeeper|grep -v grep|awk '{print $2}' '''
  
         pidout = subprocess.Popen(pidarg,shell=True,stdout=subprocess.PIPE)
  
         pid = pidout.stdout.readline().strip('\n')
  
         return pid
  

  

  
    def send_to_zabbix(self, metric):
  
         key = "zookeeper.status[" +  metric + "]"
  

  
         if send_to_zabbix > 0:
  
             #print key + ":" + str(self._result[metric])
  
             try:
  

  
                subprocess.call([zabbix_sender, "-c", zabbix_conf, "-k", key, "-o", str(self._result[metric]) ], stdout=FNULL, stderr=FNULL, shell=False)
  
             except OSError, detail:
  
                print "Something went wrong while exectuting zabbix_sender : ", detail
  
         else:
  
                print "Simulation: the following command would be execucted :\n", zabbix_sender, "-c", zabbix_conf, "-k", key, "-o", self._result[metric], "\n"
  

  

  

  

  
def usage():
  
        """Display program usage"""
  

  
        print "\nUsage : ", sys.argv[0], " alive|all"
  
        print "Modes : \n\talive : Return pid of running zookeeper\n\tall : Send zookeeper stats as well"
  
        sys.exit(1)
  

  

  

  
accepted_modes = ['alive', 'all']
  

  
if len(sys.argv) == 2 and sys.argv[1] in accepted_modes:
  
        mode = sys.argv[1]
  
else:
  
        usage()
  

  

  

  

  
zk = ZooKeeperServer()
  
#  print zk.get_stats()
  
pid = zk.get_pid()
  

  
if pid != "" and  mode == 'all':
  
   zk.get_stats()
  
   # print zk._result
  
   FNULL = open(os.devnull, 'w')
  
   for key in zk._result:
  
       zk.send_to_zabbix(key)
  
   FNULL.close()
  
   print pid
  

  
elif pid != "" and mode == "alive":
  
    print pid
  
else:
  
    print 0

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-543320-1-1.html 上篇帖子: 20分钟教你学会熟练使用ansible-10995114 下篇帖子: ansible-10846468
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表