侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

基于python3抓取pinpoint应用信息入库

Python  /  管理员 发布于 7年前   182

这篇文章主要介绍了基于python3抓取pinpoint应用信息入库,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

Pinpoint是用Java编写的大型分布式系统的APM(应用程序性能管理)工具。 受Dapper的启发,Pinpoint提供了一种解决方案,通过在分布式应用程序中跟踪事务来帮助分析系统的整体结构以及它们中的组件之间的相互关系.

pinpoint api:

  • /applications.pinpoint 获取applications基本信息
  • /getAgentList.pinpoint 获取对应application agent信息
  • /getServerMapData.pinpoint 获取对应app 基本数据流信息

db.py

import mysql.connectorclass 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, mersapAll rights reserved.摘 要: pinpoint.py创 建 者: mersap创建日期: 2019-01-17'''import sysimport requestsimport timeimport datetimeimport jsonsys.path.append('../Golf')import db #db.pyPPURL = "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()))*1000To_TimeStamp = int(time.mktime(datetime.datetime.now().timetuple()))*1000class 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 Truedef 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 mydbdef 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='应用链路数据'

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    python 爬取古诗文存入mysql数据库的方法
    下一条:
    Python PyInstaller安装和使用教程详解
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客