예제 #1
0
def updateIface(evt, device, component):
    """
        incremental interface modeling based on events sent
        here we only consider interface UP or DOWN
    """
    if 'interface' not in evt.component:
        # for interface only
        return 0

    log.info("event: %s", str(evt))
    astate = 'UP'
    lstate = 'UP'
    if 'admin state: DOWN' in evt.summary:
        astate = 'DOWN'
    if 'link state: DOWN' in evt.summary:
        lstate = 'DOWN'

    objmap = ObjectMap(
        modname='ZenPacks.zenoss.OpenvSwitch.Interface',
        compname='',
        data={
            'id':      evt.component,
            'lstate':  lstate,
            'astate':  astate,
        },
    )
    adm = ApplyDataMap(device)
    adm.applyDataMap(component, objmap)

    return 1
 def xmlrpc_applyDataMap(self, devName, datamap, 
                         relname="", compname="", modname=""):
     """Apply a datamap passed as a list of dicts through XML-RPC.
     """
     dev = self.dmd.findDevice(devName)
     adm = ApplyDataMap()
     adm.applyDataMap(dev, datamap, relname=relname,
                      compname=compname, modname=modname)
class TestInterfaceAliasMap(BaseTestCase):
    def afterSetUp(self):
        super(TestInterfaceAliasMap, self).afterSetUp()
        self.adm = ApplyDataMap()
        self.iamap = InterfaceAliasMap()
        self.device = self.dmd.Devices.createInstance('testDevice')

    def testCisco3560(self):
        pickle = open(
            "%s/data/InterfaceAliasMap_cisco3560.pickle" %
            os.path.dirname(__file__), 'rb')
        results = load(pickle)
        pickle.close()

        # Verify that the modeler plugin processes the data properly.
        relmap = self.iamap.process(self.device, results, log)
        relmap_orig = copy.deepcopy(relmap)

        self.assertEquals(relmap.compname, 'os')
        self.assertEquals(relmap.relname, 'interfaces')
        self.assertEquals(len(relmap.maps), 58)
        om = relmap.maps[0]
        self.assertEquals(om.id, 'Vl1')
        self.assertEquals(om.description, 'Description of Vlan1')

        # Verify that the data made it into the model properly.
        self.adm.applyDataMap(self.device, relmap)

        iface = self.device.os.interfaces.Vl1
        self.assertEquals(iface.id, 'Vl1')
        self.assertEquals(iface.description, 'Description of Vlan1')

        #print(
        #    '\n========================================\n'
        #    '    UPDATE MODEL'
        #    '\n========================================\n'
        #)
        # clear old directives
        relmap = relmap_orig
        om = relmap.maps[0]
        # update the device
        om.description = 'New Description of Vlan1'
        om._do_not_include = 'ignore me!'
        self.assertEquals(om.description, 'New Description of Vlan1')
        self.adm.applyDataMap(self.device, relmap)
        iface = self.device.os.interfaces.Vl1
        self.assertEquals(iface.id, 'Vl1')
        self.assertEquals(iface.description, 'New Description of Vlan1')
        self.assertFalse(hasattr(iface, '_do_not_include'))
예제 #4
0
 def xmlrpc_applyDataMap(self,
                         devName,
                         datamap,
                         relname="",
                         compname="",
                         modname=""):
     """Apply a datamap passed as a list of dicts through XML-RPC.
     """
     dev = self.dmd.findDevice(devName)
     adm = ApplyDataMap()
     adm.applyDataMap(dev,
                      datamap,
                      relname=relname,
                      compname=compname,
                      modname=modname)
