定时push+告警

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. # Author : 71standby@gmail.com
  4. # Description : Keep static-file cached in local, which provide to partner upstream.
  5.  
  6. import re
  7. import json
  8. import time
  9. import socket
  10. import logging
  11. import urllib
  12. import urllib2
  13. import subprocess
  14.  
  15. class Utils(object):
  16. def __init__(self, logger):
  17. self.logger = logger
  18.  
  19. @classmethod
  20. def from_logger(cls):
  21. logger = logging.getLogger(__name__)
  22. logger.setLevel(logging.INFO)
  23. formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
  24. handler = logging.FileHandler("/path/keeping.log", mode='a')
  25. handler.setLevel(logging.INFO)
  26. handler.setFormatter(formatter)
  27. logger.addHandler(handler)
  28. return cls(logger)
  29.  
  30. def subprocess_caller(self, cmd):
  31. try:
  32. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
  33. output, error = p.communicate()
  34. code = p.returncode
  35. except Exception, e:
  36. self.logging.error('Execute %s failed: %s' % (cmd, e))
  37. return dict(output=output, error=error, code=1)
  38. return dict(output=output, error=error, code=code)
  39.  
  40. def get_local_ip(self):
  41. inner_ips = []
  42. outer_ips = []
  43. ipaddr = "/sbin/ip addr | grep inet | grep -v inet6 | grep -v 127.0.0.1 | awk -F[' '/]+ '{print $3}'"
  44. ip_regex = re.compile(r"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$")
  45. p = self.subprocess_caller(ipaddr)
  46. if 0 == p['code']:
  47. for ip in [ips.strip() for ips in p['output'].split('\n') if ips]:
  48. if ip_regex.match(ip) and ip.startswith(r'10.'):
  49. inner_ips.append(ip)
  50. elif ip_regex.match(ip):
  51. outer_ips.append(ip)
  52. else:
  53. continue
  54. if inner_ips and outer_ips:
  55. return inner_ips[0],outer_ips[0]
  56. elif not inner_ips and outer_ips:
  57. return None,outer_ips[0]
  58. else:
  59. return None,'NoPublicIP'
  60. else:
  61. self.logging.error('Get ips failed: %s' % p['error'])
  62. return None,None
  63.  
  64. class PartnerDetection(object):
  65. def __init__(self, utils):
  66. self.logger = utils.logger
  67. self.private_ip,self.public_ip = utils.get_local_ip()
  68. self.subprocess_caller = utils.subprocess_caller
  69. self.url = "http://%s:80/path/test.file" % self.public_ip
  70. self.cmd = "dd if=/dev/zero of=/data/test.file bs=1K count=100"
  71. self.alarm_url = 'http://alert.standby.pub/event/interface/'
  72. self.topic_id = 666666
  73. self.secret_key = "1234567890xxxooo"
  74.  
  75. @classmethod
  76. def from_subprocess(cls, utils):
  77. return cls(utils)
  78.  
  79. def send_alarm(self, bodyDict):
  80. data = {
  81. "topic_id": self.topic_id,
  82. "secret_key": self.secret_key,
  83. "data": json.dumps(bodyDict)
  84. }
  85. try:
  86. data = urllib.urlencode(data)
  87. req = urllib2.Request(self.alarm_url, data)
  88. response = urllib2.urlopen(req, timeout=6)
  89. result = response.read()
  90. code = response.getcode()
  91. response.close()
  92. except Exception, e:
  93. self.logger.error("Alarm exception: %s" % e)
  94. return False
  95. else:
  96. if 200 != code:
  97. self.logger.error("Alarm faild: %s" % code)
  98. return False
  99. return True
  100.  
  101. def active_cache(self):
  102. p = self.subprocess_caller(self.cmd)
  103. if 0 != p['code']:
  104. self.logger.error('Test file create failed: %s' % p['error'])
  105. ret = self.send_alarm({'ip':self.private_ip, 'error':'test.file create failed'})
  106. if not ret:
  107. self.logger.error('Test file create alarm faile!!!')
  108. else:
  109. with open("/data/test.file", mode='r') as fr:
  110. data = fr.read()
  111. self.tspush(data)
  112.  
  113. def tspush(self, data):
  114. response = "HTTP/1.1 200 OK\r\nContent-type:application/octet-stream\r\n\r\n"
  115. len_push = len(response) + len(data)
  116. push = "PUSH %s HTTP/1.0\r\nContent-Length:%d\r\n\r\n%s" % (self.url, len_push, response)
  117. push_bytes = push.encode('utf-8')
  118. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  119. try:
  120. sock.connect(('127.0.0.1', 55336))
  121. sock.send(push_bytes + data)
  122. msg = sock.recv(1024)
  123. if "200 OK" in msg or "201 Created" in msg:
  124. self.logger.info('Tspush successfully: %s' % msg.split('\r\n')[0])
  125. else:
  126. self.logger.error('Tspush failed: %s' % msg)
  127. ret = self.send_alarm({'ip':self.private_ip, 'error':'Tspush failed: %s' % msg})
  128. if not ret:
  129. self.logger.error('Tspush alarm faile!!!')
  130. except Exception, e:
  131. self.logger.error('Tspush exception: %s' % e)
  132. ret = self.send_alarm({'ip':self.private_ip, 'error':'Tspush exception: %s' % e})
  133. if not ret:
  134. self.logger.error('Tspush exception alarm faile!!!')
  135. finally:
  136. sock.close()
  137.  
  138. def url_test(self):
  139. try:
  140. response = urllib2.urlopen(url=self.url, timeout=6)
  141. code = response.getcode()
  142. data = response.read()
  143. response.close()
  144. except Exception, e:
  145. self.logger.error('Detect failed: %s' % e)
  146. code = 199
  147. finally:
  148. return code
  149.  
  150. def running(self):
  151. while True:
  152. code = self.url_test()
  153. if 200 != code:
  154. self.logger.info("MISS, start to active cache...")
  155. ret = self.send_alarm({'ip':self.private_ip, 'error':'MISS at %s' % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())})
  156. if not ret:
  157. self.logger.error('MISS alarm faile!!!')
  158. self.active_cache()
  159. else:
  160. self.logger.info("HIT")
  161. time.sleep(60)
  162.  
  163. if __name__ == '__main__':
  164. utils = Utils.from_logger()
  165. obj = PartnerDetection.from_subprocess(utils)
  166. obj.running()

  

