代码地址:https://github.com/Ma-Jing/python/blob/master/ngxv2_traffic_daemon.py

READ.md里有使用说明!

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
# a daemon which collecting channel traffic import subprocess
import multiprocessing
import re
import os
import sys
import time
from os import stat
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from SocketServer import ThreadingMixIn __authors__ = ['majing <majing@staff.sina.com.cn>']
__version__ = "1.1"
__date__ = "Aug 14, 2015"
__license__ = "GPL license" if (hasattr(os, "devnull")):
NULL_DEVICE = os.devnull
else:
NULL_DEVICE = "/dev/null" def _redirectFileDescriptors():
"""
Redirect stdout and stderr.
"""
import resource # POSIX resource information
maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
if maxfd == resource.RLIM_INFINITY:
maxfd = 1024 for fd in range(0, maxfd):
try:
os.ttyname(fd)
except:
continue
try:
os.close(fd)
except OSError:
pass os.open(NULL_DEVICE, os.O_RDWR)
os.dup2(0, 1)
os.dup2(0, 2) def python_daemon():
"""
Make program run on daemon mode.
"""
if os.name != 'posix':
print 'Daemon is only supported on Posix-compliant systems.'
os._exit(1) try:
if(os.fork() > 0):
os._exit(0)
except OSError:
print "create daemon failed."
os._exit(1) os.chdir('/')
os.setsid()
os.umask(0) try:
if(os.fork() > 0):
os._exit(0)
_redirectFileDescriptors()
except OSError:
print "create daemon failed."
os._exit(1) logfile = '/data0/log/sinaedge/esnv2/access.log'
if not os.path.isfile(logfile):
os._exit(1) # ensure data is shared between every processes.
manager = multiprocessing.Manager()
channel_traffics = {}
channel_traffics = manager.dict() # a log generator
def logtailer(logfile):
''' custom a generator, when logfile
rotated, this generator will be closed'''
with open(logfile) as f:
last_inode = stat(logfile).st_ino
f.seek(0, 2) # seek to eof
while True:
line = f.readline()
if not line:
if last_inode != stat(logfile).st_ino:
raise StopIteration('logfile rotated')
else:
time.sleep(0.05)
continue
yield line def analysis_and_format_log():
sourcelines = logtailer(logfile)
while True:
try:
line = sourcelines.next()
channel, transfer_bytes = line.split()[0:11:10]
if not transfer_bytes.isdigit():
continue
if channel_traffics.has_key(channel):
channel_traffics[channel] += int(transfer_bytes)
else:
channel_traffics[channel] = int(transfer_bytes)
except StopIteration, e:
'''
if log rotated, clear channel_traffics dict;
then close old generator, start a new lines generator.
'''
sourcelines.close()
channel_traffics.clear()
sourcelines = logtailer(logfile)
except Exception, e:
continue #ignore other error. class GetChannelBandHandler(BaseHTTPRequestHandler):
''' a interface for query a channel current traffic'''
def do_GET(self):
self.send_response(200)
self.end_headers()
query_channel = self.path.split('/')[-1]
if query_channel in channel_traffics:
current_traffic = channel_traffics[query_channel]
self.wfile.write(current_traffic)
else:
self.wfile.write("404: channel not found")
return class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
pass if __name__ == "__main__":
python_daemon()
# start analysis_and_format_log function, run in backgroud.
d = multiprocessing.Process(name='daemon', target=analysis_and_format_log)
d.daemon = True
d.start()
server = ThreadedHTTPServer(("127.0.0.1", 8888), GetChannelBandHandler)
print 'Starting server on 8888, use <Ctrl-C> to stop'
server.serve_forever()