예제 #5
0
def updateBridgePort(evt, device, component):
    """
        incremental bridge modeling based on events sent
        here we only consider delete event

        We can only incrementally model for delete events,
        but not for add event.
        The reason being that for deleting, we only need to know the
        component name. But for adding, we need to know much more
        ovsdb-tool show-log would not give us all info needed for adding
    """
    existingBridgeObjects = device.getDeviceComponents(type='OpenvSwitchBridge')
    bridgeTitleOrIds = [bridge.titleOrId() for bridge in existingBridgeObjects]
    bridgeIDs = [bridge.id for bridge in existingBridgeObjects]

    if evt.component not in bridgeTitleOrIds and \
            evt.component not in bridgeIDs:
        # for existing bridge only
        return 0

    log.info("event: %s", str(evt))
    bridges = []
    compname = ''
    relname = ''
    modname = ''
    if 'del bridge' in evt.summary:
        relname = 'bridges'
        modname = 'ZenPacks.zenoss.OpenvSwitch.Bridge'
        for brdg in existingBridgeObjects:
            if brdg and evt.component in (brdg.id, brdg.titleOrId()):
                continue

            bridges.append(ObjectMap(
                data={
                    'id':       brdg.id,
                    'title':    brdg.titleOrId(),
                    'bridgeId': brdg.uuid,
                    }))
        relmap = RelationshipMap(
            objmaps=bridges)

    if len(bridges) > 0:
        adm = ApplyDataMap(device)
        adm.applyDataMap(device, relmap, relname=relname, compname=compname, modname=modname)

        return 1
    else:
        return 0
예제 #6
0
class ApplyDataMapTest(BaseTestCase):

    def afterSetUp(self):
        super(ApplyDataMapTest, self).afterSetUp()
        self.adm = ApplyDataMap()

    def test_updateObject_encoding(self):
        for enc in ('ascii', 'latin-1', 'utf-8', 'utf-16'):
            obj = _obj()
            obj.zCollectorDecoding = enc
            objmap = eval(enc.replace('-','')+'_objmap')
            self.adm._updateObject(obj, objmap)
            for key in objmap:
                self.assertEqual(getattr(obj, key), objmap[key].decode(enc))

    def test_applyDataMap_relmap(self):
        dmd = self.dmd
        class datamap(list):
            compname = "a/b"
            relname  = "c"

        class Device(object):

            def deviceClass(self):
                return dmd.Devices

            class dmd:
                "Used for faking sync()"
                class _p_jar:
                    @staticmethod
                    def sync():
                        pass

            def getObjByPath(self, path):
                return reduce(getattr, path.split("/"), self)
            def getId(self):
                return "testDevice"

            class a:
                class b:
                    class c:
                        "The relationship to populate"
                        @staticmethod
                        def objectIdsAll():
                            "returns the list of object ids in this relationship"
                            return []
        self.adm.applyDataMap(Device(), datamap(), datamap.relname, datamap.compname)
예제 #7
0
class ApplyDataMapTest(BaseTestCase):
    def afterSetUp(self):
        super(ApplyDataMapTest, self).afterSetUp()
        self.adm = ApplyDataMap()

    def test_updateObject_encoding(self):
        for enc in ('ascii', 'latin-1', 'utf-8', 'utf-16'):
            obj = _obj()
            obj.zCollectorDecoding = enc
            objmap = eval(enc.replace('-', '') + '_objmap')
            self.adm._updateObject(obj, objmap)
            for key in objmap:
                self.assertEqual(getattr(obj, key), objmap[key].decode(enc))

    def test_applyDataMap_relmap(self):
        dmd = self.dmd

        class datamap(list):
            compname = "a/b"
            relname = "c"

        class Device(object):
            def deviceClass(self):
                return dmd.Devices

            class dmd:
                "Used for faking sync()"

                class _p_jar:
                    @staticmethod
                    def sync():
                        pass

            def getObjByPath(self, path):
                return reduce(getattr, path.split("/"), self)

            def getId(self):
                return "testDevice"

            class a:
                class b:
                    class c:
                        "The relationship to populate"

                        @staticmethod
                        def objectIdsAll():
                            "returns the list of object ids in this relationship"
                            return []

        self.adm.applyDataMap(Device(), datamap(), datamap.relname,
                              datamap.compname)

    def test_applyDataMap_relmapException(self):
        '''test_applyDataMap_exception is mostly the same as test_applyDataMap_relmap
    	     - difference #1: compname is commented out
	     - difference #2: with self.assertRaises(AttributeError) is added
    	'''
        dmd = self.dmd

        class datamap(list):
            #compname = "a/b"
            relname = "c"

        class Device(object):
            def deviceClass(self):
                return dmd.Devices

            class dmd:
                "Used for faking sync()"

                class _p_jar:
                    @staticmethod
                    def sync():
                        pass

            def getObjByPath(self, path):
                return reduce(getattr, path.split("/"), self)

            class a:
                class b:
                    class c:
                        "The relationship to populate"

                        @staticmethod
                        def objectIdsAll():
                            "returns the list of object ids in this relationship"
                            return []

        with self.assertRaises(AttributeError) as theException:
            self.adm.applyDataMap(Device(), datamap(), datamap.relname,
                                  datamap.compname)

        self.assertEqual(theException.exception.message,
                         "type object 'datamap' has no attribute 'compname'")

    def testNoChangeAllComponentsLocked(self):
        device = self.dmd.Devices.createInstance('testDevice')
        # Create an IP interface
        device.os.addIpInterface('eth0', False)
        iface = device.os.interfaces._getOb('eth0')
        iface.lockFromDeletion()

        # Apply a RelMap with no interfaces
        relmap = RelationshipMap("interfaces", "os",
                                 "Products.ZenModel.IpInterface")
        self.assertFalse(self.adm._applyDataMap(device, relmap))

        self.assertEquals(1, len(device.os.interfaces))
