blob: 80e7c642a2e3aa135d2cede0e8dac4d8cab14b39 [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
Dan Smithe85c68e2022-05-26 09:31:36 -070057 glob.glob('/etc/systemd/system/devstack@*.service')] + \
58 ['apache2.service']
Dan Smithc2772c22022-04-08 08:48:49 -070059 return [dict(service=service, **get_service_stats(service))
60 for service in services]
61
62
63def get_process_stats(proc):
64 cmdline = proc.cmdline()
65 if 'python' in cmdline[0]:
66 cmdline = cmdline[1:]
67 return {'cmd': cmdline[0],
68 'pid': proc.pid,
69 'args': ' '.join(cmdline[1:]),
70 'rss': proc.memory_info().rss}
71
72
73def get_processes_stats(matches):
74 me = os.getpid()
75 procs = psutil.process_iter()
76
77 def proc_matches(proc):
78 return me != proc.pid and any(
79 re.search(match, ' '.join(proc.cmdline()))
80 for match in matches)
81
82 return [
83 get_process_stats(proc)
84 for proc in procs
85 if proc_matches(proc)]
86
87
88def get_db_stats(host, user, passwd):
89 dbs = []
90 db = pymysql.connect(host=host, user=user, password=passwd,
Dan Smithfe52d7f2022-04-28 12:34:38 -070091 database='stats',
Dan Smithc2772c22022-04-08 08:48:49 -070092 cursorclass=pymysql.cursors.DictCursor)
93 with db:
94 with db.cursor() as cur:
Dan Smithfe52d7f2022-04-28 12:34:38 -070095 cur.execute('SELECT db,op,count FROM queries')
Dan Smithc2772c22022-04-08 08:48:49 -070096 for row in cur:
97 dbs.append({k: tryint(v) for k, v in row.items()})
98 return dbs
99
100
101def get_http_stats_for_log(logfile):
102 stats = {}
Dan Smith64d68672022-04-22 07:58:29 -0700103 apache_fields = ('host', 'a', 'b', 'date', 'tz', 'request', 'status',
104 'length', 'c', 'agent')
105 ignore_agents = ('curl', 'uwsgi', 'nova-status')
106 for line in csv.reader(open(logfile), delimiter=' '):
107 fields = dict(zip(apache_fields, line))
108 if len(fields) != len(apache_fields):
109 # Not a combined access log, so we can bail completely
110 return []
111 try:
112 method, url, http = fields['request'].split(' ')
113 except ValueError:
114 method = url = http = ''
115 if 'HTTP' not in http:
116 # Not a combined access log, so we can bail completely
117 return []
Dan Smithc2772c22022-04-08 08:48:49 -0700118
Dan Smith64d68672022-04-22 07:58:29 -0700119 # Tempest's User-Agent is unchanged, but client libraries and
120 # inter-service API calls use proper strings. So assume
121 # 'python-urllib' is tempest so we can tell it apart.
122 if 'python-urllib' in fields['agent'].lower():
123 agent = 'tempest'
124 else:
125 agent = fields['agent'].split(' ')[0]
126 if agent.startswith('python-'):
127 agent = agent.replace('python-', '')
128 if '/' in agent:
129 agent = agent.split('/')[0]
Dan Smithc2772c22022-04-08 08:48:49 -0700130
Dan Smith64d68672022-04-22 07:58:29 -0700131 if agent in ignore_agents:
132 continue
133
134 try:
135 service, rest = url.strip('/').split('/', 1)
136 except ValueError:
137 # Root calls like "GET /identity"
138 service = url.strip('/')
139 rest = ''
140
141 method_key = '%s-%s' % (agent, method)
142 try:
143 length = int(fields['length'])
144 except ValueError:
145 LOG.warning('[%s] Failed to parse length %r from line %r' % (
146 logfile, fields['length'], line))
147 length = 0
148 stats.setdefault(service, {'largest': 0})
149 stats[service].setdefault(method_key, 0)
150 stats[service][method_key] += 1
151 stats[service]['largest'] = max(stats[service]['largest'],
152 length)
Dan Smithc2772c22022-04-08 08:48:49 -0700153
154 # Flatten this for ES
155 return [{'service': service, 'log': os.path.basename(logfile),
156 **vals}
157 for service, vals in stats.items()]
158
159
160def get_http_stats(logfiles):
161 return list(itertools.chain.from_iterable(get_http_stats_for_log(log)
162 for log in logfiles))
163
164
165def get_report_info():
166 return {
167 'timestamp': datetime.datetime.now().isoformat(),
168 'hostname': socket.gethostname(),
Dan Smith64d68672022-04-22 07:58:29 -0700169 'version': 2,
Dan Smithc2772c22022-04-08 08:48:49 -0700170 }
171
172
173if __name__ == '__main__':
174 process_defaults = ['privsep', 'mysqld', 'erlang', 'etcd']
175 parser = argparse.ArgumentParser()
176 parser.add_argument('--db-user', default='root',
177 help=('MySQL user for collecting stats '
178 '(default: "root")'))
179 parser.add_argument('--db-pass', default=None,
180 help='MySQL password for db-user')
181 parser.add_argument('--db-host', default='localhost',
182 help='MySQL hostname')
183 parser.add_argument('--apache-log', action='append', default=[],
184 help='Collect API call stats from this apache log')
185 parser.add_argument('--process', action='append',
186 default=process_defaults,
187 help=('Include process stats for this cmdline regex '
188 '(default is %s)' % ','.join(process_defaults)))
189 args = parser.parse_args()
190
Dan Smith64d68672022-04-22 07:58:29 -0700191 logging.basicConfig(level=logging.WARNING)
192
Dan Smithc2772c22022-04-08 08:48:49 -0700193 data = {
194 'services': get_services_stats(),
Dan Smith1b601c72022-04-25 07:47:56 -0700195 'db': pymysql and args.db_pass and get_db_stats(args.db_host,
196 args.db_user,
197 args.db_pass) or [],
198 'processes': psutil and get_processes_stats(args.process) or [],
Dan Smithc2772c22022-04-08 08:48:49 -0700199 'api': get_http_stats(args.apache_log),
200 'report': get_report_info(),
201 }
202
203 print(json.dumps(data, indent=2))