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

# Source Code for Module Products.ZenModel.NotificationSubscription

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