예제 #8
0
class ApplyDataMapTest(BaseTestCase):

    def afterSetUp(self):
        super(ApplyDataMapTest, self).afterSetUp()
        self.adm = ApplyDataMap()

    def test_updateObject_encoding(self):
        for enc in ('ascii', 'latin-1', 'utf-8', 'utf-16'):
            obj = _obj()
            obj.zCollectorDecoding = enc
            objmap = eval(enc.replace('-','')+'_objmap')
            self.adm._updateObject(obj, objmap)
            for key, val in objmap.items():
                self.assertEqual(getattr(obj, key), val.decode(enc))

    def test_applyDataMap_relmap(self):
        dmd = self.dmd
        class datamap(list):
            compname = "a/b"
            relname  = "c"

        class Device(object):

            def deviceClass(self):
                return dmd.Devices

            def getPrimaryId(self):
                return "{}/{}".format(self.deviceClass().getPrimaryId(), self.getId())

            class dmd:
                "Used for faking sync()"
                class _p_jar:
                    @staticmethod
                    def sync():
                        pass

            def getObjByPath(self, path):
                return reduce(getattr, path.split("/"), self)

            def getId(self):
                return "testDevice"

            class a:
                class b:
                    class c:
                        "The relationship to populate"
                        @staticmethod
                        def objectIdsAll():
                            "returns the list of object ids in this relationship"
                            return []
        self.adm.applyDataMap(Device(), datamap(), datamap.relname, datamap.compname)

    def test_applyDataMap_relmapException(self):
    	'''test_applyDataMap_exception is mostly the same as test_applyDataMap_relmap
    	     - difference #1: compname is commented out
	     - difference #2: with self.assertRaises(AttributeError) is added
    	'''
        dmd = self.dmd
        class datamap(list):
            #compname = "a/b"
            relname  = "c"

        class Device(object):

            def deviceClass(self):
                return dmd.Devices

            class dmd:
                "Used for faking sync()"
                class _p_jar:
                    @staticmethod
                    def sync():
                        pass

            def getObjByPath(self, path):
                return reduce(getattr, path.split("/"), self)

            class a:
                class b:
                    class c:
                        "The relationship to populate"
                        @staticmethod
                        def objectIdsAll():
                            "returns the list of object ids in this relationship"
                            return []
 
        with self.assertRaises(AttributeError) as theException:
            self.adm.applyDataMap(Device(), datamap(), datamap.relname, datamap.compname)

        self.assertEqual(theException.exception.message, "type object 'datamap' has no attribute 'compname'")

    def testNoChangeAllComponentsLocked(self):
        device = self.dmd.Devices.createInstance('testDevice')
        # Create an IP interface
        device.os.addIpInterface('eth0', False)
        iface = device.os.interfaces._getOb('eth0')
        iface.lockFromDeletion()

        # Apply a RelMap with no interfaces
        relmap = RelationshipMap("interfaces", "os", "Products.ZenModel.IpInterface")
        self.assertFalse(self.adm._applyDataMap(device, relmap))

        self.assertEquals(1, len(device.os.interfaces))
