基于python3抓取pinpoint应用信息入库
作者:whitesky-root 发布时间:2021-08-05 12:21:02
标签:python,抓取,pinpoint,信息,库
这篇文章主要介绍了基于python3抓取pinpoint应用信息入库,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
Pinpoint是用Java编写的大型分布式系统的APM(应用程序性能管理)工具。 受Dapper的启发,Pinpoint提供了一种解决方案,通过在分布式应用程序中跟踪事务来帮助分析系统的整体结构以及它们中的组件之间的相互关系.
pinpoint api:
/applications.pinpoint 获取applications基本信息
/getAgentList.pinpoint 获取对应application agent信息
/getServerMapData.pinpoint 获取对应app 基本数据流信息
db.py
import mysql.connector
class MyDB(object):
"""docstring for MyDB"""
def __init__(self, host, user, passwd , db):
self.host = host
self.user = user
self.passwd = passwd
self.db = db
self.connect = None
self.cursor = None
def db_connect(self):
"""数据库连接
"""
self.connect = mysql.connector.connect(host=self.host, user=self.user, passwd=self.passwd, database=self.db)
return self
def db_cursor(self):
if self.connect is None:
self.connect = self.db_connect()
if not self.connect.is_connected():
self.connect = self.db_connect()
self.cursor = self.connect.cursor()
return self
def get_rows(self , sql):
""" 查询数据库结果
:param sql: SQL语句
:param cursor: 数据库游标
"""
self.cursor.execute(sql)
return self.cursor.fetchall()
def db_execute(self, sql):
self.cursor.execute(sql)
self.connect.commit()
def db_close(self):
"""关闭数据库连接和游标
:param connect: 数据库连接实例
:param cursor: 数据库游标
"""
if self.connect:
self.connect.close()
if self.cursor:
self.cursor.close()
pinpoint.py:
# -*- coding: utf-8 -*-
'''
Copyright (c) 2018, mersap
All rights reserved.
摘 要: pinpoint.py
创 建 者: mersap
创建日期: 2019-01-17
'''
import sys
import requests
import time
import datetime
import json
sys.path.append('../Golf')
import db #db.py
PPURL = "https://pinpoint.*******.com"
From_Time = datetime.datetime.now() + datetime.timedelta(seconds=-60)
To_Time = datetime.datetime.now()
From_TimeStamp = int(time.mktime(From_Time.timetuple()))*1000
To_TimeStamp = int(time.mktime(datetime.datetime.now().timetuple()))*1000
class PinPoint(object):
"""docstring for PinPoint"""
def __init__(self, db):
self.db = db
super(PinPoint, self).__init__()
"""获取pinpoint中应用"""
def get_applications(self):
'''return application dict
'''
applicationListUrl = PPURL + "/applications.pinpoint"
res = requests.get(applicationListUrl)
if res.status_code != 200:
print("请求异常,请检查")
return
applicationLists = []
for app in res.json():
applicationLists.append(app)
applicationListDict={}
applicationListDict["applicationList"] = applicationLists
return applicationListDict
def getAgentList(self, appname):
AgentListUrl = PPURL + "/getAgentList.pinpoint"
param = {
'application':appname
}
res = requests.get(AgentListUrl, params=param)
if res.status_code != 200:
print("请求异常,请检查")
return
return len(res.json().keys()),json.dumps(list(res.json().keys()))
def update_servermap(self, appname , from_time=From_TimeStamp,
to_time=To_TimeStamp, serviceType='SPRING_BOOT'):
'''更新app上下游关系
:param appname: 应用名称
:param serviceType: 应用类型
:param from_time: 起始时间
:param to_time: 终止时间
:
'''
#https://pinpoint.*****.com/getServerMapData.pinpoint?applicationName=test-app&from=1547721493000&to=1547721553000&callerRange=1&calleeRange=1&serviceTypeName=TOMCAT&_=1547720614229
param = {
'applicationName':appname,
'from':from_time,
'to':to_time,
'callerRange':1,
'calleeRange':1,
'serviceTypeName':serviceType
}
# serverMapUrl = PPURL + "/getServerMapData.pinpoint"
serverMapUrl = "{}{}".format(PPURL, "/getServerMapData.pinpoint")
res = requests.get(serverMapUrl, params=param)
if res.status_code != 200:
print("请求异常,请检查")
return
update_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
links = res.json()["applicationMapData"]["linkDataArray"]
for link in links :
###排除test的应用
if link['sourceInfo']['applicationName'].startswith('test'):
continue
#应用名称、应用类型、下游应用名称、下游应用类型、应用节点数、下游应用节点数、总请求数、 错误请求数、慢请求数(本应用到下一个应用的数量)
application = link['sourceInfo']['applicationName']
serviceType = link['sourceInfo']['serviceType']
to_application = link['targetInfo']['applicationName']
to_serviceType = link['targetInfo']['serviceType']
agents = len(link.get('fromAgent',' '))
to_agents = len(link.get('toAgent',' '))
totalCount = link['totalCount']
errorCount = link['errorCount']
slowCount = link['slowCount']
sql = """
REPLACE into application_server_map (application, serviceType,
agents, to_application, to_serviceType, to_agents, totalCount,
errorCount,slowCount, update_time, from_time, to_time)
VALUES ("{}", "{}", {}, "{}", "{}", {}, {}, {}, {},"{}","{}",
"{}")""".format(
application, serviceType, agents, to_application,
to_serviceType, to_agents, totalCount, errorCount,
slowCount, update_time, From_Time, To_Time)
self.db.db_execute(sql)
def update_app(self):
"""更新application
"""
appdict = self.get_applications()
apps = appdict.get("applicationList")
update_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
for app in apps:
if app['applicationName'].startswith('test'):
continue
agents, agentlists = self.getAgentList(app['applicationName'])
sql = """
REPLACE into application_list( application_name,
service_type, code, agents, agentlists, update_time)
VALUES ("{}", "{}", {}, {}, '{}', "{}");""".format(
app['applicationName'], app['serviceType'],
app['code'], agents, agentlists, update_time)
self.db.db_execute(sql)
return True
def update_all_servermaps(self):
"""更新所有应用数
"""
appdict = self.get_applications()
apps = appdict.get("applicationList")
for app in apps:
self.update_servermap(app['applicationName'], serviceType=app['serviceType'])
###删除7天前数据
Del_Time = datetime.datetime.now() + datetime.timedelta(days=-7)
sql = """delete from application_server_map where update_time <= "{}"
""".format(Del_Time)
self.db.db_execute(sql)
return True
def connect_db():
""" 建立SQL连接
"""
mydb = db.MyDB(
host="rm-*****.mysql.rds.aliyuncs.com",
user="user",
passwd="passwd",
db="pinpoint"
)
mydb.db_connect()
mydb.db_cursor()
return mydb
def main():
db = connect_db()
pp = PinPoint(db)
pp.update_app()
pp.update_all_servermaps()
db.db_close()
if __name__ == '__main__':
main()
附sql语句
CREATE TABLE `application_list` (
`application_name` varchar(32) NOT NULL,
`service_type` varchar(32) DEFAULT NULL COMMENT '服务类型',
`code` int(11) DEFAULT NULL COMMENT '服务类型代码',
`agents` int(11) DEFAULT NULL COMMENT 'agent个数',
`agentlists` varchar(256) DEFAULT NULL COMMENT 'agent list',
`update_time` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`application_name`),
UNIQUE KEY `Unique_App` (`application_name`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='pinpoint app list'
CREATE TABLE `application_server_map` (
`application` varchar(32) NOT NULL COMMENT '应用名称',
`serviceType` varchar(8) NOT NULL,
`agents` int(2) NOT NULL COMMENT 'agent个数',
`to_application` varchar(32) NOT NULL COMMENT '下游服务名称',
`to_serviceType` varchar(32) DEFAULT NULL COMMENT '下游服务类型',
`to_agents` int(2) DEFAULT NULL COMMENT '下游服务agent数量',
`totalCount` int(8) DEFAULT NULL COMMENT '总请求数',
`errorCount` int(8) DEFAULT NULL,
`slowCount` int(8) DEFAULT NULL,
`update_time` datetime NOT NULL ON UPDATE CURRENT_TIMESTAMP,
`from_time` datetime DEFAULT NULL,
`to_time` datetime DEFAULT NULL,
PRIMARY KEY (`application`,`to_application`),
UNIQUE KEY `Unique_AppMap` (`application`,`to_application`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='应用链路数据'
来源:https://www.cnblogs.com/yum777/p/12155632.html
0
投稿
猜你喜欢
- 认识pip众所周知,pip可以对python的第三方库进行安装、更新、卸载等操作,十分方便。pip的全称:package installer
- 这两条是关于IE环境中的CSS的。不要使用import引入CSS,可以避免内容的无样式瞬间(FOUC)问题。不要把样式的link放到页面后(
- 我在一篇文章所说,首页的“站点名称”最好用h1标签来定义,但从美观考虑,要用logo图片来代替h1,这时需要隐藏h1内的这段文字,但又不能对
- 看完了这个你就可以用asp修改注册表了!大名鼎鼎的WSH听说过吗? 它就是Windows script Host的缩写形式,WSH是Wind
- 问题你想使用一个Python字典存储数据,并将它转换成XML格式。解决方案尽管 xml.etree.ElementTree 库通常用来做解析
- 前言首先抛出几个问题:console.log(Boolean({}));console.log(Number([]));console.lo
- 漂亮的代码是漂亮网站的基础,优秀的 CSS 只存在与同样优秀的 HTML 之上,干净的,语义的 HTML 代码让一个网站更健壮。本文讲述了1
- 看那个自由落体div有感。这个没落体,画个圆。(ie only)<html><head><style>v
- django中,很多时候我们都需要有一个地方来进行更加详细的权限控制,例如说哪些用户可以访问哪些页面,检查登录状态等,这里的话就涉及到了中间
- 如下所示:import dateutildef before_month_lastday(ti): today=dateutil
- 用JDBC实现对MySQL的“增删改查”:import java.sql.Connection;im
- Oracle的Nvl函数nvl( ) 函数从两个表达式返回一个非null 值。语法NVL(eExpression1, eExpression
- 我们在浏览网页的时候偶尔会遇到一些陌生的网页交互行为,通常情况下它们并不会影响你的正常使用,之所以出现情况往往是因为,设计师在设计某个交互方
- 一、表示修饰符。可以在模块或者类的定义层内对函数进行修饰。出现在函数定义的前一行,不允许和函数定义在同一行。一个修饰符就是一个函数,它将被修
- 一、读者指引读者指引帮助你掌握本文的梗概。以免你看了大半才明白这编文章不适合你,给你造成视觉污染。如果你正在用ASP+XML写一些程序,或者
- 今天在 ajaxian 上看到一篇文章,名为 Five Ajax Anti-pattern ,觉得讲得比较有道理,现粗略翻译一下,加一些自己
- php中可以使用 mb_detect_encoding() 函数来判断字符串是什么编码的。当在php中使用mb_detect_encodin
- python版本:3.6+需要模块:flask,pillow需求:开发一个支持多格式图片上传的接口,并且将图片压缩,支持在线预览图片。目录结
- 微软最近出了个 必应bing 缤纷桌面,使用下来还是不错,可以每天更换Bing首页的北京作为壁纸,但是该软件有个不好的地方是,安装后桌面上会
- 在讨论IE6的BUG及如何修复之前,有必要讲叙一些策略去避免这些恼人的问题——正所谓防患于未然 。IE6 市场占有率据Market Shar