keeping.py的更多相关文章

  1. web.py 学习(-)Rocket web框架

    Rocket是一个轻量级,多线程,符合WSGI规范的web框架. Rocket使用一个线程监听连接,接收到连接之后放到Queue中,有worker线程进行处理. Rocket含有以下属性: metho ...

  2. Python 打包中 setpy.py settuptools pbr 的了解

    背景 nova服务构建失败,报错: 'tests_require' must be a string or list of strings containing valid project/versi ...

  3. Flask源码阅读-第四篇(flask\app.py)

    flask.app该模块2000多行代码,主要完成应用的配置.初始化.蓝图注册.请求装饰器定义.应用的启动和监听,其中以下方法可以重点品读和关注 def setupmethod(f): @setupm ...

  4. tensorflow 的rnn的示例 ptb_word_lm.py 的完整代码

    其训练数据源在我的空间里,名字为:tensorflow的ptb-word-lm示例的训练数据源.tgz 讲解参见另一篇文章:  http://www.cnblogs.com/welhzh/p/6739 ...

  5. python的setup.py文件及其常用命令

    编写setup.py文件,获取帮助:python setup.py --help-commands [python]  Standard commands:    build             ...

  6. python调用py中rar的路径问题。

    1.python调用py,在py中的os.getcwd()获取的不是py的路径,可以通过os.path.split(os.path.realpath(__file__))[0]来获取py的路径. 2. ...

  7. Python导入其他文件中的.py文件 即模块

    import sys sys.path.append("路径") import .py文件

  8. import renumber.py in pymol

    cp renumber.py /usr/local/lib/python2.7/dist-packages/pymol import renumber or run /path/to/renumber ...

  9. python gettitle.py

    #!/usr/bin/env python # coding=utf-8 import threading import requests import Queue import sys import ...

随机推荐

  1. Qt Creator 搭配Git 版本控制

    再次介绍一下Git的使用,这次是在Coding.net上部署项目的.这个是写给大作业合作的小伙伴们(我和我的A奶朋友们和某A的男朋友)看的. 安装Git 首先安装Git(msysGit) 下载地址 h ...

  2. 【bfs】献给阿尔吉侬的花束

    [题目描述] 阿尔吉侬是一只聪明又慵懒的小白鼠,它最擅长的就是走各种各样的迷宫.今天它要挑战一个非常大的迷宫,研究员们为了鼓励阿尔吉侬尽快到达终点,就在终点放了一块阿尔吉侬最喜欢的奶酪.现在研究员们想 ...

  3. htmlunit 校验验证码

    htmlUnit 校验验证码 直接上代码 String url = "http://www.zycg.gov.cn/"; WebclientUtil webClientUtils ...

  4. String:字符串常量池

    String:字符串常量池 作为最基础的引用数据类型,Java 设计者为 String 提供了字符串常量池以提高其性能,那么字符串常量池的具体原理是什么,我们带着以下三个问题,去理解字符串常量池: 字 ...

  5. goroutine与调度器

    29 November 2013 by skoo 我们都知道Go语言是原生支持语言级并发的,这个并发的最小逻辑单元就是goroutine.goroutine就是Go语言提供的一种用户态线程,当然这种用 ...

  6. Learn to securely share files on the blockchain with IPFS!

    https://medium.com/@mycoralhealth/learn-to-securely-share-files-on-the-blockchain-with-ipfs-219ee47d ...

  7. 笔记:用标准c写 com dll

    在 [XXX.idl] 中 1. 如果想在脚本语言中传递一个值,并且在dll(c代码)中修改这个值并返回的话, 这个参数必须写为:[in, out] VARIANT* 如果写成 [in, out] i ...

  8. 构建flutter环境并实现属于我们的hello world

    我们知道flutter和react-native一样,都是既可以运行在andorid也可以运行在iOS环境下的. 我之前是react-native开发者,我的电脑环境中已经安装好了jdk,sdk,以及 ...

  9. 第十六节、特征描述符BRIEF(附源码)

    我们已经知道SIFT算法采用128维的特征描述子,由于描述子用的是浮点数,所以它将会占用512字节的空间.类似的SUFR算法,一般采用64维的描述子,它将占用256字节的空间.如果一幅图像中有1000 ...

  10. JavaScript的函数声明与函数表达式的区别

    1)函数声明(Function Declaration); // 函数声明 function funDeclaration(type){ return type==="Declaration ...