blob: 2418c851f96f3c7d1c1871b53ecca3a92e283249 [file] [log] [blame]
Dan Smithc2772c22022-04-08 08:48:49 -07001#!/usr/bin/python3
2
3import argparse
4import datetime
5import glob
6import itertools
7import json
8import os
Dan Smithc2772c22022-04-08 08:48:49 -07009import re
10import socket
11import subprocess
12import sys
Dan Smith1b601c72022-04-25 07:47:56 -070013
14try:
15 import psutil
16except ImportError:
17 psutil = None
18 print('No psutil, process information will not be included',
19 file=sys.stderr)
20
21try:
22 import pymysql
23except ImportError:
24 pymysql = None
25 print('No pymysql, database information will not be included',
26 file=sys.stderr)
Dan Smithc2772c22022-04-08 08:48:49 -070027
28# https://www.elastic.co/blog/found-crash-elasticsearch#mapping-explosion
29
30
31def tryint(value):
32 try:
33 return int(value)
34 except (ValueError, TypeError):
35 return value
36
37
38def get_service_stats(service):
39 stats = {'MemoryCurrent': 0}
40 output = subprocess.check_output(['/usr/bin/systemctl', 'show', service] +
41 ['-p%s' % stat for stat in stats])
42 for line in output.decode().split('\n'):
43 if not line:
44 continue
45 stat, val = line.split('=')
46 stats[stat] = int(val)
47
48 return stats
49
50
51def get_services_stats():
52 services = [os.path.basename(s) for s in
53 glob.glob('/etc/systemd/system/devstack@*.service')]
54 return [dict(service=service, **get_service_stats(service))
55 for service in services]
56
57
58def get_process_stats(proc):
59 cmdline = proc.cmdline()
60 if 'python' in cmdline[0]:
61 cmdline = cmdline[1:]
62 return {'cmd': cmdline[0],
63 'pid': proc.pid,
64 'args': ' '.join(cmdline[1:]),
65 'rss': proc.memory_info().rss}
66
67
68def get_processes_stats(matches):
69 me = os.getpid()
70 procs = psutil.process_iter()
71
72 def proc_matches(proc):
73 return me != proc.pid and any(
74 re.search(match, ' '.join(proc.cmdline()))
75 for match in matches)
76
77 return [
78 get_process_stats(proc)
79 for proc in procs
80 if proc_matches(proc)]
81
82
83def get_db_stats(host, user, passwd):
84 dbs = []
85 db = pymysql.connect(host=host, user=user, password=passwd,
86 database='performance_schema',
87 cursorclass=pymysql.cursors.DictCursor)
88 with db:
89 with db.cursor() as cur:
90 cur.execute(
91 'SELECT COUNT(*) AS queries,current_schema AS db FROM '
92 'events_statements_history_long GROUP BY current_schema')
93 for row in cur:
94 dbs.append({k: tryint(v) for k, v in row.items()})
95 return dbs
96
97
98def get_http_stats_for_log(logfile):
99 stats = {}
100 for line in open(logfile).readlines():
101 m = re.search('"([A-Z]+) /([^" ]+)( HTTP/1.1)?" ([0-9]{3}) ([0-9]+)',
102 line)
103 if m:
104 method = m.group(1)
105 path = m.group(2)
106 status = m.group(4)
107 size = int(m.group(5))
108
109 try:
110 service, rest = path.split('/', 1)
111 except ValueError:
112 # Root calls like "GET /identity"
113 service = path
114 rest = ''
115
116 stats.setdefault(service, {'largest': 0})
117 stats[service].setdefault(method, 0)
118 stats[service][method] += 1
119 stats[service]['largest'] = max(stats[service]['largest'], size)
120
121 # Flatten this for ES
122 return [{'service': service, 'log': os.path.basename(logfile),
123 **vals}
124 for service, vals in stats.items()]
125
126
127def get_http_stats(logfiles):
128 return list(itertools.chain.from_iterable(get_http_stats_for_log(log)
129 for log in logfiles))
130
131
132def get_report_info():
133 return {
134 'timestamp': datetime.datetime.now().isoformat(),
135 'hostname': socket.gethostname(),
136 }
137
138
139if __name__ == '__main__':
140 process_defaults = ['privsep', 'mysqld', 'erlang', 'etcd']
141 parser = argparse.ArgumentParser()
142 parser.add_argument('--db-user', default='root',
143 help=('MySQL user for collecting stats '
144 '(default: "root")'))
145 parser.add_argument('--db-pass', default=None,
146 help='MySQL password for db-user')
147 parser.add_argument('--db-host', default='localhost',
148 help='MySQL hostname')
149 parser.add_argument('--apache-log', action='append', default=[],
150 help='Collect API call stats from this apache log')
151 parser.add_argument('--process', action='append',
152 default=process_defaults,
153 help=('Include process stats for this cmdline regex '
154 '(default is %s)' % ','.join(process_defaults)))
155 args = parser.parse_args()
156
157 data = {
158 'services': get_services_stats(),
Dan Smith1b601c72022-04-25 07:47:56 -0700159 'db': pymysql and args.db_pass and get_db_stats(args.db_host,
160 args.db_user,
161 args.db_pass) or [],
162 'processes': psutil and get_processes_stats(args.process) or [],
Dan Smithc2772c22022-04-08 08:48:49 -0700163 'api': get_http_stats(args.apache_log),
164 'report': get_report_info(),
165 }
166
167 print(json.dumps(data, indent=2))