代码地址: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. [转载]jquery tmpl使用方法

    动态请求数据来更新页面是现在非常常用的方法,比如博客评论的分页动态加载,微博的滚动加载和定时请求加载等. 这些情况下,动态请求返回的数据一般不是已拼好的 HTML 就是 JSON 或 XML,总之不在 ...

  2. leetcode3 Two Sum III – Data structure design

    Question: Design and implement a TwoSum class. It should support the following operations: add and f ...

  3. JavaScript 踩坑心得— 为了高速(下)

    一.前言 本文的上一篇 JavaScript 踩坑心得- 为了高速(上) 主要和大家分享的是 JavaScript 使用过程中的基本原则以及编写过程中的心得分享,本文主要和大家聊聊在各个使用场景下的 ...

  4. Docker 监控实战

    如今,越来越多的公司开始使用 Docker 了,现在来给大家看几组数据: 2 / 3 的公司在尝试了 Docker 后最终使用了它 也就是说 Docker 的转化率达到了 67%,而转化市场也控制在 ...

  5. 跟随屏幕滚动层、遮罩层、获取Div相对定位、整个屏幕、html文档的jquery基本操作

    一.层跟随屏幕滚动 <div style="width:120px;height:120px;border:1px solid red; position:absolute; left ...

  6. ANDROID_MARS学习笔记_S01_004dpi、dp(dip)及计算

    一.dpi.dp介绍 sp会随着用户在手机中设置字体大小而改变,而dp不会 二.1.dpsp_layout.xml <?xml version="1.0" encoding= ...

  7. uva 993 Product of digits (贪心 + 分解因子)

      Product of digits  For a given non-negative integer number N , find the minimal natural Q such tha ...

  8. 食物卡喉别拍背部!救了100多万人性命的“海姆立克急救法"

    先讲三个事例: 一.近日,浙江金华一个17月大的小贝边玩边吃花生,被噎住.10多分钟后,奶奶发现小贝大口喘气,以为他玩累了就抱他回家,等父母赶到送医已晚.小贝大脑受损严重-父母含泪同意放弃治疗,孩子走 ...

  9. 【开源推荐】AllJoyn:打造全球物联网的通用开源框架

    摘要:随着智能设备的发展,物联网逐渐进入了人们的生活.据预测,未来几乎一切东西(超过500亿台设备)都可以互联.高通公司发布了开源项目AllJoyn,这是一个能够使连接设备间进行互操作的通用软件框架和 ...

  10. oralce索引和分区索引的使用

    oracle分区表和分区索引的本质就是将数据分段存储,包括表和索引(索引从本质上来讲也是表),表分区会将表分成多个段分别存储.由此数据查询过程改变为先根据查询条件定位分区表,然后从该表中查询数据,从而 ...