Package Products :: Package ZenModel :: Module NotificationSubscription |
[hide private]
[frames] | no frames]

# Source Code for Module Products.ZenModel.NotificationSubscription

      1  ###########################################################################
      2  #
      3  # This program is part of Zenoss Core, an open source monitoring platform.
      4  # Copyright (C) 2007, Zenoss Inc.
      5  #
      6  # This program is free software; you can redistribute it and/or modify it
      7  # under the terms of the GNU General Public License version 2 or (at your
      8  # option) any later version as published by the Free Software Foundation.
      9  #
     10  # For complete information please visit: http://www.zenoss.com/oss/
     11  #
     12  ###########################################################################
     13
     14  import logging
     15  log = logging.getLogger("zen.notifications")
     16
     17
     18  from zope.interface import implements
     19  from Globals import InitializeClass
     20  from Globals import DTMLFile
     21  from AccessControl import ClassSecurityInfo
     22  from AdministrativeRoleable import AdministrativeRoleable
     23  from Products.ZenRelations.RelSchema import *
     24  from Products.ZenModel.ZenossSecurity import *
     25  from Products.ZenModel.ZenModelRM import ZenModelRM
     26  from Products.ZenUtils.guid.interfaces import IGloballyIdentifiable
     27  from Products.ZenUtils.Time import LocalDateTime
     28  from Products.ZenUtils.ZenTales import talesEvalStr, talEval
     29  from Products.ZenEvents.events2.proxy import EventProxy, EventSummaryProxy
     30  from zenoss.protocols.protobufs.zep_pb2 import Event, EventSummary
     31  from zenoss.protocols.jsonformat import from_dict
     32  from zenoss.protocols.wrappers import EventSummaryAdapter
     33  from Products.ZenEvents.EventManagerBase import EventManagerBase
     34
     35 -def manage_addNotificationSubscriptionManager(context, REQUEST=None):
     36      """Create the notification subscription manager."""
     37      nsm = NotificationSubscriptionManager(NotificationSubscriptionManager.root)
     38      context._setObject(NotificationSubscriptionManager.root, nsm)
     39      if REQUEST is not None:
     40          REQUEST['RESPONSE'].redirect(context.absolute_url() + '/manage_main')
     41
     42 -class NotificationSubscriptionManager(ZenModelRM):
     43      """Manage notification subscriptions.
     44
     45      @todo: change the icon parameter in factory_type_information.
     46      """
     47
     48      _id = "NotificationSubscriptionManager"
     49      root = 'NotificationSubscriptions'
     50      meta_type = _id
     51
     52      sub_meta_types = ("NotificationSubscription",)
     53
     54      factory_type_information = (
     55          {
     56              'id'             : _id,
     57              'meta_type'      : _id,
     58              'description'    : """Management of notification subscriptions""",
     59              'icon'           : 'UserSettingsManager.gif',
     60              'product'        : 'ZenModel',
     61              'factory'        : 'manage_addNotificationSubscriptionManager',
     62              'immediate_view' : 'editSettings',
     63              'actions'        : (
     64                  {
     65                      'id'            : 'settings',
     66                      'name'          : 'Settings',
     67                      'action'        : '../editSettings',
     68                      'permissions'   : ( ZEN_MANAGE_DMD, )
     69                  })
     70           },
     71      )
     72
     73
     74  addNotificationSubscription = DTMLFile('dtml/addNotificationSubscription',globals())
     75
     76 -def manage_addNotificationSubscription(context, id, title = None, REQUEST = None):
     77      """Create a notification subscription"""
     78      ns = NotificationSubscription(id, title)
     79      context._setObject(id, ns)
     80      if REQUEST:
     81          REQUEST['RESPONSE'].redirect(context.absolute_url() + '/manage_main')
     82
     83 -class NoneDefaultingDict(dict):
     84 -    def __missing__(self, key):
     85          ret = NoneDefaultingDict()
     86          self[key] = ret
     87          return ret
     88
     89 -class NotificationEventSummaryProxy(EventSummaryProxy):
     90      @property
     91 -    def severityString(self):
     92          """
     93          The old event system used to export 'severityString' as a field to use in notifications.
     94          """
     95          try:
     96              return EventManagerBase.severities[self.severity]
     97          except KeyError:
     98              return "Unknown"
     99
    100 -class NotificationEventContextWrapper(NoneDefaultingDict):
    101 -    def __init__(self, evtsummary, clearevtsummary=None):
    102          super(NotificationEventContextWrapper,self).__init__()
    103          self['evt'] = NotificationEventSummaryProxy(evtsummary)
    104          self['eventSummary'] = EventSummaryAdapter(evtsummary)
    105          if clearevtsummary is not None:
    106              self['clearEvt'] = NotificationEventSummaryProxy(clearevtsummary)
    107              self['clearEventSummary'] = EventSummaryAdapter(clearevtsummary)
    108          else:
    109              self['clearEvt'] = NoneDefaultingDict()
    110              self['clearEventSummary'] = NoneDefaultingDict()
    111
    112 -class NotificationSubscription(ZenModelRM, AdministrativeRoleable):
    113      """
    114      A subscription to a signal that produces notifications in the form of
    115      actions.
    116      """
    117      implements(IGloballyIdentifiable)
    118
    119      _id = "NotificationSubscription"
    120      meta_type = _id
    121
    122      enabled = False
    123      action = 'email'
    124      send_clear = False
    125
    126      delay_seconds = 0
    127      repeat_seconds = 0
    128      send_initial_occurrence = True
    129
    130      # recipients is a list of uuids that will recieve the push from this
    131      # notification. (the User, Group or Role to email/page/etc.)
    132      # the uuid objects will need to implement some form of actionable target
    133      # See IAction classes for more info.
    134      recipients = []
    135
    136      # a list of trigger uuids that this notification is subscribed to.
    137      subscriptions = []
    138
    139      _properties = ZenModelRM._properties + (
    140          {'id':'enabled', 'type':'boolean', 'mode':'w'},
    141          {'id':'send_clear', 'type':'boolean', 'mode':'w'},
    142          {'id':'send_initial_occurrence', 'type':'boolean', 'mode':'w'},
    143          {'id':'delay_seconds', 'type':'int', 'mode':'w'},
    144          {'id':'repeat_seconds', 'type':'int', 'mode':'w'},
    145      )
    146
    147      _relations = (
    148          ("adminRoles",
    149          ToManyCont(
    150              ToOne,
    151              "Products.ZenModel.AdministrativeRole",
    152              "managedObject"
    153          )),
    154          ("windows",
    155          ToManyCont(
    156              ToOne,
    157              "Products.ZenModel.NotificationSubscriptionWindow",
    158              "notificationSubscription"
    159          )),
    160      )
    161
    162      factory_type_information = (
    163          {
    164              'id'             : _id,
    165              'meta_type'      : _id,
    166              'description'    : """Define the notification and the signals to
    167                  which it is subscribed.""",
    168              # @todo: fix this icon
    169              'icon'           : 'ActionRule.gif',
    170              'product'        : 'ZenEvents',
    171              'factory'        : 'manage_addNotificationSubscription',
    172              'immediate_view' : 'editNotificationSubscription',
    173              'actions'        :(
    174                  {
    175                      'id'            : 'edit',
    176                      'name'          : 'Edit',
    177                      'action'        : 'editNotificationSubscription',
    178                      'permissions'   : (ZEN_CHANGE_ALERTING_RULES,)
    179                  }
    180              )
    181           },
    182      )
    183
    184      security = ClassSecurityInfo()
    185
    186 -    def __init__(self, id, title=None, buildRelations=True):
    187          self.globalRead = False
    188          self.globalWrite = False
    189          self.globalManage = False
    190
    191          self.content = {}
    192
    193          super(ZenModelRM, self).__init__(id, title=title, buildRelations=buildRelations)
    194
    195      security.declareProtected(ZEN_CHANGE_ALERTING_RULES, 'manage_editNotificationSubscription')
    196 -    def manage_editNotificationSubscription(self, REQUEST=None):
    197          """Update notification subscription properties"""
    198          return self.zmanage_editProperties(REQUEST)
    199
    200 -    def isActive(self):
    201          """
    202          Using maintenance windows and `enabled`, determine if this notification
    203          is active for right now.
    204          """
    205          if self.enabled:
    206              log.debug('Notification is enabled: %s' %  self.id)
    207              windows = self.windows()
    208              if windows:
    209                  log.debug('Notification has (%s) windows.' % len(windows))
    210
    211                  enabled_windows = []
    212                  for window in windows:
    213                      if window.enabled:
    214                          log.debug('Notification has enabled window: %s' % window.id)
    215                          enabled_windows.append(window)
    216
    217                  if enabled_windows:
    218                      for window in enabled_windows:
    219                          if window.isActive():
    220                              log.debug('Window is active: %s' % window.id)
    221                              return True
    222
    223                      # there are windows that are enabled, but none of them are
    224                      # active. This notification isn't active.
    225                      return False
    226
    227                  # If there are no enabled windows, defer to the notification's
    228                  # enabled setting
    229                  return True
    230              else:
    231                  log.debug('Notification is enabled, but has no windows, it is active.')
    232                  return True
    233          else:
    234              log.debug('Notification NOT enabled: %s' %  self.id)
    235              return False
    236
    237  InitializeClass(NotificationSubscriptionManager)
    238  InitializeClass(NotificationSubscription)
    239