blob: ffe467691c8ef59734d6dfea68a56c6a890e0f56 [file] [log] [blame]
Dan Smithc2772c22022-04-08 08:48:49 -07001#!/usr/bin/python3
2
3import argparse
Dan Smith64d68672022-04-22 07:58:29 -07004import csv
Dan Smithc2772c22022-04-08 08:48:49 -07005import datetime
6import glob
7import itertools
8import json
Dan Smith64d68672022-04-22 07:58:29 -07009import logging
Dan Smithc2772c22022-04-08 08:48:49 -070010import os
Dan Smithc2772c22022-04-08 08:48:49 -070011import re
12import socket
13import subprocess
14import sys
Dan Smith1b601c72022-04-25 07:47:56 -070015
16try:
17 import psutil
18except ImportError:
19 psutil = None
20 print('No psutil, process information will not be included',
21 file=sys.stderr)
22
23try:
24 import pymysql
25except ImportError:
26 pymysql = None
27 print('No pymysql, database information will not be included',
28 file=sys.stderr)
Dan Smithc2772c22022-04-08 08:48:49 -070029
Dan Smith64d68672022-04-22 07:58:29 -070030LOG = logging.getLogger('perf')
31
Dan Smithc2772c22022-04-08 08:48:49 -070032# https://www.elastic.co/blog/found-crash-elasticsearch#mapping-explosion
33
34
35def tryint(value):
36 try:
37 return int(value)
38 except (ValueError, TypeError):
39 return value
40
41
42def get_service_stats(service):
43 stats = {'MemoryCurrent': 0}
44 output = subprocess.check_output(['/usr/bin/systemctl', 'show', service] +
45 ['-p%s' % stat for stat in stats])
46 for line in output.decode().split('\n'):
47 if not line:
48 continue
49 stat, val = line.split('=')
Harald Jensåsbab0c922022-04-26 15:46:56 +020050 stats[stat] = tryint(val)
Dan Smithc2772c22022-04-08 08:48:49 -070051
52 return stats
53
54
55def get_services_stats():
56 services = [os.path.basename(s) for s in
57 glob.glob('/etc/systemd/system/devstack@*.service')]
58 return [dict(service=service, **get_service_stats(service))
59 for service in services]
60
61
62def get_process_stats(proc):
63 cmdline = proc.cmdline()
64 if 'python' in cmdline[0]:
65 cmdline = cmdline[1:]
66 return {'cmd': cmdline[0],
67 'pid': proc.pid,
68 'args': ' '.join(cmdline[1:]),
69 'rss': proc.memory_info().rss}
70
71
72def get_processes_stats(matches):
73 me = os.getpid()
74 procs = psutil.process_iter()
75
76 def proc_matches(proc):
77 return me != proc.pid and any(
78 re.search(match, ' '.join(proc.cmdline()))
79 for match in matches)
80
81 return [
82 get_process_stats(proc)
83 for proc in procs
84 if proc_matches(proc)]
85
86
87def get_db_stats(host, user, passwd):
88 dbs = []
89 db = pymysql.connect(host=host, user=user, password=passwd,
Dan Smithfe52d7f2022-04-28 12:34:38 -070090 database='stats',
Dan Smithc2772c22022-04-08 08:48:49 -070091 cursorclass=pymysql.cursors.DictCursor)
92 with db:
93 with db.cursor() as cur:
Dan Smithfe52d7f2022-04-28 12:34:38 -070094 cur.execute('SELECT db,op,count FROM queries')
Dan Smithc2772c22022-04-08 08:48:49 -070095 for row in cur:
96 dbs.append({k: tryint(v) for k, v in row.items()})
97 return dbs
98
99
100def get_http_stats_for_log(logfile):
101 stats = {}
Dan Smith64d68672022-04-22 07:58:29 -0700102 apache_fields = ('host', 'a', 'b', 'date', 'tz', 'request', 'status',
103 'length', 'c', 'agent')
104 ignore_agents = ('curl', 'uwsgi', 'nova-status')
105 for line in csv.reader(open(logfile), delimiter=' '):
106 fields = dict(zip(apache_fields, line))
107 if len(fields) != len(apache_fields):
108 # Not a combined access log, so we can bail completely
109 return []
110 try:
111 method, url, http = fields['request'].split(' ')
112 except ValueError:
113 method = url = http = ''
114 if 'HTTP' not in http:
115 # Not a combined access log, so we can bail completely
116 return []
Dan Smithc2772c22022-04-08 08:48:49 -0700117
Dan Smith64d68672022-04-22 07:58:29 -0700118 # Tempest's User-Agent is unchanged, but client libraries and
119 # inter-service API calls use proper strings. So assume
120 # 'python-urllib' is tempest so we can tell it apart.
121 if 'python-urllib' in fields['agent'].lower():
122 agent = 'tempest'
123 else:
124 agent = fields['agent'].split(' ')[0]
125 if agent.startswith('python-'):
126 agent = agent.replace('python-', '')
127 if '/' in agent:
128 agent = agent.split('/')[0]
Dan Smithc2772c22022-04-08 08:48:49 -0700129
Dan Smith64d68672022-04-22 07:58:29 -0700130 if agent in ignore_agents:
131 continue
132
133 try:
134 service, rest = url.strip('/').split('/', 1)
135 except ValueError:
136 # Root calls like "GET /identity"
137 service = url.strip('/')
138 rest = ''
139
140 method_key = '%s-%s' % (agent, method)
141 try:
142 length = int(fields['length'])
143 except ValueError:
144 LOG.warning('[%s] Failed to parse length %r from line %r' % (
145 logfile, fields['length'], line))
146 length = 0
147 stats.setdefault(service, {'largest': 0})
148 stats[service].setdefault(method_key, 0)
149 stats[service][method_key] += 1
150 stats[service]['largest'] = max(stats[service]['largest'],
151 length)
Dan Smithc2772c22022-04-08 08:48:49 -0700152
153 # Flatten this for ES
154 return [{'service': service, 'log': os.path.basename(logfile),
155 **vals}
156 for service, vals in stats.items()]
157
158
159def get_http_stats(logfiles):
160 return list(itertools.chain.from_iterable(get_http_stats_for_log(log)
161 for log in logfiles))
162
163
164def get_report_info():
165 return {
166 'timestamp': datetime.datetime.now().isoformat(),
167 'hostname': socket.gethostname(),
Dan Smith64d68672022-04-22 07:58:29 -0700168 'version': 2,
Dan Smithc2772c22022-04-08 08:48:49 -0700169 }
170
171
172if __name__ == '__main__':
173 process_defaults = ['privsep', 'mysqld', 'erlang', 'etcd']
174 parser = argparse.ArgumentParser()
175 parser.add_argument('--db-user', default='root',
176 help=('MySQL user for collecting stats '
177 '(default: "root")'))
178 parser.add_argument('--db-pass', default=None,
179 help='MySQL password for db-user')
180 parser.add_argument('--db-host', default='localhost',
181 help='MySQL hostname')
182 parser.add_argument('--apache-log', action='append', default=[],
183 help='Collect API call stats from this apache log')
184 parser.add_argument('--process', action='append',
185 default=process_defaults,
186 help=('Include process stats for this cmdline regex '
187 '(default is %s)' % ','.join(process_defaults)))
188 args = parser.parse_args()
189
Dan Smith64d68672022-04-22 07:58:29 -0700190 logging.basicConfig(level=logging.WARNING)
191
Dan Smithc2772c22022-04-08 08:48:49 -0700192 data = {
193 'services': get_services_stats(),
Dan Smith1b601c72022-04-25 07:47:56 -0700194 'db': pymysql and args.db_pass and get_db_stats(args.db_host,
195 args.db_user,
196 args.db_pass) or [],
197 'processes': psutil and get_processes_stats(args.process) or [],
Dan Smithc2772c22022-04-08 08:48:49 -0700198 'api': get_http_stats(args.apache_log),
199 'report': get_report_info(),
200 }
201
202 print(json.dumps(data, indent=2))