Package Products :: Package ZenRelations :: Module ImportDevices |
[hide private]
[frames] | no frames]

# Source Code for Module Products.ZenRelations.ImportDevices

      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  __doc__ = """ImportRM
     12
     13  Import RelationshipManager objects into a Zope database
     14
     15  """
     16
     17  import sys
     18  import urllib2
     19  import transaction
     20  from urlparse import urlparse
     21  from xml.dom.minidom import parse
     22
     23  import Globals
     24  from Products.ZenUtils.ZCmdBase import ZCmdBase
     25
     26  from Products.ZenRelations.Exceptions import *
     27
     28  #TODO: ZEN-1855 May want to remove this class
     29 -class ImportDevices(ZCmdBase):
     30
     31 -    def getDevicePath(self, device):
     32
     33          def _getParentDevClass(node):
     34              ancestor = node.parentNode
     35              while ancestor.getAttribute('class') != 'DeviceClass':
     36                  ancestor = ancestor.parentNode
     37              return ancestor
     38
     39          ancestor = _getParentDevClass(device)
     40          path = []
     41          while ancestor.getAttribute('id') != '/zport/dmd/Devices':
     42              path.append(ancestor.getAttribute('id'))
     43              ancestor = _getParentDevClass(ancestor)
     44          path.reverse()
     45          return '/' + '/'.join(path)
     46
     47 -    def processLinks(self, device):
     48          def parse_objid(objid, last=False):
     49              if last: objid = objid.split('/')[-1]
     50              else: objid = '/'.join(objid.split('/')[4:])
     51              objid = objid.encode('ascii')
     52              return objid
     53          d = dict(
     54              systemPaths = [],
     55              groupPaths = [],
     56              performanceMonitor = '',
     57              locationPath = ''
     58          )
     59          tomanys = device.getElementsByTagName('tomany')
     60          toones = device.getElementsByTagName('toone')
     61          for tomany in tomanys:
     62              id = tomany.getAttribute('id')
     63              links = tomany.getElementsByTagName('link')
     64              if id == 'systems':
     65                  for link in links:
     66                      d['systemPaths'].append(parse_objid(link.getAttribute('objid')))
     67              elif id == 'groups':
     68                  for link in links:
     69                      d['groupPaths'].append(parse_objid(link.getAttribute('objid')))
     70          for toone in toones:
     71              id = toone.getAttribute('id')
     72              objid = toone.getAttribute('objid')
     73              if id=='perfServer': d['performanceMonitor'] = parse_objid(objid,
     74                                                                         True)
     75              elif id=='location': d['locationPath'] = parse_objid(objid)
     76          return d
     77
     78
     79 -    def handleDevices(self):
     80          devs = self.doc.getElementsByTagName('object')
     81          for dev in devs:
     82              if dev.getAttribute('class') != 'Device': continue
     83              device = {
     84                  'deviceName' : dev.getAttribute('id').encode('ascii'),
     85                  'devicePath' : self.getDevicePath(dev).encode('ascii')
     86                  }
     87              device.update(self.processLinks(dev))
     88              print "Loading %s into %s..." % (device['deviceName'],
     89                                               device['devicePath'])
     90              self.dmd.DeviceLoader.loadDevice(**device)
     91
     92
     93 -    def buildOptions(self):
     94          """basic options setup sub classes can add more options here"""
     95          ZCmdBase.buildOptions(self)
     96
     97          self.parser.add_option('-i', '--infile',
     98                      dest="infile",
     99                      help="Input file for import. The default is stdin")
    100          print "Build option infile"
    101
    102          self.parser.add_option('-x', '--commitCount',
    103                      dest='commitCount',
    104                      default=20,
    105                      type="int",
    106                      help='How many lines should be loaded before a database commit')
    107
    108          self.parser.add_option('--noindex',
    109                      dest='noindex',action="store_true",default=False,
    110                      help='Do not try to index data that was just loaded')
    111
    112          self.parser.add_option('-n', '--noCommit',
    113                      dest='noCommit',
    114                      action="store_true",
    115                      default=0,
    116                      help='Do not store changes to the Dmd (for debugging)')
    117
    118
    119 -    def loadObjectFromXML(self, objstack=None, xmlfile=''):
    120          """This method can be used to load data for the root of Zenoss (default
    121          behavior) or it can be used to operate on a specific point in the
    122          Zenoss hierarchy (ZODB).
    123
    124          Upon loading the XML file to be processed, the content of the XML file
    125          is handled (processed) by the methods in this class.
    126          """
    127          from Products.ZenUtils.Utils import unused
    128          unused(objstack)
    129          if xmlfile:
    130              # check to see if we're getting the XML from a URL ...
    131              schema, host, path, null, null, null = urlparse(xmlfile)
    132              if schema and host:
    133                  self.infile = urllib2.urlopen(xmlfile)
    134              # ... or from a file on the file system
    135              else:
    136                  self.infile = open(xmlfile)
    137          elif self.options.infile:
    138              self.infile = open(self.options.infile)
    139          else:
    140              self.infile = sys.stdin
    141          self.doc = parse(self.infile)
    142          self.handleDevices()
    143          self.doc.unlink()
    144          self.infile.close()
    145
    146 -    def loadDatabase(self):
    147          """The default behavior of loadObjectFromXML() will be to use the Zope
    148          app object, and thus operatate on the whole of Zenoss.
    149          """
    150          self.loadObjectFromXML()
    151
    152 -    def commit(self):
    153          trans = transaction.get()
    154          trans.note('Import from file %s using %s'
    155                      % (self.options.infile, self.__class__.__name__))
    156          trans.commit()
    157
    158
    159  if __name__ == '__main__':
    160      im = ImportDevices()
    161      im.loadDatabase()
    162