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.

96 lines
3.1 KiB

  1. # -*- coding: utf-8 -*-
  2. # © 2015 Therp BV <http://therp.nl>
  3. # © 2015 Grupo ESOC Ingeniería de Servicios, S.L.U. - Jairo Llopis
  4. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
  5. import json
  6. import logging
  7. import os
  8. try:
  9. import psutil
  10. except ImportError:
  11. psutil = None
  12. import urllib2
  13. from openerp import api, models
  14. SEND_TIMEOUT = 60
  15. class DeadMansSwitchClient(models.AbstractModel):
  16. _name = 'dead.mans.switch.client'
  17. _register = True
  18. @api.model
  19. def _get_data(self):
  20. ram = 0
  21. cpu = 0
  22. if psutil:
  23. process = psutil.Process(os.getpid())
  24. # psutil changed its api through versions
  25. processes = [process]
  26. if process.parent:
  27. if hasattr(process.parent, '__call__'):
  28. process = process.parent()
  29. else:
  30. process = process.parent
  31. if hasattr(process, 'children'):
  32. processes += process.children(True)
  33. elif hasattr(process, 'get_children'):
  34. processes += process.get_children(True)
  35. for process in processes:
  36. if hasattr(process, 'memory_percent'):
  37. ram += process.memory_percent()
  38. if hasattr(process, 'cpu_percent'):
  39. cpu += process.cpu_percent()
  40. user_count = 0
  41. if 'im_chat.presence' in self.env.registry:
  42. user_count = len(self.env['im_chat.presence'].search([
  43. ('status', '!=', 'offline'),
  44. ]))
  45. return {
  46. 'database_uuid': self.env['ir.config_parameter'].get_param(
  47. 'database.uuid'),
  48. 'cpu': cpu,
  49. 'ram': ram,
  50. 'user_count': user_count,
  51. }
  52. @api.model
  53. def alive(self):
  54. url = self.env['ir.config_parameter'].get_param(
  55. 'dead_mans_switch_client.url')
  56. logger = logging.getLogger(__name__)
  57. if not url:
  58. logger.error('No server configured!')
  59. return
  60. timeout = self.env['ir.config_parameter'].get_param(
  61. 'dead_mans_switch_client.send_timeout', SEND_TIMEOUT)
  62. data = self._get_data()
  63. logger.debug('sending %s', data)
  64. urllib2.urlopen(
  65. urllib2.Request(
  66. url,
  67. json.dumps({
  68. 'jsonrpc': '2.0',
  69. 'method': 'call',
  70. 'params': data,
  71. }),
  72. {
  73. 'Content-Type': 'application/json',
  74. }),
  75. timeout)
  76. @api.model
  77. def _install_default_url(self):
  78. """Set up a default URL."""
  79. conf = self.env["ir.config_parameter"]
  80. name = "dead_mans_switch_client.url"
  81. param = conf.get_param(name)
  82. if not param:
  83. url = "{}/dead_mans_switch/alive".format(
  84. conf.get_param(
  85. "report.url",
  86. conf.get_param(
  87. "web.base.url",
  88. "http://localhost")))
  89. conf.set_param(name, url)