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.

82 lines
2.8 KiB

  1. # -*- coding: utf-8 -*-
  2. # © 2015 Therp BV <http://therp.nl>
  3. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
  4. import json
  5. import logging
  6. import os
  7. try:
  8. import psutil
  9. except ImportError:
  10. psutil = None
  11. import urllib2
  12. from openerp.osv import orm
  13. from openerp.tools.config import config
  14. SEND_TIMEOUT = 60
  15. class DeadMansSwitchClient(orm.AbstractModel):
  16. _name = 'dead.mans.switch.client'
  17. _register = True
  18. def _get_data(self, cr, uid, context=None):
  19. ram = 0
  20. cpu = 0
  21. if psutil:
  22. process = psutil.Process(os.getpid())
  23. # psutil changed its api through versions
  24. processes = [process]
  25. if config.get('workers') and process.parent:
  26. if hasattr(process.parent, '__call__'):
  27. process = process.parent()
  28. else:
  29. process = process.parent
  30. if hasattr(process, 'children'):
  31. processes += process.children(True)
  32. elif hasattr(process, 'get_children'):
  33. processes += process.get_children(True)
  34. for process in processes:
  35. if hasattr(process, 'memory_percent'):
  36. ram += process.memory_percent()
  37. elif hasattr(process, 'get_memory_percent'):
  38. ram += process.get_memory_percent()
  39. else:
  40. ram = None
  41. if hasattr(process, 'cpu_percent'):
  42. cpu += process.cpu_percent()
  43. elif hasattr(process, 'get_cpu_percent'):
  44. cpu += process.get_cpu_percent()
  45. else:
  46. cpu = None
  47. return {
  48. 'database_uuid': self.pool['ir.config_parameter'].get_param(
  49. cr, uid, 'database.uuid', context=context),
  50. 'cpu': cpu,
  51. 'ram': ram,
  52. 'user_count': None,
  53. }
  54. def alive(self, cr, uid, context=None):
  55. url = self.pool['ir.config_parameter'].get_param(
  56. cr, uid, 'dead_mans_switch_client.url')
  57. logger = logging.getLogger(__name__)
  58. if not url:
  59. logger.error('No server configured!')
  60. return
  61. timeout = self.pool['ir.config_parameter'].get_param(
  62. cr, uid, 'dead_mans_switch_client.send_timeout', SEND_TIMEOUT,
  63. context=context)
  64. data = self._get_data(cr, uid, context=context)
  65. logger.debug('sending %s', data)
  66. urllib2.urlopen(
  67. urllib2.Request(
  68. url,
  69. json.dumps({
  70. 'jsonrpc': '2.0',
  71. 'method': 'call',
  72. 'params': data,
  73. }),
  74. {
  75. 'Content-Type': 'application/json',
  76. }),
  77. timeout=timeout)