Linux 监控工具 tsar(转)

转自:https://blog.csdn.net/u010945668/article/details/113904993

简介
    tsar是一个淘宝开发的服务器信息采集工具。

支持采集的信息如下:

系统信息:如cpu、io、mem、tcp等
应用数据:squid、haproxy、nginx等
其他:自定义模块
具体介绍请参看以下文档:

tsar 官网
tsar工具使用
Linux系统性能监控工具介绍之-tsar
tsar 安装
安装准备
tsar 需要编译安装,安装前我们需要确保有编译环境

[root@base ~]# yum install -y cpp binutils glibc glibc-kernheaders glibc-common glibc-devel gcc gcc-c++ make
1
安装
#下载源码包
[root@base ~]# wget -O tsar.zip https://github.com/alibaba/tsar/archive/master.zip --no-check-certificate
# 解压源码包
[root@base ~]# unzip tsar.zip && mv tsar-master tsar
[root@base ~]# cd tsar
# 编译安装
[root@base tsar]# make && make install
1
2
3
4
5
6
7
tsar使用
参考下面的帮助信息,完成对应的监控。

$tsar -h
Usage: tsar [options]
Options:
    -check         查看最后一次的采集数据
    --check/-C     查看最后一次tsar的提醒信息,如:tsar --check / tsar --check --cpu --io
    --cron/-c      使用crond模式来进行tsar监控
    --interval/-i  指明tsar的间隔时间,默认单位分钟,带上--live参数则单位是秒 
    --list/-L      列出启用的模块
    --live/-l      查看实时数据
    --file/-f      指定输入文件
    --ndays/-n     指定过去的数据天数,默认1天
    --date/-d      指定日期,YYYYMMDD或者n代表n天前
    --detail/-D    能够指定查看主要字段还是模块的所有字段
    --spec/-s      指定字段,tsar –cpu -s sys,util

Modules Enabled:
    --cpu               列出cpu相关的监控计数
    --mem               物理内存的使用情况
    --swap              虚拟内存的使用情况
    --tcp               TCP 协议 IPV4的使用情况
    --udp               UDP 协议 IPV4的使用情况
    --traffic           网络传出的使用情况
    --io                Linux IO的情况
    --pcsw              进程和上下文切换
    --partition         磁盘使用情况
    --tcpx              TCP 连接相关的数据参数
    --load              系统负载情况
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
脚本导出CSV文件
注意:使用 Python 2.7.5 版本

#!/bin/python
# encoding=utf-8
# author: Onovo
import sys
import calendar
import time
import datetime
import os
import re

def tsar(type='', date=''):
    """
        tsar 导出概览信息
        type: 查询类型
        date: 查询日期(格式:yyyyMMdd)
    """
    date = date if date != '' else (datetime.date.today() + datetime.timedelta(-1)).strftime("%Y%m%d")
    print "export " + date + ": " + type + " data ..."
    os.environ['type'] = '' if type == '' else '--' + type
    os.environ['date'] = date
    exportFileName = ''
    title = ''
    if type == '':
        exportFileName = "00 概述信息-"
        # 执行 `tsar -d 1` 查看修正title
        title = 'Time,cpu,mem,tcp-retran,traffic-bytin,traffic-bytout,sda,dm-0,dm-1,load\n'
    elif type.lower() == 'cpu':
        exportFileName = "01 CPU相关监控计数-"
        title = 'Time,user,sys,wait,hirq,sirq,util\n'
    elif type.lower() == 'mem':
        exportFileName = "02 物理内存使用情况-"
        title = 'Time,free,used,buff,cach,total,util\n'
    elif type.lower() == 'swap':
        exportFileName = "03 虚拟内存使用情况-"
        title = 'Time,swpin,swpout,total,util\n'
    elif type.lower() == 'tcp':
        exportFileName = "04 TCP(IPV4)使用情况-"
        title = 'Time,active,pasive,iseg,outseg,EstRes,AtmpFa,CurrEs,retran\n'
    elif type.lower() == 'udp':
        exportFileName = "05 UDP(IPV4)使用情况-"
        title = 'Time,idgm,odgm,noport,idmerr\n'
    elif type.lower() == 'traffic':
        exportFileName = "06 网络传输情况-"
        title = 'Time,bytin,bytout,pktin,pktout,pkterr,pktdrp\n'
    elif type.lower() == 'io':
        exportFileName = "07 IO使用情况-"
        disks = os.popen("tsar --io -d 1 | head -n 1 | sed 's/-//g' | sed 's/[ ][ ]*/ /g'").readline().strip().split(' ')
        diskNumber = len(disks)
        if diskNumber > 1:
            for index in range(1, diskNumber):
                if index == 1:
                    title = title + ','
                title = title + disks[index] + ',,,,,,,,,,,,,,,,,'
            title = title + '\n'
            for index in range(1, diskNumber):
                if index == 1:
                    title = title + 'Time,'
                title = title + 'rrqms,wrqms,%rrqm,%wrqm,rs,ws,rsecs,wsecs,rqsize,rarqsz,warqsz,qusize,await,rawait,wawait,svctm,util,'
            title = title + '\n'
        else:
            title = title + 'Time,rrqms,wrqms,%rrqm,%wrqm,rs,ws,rsecs,wsecs,rqsize,rarqsz,warqsz,qusize,await,rawait,wawait,svctm,util\n'
    elif type.lower() == 'pcsw':
        exportFileName = "08 进程和上下文切换情况-"
        title = 'Time,swch,proc\n'
    elif type.lower() == 'partition':
        exportFileName = "09 磁盘使用情况-"
        title = 'Time,bfree,bused,btotl,util,ifree,itotl,iutil,bfree,bused,btotl,util,ifree,itotl,iutil\n'
    elif type.lower() == 'tcpx':
        exportFileName = "10 TCP连接相关数据参数情况-"
        title = 'Time,recvq,sendq,est,twait,fwait1,fwait2,lisq,lising,lisove,cnest,ndrop,edrop,rdrop,pdrop,kdrop\n'
    elif type.lower() == 'load':
        exportFileName = "11 系统负载情况-"
        title = 'Time,load1,load5,load15,runq,plit\n'
    else:
        raise ValueError('参数 type 错误!')

    export = open("./inspection-logs/" + exportFileName + date + ".csv", "a+")
    # 添加表头
    if len(export.readlines()) < 1:
        export.write(title)
    # 获取数据
    lines = os.popen("tsar $type --date $date | grep -v Time | grep -v MAX | grep -v MEAN | grep -v MIN").readlines()
    for line in lines:
        if len(line) < 2:
            continue
        hard_info = re.sub('\s+', ' ', line.replace('\n', '').strip()).split(' ')
        hard_info[0] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.mktime(time.strptime(hard_info[0], "%d/%m/%y-%H:%M"))))
        export.write(','.join(hard_info) + '\n')
    export.close()

