You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

468 lines
18 KiB

  1. import base64
  2. import logging
  3. import os
  4. import pstats
  5. import re
  6. import subprocess
  7. import lxml.html
  8. from contextlib import contextmanager
  9. from cProfile import Profile
  10. from io import StringIO
  11. from psycopg2 import OperationalError, ProgrammingError
  12. from odoo import api, exceptions, fields, models, sql_db, tools, _
  13. DATETIME_FORMAT_FILE = "%Y%m%d_%H%M%S"
  14. CPROFILE_EMPTY_CHARS = b"{0"
  15. PGOPTIONS = {
  16. 'log_min_duration_statement': '0',
  17. 'client_min_messages': 'notice',
  18. 'log_min_messages': 'warning',
  19. 'log_min_error_statement': 'error',
  20. 'log_duration': 'off',
  21. 'log_error_verbosity': 'verbose',
  22. 'log_lock_waits': 'on',
  23. 'log_statement': 'none',
  24. 'log_temp_files': '0',
  25. }
  26. PGOPTIONS_ENV = ' '.join(["-c %s=%s" % (param, value)
  27. for param, value in PGOPTIONS.items()])
  28. PY_STATS_FIELDS = [
  29. 'ncalls',
  30. 'tottime', 'tt_percall',
  31. 'cumtime', 'ct_percall',
  32. 'file', 'lineno', 'method',
  33. ]
  34. LINE_STATS_RE = re.compile(
  35. r'(?P<%s>\d+/?\d+|\d+)\s+(?P<%s>\d+\.?\d+)\s+(?P<%s>\d+\.?\d+)\s+'
  36. r'(?P<%s>\d+\.?\d+)\s+(?P<%s>\d+\.?\d+)\s+(?P<%s>.*):(?P<%s>\d+)'
  37. r'\((?P<%s>.*)\)' % tuple(PY_STATS_FIELDS))
  38. _logger = logging.getLogger(__name__)
  39. class ProfilerProfilePythonLine(models.Model):
  40. _name = 'profiler.profile.python.line'
  41. _description = 'Profiler Python Line to save cProfiling results'
  42. _rec_name = 'cprof_fname'
  43. _order = 'cprof_cumtime DESC'
  44. profile_id = fields.Many2one('profiler.profile', required=True,
  45. ondelete='cascade')
  46. cprof_tottime = fields.Float("Total time")
  47. cprof_ncalls = fields.Float("Calls")
  48. cprof_nrcalls = fields.Float("Recursive Calls")
  49. cprof_ttpercall = fields.Float("Time per call")
  50. cprof_cumtime = fields.Float("Cumulative time")
  51. cprof_ctpercall = fields.Float("CT per call")
  52. cprof_fname = fields.Char("Filename:lineno(method)")
  53. class ProfilerProfile(models.Model):
  54. _name = 'profiler.profile'
  55. _description = 'Profiler Profile'
  56. @api.model
  57. def _find_loggers_path(self):
  58. self.env.cr.execute("SHOW log_directory")
  59. log_directory = self.env.cr.fetchone()[0]
  60. self.env.cr.execute("SHOW log_filename")
  61. log_filename = self.env.cr.fetchone()[0]
  62. log_path = os.path.join(log_directory, log_filename)
  63. if not os.path.isabs(log_path):
  64. # It is relative path then join data_directory
  65. self.env.cr.execute("SHOW data_directory")
  66. data_dir = self.env.cr.fetchone()[0]
  67. log_path = os.path.join(data_dir, log_path)
  68. return log_path
  69. name = fields.Char(required=True)
  70. enable_python = fields.Boolean(default=True)
  71. enable_postgresql = fields.Boolean(
  72. default=False,
  73. help="It requires postgresql server logs seudo-enabled")
  74. use_py_index = fields.Boolean(
  75. name="Get cProfiling report", default=False,
  76. help="Index human-readable cProfile attachment."
  77. "\nTo access this report, you must open the cprofile attachment view "
  78. "using debug mode.\nWarning: Uses more resources.")
  79. date_started = fields.Char(readonly=True)
  80. date_finished = fields.Char(readonly=True)
  81. state = fields.Selection([
  82. ('enabled', 'Enabled'),
  83. ('disabled', 'Disabled'),
  84. ], default='disabled', readonly=True, required=True)
  85. description = fields.Text(readonly=True)
  86. attachment_count = fields.Integer(compute="_compute_attachment_count")
  87. pg_log_path = fields.Char(help="Getting the path to the logger",
  88. default=_find_loggers_path)
  89. pg_remote = fields.Char()
  90. pg_stats_slowest_html = fields.Html(
  91. "PostgreSQL Stats - Slowest", readonly=True)
  92. pg_stats_time_consuming_html = fields.Html(
  93. "PostgreSQL Stats - Time Consuming", readonly=True)
  94. pg_stats_most_frequent_html = fields.Html(
  95. "PostgreSQL Stats - Most Frequent", readonly=True)
  96. py_stats_lines = fields.One2many(
  97. "profiler.profile.python.line", "profile_id", "PY Stats Lines")
  98. @api.multi
  99. def _compute_attachment_count(self):
  100. for record in self:
  101. self.attachment_count = self.env['ir.attachment'].search_count([
  102. ('res_model', '=', self._name), ('res_id', '=', record.id)])
  103. @api.onchange('enable_postgresql')
  104. def onchange_enable_postgresql(self):
  105. if not self.enable_postgresql:
  106. return
  107. self.env.cr.execute("SHOW config_file")
  108. pg_config_file = self.env.cr.fetchone()[0]
  109. db_host = tools.config.get('db_host')
  110. if db_host == 'localhost' or db_host == '127.0.0.1':
  111. db_host = False
  112. if db_host:
  113. pg_config_file = 'postgres@%s:%s' % (db_host, pg_config_file)
  114. self.pg_remote = db_host
  115. self.description = (
  116. "You need seudo-enable logs from your "
  117. "postgresql-server configuration file.\n"
  118. "Common paths:\n\t- %s\n"
  119. "or your can looking for the service using: "
  120. "'ps aux | grep postgres'\n\n"
  121. ) % pg_config_file
  122. self.description += """Adds the following parameters:
  123. # Pre-enable logs
  124. logging_collector=on
  125. log_destination='stderr'
  126. log_directory='pg_log'
  127. log_filename='postgresql.log'
  128. log_rotation_age=0
  129. log_checkpoints=on
  130. log_hostname=on
  131. log_line_prefix='%t [%p]: [%l-1] db=%d,user=%u '
  132. log_connections=on
  133. log_disconnections=on
  134. Reload configuration using the following query:
  135. - select pg_reload_conf()
  136. Or restart the postgresql server service.
  137. FYI This module will enable the following parameter from the client
  138. It's not needed added them to configuration file if database user is
  139. superuser or use PGOPTIONS environment variable in the terminal
  140. that you start your odoo server.
  141. If you don't add these parameters or PGOPTIONS this module will try do it.
  142. # Enable logs from postgresql.conf
  143. log_min_duration_statement=0
  144. client_min_messages=notice
  145. log_min_messages=warning
  146. log_min_error_statement=error
  147. log_duration=off
  148. log_error_verbosity=verbose
  149. log_lock_waits=on
  150. log_statement=none
  151. log_temp_files=0
  152. # Or enable logs from PGOPTIONS environment variable before to start odoo
  153. # server
  154. export PGOPTIONS="-c log_min_duration_statement=0 \\
  155. -c client_min_messages=notice -c log_min_messages=warning \\
  156. -c log_min_error_statement=error -c log_connections=on \\
  157. -c log_disconnections=on -c log_duration=off -c log_error_verbosity=verbose \\
  158. -c log_lock_waits=on -c log_statement=none -c log_temp_files=0"
  159. ~/odoo_path/odoo-bin ...
  160. """
  161. profile = Profile()
  162. enabled = None
  163. pglogs_enabled = None
  164. # True to activate it False to inactivate None to do nothing
  165. activate_deactivate_pglogs = None
  166. # Params dict with values before to change it.
  167. psql_params_original = {}
  168. @api.model
  169. def now_utc(self):
  170. self.env.cr.execute("SELECT to_char(now(), 'YYYY-MM-DD HH24:MI:SS')")
  171. now = self.env.cr.fetchall()[0][0]
  172. # now = fields.Datetime.to_string(
  173. # fields.Datetime.context_timestamp(self, datetime.now()))
  174. return now
  175. @api.multi
  176. def enable(self):
  177. self.ensure_one()
  178. if tools.config.get('workers'):
  179. raise exceptions.UserError(
  180. _("Start the odoo server using the parameter '--workers=0'"))
  181. _logger.info("Enabling profiler")
  182. self.write(dict(
  183. date_started=self.now_utc(),
  184. state='enabled'
  185. ))
  186. ProfilerProfile.enabled = self.enable_python
  187. self._reset_postgresql()
  188. @api.multi
  189. def _reset_postgresql(self):
  190. if not self.enable_postgresql:
  191. return
  192. if ProfilerProfile.pglogs_enabled:
  193. _logger.info("Using postgresql.conf or PGOPTIONS predefined.")
  194. return
  195. os.environ['PGOPTIONS'] = (
  196. PGOPTIONS_ENV if self.state == 'enabled' else '')
  197. self._reset_connection(self.state == 'enabled')
  198. def _reset_connection(self, enable):
  199. for connection in sql_db._Pool._connections:
  200. with connection[0].cursor() as pool_cr:
  201. params = (PGOPTIONS if enable
  202. else ProfilerProfile.psql_params_original)
  203. for param, value in params.items():
  204. try:
  205. pool_cr.execute('SET %s TO %s' % (param, value))
  206. except (OperationalError, ProgrammingError) as oe:
  207. pool_cr.connection.rollback()
  208. raise exceptions.UserError(
  209. _("It's not possible change parameter.\n%s\n"
  210. "Please, disable postgresql or re-enable it "
  211. "in order to read the instructions") % str(oe))
  212. ProfilerProfile.activate_deactivate_pglogs = enable
  213. def get_stats_string(self, cprofile_path):
  214. pstats_stream = StringIO()
  215. pstats_obj = pstats.Stats(cprofile_path, stream=pstats_stream)
  216. pstats_obj.sort_stats('cumulative')
  217. pstats_obj.print_stats()
  218. pstats_stream.seek(0)
  219. stats_string = pstats_stream.read()
  220. pstats_stream = None
  221. return stats_string
  222. @api.multi
  223. def dump_postgresql_logs(self, indexed=None):
  224. self.ensure_one()
  225. self.description = ''
  226. pgbadger_cmd = self._get_pgbadger_command()
  227. if pgbadger_cmd is None:
  228. return
  229. pgbadger_cmd_str = subprocess.list2cmdline(pgbadger_cmd)
  230. self.description += (
  231. '\nRunning the command: %s') % pgbadger_cmd_str
  232. result = tools.exec_command_pipe(*pgbadger_cmd)
  233. datas = result[1].read()
  234. if not datas:
  235. self.description += "\nPgbadger output is empty!"
  236. return
  237. fname = self._get_attachment_name("pg_stats", ".html")
  238. self.env['ir.attachment'].create({
  239. 'name': fname,
  240. 'res_id': self.id,
  241. 'res_model': self._name,
  242. 'datas': base64.b64encode(datas),
  243. 'datas_fname': fname,
  244. 'description': 'pgbadger html output',
  245. })
  246. xpaths = [
  247. '//*[@id="slowest-individual-queries"]',
  248. '//*[@id="time-consuming-queries"]',
  249. '//*[@id="most-frequent-queries"]',
  250. ]
  251. # pylint: disable=unbalanced-tuple-unpacking
  252. self.pg_stats_slowest_html, self.pg_stats_time_consuming_html, \
  253. self.pg_stats_most_frequent_html = self._compute_pgbadger_html(
  254. datas, xpaths)
  255. @staticmethod
  256. def _compute_pgbadger_html(html_doc, xpaths):
  257. html = lxml.html.document_fromstring(html_doc)
  258. result = []
  259. for this_xpath in xpaths:
  260. this_result = html.xpath(this_xpath)
  261. result.append(
  262. tools.html_sanitize(lxml.html.tostring(this_result[0])))
  263. return result
  264. @api.multi
  265. def _get_pgbadger_command(self):
  266. self.ensure_one()
  267. # TODO: Catch early the following errors.
  268. try:
  269. pgbadger_bin = tools.find_in_path('pgbadger')
  270. except IOError:
  271. self.description += (
  272. "\nInstall 'apt-get install pgbadger'")
  273. try:
  274. with open(self.pg_log_path, "r"):
  275. pass
  276. except IOError:
  277. self.description += (
  278. "\nCheck if exists and has permission to read the log file."
  279. "\nMaybe running: chmod 604 '%s'"
  280. ) % self.pg_log_path
  281. pgbadger_cmd = [
  282. pgbadger_bin, '-f', 'stderr', '--sample', '15',
  283. '-o', '-', '-x', 'html', '--quiet',
  284. '-T', self.name,
  285. '-d', self.env.cr.dbname,
  286. '-b', self.date_started,
  287. '-e', self.date_finished,
  288. self.pg_log_path,
  289. ]
  290. return pgbadger_cmd
  291. def _get_attachment_name(self, prefix, suffix):
  292. started = fields.Datetime.from_string(
  293. self.date_started).strftime(DATETIME_FORMAT_FILE)
  294. finished = fields.Datetime.from_string(
  295. self.date_finished).strftime(DATETIME_FORMAT_FILE)
  296. fname = '%s_%d_%s_to_%s%s' % (
  297. prefix, self.id, started, finished, suffix)
  298. return fname
  299. @api.model
  300. def dump_stats(self):
  301. attachment = None
  302. with tools.osutil.tempdir() as dump_dir:
  303. cprofile_fname = self._get_attachment_name("py_stats", ".cprofile")
  304. cprofile_path = os.path.join(dump_dir, cprofile_fname)
  305. _logger.info("Dumping cProfile '%s'", cprofile_path)
  306. ProfilerProfile.profile.dump_stats(cprofile_path)
  307. with open(cprofile_path, "rb") as f_cprofile:
  308. datas = f_cprofile.read()
  309. if datas and datas != CPROFILE_EMPTY_CHARS:
  310. attachment = self.env['ir.attachment'].create({
  311. 'name': cprofile_fname,
  312. 'res_id': self.id,
  313. 'res_model': self._name,
  314. 'datas': base64.b64encode(datas),
  315. 'datas_fname': cprofile_fname,
  316. 'description': 'cProfile dump stats',
  317. })
  318. _logger.info("A datas was saved, here %s", attachment.name)
  319. try:
  320. if self.use_py_index:
  321. py_stats = self.get_stats_string(cprofile_path)
  322. self.env['profiler.profile.python.line'].search([
  323. ('profile_id', '=', self.id)]).unlink()
  324. for py_stat_line in py_stats.splitlines():
  325. py_stat_line = py_stat_line.strip('\r\n ')
  326. py_stat_line_match = LINE_STATS_RE.match(
  327. py_stat_line) if py_stat_line else None
  328. if not py_stat_line_match:
  329. continue
  330. data = dict((
  331. field, py_stat_line_match.group(field))
  332. for field in PY_STATS_FIELDS)
  333. data['rcalls'], data['calls'] = (
  334. "%(ncalls)s/%(ncalls)s" % data).split('/')[:2]
  335. self.env['profiler.profile.python.line'].create({
  336. 'cprof_tottime': data['tottime'],
  337. 'cprof_ncalls': data['calls'],
  338. 'cprof_nrcalls': data['rcalls'],
  339. 'cprof_ttpercall': data['tt_percall'],
  340. 'cprof_cumtime': data['cumtime'],
  341. 'cprof_ctpercall': data['ct_percall'],
  342. 'cprof_fname': (
  343. "%(file)s:%(lineno)s (%(method)s)" % data),
  344. 'profile_id': self.id,
  345. })
  346. attachment.index_content = py_stats
  347. except IOError:
  348. # Fancy feature but not stop process if fails
  349. _logger.info("There was an error while getting the stats"
  350. "from the cprofile_path")
  351. # pylint: disable=unnecessary-pass
  352. pass
  353. self.dump_postgresql_logs()
  354. _logger.info("cProfile stats stored.")
  355. else:
  356. _logger.info("cProfile stats empty.")
  357. return attachment
  358. @api.multi
  359. def clear(self, reset_date=True):
  360. self.ensure_one()
  361. _logger.info("Clear profiler")
  362. if reset_date:
  363. self.date_started = self.now_utc()
  364. ProfilerProfile.profile.clear()
  365. @api.multi
  366. def disable(self):
  367. self.ensure_one()
  368. _logger.info("Disabling profiler")
  369. ProfilerProfile.enabled = False
  370. self.state = 'disabled'
  371. self.date_finished = self.now_utc()
  372. self.dump_stats()
  373. self.clear(reset_date=False)
  374. self._reset_postgresql()
  375. @staticmethod
  376. @contextmanager
  377. def profiling():
  378. """Thread local profile management, according to the shared "enabled"
  379. """
  380. if ProfilerProfile.enabled:
  381. _logger.debug("Catching profiling")
  382. ProfilerProfile.profile.enable()
  383. try:
  384. yield
  385. finally:
  386. if ProfilerProfile.enabled:
  387. ProfilerProfile.profile.disable()
  388. @api.multi
  389. def action_view_attachment(self):
  390. attachments = self.env['ir.attachment'].search([
  391. ('res_model', '=', self._name), ('res_id', '=', self.id)])
  392. action = self.env.ref("base.action_attachment").read()[0]
  393. action['domain'] = [('id', 'in', attachments.ids)]
  394. return action
  395. @api.model
  396. def set_pgoptions_enabled(self):
  397. """Verify if postgresql has configured the parameters for logging"""
  398. ProfilerProfile.pglogs_enabled = True
  399. pgoptions_enabled = bool(os.environ.get('PGOPTIONS'))
  400. _logger.info('Logging enabled from environment '
  401. 'variable PGOPTIONS? %s', pgoptions_enabled)
  402. if pgoptions_enabled:
  403. return
  404. pgparams_required = {
  405. 'log_min_duration_statement': '0',
  406. }
  407. for param, value in pgparams_required.items():
  408. # pylint: disable=sql-injection
  409. self.env.cr.execute("SHOW %s" % param)
  410. db_value = self.env.cr.fetchone()[0].lower()
  411. if value.lower() != db_value:
  412. ProfilerProfile.pglogs_enabled = False
  413. break
  414. ProfilerProfile.psql_params_original = self.get_psql_params(
  415. self.env.cr, PGOPTIONS.keys())
  416. _logger.info('Logging enabled from postgresql.conf? %s',
  417. ProfilerProfile.pglogs_enabled)
  418. @staticmethod
  419. def get_psql_params(cr, params):
  420. result = {}
  421. for param in set(params):
  422. # pylint: disable=sql-injection
  423. cr.execute('SHOW %s' % param)
  424. result.update(cr.dictfetchone())
  425. return result
  426. @api.model
  427. def _setup_complete(self):
  428. self.set_pgoptions_enabled()
  429. return super(ProfilerProfile, self)._setup_complete()