class applyDataMapTests(BaseTestCase):
    def afterSetUp(self):
        """Preparation invoked before each test is run."""
        super(applyDataMapTests, self).afterSetUp()
        self.service = ApplyDataMap()
        self.deviceclass = self.dmd.Devices.createOrganizer("/Test")
        self.device = self.deviceclass.createInstance("test-device")
        self.device.setPerformanceMonitor("localhost")
        self.device.setManageIp("192.0.2.77")
        self.device.index_object()
        transaction.commit()

    def test_updateDevice(self):
        """Test updating device properties."""
        DATA = {"rackSlot": "near-the-top"}
        changed = self.service.applyDataMap(self.device, ObjectMap(DATA))
        self.assertTrue(changed, "update Device failed")
        self.assertEqual("near-the-top", self.device.rackSlot)

        changed = self.service.applyDataMap(self.device, ObjectMap(DATA))
        self.assertFalse(changed, "updateDevice not idempotent")

    def test_updateDeviceHW(self):
        """Test updating device.hw properties."""
        DATA = {
            "compname": "hw",
            "totalMemory": 45097156608,
        }
        changed = self.service.applyDataMap(self.device, ObjectMap(DATA))
        self.assertTrue(changed, "device.hw not changed by first ObjectMap")
        self.assertEqual(45097156608, self.device.hw.totalMemory)

        changed = self.service.applyDataMap(self.device, ObjectMap(DATA))
        self.assertFalse(changed, "update is not idempotent")

    def test_updateComponent_implicit(self):
        """Test updating a component with implicit _add and _remove."""
        # Test implicit add directive
        DATA = {
            "id": "eth0",
            "compname": "os",
            "relname": "interfaces",
            "modname": "Products.ZenModel.IpInterface",
            "speed": 10e9,
        }
        changed = self.service.applyDataMap(self.device, ObjectMap(DATA))
        self.assertTrue(changed, "update failed")

        self.assertEqual(1, self.device.os.interfaces.countObjects(),
                         "wrong number of interfaces created by ObjectMap")

        self.assertEqual(10e9, self.device.os.interfaces.eth0.speed,
                         "eth0.speed not updated by ObjectMap")

        # Test implicit nochange directive
        changed = self.service.applyDataMap(self.device, ObjectMap(DATA))
        self.assertFalse(changed, "update is not idempotent")

    def test_updateComponent_addFalse(self):
        """Test updating a component with _add set to False."""
        DATA = {
            "id": "eth0",
            "compname": "os",
            "relname": "interfaces",
            "modname": "Products.ZenModel.IpInterface",
            "speed": 10e9,
            "_add": False,
        }

        changed = self.service.applyDataMap(self.device, ObjectMap(DATA))
        self.assertFalse(changed, "_add = False resulted in change")

        self.assertEqual(0, self.device.os.interfaces.countObjects(),
                         "ObjectMap with _add = False created a component")

    def test_updatedComponent_removeTrue(self):
        """Test updating a component with _remove or remove set to True."""

        for remove_key in ('_remove', 'remove'):
            DATA = {
                "id": "eth0",
                "compname": "os",
                "relname": "interfaces",
                remove_key: True,
            }

            changed = self.service.applyDataMap(self.device, ObjectMap(DATA))
            self.assertFalse(changed, 'update is not idempotent')

            self.service.applyDataMap(
                self.device,
                ObjectMap({
                    "id": "eth0",
                    "compname": "os",
                    "relname": "interfaces",
                    "modname": "Products.ZenModel.IpInterface",
                    "speed": 10e9,
                }))
            self.assertEqual(1, self.device.os.interfaces.countObjects(),
                             'failed to add object')

            changed = self.service.applyDataMap(self.device, ObjectMap(DATA))
            self.assertTrue(changed, "remove object failed")

            self.assertEqual(0, self.device.os.interfaces.countObjects(),
                             "failed to remove component")

    def base_relmap(self):
        return RelationshipMap(compname="os",
                               relname="interfaces",
                               modname="Products.ZenModel.IpInterface",
                               objmaps=[
                                   ObjectMap({"id": "eth0"}),
                                   ObjectMap({"id": "eth1"}),
                               ])

    def test_updateRelationship(self):
        """Test relationship creation."""
        changed = self.service.applyDataMap(self.device, self.base_relmap())
        self.assertTrue(changed, "relationship creation failed")
        self.assertEqual(
            2, self.device.os.interfaces.countObjects(),
            "wrong number of interfaces created by first RelationshipMap")

    def test_updateRelationship_is_idempotent(self):
        changed = self.service.applyDataMap(self.device, self.base_relmap())
        self.assertTrue(changed)
        self.assertEqual(2, self.device.os.interfaces.countObjects())

        changed = self.service.applyDataMap(self.device, self.base_relmap())
        self.assertFalse(changed, "RelationshipMap is not idempotent")

    def test_updateRelationship_remove_object(self):
        changed = self.service.applyDataMap(self.device, self.base_relmap())
        self.assertTrue(changed)
        self.assertEqual(2, self.device.os.interfaces.countObjects())

        rm = self.base_relmap()
        rm.maps = rm.maps[:1]

        changed = self.service.applyDataMap(self.device, rm)

        self.assertTrue(changed, "remove related item failed")
        self.assertEquals(
            1, self.device.os.interfaces.countObjects(),
            "wrong number of interfaces after trimmed RelationshipMap")

    def test_updateRelationship_remove_all_objects(self):
        changed = self.service.applyDataMap(self.device, self.base_relmap())
        self.assertTrue(changed)
        self.assertEqual(2, self.device.os.interfaces.countObjects())
        rm = self.base_relmap()
        rm.maps = []

        changed = self.service.applyDataMap(self.device, rm)

        self.assertTrue(changed, "failed to remove related objects")
        self.assertEquals(
            0, self.device.os.interfaces.countObjects(),
            "wrong number of interfaces after empty RelationshipMap")
