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.

141 lines
5.2 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. from datetime import datetime, timedelta
  6. from openerp import _, api, fields, models
  7. class DeadMansSwitchInstance(models.Model):
  8. _inherit = ['mail.thread']
  9. _name = 'dead.mans.switch.instance'
  10. _description = 'Instance to monitor'
  11. _order = 'state, partner_id'
  12. _rec_name = 'partner_id'
  13. state = fields.Selection(
  14. [('new', 'New'), ('active', 'Active'), ('suspended', 'Suspended')],
  15. 'State', default='new')
  16. partner_id = fields.Many2one(
  17. 'res.partner', 'Customer',
  18. domain=[('is_company', '=', True), ('customer', '=', True)])
  19. database_uuid = fields.Char('Database id', required=True, readonly=True)
  20. user_id = fields.Many2one('res.users', 'Responsible user',
  21. track_visibility='onchange')
  22. description = fields.Char('Description')
  23. log_ids = fields.One2many(
  24. 'dead.mans.switch.log', 'instance_id', string='Log lines')
  25. alive = fields.Boolean('Alive', compute='_compute_alive')
  26. alive_max_delay = fields.Integer(
  27. 'Alive delay', help='The amount of seconds without notice after which '
  28. 'the instance is considered dead', default=600)
  29. last_seen = fields.Datetime('Last seen', compute='_compute_last_log')
  30. last_cpu = fields.Float('CPU', compute='_compute_last_log')
  31. last_cpu_sparkline = fields.Text('CPU', compute='_compute_last_log')
  32. last_ram = fields.Float('RAM', compute='_compute_last_log')
  33. last_ram_sparkline = fields.Text('RAM', compute='_compute_last_log')
  34. last_user_count = fields.Integer(
  35. 'Active users', compute='_compute_last_log')
  36. last_user_count_sparkline = fields.Text(
  37. 'Active users', compute='_compute_last_log')
  38. _sql_constraints = [
  39. ('uuid_unique', 'unique(database_uuid)', 'Database ID must be unique'),
  40. ]
  41. @api.multi
  42. def name_get(self):
  43. return [
  44. (
  45. this.id,
  46. '%s%s' % (
  47. this.partner_id.name or this.database_uuid,
  48. ' (%s)' % (this.description) if this.description else '',
  49. )
  50. )
  51. for this in self
  52. ]
  53. @api.onchange('partner_id')
  54. def _onchange_partner_id(self):
  55. if not self.user_id:
  56. self.user_id = self.partner_id.user_id
  57. @api.multi
  58. def button_active(self):
  59. self.write({'state': 'active'})
  60. @api.multi
  61. def button_suspended(self):
  62. self.write({'state': 'suspended'})
  63. @api.multi
  64. def button_logs(self):
  65. return {
  66. 'type': 'ir.actions.act_window',
  67. 'res_model': 'dead.mans.switch.log',
  68. 'domain': [('instance_id', 'in', self.ids)],
  69. 'name': _('Logs'),
  70. 'view_mode': 'graph,tree,form',
  71. 'context': {
  72. 'search_default_this_month': 1,
  73. },
  74. }
  75. @api.multi
  76. def _compute_alive(self):
  77. for this in self:
  78. if this.state in ['new', 'suspended']:
  79. this.alive = False
  80. continue
  81. this.alive = bool(
  82. self.env['dead.mans.switch.log'].search(
  83. [
  84. ('instance_id', '=', this.id),
  85. ('create_date', '>=', fields.Datetime.to_string(
  86. datetime.utcnow() -
  87. timedelta(seconds=this.alive_max_delay))),
  88. ],
  89. limit=1))
  90. @api.multi
  91. def _compute_last_log(self):
  92. for this in self:
  93. last_log = self.env['dead.mans.switch.log'].search(
  94. [('instance_id', '=', this.id)], limit=12)
  95. field_mapping = {
  96. 'last_seen': 'create_date',
  97. 'last_cpu': 'cpu',
  98. 'last_ram': 'ram',
  99. 'last_user_count': 'user_count',
  100. }
  101. for field, mapped_field in field_mapping.iteritems():
  102. this[field] = last_log[:1][mapped_field]
  103. sparkline_fields = ['last_cpu', 'last_ram', 'last_user_count']
  104. for field in sparkline_fields:
  105. this['%s_sparkline' % field] = json.dumps(
  106. list(reversed(last_log.mapped(lambda log: {
  107. 'value': log[field_mapping[field]],
  108. 'tooltip': log.create_date,
  109. }))))
  110. @api.model
  111. def check_alive(self):
  112. """handle cronjob"""
  113. for this in self.search([('state', '=', 'active')]):
  114. if this.alive:
  115. continue
  116. last_post = fields.Datetime.from_string(this.message_last_post)
  117. if not last_post or datetime.utcnow() - timedelta(
  118. seconds=this.alive_max_delay * 2) > last_post:
  119. this.panic()
  120. @api.multi
  121. def panic(self):
  122. """override for custom handling"""
  123. self.ensure_one()
  124. self.message_post(
  125. type='comment', subtype='mt_comment',
  126. subject=_('Dead man\'s switch warning: %s') %
  127. self.display_name, content_subtype='plaintext',
  128. body=_('%s seems to be dead') % self.display_name)