代码地址: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. asp 文件上传(无组件上传)

    文件1.上传界面文件 upload.htm<html><head><meta http-equiv="Content-Language" conten ...

  2. 以守护进程方式启动firefly

    原地址:http://www.9miao.com/question-15-53966.html 最近看源码,查了半天,没找到已守护进程方式启动firefly的方法,自己改了改写了一个,废话不多说直接上 ...

  3. dll的概念 dll导出变量 函数 类

    1. DLL的概念 DLL(Dynamic Linkable Library),动态链接库,可以向程序提供一些函数.变量或类.这些可以直接拿来使用. 静态链接库与动态链接库的区别:   (1)静态链接 ...

  4. poj 1487 Single-Player Games

    主要考察表达式的解析和高斯消元!!! #include<iostream> #include<stdio.h> #include<algorithm> #inclu ...

  5. shell中截取字符串的方法总结

    shell中截取字符串的方法有很多种, ${expression}一共有9种使用方法. ${parameter:-word} ${parameter:=word} ${parameter:?word} ...

  6. beyond compare ftp 文件夹同步

    因为经常要同步服务器上的代码,今天试了一下beyond compare 的ftp同步非常爽.以前都只用了beyond compare的文件夹比较功能了,ftp功能没有使用过. 步骤1:点击:会话——& ...

  7. SGU 168

    SGU 168,寻找矩阵中右上方,右方,下方最小的元素,采用动态规划解答. #include <iostream> #include <vector> #include < ...

  8. 【HDOJ】4347 The Closest M Points

    居然是KD解. /* 4347 */ #include <iostream> #include <sstream> #include <string> #inclu ...

  9. Lua从入门到精通

    1. 入门指南 http://www.cnblogs.com/linbc/archive/2009/06/02/1494622.html

  10. pku,杨建武:文本挖掘技术

    http://webkdd.org/course/ http://www.icst.pku.edu.cn/lcwm/course/WebDataMining/ http://www.icst.pku. ...