예제 #10
0
class ApplyDataMapTest(BaseTestCase):

    def afterSetUp(self):
        super(ApplyDataMapTest, self).afterSetUp()
        self.adm = ApplyDataMap()

    def test_applyDataMap_relmap(self):
        compname = "module/component"
        relname = "relationship"

        datamap = RelationshipMap()
        device = Device(id='test_device')
        device.dmd = self.dmd

        self.adm.applyDataMap(device, datamap, datamap.relname, datamap.compname)

    def test_applyDataMap_relmapException(self):
    	'''test_applyDataMap_exception is mostly the same as test_applyDataMap_relmap
    	     - difference #1: compname is commented out
	     - difference #2: with self.assertRaises(AttributeError) is added
    	'''
        dmd = self.dmd
        class datamap(list):
            #compname = "a/b"
            relname  = "c"

        class Device(object):

            def deviceClass(self):
                return dmd.Devices

            class dmd:
                "Used for faking sync()"
                class _p_jar:
                    @staticmethod
                    def sync():
                        pass

            def getObjByPath(self, path):
                return reduce(getattr, path.split("/"), self)

            class a:
                class b:
                    class c:
                        "The relationship to populate"
                        @staticmethod
                        def objectIdsAll():
                            "returns the list of object ids in this relationship"
                            return []

        with self.assertRaises(AttributeError) as theException:
            self.adm.applyDataMap(Device(), datamap(), datamap.relname, datamap.compname)

        self.assertEqual(theException.exception.message, "type object 'datamap' has no attribute 'compname'")

    def testNoChangeAllComponentsLocked(self):
        device = self.dmd.Devices.createInstance('testDevice')
        # Create an IP interface
        device.os.addIpInterface('eth0', False)
        iface = device.os.interfaces._getOb('eth0')
        iface.lockFromDeletion()

        # Apply a RelMap with no interfaces
        relmap = RelationshipMap("interfaces", "os", "Products.ZenModel.IpInterface")
        self.assertFalse(self.adm._applyDataMap(device, relmap))

        self.assertEquals(1, len(device.os.interfaces))