zabbix监控域名带宽的更多相关文章

  1. zabbix 监控域名证书到期时间!!!!

    在客户端机器上创建脚本 vim /etc/zabbix/zabbix_agentd.d/check-cert-expire.sh #!/bin/sh host=$1port=$2end_date=`o ...

  2. Zabbix监控mysql performance

    介绍 zabbix监控mysql性能,使用zabbix自带的mysql监控模板,可以监控以下内容OPS(增删改查).mysql慢查询数量.mysql请求\响应流量带宽 配置 新建mysql监控用户 G ...

  3. 分布式数据存储 - Zabbix监控MySQL性能

    Zabbix如何监控mysql性能,我们可以使用mysql自带的模板,可以监控如下内容:OPS(增删改查).mysql请求流量带宽,mysql响应流量带宽,最后会附上相应的监控图! 编写check_m ...

  4. zabbix监控的基础概念、工作原理及架构

    一.什么是zabbix及优缺点(对比cacti和nagios) Zabbix能监视各种网络参数,保证服务器系统的安全运营:并提供灵活的通知机制以让系统管理员快速定位/解决存在的各种问题.是一个基于WE ...

  5. Linux实战教学笔记49:Zabbix监控平台3.2.4(一)搭建部署与概述

    https://www.cnblogs.com/chensiqiqi/p/9162986.html 一,Zabbix架构 zabbix 是一个基于 WEB 界面的提供分布式系统监视以及网络监视功能的企 ...

  6. zabbix监控实战<1>

    第一章 监控家族 1.1 为什么选择监控? 因为在一个IT集群中或者是一个大环境中,包括各种硬件设备.软件设备等系统的构成也是极其复杂的. 多种应用构成负载的IT业务系统,保证这些资源的正常运转,是一 ...

  7. Zabbix监控平台3.2.4(一)搭建部署与概述

    一,Zabbix架构 zabbix 是一个基于 WEB 界面的提供分布式系统监视以及网络监视功能的企业级的开源解决方案.zabbix 能监视各种网络参数,保证服务器系统的安全运营:并提供灵活的通知机制 ...

  8. Zabbix监控Low level discovery实时监控网站URL状态

    今天我们来聊一聊Low level discovery这个功能,我们为什么要用到loe level discovery这个功能呢? 很多时候,在使用zabbix监控一些东西,需要对类似于Itens进行 ...

  9. zabbix监控-基本原理介绍

    一.Linux下开源监控系统简单介绍1)cacti:存储数据能力强,报警性能差2)nagios:报警性能差,存储数据仅有简单的一段可以判断是否在合理范围内的数据长度,储存在内存中.比如,连续采样数据存 ...

随机推荐

  1. 1030: [JSOI2007]文本生成器 - BZOJ

    Description JSOI交给队员ZYX一个任务,编制一个称之为“文本生成器”的电脑软件:该软件的使用者是一些低幼人群,他们现在使用的是GW文本生成器v6版.该软件可以随机生成一些文章―――总是 ...

  2. [Jquery] js验证手机号

    function checkIdPhone(id,idErr){ var reg0=/^(13[0-9]|15[012356789]|18[01235,idErr6789]|14[57]|17[0]) ...

  3. js解决checkbox全选和反选的问题

    function SelectAll() { var checkboxs=document.getElementsByName("chk_list"); for (var i=0; ...

  4. WPF SplitButton 的杂七杂八

    原文: http://www.codeproject.com/Articles/20612/A-WPF-SplitButton SplitButton.cs using System; using S ...

  5. 电商安全无小事,如何有效地抵御 CSRF 攻击?

    现在,我们绝大多数人都会在网上购物买东西.但是很多人都不清楚的是,很多电商网站会存在安全漏洞.比如乌云就通报过,国内很多家公司的网站都存在 CSRF 漏洞.如果某个网站存在这种安全漏洞的话,那么我们在 ...

  6. hbase 使用备忘

    hbase是基于hadoop的,所以hbase服务器必须启动hadoop,这点很重要. 当然hbase其实只用到了dadoop的一个组件 1. 启动hadoop-dfs 在主上执行如下命令,可以把主和 ...

  7. http://www.cnblogs.com/amboyna/archive/2008/03/08/1096024.html

    http://www.cnblogs.com/amboyna/archive/2008/03/08/1096024.html

  8. 李洪强iOS开发之XMPP

      XMPP历史 这个xmpp框架在2008年开始,不过是一个简单地RFC实现.提供一个最小的代理去接受三种xmpp的基本类型presence.message.iq.因为framwork只提供了最小的 ...

  9. arcgis 10.2 安装教程

    arcgis 10.2 安装教程(含下载地址)_百度经验 http://jingyan.baidu.com/article/fc07f98911b66912ffe5199b.html arcgis 1 ...

  10. MAC OS Nginx php-fpm相关

    Nginx 命令 sudo nginx // 启动Nginx #重新加载|重启|停止|退出 sudo nginx -s reload|reopen|stop|quit #上传文件限制更改: 进入ngi ...