Blame view

product/ERP5/Tool/AlarmTool.py 8.25 KB
Sebastien Robin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
##############################################################################
#
# Copyright (c) 2004 Nexedi SARL and Contributors. All Rights Reserved.
#                    Sebastien Robin <seb@nexedi.com>
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

Jean-Paul Smets committed
29
import time
Jérome Perrin committed
30 31
import threading

Sebastien Robin committed
32
from AccessControl import ClassSecurityInfo
Jérome Perrin committed
33 34
from AccessControl.SecurityManagement import getSecurityManager, \
        newSecurityManager, setSecurityManager
Sebastien Robin committed
35
from Products.CMFActivity.ActivityTool import getCurrentNode
36
from Products.ERP5Type.Globals import InitializeClass, DTMLFile, PersistentMapping
Jean-Paul Smets committed
37
from Products.ERP5Type.Core.Folder import Folder
Sebastien Robin committed
38 39 40
from Products.ERP5Type.Tool.BaseTool import BaseTool
from Products.ERP5Type import Permissions
from Products.ERP5 import _dtmldir
Julien Muchembled committed
41
from Products.ERP5.mixin.timer_service import TimerServiceMixin
Sebastien Robin committed
42
from DateTime import DateTime
Nicolas Delaby committed
43
import urllib
Sebastien Robin committed
44

Jérome Perrin committed
45 46
last_tic = time.time()
last_tic_lock = threading.Lock()
Vincent Pelletier committed
47
_check_upgrade = True
Jérome Perrin committed
48

Julien Muchembled committed
49
class AlarmTool(TimerServiceMixin, BaseTool):
Sebastien Robin committed
50
  """
Aurel committed
51 52
    This tool manages alarms.

Vincent Pelletier committed
53
    It is used as a central managment point for all alarms.
Sebastien Robin committed
54

Vincent Pelletier committed
55
    Inside this tool we have a way to retrieve all reports coming
Vincent Pelletier committed
56
    from Alarms,...
Sebastien Robin committed
57 58 59 60 61 62 63 64 65 66 67
  """
  id = 'portal_alarms'
  meta_type = 'ERP5 Alarm Tool'
  portal_type = 'Alarm Tool'

  # Declarative Security
  security = ClassSecurityInfo()

  security.declareProtected( Permissions.ManagePortal, 'manage_overview' )
  manage_overview = DTMLFile( 'explainAlarmTool', _dtmldir )

Sebastien Robin committed
68 69
  security.declareProtected( Permissions.ManagePortal , 'manageAlarmNode' )
  manageAlarmNode = DTMLFile( 'manageAlarmNode', _dtmldir )
Aurel committed
70 71


Sebastien Robin committed
72
  manage_options = ( ( { 'label'   : 'Overview'
Vincent Pelletier committed
73 74
                       , 'action'   : 'manage_overview'
                       }
Sebastien Robin committed
75 76
                     , { 'label'   : 'Alarm Node'
                       , 'action'   : 'manageAlarmNode'
Aurel committed
77 78
                       }
                     ,
Vincent Pelletier committed
79 80 81
                     )
                     + Folder.manage_options
                   )
Sebastien Robin committed
82

Jérome Perrin committed
83
  _properties = ( {'id': 'interval', 'type': 'int', 'mode': 'w', }, )
Jean-Paul Smets committed
84
  interval = 60 # Default interval for alarms is 60 seconds
Vincent Pelletier committed
85 86 87 88 89 90 91
  # alarmNode possible values:
  #  ''      Bootstraping. The first node to call process_timer will cause this
  #          value to be set to its node id.
  #  (other) Node id matching this value will be the alarmNode.
  # Those values were chosen for backward compatibility with sites having an
  # alarmNode set to '' but expecting alarms to be executed. Use None to
  # disable alarm processing (see setAlarmNode).
Sebastien Robin committed
92
  alarmNode = ''
Vincent Pelletier committed
93

Sebastien Robin committed
94
  # API to manage alarms
Vincent Pelletier committed
95 96 97 98 99 100 101
  # Aim of this API:
  #-- see all alarms stored everywhere
  #-- defines global alarms
  #-- activate an alarm
  #-- see reports
  #-- see active alarms
  #-- retrieve all alarms
Sebastien Robin committed
102 103

  security.declareProtected(Permissions.ModifyPortalContent, 'getAlarmList')
Vincent Pelletier committed
104
  def getAlarmList(self, to_active = 0):
Sebastien Robin committed
105
    """
Vincent Pelletier committed
106
      We retrieve thanks to the catalog the full list of alarms
Sebastien Robin committed
107
    """
Sebastien Robin committed
108
    if to_active:
Sebastien Robin committed
109
      now = DateTime()
Jérome Perrin committed
110 111
      catalog_search = self.portal_catalog.unrestrictedSearchResults(
        portal_type = self.getPortalAlarmTypeList(),
Sebastien Robin committed
112
        alarm_date={'query':now,'range':'ngt'}
Vincent Pelletier committed
113
      )
Sebastien Robin committed
114
      # check again the alarm date in case the alarm was not yet reindexed
Yoshinori Okuji committed
115 116 117 118 119 120
      alarm_list = []
      for x in catalog_search:
        alarm = x.getObject()
        alarm_date = alarm.getAlarmDate()
        if alarm_date is not None and alarm_date <= now:
          alarm_list.append(alarm)
