基于python3抓取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='应用链路数据'

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

(0)

相关推荐

  • Python3爬虫学习之MySQL数据库存储爬取的信息详解

    本文实例讲述了Python3爬虫学习之MySQL数据库存储爬取的信息.分享给大家供大家参考,具体如下: 数据库存储爬取的信息(MySQL) 爬取到的数据为了更好地进行分析利用,而之前将爬取得数据存放在txt文件中后期处理起来会比较麻烦,很不方便,如果数据量比较大的情况下,查找更加麻烦,所以我们通常会把爬取的数据存储到数据库中便于后期分析利用. 这里,数据库选择MySQL,采用pymysql 这个第三方库来处理python和mysql数据库的存取,python连接mysql数据库的配置信息 db_

  • Python实现的查询mysql数据库并通过邮件发送信息功能

    本文实例讲述了Python实现的查询mysql数据库并通过邮件发送信息功能.分享给大家供大家参考,具体如下: 这里使用Python查询mysql数据库,并通过邮件发送宕机信息. Python代码如下: #-*- coding: UTF-8 -*- #!/usr/bin/env python ''''' author:qlzhong Created on 2015-6-29 征途宕机日志统计汇总 ''' import MySQLdb import time import datetime impo

  • 使用python BeautifulSoup库抓取58手机维修信息

    直接上代码: 复制代码 代码如下: #!/usr/bin/python# -*- coding: utf-8 -*- import urllib import os,datetime,string import sys from bs4 import BeautifulSoup reload(sys) sys.setdefaultencoding('utf-8') __BASEURL__ = 'http://bj.58.com/' __INITURL__ = "http://bj.58.com/

  • Python读取图片EXIF信息类库介绍和使用实例

    首先要介绍的是 Python Imaging Library,使用方法如下: 复制代码 代码如下: from PIL import Image from PIL.ExifTags import TAGS def get_exif_data(fname):     """Get embedded EXIF data from image file."""     ret = {}     try:         img = Image.open(

  • Python 模拟员工信息数据库操作的实例

    1.功能简介 此程序模拟员工信息数据库操作,按照语法输入指令即能实现员工信息的增.删.改.查功能. 2.实现方法 • 架构: 本程序采用python语言编写,关键在于指令的解析和执行:其中指令解析主要运用了正则表达式来高效匹配有效信息:指令执行通过一个commd_exe主执行函数和增.删.改.查4个子执行函数来实现,操作方法主要是运用面向对象方法将员工信息对象化,从而使各项操作都能方便高效实现.程序主要函数如下: (1)command_exe(command) 指令执行主函数,根据指令第一个字段

  • python3 实现爬取TOP500的音乐信息并存储到mongoDB数据库中

    爬取TOP500的音乐信息,包括排名情况.歌曲名.歌曲时间. 网页版酷狗不能手动翻页进行下一步的浏览,仔细观察第一页的URL: http://www.kugou.com/yy/rank/home/1-8888.html 这里尝试将1改为2,再进行浏览,恰好是第二页的信息,再改为3,恰好是第三页的信息,多次尝试发现不同的数字即为不同的页面.因此只需更改home/后面的数字即可.由于每页显示的为22首歌曲,所以总共需要23个URL. import requests from bs4 import B

  • Python使用pyshp库读取shapefile信息的方法

    通过pyshp库,可以读写Shapefile文件,查询相关信息,github地址为 https://github.com/GeospatialPython/pyshp#reading-shapefile-meta-data import shapefile # 使用pyshp库 file = shapefile.Reader("data\\市界.shp") shapes = file.shapes() # <editor-fold desc="读取元数据"&g

  • python用来获得图片exif信息的库实例分析

    本文实例讲述了python用来获得图片exif信息的库用法.分享给大家供大家参考.具体分析如下: exif-py是一个纯python实现的获取图片元数据的python库,官方下载地址: http://exif-py.svn.sourceforge.net/viewvc/exif-py/source/EXIF.py?revision=19&view=markup 下面的代码演示的是调用方法. 复制代码 代码如下: # library test/debug function (dump given

  • python爬取cnvd漏洞库信息的实例

    今天一同事需要整理http://ics.cnvd.org.cn/工控漏洞库里面的信息,一看960多个要整理到什么时候才结束. 所以我决定写个爬虫帮他抓取数据. 看了一下各类信息还是很规则的,感觉应该很好写. but这个网站设置了各种反爬虫手段. 经过各种百度,还是解决问题了. 设计思路: 1.先抓取每一个漏洞信息对应的网页url 2.获取每个页面的漏洞信息 # -*- coding: utf-8 -*- import requests import re import xlwt import t

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

    这篇文章主要介绍了基于python3抓取pinpoint应用信息入库,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 Pinpoint是用Java编写的大型分布式系统的APM(应用程序性能管理)工具. 受Dapper的启发,Pinpoint提供了一种解决方案,通过在分布式应用程序中跟踪事务来帮助分析系统的整体结构以及它们中的组件之间的相互关系. pinpoint api: /applications.pinpoint 获取applications

  • 解决Python3 抓取微信账单信息问题

    这段时间有个朋友想导出微信里面的账单信息,后来发现微信的反爬虫还是很厉害的,花了点时间去分析. 一.采用传统模拟http抓取 抓取的主要URL:https://wx.tenpay.com/userroll/userrolllist,其中后面带上三个参数,具体参数见代码,其中exportkey这参数是会过期的,userroll_encryption和userroll_pass_ticket 这两个参数需要从cookie中获得,应该是作为获取数据的标识,通过抓包也看不出端倪,应该是微信程序内部生成的

  • Python爬虫实现抓取电影网站信息并入库

    目录 一.环境搭建 1.下载安装包 2.修改环境变量 3.安装依赖模块 二.代码开发 三.运行测试 1.新建电影信息表 2.代码运行 四.问题排查和修复 1.空白字符报错 2.请求报错 一.环境搭建 1.下载安装包 访问 Python官网下载地址:https://www.python.org/downloads/ 下载适合自己系统的安装包: 我用的是 Windows 环境,所以直接下的 exe 包进行安装. 下载后,双击下载包,进入 Python 安装向导,安装非常简单,你只需要使用默认的设置一

  • C#基于正则表达式抓取a标签链接和innerhtml的方法

    本文实例讲述了C#基于正则表达式抓取a标签链接和innerhtml的方法.分享给大家供大家参考,具体如下: //读取网页html string text = File.ReadAllText(Environment.CurrentDirectory + "//test.txt", Encoding.GetEncoding("gb2312")); string prttern = "<a(\\s+(href=\"(?<url>([

  • C#.Net基于正则表达式抓取百度百家文章列表的方法示例

    本文实例讲述了C#.Net基于正则表达式抓取百度百家文章列表的方法.分享给大家供大家参考,具体如下: 工作之余,学习了一下正则表达式,鉴于实践是检验真理的唯一标准,于是便写了一个利用正则表达式抓取百度百家文章的例子,具体过程请看下面源码: 一.获取百度百家网页内容 public List<string[]> GetUrl() { try { string url = "http://baijia.baidu.com/"; WebRequest webRequest = We

  • Python使用scrapy抓取网站sitemap信息的方法

    本文实例讲述了Python使用scrapy抓取网站sitemap信息的方法.分享给大家供大家参考.具体如下: import re from scrapy.spider import BaseSpider from scrapy import log from scrapy.utils.response import body_or_str from scrapy.http import Request from scrapy.selector import HtmlXPathSelector c

  • python3抓取中文网页的方法

    本文实例讲述了python3抓取中文网页的方法.分享给大家供大家参考.具体如下: #! /usr/bin/python3.2 import sys import urllib.request req = urllib.request.Request('http://www.baidu.com') response = urllib.request.urlopen(req) the_page = response.read() type = sys.getfilesystemencoding()

  • python3爬取各类天气信息

    本来是想从网上找找有没有现成的爬取空气质量状况和天气情况的爬虫程序,结果找了一会儿感觉还是自己写一个吧. 主要是爬取北京包括北京周边省会城市的空气质量数据和天气数据. 过程中出现了一个错误:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa1 in position 250. 原来发现是页面的编码是gbk,把语句改成data=urllib.request.urlopen(url).read().decode("gbk")就可以

  • python3爬取淘宝信息代码分析

    # encoding:utf-8 import re # 使用正则 匹配想要的数据 import requests # 使用requests得到网页源码 这个函数是用来得到源码 # 得到主函数传入的链接 def getHtmlText(url): try: # 异常处理 # 得到你传入的URL链接 设置超时时间3秒 r = requests.get(url, timeout=3) # 判断它的http状态码 r.raise_for_status() # 设置它的编码 encoding是设置它的头

  • Python爬虫实现抓取京东店铺信息及下载图片功能示例

    本文实例讲述了Python爬虫实现抓取京东店铺信息及下载图片功能.分享给大家供大家参考,具体如下: 这个是抓取信息的 from bs4 import BeautifulSoup import requests url = 'https://list.tmall.com/search_product.htm?q=%CB%AE%BA%F8+%C9%D5%CB%AE&type=p&vmarket=&spm=875.7931836%2FA.a2227oh.d100&from=mal

随机推荐