代码地址: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. vs2010 使用SignalR 提高B2C商城用户体验(二)

    vs2010 使用SignalR 提高B2C商城用户体验(二) 上一节,已经实现了,当前域内的通信,这一节中,介绍一下跨域的即时通信,既然要做,我们肯定要把这个推送及聊天服务器做为一个单独的服务器,以 ...

  2. FileFilter

    FileFilter 下面的例子中我们创建了一个FileFilter类,此类根据文件名的扩展名是否为.png来筛选文件.创建FileFilter实例之后需要将此实例作为参数传给File的listFil ...

  3. mysql分表与分区表

    mysql分表与分区表 转自:http://blog.51yip.com/mysql/949.html   一,什么是mysql分表,分区 什么是分表,从表面意思上看呢,就是把一张表分成N多个小表,具 ...

  4. POJ 3786 Adjacent Bit Counts (DP)

    点我看题目 题意 :给你一串由1和0组成的长度为n的数串a1,a2,a3,a4.....an,定义一个操作为AdjBC(a) = a1*a2+a2*a3+a3*a4+....+an-1*an.输入两个 ...

  5. HashTable、HashMap、LinkedHashMap、TreeMap的比较

    HashTable:继承自Dictionary类,实现了Map接口,不允许键或值为空,线程同步: HashMap:继承自AbstractMap类,实现了Map接口,允许键或值为空,线程不同步: Lin ...

  6. 一张图让你看懂锻压、CNC、压铸、冲压四类工艺!

    (锻压+CNC+阳极.CNC+阳极.压铸+阳极.冲压+阳极手机外壳比较) 上图为一张雷达图,该图比较直观形象地描述了4大手机外壳工艺在6个维度(加工成本.CNC用量.加工周期.成品率.可设计性.外观质 ...

  7. MAC下编译FFMPEG

    1.下载ffmpeg,我使用xcode自带的git下载. 或者直接下载压缩包: 2.下载gas-preprocessor脚本 https://raw.github.com/mansr/gas-prep ...

  8. R语言学习笔记:生成序列(Genenrating Sequences)

    R提供了多种生成不同类型序列的方法.如: > x<-1:20 > x [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 1 ...

  9. Node.js学习(11)----HTTP服务器与客户端

    Node.js 标准库提供了 http 模块,其中封装了一个高效的 HTTP 服务器和一个简易的HTTP 客户端.http.Server 是一个基于事件的 HTTP 服务器,它的核心由 Node.js ...

  10. lib库依赖解决

    当前环境之前是装过MySQL官方版本5.6.22,想测试Percona版本MySQL.启动Percona-MySQL报错. [root@dg7 support-files]# /etc/init.d/ ...