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.

470 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. lc_messages='en_US.UTF-8'
  135. Reload configuration using the following query:
  136. - select pg_reload_conf()
  137. Or restart the postgresql server service.
  138. FYI This module will enable the following parameter from the client
  139. It's not needed added them to configuration file if database user is
  140. superuser or use PGOPTIONS environment variable in the terminal
  141. that you start your odoo server.
  142. If you don't add these parameters or PGOPTIONS this module will try do it.
  143. # Enable logs from postgresql.conf
  144. log_min_duration_statement=0
  145. client_min_messages=notice
  146. log_min_messages=warning
  147. log_min_error_statement=error
  148. log_duration=off
  149. log_error_verbosity=verbose
  150. log_lock_waits=on
  151. log_statement=none
  152. log_temp_files=0
  153. # Or enable logs from PGOPTIONS environment variable before to start odoo
  154. # server
  155. export PGOPTIONS="-c log_min_duration_statement=0 \\
  156. -c client_min_messages=notice -c log_min_messages=warning \\
  157. -c log_min_error_statement=error -c log_connections=on \\
  158. -c log_disconnections=on -c log_duration=off -c log_error_verbosity=verbose \\
  159. -c log_lock_waits=on -c log_statement=none -c log_temp_files=0"
  160. ~/odoo_path/odoo-bin ...
  161. """
  162. profile = Profile()
  163. enabled = None
  164. pglogs_enabled = None
  165. # True to activate it False to inactivate None to do nothing
  166. activate_deactivate_pglogs = None
  167. # Params dict with values before to change it.
  168. psql_params_original = {}
  169. @api.model
  170. def now_utc(self):
  171. self.env.cr.execute("SELECT to_char(current_timestamp AT TIME "
  172. "ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS')")
  173. now = self.env.cr.fetchall()[0][0]
  174. # now = fields.Datetime.to_string(
  175. # fields.Datetime.context_timestamp(self, datetime.now()))
  176. return now
  177. @api.multi
  178. def enable(self):
  179. self.ensure_one()
  180. if tools.config.get('workers'):
  181. raise exceptions.UserError(
  182. _("Start the odoo server using the parameter '--workers=0'"))
  183. _logger.info("Enabling profiler")
  184. self.write(dict(
  185. date_started=self.now_utc(),
  186. state='enabled'
  187. ))
  188. ProfilerProfile.enabled = self.enable_python
  189. self._reset_postgresql()
  190. @api.multi
  191. def _reset_postgresql(self):
  192. if not self.enable_postgresql:
  193. return
  194. if ProfilerProfile.pglogs_enabled:
  195. _logger.info("Using postgresql.conf or PGOPTIONS predefined.")
  196. return
  197. os.environ['PGOPTIONS'] = (
  198. PGOPTIONS_ENV if self.state == 'enabled' else '')
  199. self._reset_connection(self.state == 'enabled')
  200. def _reset_connection(self, enable):
  201. for connection in sql_db._Pool._connections:
  202. with connection[0].cursor() as pool_cr:
  203. params = (PGOPTIONS if enable
  204. else ProfilerProfile.psql_params_original)
  205. for param, value in params.items():
  206. try:
  207. pool_cr.execute('SET %s TO %s' % (param, value))
  208. except (OperationalError, ProgrammingError) as oe:
  209. pool_cr.connection.rollback()
  210. raise exceptions.UserError(
  211. _("It's not possible change parameter.\n%s\n"
  212. "Please, disable postgresql or re-enable it "
  213. "in order to read the instructions") % str(oe))
  214. ProfilerProfile.activate_deactivate_pglogs = enable
  215. def get_stats_string(self, cprofile_path):
  216. pstats_stream = StringIO()
  217. pstats_obj = pstats.Stats(cprofile_path, stream=pstats_stream)
  218. pstats_obj.sort_stats('cumulative')
  219. pstats_obj.print_stats()
  220. pstats_stream.seek(0)
  221. stats_string = pstats_stream.read()
  222. pstats_stream = None
  223. return stats_string
  224. @api.multi
  225. def dump_postgresql_logs(self, indexed=None):
  226. self.ensure_one()
  227. self.description = ''
  228. pgbadger_cmd = self._get_pgbadger_command()
  229. if pgbadger_cmd is None:
  230. return
  231. pgbadger_cmd_str = subprocess.list2cmdline(pgbadger_cmd)
  232. self.description += (
  233. '\nRunning the command: %s') % pgbadger_cmd_str
  234. result = tools.exec_command_pipe(*pgbadger_cmd)
  235. datas = result[1].read()
  236. if not datas:
  237. self.description += "\nPgbadger output is empty!"
  238. return
  239. fname = self._get_attachment_name("pg_stats", ".html")
  240. self.env['ir.attachment'].create({
  241. 'name': fname,
  242. 'res_id': self.id,
  243. 'res_model': self._name,
  244. 'datas': base64.b64encode(datas),
  245. 'datas_fname': fname,
  246. 'description': 'pgbadger html output',
  247. })
  248. xpaths = [
  249. '//*[@id="slowest-individual-queries"]',
  250. '//*[@id="time-consuming-queries"]',
  251. '//*[@id="most-frequent-queries"]',
  252. ]
  253. # pylint: disable=unbalanced-tuple-unpacking
  254. self.pg_stats_slowest_html, self.pg_stats_time_consuming_html, \
  255. self.pg_stats_most_frequent_html = self._compute_pgbadger_html(
  256. datas, xpaths)
  257. @staticmethod
  258. def _compute_pgbadger_html(html_doc, xpaths):
  259. html = lxml.html.document_fromstring(html_doc)
  260. result = []
  261. for this_xpath in xpaths:
  262. this_result = html.xpath(this_xpath)
  263. result.append(
  264. tools.html_sanitize(lxml.html.tostring(this_result[0])))
  265. return result
  266. @api.multi
  267. def _get_pgbadger_command(self):
  268. self.ensure_one()
  269. # TODO: Catch early the following errors.
  270. try:
  271. pgbadger_bin = tools.find_in_path('pgbadger')
  272. except IOError:
  273. self.description += (
  274. "\nInstall 'apt-get install pgbadger'")
  275. try:
  276. with open(self.pg_log_path, "r"):
  277. pass
  278. except IOError:
  279. self.description += (
  280. "\nCheck if exists and has permission to read the log file."
  281. "\nMaybe running: chmod 604 '%s'"
  282. ) % self.pg_log_path
  283. pgbadger_cmd = [
  284. pgbadger_bin, '-f', 'stderr', '--sample', '15',
  285. '-o', '-', '-x', 'html', '--quiet',
  286. '-T', self.name,
  287. '-d', self.env.cr.dbname,
  288. '-b', self.date_started,
  289. '-e', self.date_finished,
  290. self.pg_log_path,
  291. ]
  292. return pgbadger_cmd
  293. def _get_attachment_name(self, prefix, suffix):
  294. started = fields.Datetime.from_string(
  295. self.date_started).strftime(DATETIME_FORMAT_FILE)
  296. finished = fields.Datetime.from_string(
  297. self.date_finished).strftime(DATETIME_FORMAT_FILE)
  298. fname = '%s_%d_%s_to_%s%s' % (
  299. prefix, self.id, started, finished, suffix)
  300. return fname
  301. @api.model
  302. def dump_stats(self):
  303. attachment = None
  304. with tools.osutil.tempdir() as dump_dir:
  305. cprofile_fname = self._get_attachment_name("py_stats", ".cprofile")
  306. cprofile_path = os.path.join(dump_dir, cprofile_fname)
  307. _logger.info("Dumping cProfile '%s'", cprofile_path)
  308. ProfilerProfile.profile.dump_stats(cprofile_path)
  309. with open(cprofile_path, "rb") as f_cprofile:
  310. datas = f_cprofile.read()
  311. if datas and datas != CPROFILE_EMPTY_CHARS:
  312. attachment = self.env['ir.attachment'].create({
  313. 'name': cprofile_fname,
  314. 'res_id': self.id,
  315. 'res_model': self._name,
  316. 'datas': base64.b64encode(datas),
  317. 'datas_fname': cprofile_fname,
  318. 'description': 'cProfile dump stats',
  319. })
  320. _logger.info("A datas was saved, here %s", attachment.name)
  321. try:
  322. if self.use_py_index:
  323. py_stats = self.get_stats_string(cprofile_path)
  324. self.env['profiler.profile.python.line'].search([
  325. ('profile_id', '=', self.id)]).unlink()
  326. for py_stat_line in py_stats.splitlines():
  327. py_stat_line = py_stat_line.strip('\r\n ')
  328. py_stat_line_match = LINE_STATS_RE.match(
  329. py_stat_line) if py_stat_line else None
  330. if not py_stat_line_match:
  331. continue
  332. data = dict((
  333. field, py_stat_line_match.group(field))
  334. for field in PY_STATS_FIELDS)
  335. data['rcalls'], data['calls'] = (
  336. "%(ncalls)s/%(ncalls)s" % data).split('/')[:2]
  337. self.env['profiler.profile.python.line'].create({
  338. 'cprof_tottime': data['tottime'],
  339. 'cprof_ncalls': data['calls'],
  340. 'cprof_nrcalls': data['rcalls'],
  341. 'cprof_ttpercall': data['tt_percall'],
  342. 'cprof_cumtime': data['cumtime'],
  343. 'cprof_ctpercall': data['ct_percall'],
  344. 'cprof_fname': (
  345. "%(file)s:%(lineno)s (%(method)s)" % data),
  346. 'profile_id': self.id,
  347. })
  348. attachment.index_content = py_stats
  349. except IOError:
  350. # Fancy feature but not stop process if fails
  351. _logger.info("There was an error while getting the stats"
  352. "from the cprofile_path")
  353. # pylint: disable=unnecessary-pass
  354. pass
  355. self.dump_postgresql_logs()
  356. _logger.info("cProfile stats stored.")
  357. else:
  358. _logger.info("cProfile stats empty.")
  359. return attachment
  360. @api.multi
  361. def clear(self, reset_date=True):
  362. self.ensure_one()
  363. _logger.info("Clear profiler")
  364. if reset_date:
  365. self.date_started = self.now_utc()
  366. ProfilerProfile.profile.clear()
  367. @api.multi
  368. def disable(self):
  369. self.ensure_one()
  370. _logger.info("Disabling profiler")
  371. ProfilerProfile.enabled = False
  372. self.state = 'disabled'
  373. self.date_finished = self.now_utc()
  374. self.dump_stats()
  375. self.clear(reset_date=False)
  376. self._reset_postgresql()
  377. @staticmethod
  378. @contextmanager
  379. def profiling():
  380. """Thread local profile management, according to the shared "enabled"
  381. """
  382. if ProfilerProfile.enabled:
  383. _logger.debug("Catching profiling")
  384. ProfilerProfile.profile.enable()
  385. try:
  386. yield
  387. finally:
  388. if ProfilerProfile.enabled:
  389. ProfilerProfile.profile.disable()
  390. @api.multi
  391. def action_view_attachment(self):
  392. attachments = self.env['ir.attachment'].search([
  393. ('res_model', '=', self._name), ('res_id', '=', self.id)])
  394. action = self.env.ref("base.action_attachment").read()[0]
  395. action['domain'] = [('id', 'in', attachments.ids)]
  396. return action
  397. @api.model
  398. def set_pgoptions_enabled(self):
  399. """Verify if postgresql has configured the parameters for logging"""
  400. ProfilerProfile.pglogs_enabled = True
  401. pgoptions_enabled = bool(os.environ.get('PGOPTIONS'))
  402. _logger.info('Logging enabled from environment '
  403. 'variable PGOPTIONS? %s', pgoptions_enabled)
  404. if pgoptions_enabled:
  405. return
  406. pgparams_required = {
  407. 'log_min_duration_statement': '0',
  408. }
  409. for param, value in pgparams_required.items():
  410. # pylint: disable=sql-injection
  411. self.env.cr.execute("SHOW %s" % param)
  412. db_value = self.env.cr.fetchone()[0].lower()
  413. if value.lower() != db_value:
  414. ProfilerProfile.pglogs_enabled = False
  415. break
  416. ProfilerProfile.psql_params_original = self.get_psql_params(
  417. self.env.cr, PGOPTIONS.keys())
  418. _logger.info('Logging enabled from postgresql.conf? %s',
  419. ProfilerProfile.pglogs_enabled)
  420. @staticmethod
  421. def get_psql_params(cr, params):
  422. result = {}
  423. for param in set(params):
  424. # pylint: disable=sql-injection
  425. cr.execute('SHOW %s' % param)
  426. result.update(cr.dictfetchone())
  427. return result
  428. @api.model
  429. def _setup_complete(self):
  430. self.set_pgoptions_enabled()
  431. return super(ProfilerProfile, self)._setup_complete()