def export_summarize_info(date=''):
    """
        导出概述信息
    """
    tsar('', date)

def export_cpu_info(date=''):
    """
        导出CPU相关监控计数
    """
    tsar('cpu', date)


def export_mem_info(date=''):
    """
        导出物理内存使用情况
    """
    tsar('mem', date)

def export_swap_info(date=''):
    """
        导出虚拟内存使用情况
    """
    tsar('swap', date)

def export_tcp_info(date=''):
    """
        导出TCP(IPV4)使用情况
    """
    tsar('tcp', date)

def export_udp_info(date=''):
    """
        导出UDP(IPV4)使用情况
    """
    tsar('udp', date)

def export_traffic_info(date=''):
    """
        导出网络传输情况
    """
    tsar('traffic', date)

def export_io_info(date=''):
    """
        导出IO使用情况
    """
    tsar('io', date)

def export_pcsw_info(date=''):
    """
        导出进程和上下文切换情况
    """
    tsar('pcsw', date)

def export_partition_info(date=''):
    """
        导出磁盘使用情况
    """
    tsar('partition', date)

def export_tcpx_info(date=''):
    """
        导出TCP连接相关数据参数情况
    """
    tsar('tcpx', date)

def export_load_info(date=''):
    """
        导出系统负载情况
    """
    tsar('load', date)

def export_all_info(date=''):
    """
        导出所有信息
    """
    export_summarize_info(date)
    export_cpu_info(date)
    export_mem_info(date)
    export_swap_info(date)
    export_tcp_info(date)
    export_udp_info(date)
    export_traffic_info(date)
    export_io_info(date)
    export_pcsw_info(date)
    export_partition_info(date)
    export_tcpx_info(date)
    export_load_info(date)

if __name__ == "__main__":
    """
        巡检主函数
    """
    date = sys.argv[1]
    print '即将导出数据: ' + date
    start_time = time.time()
    if len(date) == 6:
        # 数据切片取得年
        year = date[0:4]
        # 数据切片取得月
        month = date[4:6]
        date_now = int(time.strftime("%Y%m%d", time.localtime()))
        # 遍历指定月份的每一天
        for day in range(1, calendar.monthrange(int(year), int(month))[1] + 1):
            if day < 9:
                date = year + month + str(0) + str(day)
            else:
                date = year + month + str(day)
            day = day + 1
            # 判断结束日期
            if int(date) > date_now:
                continue
            export_all_info(date)
    elif len(date) == 8:
        export_all_info(date)
    else:
        print '输入的日期格式错误,正确格式为 yyyyMM 或 yyyyMMdd'
    total_time = time.time() - start_time
    print '耗时:', time.strftime("%M分%S秒", time.localtime(total_time))

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
脚本调用方法

# 按日导出
[root@localhost ~]# ./tsar_check.py 20210221
# 按月导出
[root@localhost ~]# ./tsar_check.py 202102
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值