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

# Source Code for Module Products.ZenModel.MibOrganizer

      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 os
     12  import logging
     13  log = logging.getLogger('zen.Mibs')
     14
     15  from Globals import DTMLFile
     16  from Globals import InitializeClass
     17  from AccessControl import ClassSecurityInfo
     18  from AccessControl import Permissions
     19  from Products.Jobber.jobs import SubprocessJob
     20  from Products.ZenModel.ZenossSecurity import *
     21
     22  from Products.ZenRelations.RelSchema import *
     23  from Products.ZenUtils.Search import makeCaseInsensitiveKeywordIndex
     24  from Products.ZenWidgets import messaging
     25  from Products.ZenUtils.Utils import binPath
     26  from Organizer import Organizer
     27  from MibModule import MibModule
     28  from ZenPackable import ZenPackable
     29
     30 -def manage_addMibOrganizer(context, id, REQUEST = None):
     31      """make a device class"""
     32      sc = MibOrganizer(id)
     33      context._setObject(id, sc)
     34      sc = context._getOb(id)
     35      if REQUEST is not None:
     36          REQUEST['RESPONSE'].redirect(context.absolute_url() + '/manage_main')
     37
     38  addMibOrganizer = DTMLFile('dtml/addMibOrganizer',globals())
     39
     40
     41 -def _oid2name(mibSearch, oid, exactMatch=True, strip=False):
     42      """Return a name for an oid. This function is extracted out of the
     43      MibOrganizer class and takes mibSearch as a parameter to make it easier to
     44      unit test.
     45      """
     46      oid = oid.strip('.')
     47
     48      if exactMatch:
     49          brains = mibSearch(oid=oid)
     50          if len(brains) > 0:
     51              return brains[0].id
     52          else:
     53              return ""
     54
     55      oidlist = oid.split('.')
     56      for i in range(len(oidlist), 0, -1):
     57          brains = mibSearch(oid='.'.join(oidlist[:i]))
     58          if len(brains) < 1: continue
     59          if len(oidlist[i:]) > 0 and not strip:
     60              return "%s.%s" % (brains[0].id, '.'.join(oidlist[i:]))
     61          else:
     62              return brains[0].id
     63      return ""
     64
     65
     66 -class MibOrganizer(Organizer, ZenPackable):
     67      """
     68      DeviceOrganizer is the base class for device organizers.
     69      It has lots of methods for rolling up device statistics and information.
     70      """
     71      meta_type = "MibOrganizer"
     72      dmdRootName = "Mibs"
     73      default_catalog = 'mibSearch'
     74
     75      security = ClassSecurityInfo()
     76
     77      _relations = Organizer._relations + ZenPackable._relations + (
     78          ("mibs", ToManyCont(ToOne,"Products.ZenModel.MibModule","miborganizer")),
     79          )
     80
     81
     82      # Screen action bindings (and tab definitions)
     83      factory_type_information = (
     84          {
     85              'immediate_view' : 'mibOrganizerOverview',
     86              'actions'        :
     87              (
     88                  { 'id'            : 'overview'
     89                  , 'name'          : 'Overview'
     90                  , 'action'        : 'mibOrganizerOverview'
     91                  , 'permissions'   : ( Permissions.view, )
     92                  },
     93              )
     94           },
     95          )
     96
     97
     98 -    def __init__(self, id=None, description=None, text=None, content_type='text/html'):
     99          if not id: id = self.dmdRootName
    100          super(MibOrganizer, self).__init__(id, description)
    101          if self.id == self.dmdRootName:
    102              self.createCatalog()
    103
    104 -    def getMibClass(self):
    105          return MibOrganizer
    106
    107 -    def countMibs(self):
    108          """Return a count of all our contained children."""
    109          count = len(self.mibs())
    110          for child in self.children():
    111              count += child.countMibs()
    112          return count
    113
    114 -    def oid2name(self, oid, exactMatch=True, strip=False):
    115          """Return a name for an oid.
    116          """
    117          return _oid2name(self.getDmdRoot("Mibs").mibSearch, oid,
    118              exactMatch, strip)
    119
    120
    121 -    def name2oid(self, name):
    122          """Return an oid based on a name in the form MIB::name.
    123          """
    124          brains = self.getDmdRoot("Mibs").mibSearch({'id': name})
    125          if len(brains) > 0: return brains[0].oid
    126          return ""
    127
    128
    129 -    def countClasses(self):
    130          """Count all mibs with in a MibOrganizer.
    131          """
    132          count = self.mibs.countObjects()
    133          for group in self.children():
    134              count += group.countClasses()
    135          return count
    136
    137
    138 -    def createMibModule(self, name, path="/"):
    139          """Create a MibModule
    140          """
    141          mibs = self.getDmdRoot(self.dmdRootName)
    142          mod = None
    143          if not mod:
    144              modorg = mibs.createOrganizer(path)
    145              mod = MibModule(name)
    146              modorg.mibs._setObject(mod.id, mod)
    147              mod = modorg.mibs._getOb(mod.id)
    148          return mod
    149
    150
    151 -    def manage_addMibModule(self, id, REQUEST=None):
    152          """Create a new service class in this Organizer.
    153          """
    154          mm = MibModule(id)
    155          self.mibs._setObject(id, mm)
    156          if REQUEST:
    157              messaging.IMessageSender(self).sendToBrowser(
    158                  'Mib Module Created',
    159                  'Mib module %s was created.' % id
    160              )
    161              return self.callZenScreen(REQUEST)
    162          else:
    163              return self.mibs._getOb(id)
    164
    165
    166 -    def removeMibModules(self, ids=None, REQUEST=None):
    167          """Remove MibModules from an EventClass.
    168          """
    169          if not ids: return self()
    170          if isinstance(ids, basestring): ids = (ids,)
    171          for id in ids:
    172              self.mibs._delObject(id)
    173          if REQUEST:
    174              messaging.IMessageSender(self).sendToBrowser(
    175                  'Mib Module Deleted',
    176                  'Mib modules deleted: %s' % ', '.join(ids)
    177              )
    178              return self()
    179
    180
    181 -    def moveMibModules(self, moveTarget, ids=None, REQUEST=None):
    182          """Move MibModules from this organizer to moveTarget.
    183          """
    184          if not moveTarget or not ids: return self()
    185          if isinstance(ids, basestring): ids = (ids,)
    186          target = self.getChildMoveTarget(moveTarget)
    187          for id in ids:
    188              rec = self.mibs._getOb(id)
    189              rec._operation = 1 # moving object state
    190              self.mibs._delObject(id)
    191              target.mibs._setObject(id, rec)
    192          if REQUEST:
    193              messaging.IMessageSender(self).sendToBrowser(
    194                  'Mib Module Moved',
    195                  'Mib modules moved to %s.' % moveTarget
    196              )
    197              REQUEST['RESPONSE'].redirect(target.getPrimaryUrlPath())
    198
    199
    200 -    def reIndex(self):
    201          """Go through all devices in this tree and reindex them."""
    202          zcat = self._getOb(self.default_catalog)
    203          zcat.manage_catalogClear()
    204          for org in [self,] + self.getSubOrganizers():
    205              for mib in org.mibs():
    206                  for thing in mib.nodes() + mib.notifications():
    207                      thing.index_object()
    208
    209
    210 -    def createCatalog(self):
    211          """Create a catalog for mibs searching"""
    212          from Products.ZCatalog.ZCatalog import manage_addZCatalog
    213
    214          # XXX update to use ManagableIndex
    215          manage_addZCatalog(self, self.default_catalog, self.default_catalog)
    216          zcat = self._getOb(self.default_catalog)
    217          cat = zcat._catalog
    218          cat.addIndex('oid', makeCaseInsensitiveKeywordIndex('oid'))
    219          cat.addIndex('id', makeCaseInsensitiveKeywordIndex('id'))
    220          cat.addIndex('summary', makeCaseInsensitiveKeywordIndex('summary'))
    221          zcat.addColumn('getPrimaryId')
    222          zcat.addColumn('id')
    223          zcat.addColumn('oid')
    224
    225 -    def handleUploadedFile(self, REQUEST):
    226          """
    227          Assumes the file to be a mib so we need to create a mib module with
    228          its contents
    229          File will be available with REQUEST.upload
    230          """
    231          filename = REQUEST.upload.filename
    232          mibs = REQUEST.upload.read()
    233          # write it to a temp file
    234          path = '/tmp/%s' % filename
    235          with open(path, 'w') as f:
    236              f.write(mibs)
    237
    238          # create the job
    239          mypath = self.absolute_url_path().replace('/zport/dmd/Mibs', '')
    240          if not mypath:
    241              mypath = '/'
    242          commandArgs = [binPath('zenmib'), 'run', path,
    243                  '--path=%s' % mypath]
    244          return self.dmd.JobManager.addJob(SubprocessJob,
    245                     description="Load MIB at %s" % mypath,
    246                     kwargs=dict(cmd=commandArgs))
    247
    248
    249  InitializeClass(MibOrganizer)
    250