Sebastien Robin committed
121
    else:
Jérome Perrin committed
122
      catalog_search = self.portal_catalog.unrestrictedSearchResults(
Vincent Pelletier committed
123 124
        portal_type = self.getPortalAlarmTypeList()
      )
Sebastien Robin committed
125
      alarm_list = [x.getObject() for x in catalog_search]
Sebastien Robin committed
126 127 128 129 130
    return alarm_list

  security.declareProtected(Permissions.ModifyPortalContent, 'tic')
  def tic(self):
    """
Vincent Pelletier committed
131 132
      We will look at all alarms and see if they should be activated,
      if so then we will activate them.
Sebastien Robin committed
133
    """
Jérome Perrin committed
134 135 136 137 138 139 140 141 142
    security_manager = getSecurityManager()
    try:
      for alarm in self.getAlarmList(to_active=1):
        if alarm is not None:
          user = alarm.getWrappedOwner()
          newSecurityManager(self.REQUEST, user)
          if alarm.isActive() or not alarm.isEnabled():
            # do nothing if already active, or not enabled
            continue
Jérome Perrin committed
143
          if alarm.getProperty('automatic_solve'):
Jérome Perrin committed
144 145 146
            alarm.solve()
          else:
            alarm.activeSense()
Jérome Perrin committed
147 148
    finally:
      setSecurityManager(security_manager)
Jean-Paul Smets committed
149

Jérome Perrin committed
150
  security.declarePrivate('process_timer')
Aurel committed
151
  def process_timer(self, interval, tick, prev="", next=""):
Aurel committed
152
    """
Vincent Pelletier committed
153 154 155
      Call tic() every x seconds. x is defined in self.interval
      This method is called by TimerService in the interval given
      in zope.conf. The Default is every 5 seconds.
Jean-Paul Smets committed
156
    """
Julien Muchembled committed
157
    if not last_tic_lock.acquire(0):
Vincent Pelletier committed
158 159
      return
    try:
Vincent Pelletier committed
160 161 162 163 164 165
      # make sure our skin is set-up. On CMF 1.5 it's setup by acquisition,
      # but on 2.2 it's by traversal, and our site probably wasn't traversed
      # by the timerserver request, which goes into the Zope Control_Panel
      # calling it a second time is a harmless and cheap no-op.
      # both setupCurrentSkin and REQUEST are acquired from containers.
      self.setupCurrentSkin(self.REQUEST)
Vincent Pelletier committed
166 167
      # only start when we are the alarmNode
      alarmNode = self.getAlarmNode()
Sebastien Robin committed
168
      current_node = getCurrentNode()
Vincent Pelletier committed
169 170 171 172 173
      if alarmNode == '':
        self.setAlarmNode(current_node)
        alarmNode = current_node
      if alarmNode == current_node:
        global last_tic
Vincent Pelletier committed
174 175
        now = tick.timeTime()
        if now - last_tic >= self.interval:
Sebastien Robin committed
176
          self.tic()
Vincent Pelletier committed
177
          last_tic = now
Vincent Pelletier committed
178 179 180 181 182 183
      elif _check_upgrade and self.getServerAddress() == alarmNode:
        # BBB: check (once per run) if our node was alarm_node by address, and
        # migrate it.
        global _check_upgrade
        _check_upgrade = False
        self.setAlarmNode(current_node)
Vincent Pelletier committed
184 185
    finally:
      last_tic_lock.release()
Sebastien Robin committed
186 187 188 189 190 191

  security.declarePublic('getAlarmNode')
  def getAlarmNode(self):
      """ Return the alarmNode """
      return self.alarmNode

Sebastien Robin committed
192
  security.declareProtected(Permissions.ManageProperties, 'setAlarmNode')
Vincent Pelletier committed
193 194 195 196 197 198 199 200 201 202 203
  def setAlarmNode(self, alarm_node):
    """
      When alarm_node evaluates to false, set a None value:
      Its meaning is that alarm processing is disabled.
      This avoids an empty string to make the system re-enter boostrap mode.
    """
    if alarm_node:
      self.alarmNode = alarm_node
    else:
      self.alarmNode = None

Vincent Pelletier committed
204 205 206 207
  security.declarePublic('getNodeList')
  def getNodeList(self):
    return self.getPortalObject().portal_activities.getNodeList()

Sebastien Robin committed
208
  security.declareProtected(Permissions.ManageProperties, 'manage_setAlarmNode')
Sebastien Robin committed
209
  def manage_setAlarmNode(self, alarmNode, REQUEST=None):
Gabriel Monnerat committed
210
      """ set the alarm node """
Sebastien Robin committed
211
      if not alarmNode or self._isValidNodeName(alarmNode):
Vincent Pelletier committed
212
        self.setAlarmNode(alarmNode)
Sebastien Robin committed
213 214 215 216 217 218 219 220 221 222 223
        if REQUEST is not None:
            REQUEST.RESPONSE.redirect(
                REQUEST.URL1 +
                '/manageAlarmNode?manage_tabs_message=' +
                urllib.quote("Distributing Node successfully changed."))
      else :
        if REQUEST is not None:
            REQUEST.RESPONSE.redirect(
                REQUEST.URL1 +
                '/manageAlarmNode?manage_tabs_message=' +
                urllib.quote("Malformed Distributing Node."))
Sebastien Robin committed
224