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

# Source Code for Module Products.ZenModel.MibOrganizer

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