Esempio n. 1
0
 def reIndex(self):
     """Go through all ips in this tree and reindex them."""
     for net in self.getSubNetworks():
         for ip in net.ipaddresses():
             notify(IndexingEvent(ip))
    def afterSetUp(self):
        super(TestModel, self).afterSetUp()

        # Workaround for IMP-389:
        # When Impact 5.2.1-5.2.3 (at least) are installed, setProdState
        # is patched to re-index the object in the global catalog specifically
        # on the productionState column, but at least on older verions of RM,
        # the sandboxed version of global_catalog does not index that column,
        # which causes setProdState to fail.  Add the index for now, to
        # work around this.
        if (hasattr(self.dmd.global_catalog, 'indexes') and 'productionState'
                not in self.dmd.global_catalog.indexes()):
            from Products.ZenUtils.Search import makeCaseSensitiveFieldIndex
            self.dmd.global_catalog.addIndex(
                'productionState',
                makeCaseSensitiveFieldIndex('productionState'))
            self.dmd.global_catalog.addColumn('productionState')

        # Patch to remove DNS dependencies
        def getHostByName(name):
            return MOCK_DNS.get(name)

        def resolve_names(names):
            result = {}
            for name in names:
                result[name] = MOCK_DNS.get(name)
            return defer.maybeDeferred(lambda: result)

        self._real_resolve_names = hostmap.resolve_names
        hostmap.resolve_names = resolve_names

        self._real_getHostByName = Device.getHostByName
        Device.getHostByName = getHostByName

        dc = self.dmd.Devices.createOrganizer(
            '/Devices/OpenStack/Infrastructure')

        dc.setZenProperty('zPythonClass',
                          'ZenPacks.zenoss.OpenStackInfrastructure.Endpoint')
        dc.setZenProperty('zOpenStackHostDeviceClass',
                          '/Server/SSH/Linux/NovaHost')
        dc.setZenProperty('zOpenStackRegionName', 'RegionOne')
        dc.setZenProperty('zOpenStackAuthUrl', 'http://1.2.3.4:5000/v2.0')
        dc.setZenProperty('zOpenStackNovaApiHosts', [])
        dc.setZenProperty('zOpenStackExtraHosts', [])
        dc.setZenProperty('zOpenStackHostMapToId', [])
        dc.setZenProperty('zOpenStackHostMapSame', [])
        dc.setZenProperty('zOpenStackHostLocalDomain', '')
        dc.setZenProperty('zOpenStackExtraApiEndpoints', [])

        self.d = dc.createInstance('zenoss.OpenStackInfrastructure.testDevice')
        self.d.setPerformanceMonitor('localhost')
        self.d.index_object()
        notify(IndexingEvent(self.d))

        self.applyDataMap = ApplyDataMap()._applyDataMap

        # Required to prevent erroring out when trying to define viewlets in
        # ../browser/configure.zcml.
        import zope.viewlet
        zcml.load_config('meta.zcml', zope.viewlet)

        import ZenPacks.zenoss.OpenStackInfrastructure
        zcml.load_config('configure.zcml',
                         ZenPacks.zenoss.OpenStackInfrastructure)

        self._loadBadHosts()
        self._loadZenossData()
    def _moveDevice(self, devname, target, targetClass):
        dev = self.findDeviceByIdExact(devname)
        if not dev:
            return
        guid = IGlobalIdentifier(dev).create()
        source = dev.deviceClass().primaryAq()

        notify(
            DeviceClassMovedEvent(dev,
                                  dev.deviceClass().primaryAq(), target))

        exported = False
        if dev.__class__ != targetClass:
            from Products.ZenRelations.ImportRM import NoLoginImportRM

            def switchClass(o, module, klass):
                """
                Create an XML string representing the module in a
                new class.

                @param o: file-type object
                @type o: file-type object
                @param module: location in DMD
                @type module: string
                @param klass: class name
                @type klass: string
                @return: XML representation of the class
                @rtype: string
                """
                from xml.dom.minidom import parse

                # Note: strips almost everything out of the move
                #       as the new class may not have the same relations etc.
                #       For example, moving SNMP host to a VMware class.
                o.seek(0)
                dom = parse(o)
                root = dom.childNodes[0]
                root.setAttribute('module', module)
                root.setAttribute('class', klass)
                for obj in root.childNodes:
                    if obj.nodeType != obj.ELEMENT_NODE:
                        continue  # Keep XML-tree baggage

                    name = obj.getAttribute('id')
                    if obj.tagName == 'property':
                        # Only remove modeler plugins, templates
                        # and z*Ignore zprops
                        if name in ('zCollectorPlugins', 'zDeviceTemplates') or \
                           name.endswith('Ignore'):
                            root.removeChild(obj)

                    elif obj.tagName == 'toone' and \
                         name in ('perfServer', 'location'):
                        pass  # Preserve collector name and location

                    elif obj.tagName == 'tomany' and \
                         name in ('systems', 'groups'):
                        pass  # Preserve the Groups and Systems groupings

                    elif obj.tagName == 'tomanycont' and \
                         name in ('maintenanceWindows',
                                  'adminRoles',
                                  'userCommands'):
                        pass  # Preserve maintenance windows, admins, commands

                    else:
                        log.debug("Removing %s element id='%s'", obj.tagName,
                                  name)
                        root.removeChild(obj)

                importFile = StringIO()
                dom.writexml(importFile)
                importFile.seek(0)
                return importFile

            def devExport(d, module, klass):
                """
                Create an XML string representing the device d
                at the DMD location module of type klass.

                @param module: location in DMD
                @type module: string
                @param klass: class name
                @type klass: string
                @return: XML representation of the class
                @rtype: string
                """
                o = StringIO()
                d.exportXml(o, exportPasswords=True)
                return switchClass(o, module, klass)

            def devImport(xmlfile):
                """
                Load a new device from a file.

                @param xmlfile: file type object
                @type xmlfile: file type object
                """
                im = NoLoginImportRM(target.devices)
                im.loadObjectFromXML(xmlfile)
                im.processLinks()

            module = target.zPythonClass
            if module:
                klass = target.zPythonClass.split('.')[-1]
            else:
                module = 'Products.ZenModel.Device'
                klass = 'Device'
            log.debug('Exporting device %s from %s', devname, source)
            xmlfile = devExport(dev, module, klass)
            log.debug('Removing device %s from %s', devname, source)
            source.devices._delObject(devname)
            log.debug('Importing device %s to %s', devname, target)
            devImport(xmlfile)
            exported = True
        else:
            dev._operation = 1
            source.devices._delObject(devname)
            target.devices._setObject(devname, dev)
        dev = target.devices._getOb(devname)
        IGlobalIdentifier(dev).guid = guid
        dev.setLastChange()
        dev.setAdminLocalRoles()
        dev.index_object()
        notify(
            IndexingEvent(dev,
                          idxs=('path', 'searchKeywords'),
                          update_metadata=True))

        return exported
 def test_bad_indexing_event_indexes(self):
     with self.assertRaises(BadIndexingEvent):
         notify(IndexingEvent(self.dmd.Devices, idxs="you_d_better_raise_an_error"))