定时push+告警

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author : 71standby@gmail.com
# Description : Keep static-file cached in local, which provide to partner upstream. import re
import json
import time
import socket
import logging
import urllib
import urllib2
import subprocess class Utils(object):
def __init__(self, logger):
self.logger = logger @classmethod
def from_logger(cls):
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
handler = logging.FileHandler("/path/keeping.log", mode='a')
handler.setLevel(logging.INFO)
handler.setFormatter(formatter)
logger.addHandler(handler)
return cls(logger) def subprocess_caller(self, cmd):
try:
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
output, error = p.communicate()
code = p.returncode
except Exception, e:
self.logging.error('Execute %s failed: %s' % (cmd, e))
return dict(output=output, error=error, code=1)
return dict(output=output, error=error, code=code) def get_local_ip(self):
inner_ips = []
outer_ips = []
ipaddr = "/sbin/ip addr | grep inet | grep -v inet6 | grep -v 127.0.0.1 | awk -F[' '/]+ '{print $3}'"
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]?)$")
p = self.subprocess_caller(ipaddr)
if 0 == p['code']:
for ip in [ips.strip() for ips in p['output'].split('\n') if ips]:
if ip_regex.match(ip) and ip.startswith(r'10.'):
inner_ips.append(ip)
elif ip_regex.match(ip):
outer_ips.append(ip)
else:
continue
if inner_ips and outer_ips:
return inner_ips[0],outer_ips[0]
elif not inner_ips and outer_ips:
return None,outer_ips[0]
else:
return None,'NoPublicIP'
else:
self.logging.error('Get ips failed: %s' % p['error'])
return None,None class PartnerDetection(object):
def __init__(self, utils):
self.logger = utils.logger
self.private_ip,self.public_ip = utils.get_local_ip()
self.subprocess_caller = utils.subprocess_caller
self.url = "http://%s:80/path/test.file" % self.public_ip
self.cmd = "dd if=/dev/zero of=/data/test.file bs=1K count=100"
self.alarm_url = 'http://alert.standby.pub/event/interface/'
self.topic_id = 666666
self.secret_key = "1234567890xxxooo" @classmethod
def from_subprocess(cls, utils):
return cls(utils) def send_alarm(self, bodyDict):
data = {
"topic_id": self.topic_id,
"secret_key": self.secret_key,
"data": json.dumps(bodyDict)
}
try:
data = urllib.urlencode(data)
req = urllib2.Request(self.alarm_url, data)
response = urllib2.urlopen(req, timeout=6)
result = response.read()
code = response.getcode()
response.close()
except Exception, e:
self.logger.error("Alarm exception: %s" % e)
return False
else:
if 200 != code:
self.logger.error("Alarm faild: %s" % code)
return False
return True def active_cache(self):
p = self.subprocess_caller(self.cmd)
if 0 != p['code']:
self.logger.error('Test file create failed: %s' % p['error'])
ret = self.send_alarm({'ip':self.private_ip, 'error':'test.file create failed'})
if not ret:
self.logger.error('Test file create alarm faile!!!')
else:
with open("/data/test.file", mode='r') as fr:
data = fr.read()
self.tspush(data) def tspush(self, data):
response = "HTTP/1.1 200 OK\r\nContent-type:application/octet-stream\r\n\r\n"
len_push = len(response) + len(data)
push = "PUSH %s HTTP/1.0\r\nContent-Length:%d\r\n\r\n%s" % (self.url, len_push, response)
push_bytes = push.encode('utf-8')
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect(('127.0.0.1', 55336))
sock.send(push_bytes + data)
msg = sock.recv(1024)
if "200 OK" in msg or "201 Created" in msg:
self.logger.info('Tspush successfully: %s' % msg.split('\r\n')[0])
else:
self.logger.error('Tspush failed: %s' % msg)
ret = self.send_alarm({'ip':self.private_ip, 'error':'Tspush failed: %s' % msg})
if not ret:
self.logger.error('Tspush alarm faile!!!')
except Exception, e:
self.logger.error('Tspush exception: %s' % e)
ret = self.send_alarm({'ip':self.private_ip, 'error':'Tspush exception: %s' % e})
if not ret:
self.logger.error('Tspush exception alarm faile!!!')
finally:
sock.close() def url_test(self):
try:
response = urllib2.urlopen(url=self.url, timeout=6)
code = response.getcode()
data = response.read()
response.close()
except Exception, e:
self.logger.error('Detect failed: %s' % e)
code = 199
finally:
return code def running(self):
while True:
code = self.url_test()
if 200 != code:
self.logger.info("MISS, start to active cache...")
ret = self.send_alarm({'ip':self.private_ip, 'error':'MISS at %s' % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())})
if not ret:
self.logger.error('MISS alarm faile!!!')
self.active_cache()
else:
self.logger.info("HIT")
time.sleep(60) if __name__ == '__main__':
utils = Utils.from_logger()
obj = PartnerDetection.from_subprocess(utils)
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. Android客户端与数据库交互数据的简单学习

    Ø  数据库整理方案如下: 一.Android+ webservices+SQLServer  : 通过webservices客户端向指定服务器发送请求,服务器响应返回指定格式的数据,如json或者x ...

  2. 求集合中选一个数与当前值进行位运算的max

    求集合中选一个数与当前值进行位运算的max 这是一个听来的神仙东西. 先确定一下值域把,大概\(2^{16}\),再大点也可以,但是这里就只是写写,所以无所谓啦. 我们先看看如果暴力求怎么做,位运算需 ...

  3. 不能靠眼睛之 KEIL 中失效代码灰暗特性

    @2019-02-15 [问题描述] 使用 KEIL(带灰暗特性版本) 查看头文件代码时,其中有依据不同宏定义对应不同执行语句代码部分,依据灰暗特性呈现生效与失效代码,靠眼睛反应就是灰暗呈现为失效代码 ...

  4. 51NOD1174 区间最大数 && RMQ问题(ST算法)

    RMQ问题(区间最值问题Range Minimum/Maximum Query) ST算法 RMQ(Range Minimum/Maximum Query),即区间最值查询,是指这样一个问题:对于长度 ...

  5. HR_Two Strings

    https://www.hackerrank.com/challenges/two-strings/problem?h_l=interview&playlist_slugs%5B%5D=int ...

  6. 【nginx】nginx配置文件结构,内置变量及参数调优

    Nginx的配置文件是一个纯文本文件,它一般位于Nginx安装目录的conf目录下,整个配置文件是以block的形式组织的.每个block一般以一个大括号“{”来表示.block 可以分为几个层次,整 ...

  7. tyvj/joyoi 1043 表达式计算4

    这题怎么这么毒瘤... 一开始我想转后缀表达式来计算,后来发现有负数...弃疗. 递归求解又发现会有多余括号,我觉得不行... 实在是毒瘤啊! #include <cstdio> #inc ...

  8. 【POJ2230】Watchcow

    题目大意:给定一个 N 个点,M 条边的无向图,要求不重复地经过每条边两次,并且从 1 号节点出发最后回到 1 号节点,求一条路径. 题解:不重复地经过两次这个操作很容易地通过无向图的建边方式来实现, ...

  9. 【洛谷P4878】布局

    题目大意:给定一个长度为 N 的递增序列,有 M 组差分约束关系,求满足这些约束关系时,第一个数和第 N 个数的差是多少. 题解:首先,能否满足约束关系需要判断一下负环,若满足约束关系,再从第一个点 ...

  10. textarea高度自适应自动展开

    在使用之前,推荐两个比较好的事件,分别是oninput和onpropertychange,IE9以下不兼容oninput.在textarea发生变化时,可以通过监听这两个事件来触发你需要的功能. te ...