Exemple #1
0
 def test_attributes_in_template(self):
     """Un test dans un template a accès aux attributs définis dans ce template."""
     self.host.write("""<?xml version="1.0"?>
     <host name="testserver1" address="192.168.1.1" ventilation="Servers">
         <template>linux</template>
     </host>""")
     self.host.close()
     from vigilo.vigiconf.lib.confclasses.test import Test
     class AttributeUsingTest(Test):
         def add_test(self):
             self.host.set_attribute(
                 "attribute_in_test",
                 self.host.get_attribute("attribute_in_conf", "wrong_value")
             )
     self.hosttemplatefactory.testfactory.tests["AttributeUsingTest"] = {
             "all": AttributeUsingTest}
     htpl = HostTemplate("linux")
     htpl.add_group("Linux servers")
     htpl.add_attribute("attribute_in_conf", "right_value")
     htpl.add_test("AttributeUsingTest")
     self.hosttemplatefactory.register(htpl)
     self.hostfactory._loadhosts(os.path.join(self.tmpdir, "hosts",
                                 "host.xml"))
     self.assertEqual(self.hostsConf['testserver1']['attribute_in_test'],
                      "right_value")
Exemple #2
0
    def test_diamond_templates(self):
        """
        Attribut d'un hôte et héritage en diamant des templates (#921).

        Le template "default" définit la communauté SNMP à "public".
        Celle-ci est redéfinie dans "testtpl1" comme valant "not-public".
        Enfin, "testtpl2" est chargé après "testtpl1" et ne redéfinit
        PAS la communauté.

        Ce test vérifie que "testtpl2" n'écrase pas la communauté
        définie par "testtpl1" en chargeant à nouveau "default"
        (et donc, en réinitialisant la valeur à "public").
        """
        default = HostTemplate("default")
        default.add_attribute("snmpCommunity", "public")
        self.hosttemplatefactory.register(default)

        tpl1 = HostTemplate("testtpl1")
        tpl1.add_attribute("snmpCommunity", "not-public")
        self.hosttemplatefactory.register(tpl1)

        tpl2 = HostTemplate("testtpl2")
        self.hosttemplatefactory.register(tpl2)

        # Recharge les templates.
        self.hosttemplatefactory.load_templates()

        xmlfile = open(os.path.join(self.tmpdir, "localhost.xml"), "w")
        xmlfile.write("""
            <host name="localhost" address="127.0.0.1">
                <template>testtpl1</template>
                <template>testtpl2</template>
                <group>Linux servers</group>
            </host>
        """)
        xmlfile.close()

        f = HostFactory(
                self.tmpdir,
                self.hosttemplatefactory,
                self.testfactory,
            )

        hosts = f.load()
        print hosts
        # La communauté SNMP doit valoir "not-public"
        # (elle ne doit pas avoir été réinitialisée à "public").
        self.assertEquals(
            hosts['localhost'].get('snmpCommunity'),
            "not-public"
        )
Exemple #3
0
 def test_attributes_before_template(self):
     """Les attributs doivent pouvoir être déclarés avant les templates"""
     self.host.write("""<?xml version="1.0"?>
     <host name="testserver1" address="192.168.1.1" ventilation="Servers">
         <attribute name="snmpCommunity">new_community</attribute>
         <template>linux</template> <!-- should not reset to public -->
     </host>""")
     self.host.close()
     htpl = HostTemplate("linux")
     htpl.add_attribute("snmpCommunity", "public")
     htpl.add_group("Linux servers")
     self.hosttemplatefactory.register(htpl)
     self.hostfactory._loadhosts(os.path.join(self.tmpdir, "hosts",
                                 "host.xml"))
     self.assertEqual(self.hostsConf['testserver1']['snmpCommunity'],
                      "new_community")
 def test_deepcopy(self):
     """
     Test de la copie en profondeur
     If the template data from the parent is not copied with
     copy.deepcopy(), then the child's template data will propagate back
     into the parent
     """
     self.tpl.add_attribute("TestAttr1", "TestVal")
     tpl2 = HostTemplate("testtpl2")
     tpl2.add_parent("testtpl1")
     tpl2.add_attribute("TestAttr2", "TestVal")
     self.hosttemplatefactory.register(tpl2)
     # Reload the templates
     self.hosttemplatefactory.load_templates()
     tpldata = self.hosttemplatefactory.templates["testtpl1"]
     self.failIf(tpldata["attributes"].has_key("TestAttr2"),
             "inheritence taints parent templates")
Exemple #5
0
class HostAndHosttemplatesInheritance(unittest.TestCase):
    """
    Vérifie le comportement de l'héritage d'informations depuis les
    modèles d'hôtes à destination des hôtes eux-mêmes.
    """

    def setUp(self):
        setup_db()
        testfactory = TestFactory(confdir=settings["vigiconf"]["confdir"])
        self.tmpdir = setup_tmpdir()
        self.testfactory = TestFactory(confdir=self.tmpdir)
        self.hosttemplatefactory = HostTemplateFactory(self.testfactory)
        self.hosttemplatefactory.register(HostTemplate("default"))
        self.tpl = HostTemplate("testtpl1")
        self.hosttemplatefactory.register(self.tpl)
        conf.hostsConf = {}
        self.hostfactory = HostFactory(
            self.tmpdir,
            self.hosttemplatefactory,
            self.testfactory
        )

    def tearDown(self):
        teardown_db()
        shutil.rmtree(self.tmpdir)

    def test_inherit_test(self):
        """
        Héritage d'un test depuis un modèle d'hôte.

        Le template "testtpl1" ajoute le test "UpTime".
        Le template "testtpl2" hérite de "testtpl1".
        L'hôte "localhost" importe le template "testtpl2".
        Le test "UpTime" doit donc être appliqué à "localhost".
        """
        self.tpl.add_test("UpTime")
        tpl2 = HostTemplate("testtpl2")
        tpl2.add_parent("testtpl1")
        self.hosttemplatefactory.register(tpl2)
        # Reload the templates
        self.hosttemplatefactory.load_templates()

        xmlfile = open(os.path.join(self.tmpdir, "localhost.xml"), "w")
        xmlfile.write("""
            <host name="localhost" address="127.0.0.1">
                <template>testtpl2</template>
                <group>Linux servers</group>
            </host>
        """)
        xmlfile.close()
        hosts = self.hostfactory.load()
        print hosts
        self.assertTrue("UpTime" in hosts['localhost']['services'],
                        "inheritance does not work with tests")

    def test_inherit_group(self):
        """
        Héritage d'un groupe depuis un modèle d'hôte.

        Le template "testtpl1" s'ajoute au groupe "Test Group".
        Le template "testtpl2" hérite de "testtpl1".
        L'hôte "localhost" importe le template "testtpl2".
        L'hôte "localhost" devrait donc appartenir au groupe "Test Group".
        """
        self.tpl.add_group("Test Group")
        tpl2 = HostTemplate("testtpl2")
        tpl2.add_parent("testtpl1")
        self.hosttemplatefactory.register(tpl2)
        # Reload the templates
        self.hosttemplatefactory.load_templates()

        xmlfile = open(os.path.join(self.tmpdir, "localhost.xml"), "w")
        xmlfile.write("""
            <host name="localhost" address="127.0.0.1">
                <template>testtpl2</template>
            </host>
        """)
        xmlfile.close()
        hosts = self.hostfactory.load()
        print hosts
        self.assertTrue("Test Group" in
                hosts["localhost"]["otherGroups"],
                "inheritance does not work with groups")

    def test_inherit_attribute(self):
        """
        Héritage d'un attribut depuis un modèle d'hôte.

        Le template "testtpl1" ajoute l'attribut "TestAttr" valant "TestVal".
        Le template "testtpl2" hérite de "testtpl1".
        L'hôte "localhost" importe le template "testtpl2".
        L'hôte "localhost" devrait donc posséder cet attribut avec
        la valeur définie dans "testtpl1".
        """
        self.tpl.add_attribute("TestAttr", "TestVal")
        tpl2 = HostTemplate("testtpl2")
        tpl2.add_parent("testtpl1")
        self.hosttemplatefactory.register(tpl2)
        # Reload the templates
        self.hosttemplatefactory.load_templates()

        xmlfile = open(os.path.join(self.tmpdir, "localhost.xml"), "w")
        xmlfile.write("""
            <host name="localhost" address="127.0.0.1">
                <template>testtpl2</template>
                <group>Linux servers</group>
            </host>
        """)
        xmlfile.close()
        hosts = self.hostfactory.load()
        print hosts
        self.assertTrue(hosts['localhost'].has_key("TestAttr"),
                "inheritance does not work with attributes")
        self.assertEqual(hosts['localhost']["TestAttr"], "TestVal",
                "inheritance does not work with attributes")

    def test_inherit_redefine_attribute(self):
        """
        Héritage d'un attribut redéfini depuis un modèle d'hôte.

        Le template "testtpl1" ajoute l'attribut "TestAttr" valant "TestVal1".
        Le template "testtpl2" hérite de "testtpl1" et redéfinit "TestAttr"
        comme valant "TestVal2".
        L'hôte "localhost" importe le template "testtpl2".
        L'hôte "localhost" devrait donc posséder cet attribut avec
        la valeur définie dans "testtpl2".
        """
        self.tpl.add_attribute("TestAttr", "TestVal1")
        tpl2 = HostTemplate("testtpl2")
        tpl2.add_parent("testtpl1")
        self.tpl.add_attribute("TestAttr", "TestVal2")
        self.hosttemplatefactory.register(tpl2)
        # Reload the templates
        self.hosttemplatefactory.load_templates()

        xmlfile = open(os.path.join(self.tmpdir, "localhost.xml"), "w")
        xmlfile.write("""
            <host name="localhost" address="127.0.0.1">
                <template>testtpl2</template>
                <group>Linux servers</group>
            </host>
        """)
        xmlfile.close()
        hosts = self.hostfactory.load()
        print hosts
        self.assertTrue(hosts['localhost'].has_key("TestAttr"),
                "inheritance does not work with attributes")
        self.assertEqual(hosts['localhost']["TestAttr"], "TestVal2",
                "inheritance does not work with attributes")

    def test_inherit_multiple_test(self):
        """
        Héritage de tests issus de modèles d'hôtes multiples.

        L'hôte hérite d'un template qui hérite lui-même de deux templates
        définissant chacun 1 test. On s'assure que l'hôte hérite correctement
        des 2 tests.
        """
        self.tpl.add_test("Interface", {"ifname":"eth0", "label":"Label0"})
        tpl2 = HostTemplate("testtpl2")
        tpl2.add_test("Interface", {"ifname":"eth1", "label":"Label1"})
        self.hosttemplatefactory.register(tpl2)
        tpl3 = HostTemplate("testtpl3")
        tpl3.add_parent(["testtpl1", "testtpl2"])
        self.hosttemplatefactory.register(tpl3)
        # Reload the templates
        self.hosttemplatefactory.load_templates()

        xmlfile = open(os.path.join(self.tmpdir, "localhost.xml"), "w")
        xmlfile.write("""
            <host name="localhost" address="127.0.0.1">
                <template>testtpl3</template>
                <group>Linux servers</group>
            </host>
        """)
        xmlfile.close()
        hosts = self.hostfactory.load()
        print hosts

        for svc in ("Interface Label0", "Interface Label1"):
            self.assertTrue(svc in hosts['localhost']['services'],
                    "multiple inheritance does not work (%s)" % svc)
class HostTemplates(unittest.TestCase):

    def setUp(self):
        setup_db()
        testfactory = TestFactory(confdir=settings["vigiconf"]["confdir"])
        self.hosttemplatefactory = HostTemplateFactory(testfactory)
        self.hosttemplatefactory.register(HostTemplate("default"))
        self.tpl = HostTemplate("testtpl1")
        self.hosttemplatefactory.register(self.tpl)
        conf.hostsConf = {}
        self.host = Host(conf.hostsConf, "dummy", "testserver1",
                         "192.168.1.1", "Servers")

    def tearDown(self):
        conf.hostsConf = {}
        teardown_db()


    def test_add_test_simple(self):
        """Test for the add_test method, without test arguments"""
        self.tpl.add_test("UpTime")
        self.hosttemplatefactory.apply(self.host, "testtpl1")
        self.assertTrue(conf.hostsConf["testserver1"]["services"].has_key(
                        "UpTime"), "add_test does not work without test args")

    def test_add_test_args(self):
        """Test for the add_test method, with test arguments"""
        self.tpl.add_test("Interface", {"label":"Loopback", "ifname":"lo"})
        self.hosttemplatefactory.apply(self.host, "testtpl1")
        self.assertTrue(conf.hostsConf["testserver1"]["SNMPJobs"]
                [('Interface Loopback', 'service')]["params"]
                == ["lo", "Loopback", "i", "c"],
                "add_test does not work with test args")

    def test_add_group_simple(self):
        """Test for the add_group method, with one argument only"""
        self.tpl.add_group("/Test Group")
        self.hosttemplatefactory.apply(self.host, "testtpl1")
        self.assertTrue("/Test Group" in
                conf.hostsConf["testserver1"]["otherGroups"],
                "add_group does not work with one arg")

    def test_add_group_multiple(self):
        """Test for the add_group method, with multiple arguments"""
        self.tpl.add_group("/Test Group 1", "/Test Group 2")
        self.hosttemplatefactory.apply(self.host, "testtpl1")
        self.assertTrue("/Test Group 1" in
                conf.hostsConf["testserver1"]["otherGroups"],
                "add_group does not work with multiple args")
        self.assertTrue("/Test Group 2" in
                conf.hostsConf["testserver1"]["otherGroups"],
                "add_group does not work with multiple args")

    def test_add_attribute(self):
        """Test for the add_attribute method"""
        self.tpl.add_attribute("TestAttr", "TestVal")
        self.hosttemplatefactory.apply(self.host, "testtpl1")
        self.assertEqual(conf.hostsConf["testserver1"]["TestAttr"],
                         "TestVal", "add_attribute does not work")

    def test_add_default_service_weight(self):
        """Test for the add_weight method"""
        self.tpl.add_weight("default_service_weight", 12)
        self.hosttemplatefactory.apply(self.host, "testtpl1")
        self.assertEqual(conf.hostsConf["testserver1"][
            "default_service_weight"],
            12, "add_weight does not work")

    def test_add_default_service_warning_weight(self):
        """Test for the add_weight method"""
        self.tpl.add_weight("default_service_warning_weight", 12)
        self.hosttemplatefactory.apply(self.host, "testtpl1")
        self.assertEqual(conf.hostsConf["testserver1"][
            "default_service_warning_weight"],
            12, "add_weight does not work")

    def test_inherit_redefine_test(self):
        self.tpl.add_test("Interface", {"ifname":"eth0", "label":"Label1"})
        tpl2 = HostTemplate("testtpl2")
        tpl2.add_parent("testtpl1")
        tpl2.add_test("Interface", {"ifname":"eth0", "label":"Label2"})
        self.hosttemplatefactory.register(tpl2)
        # Reload the templates
        self.hosttemplatefactory.load_templates()
        intftest = None
        for test in self.hosttemplatefactory.templates["testtpl2"]["tests"]:
            if test["name"] == "Interface":
                intftest = test
        self.assertTrue(intftest is not None,
                        "inheritance does not work with tests")
        self.assertEqual(intftest["args"]["label"], "Label2",
                "child templates cannot redefine tests from parent templates")

    def test_deepcopy(self):
        """
        Test de la copie en profondeur
        If the template data from the parent is not copied with
        copy.deepcopy(), then the child's template data will propagate back
        into the parent
        """
        self.tpl.add_attribute("TestAttr1", "TestVal")
        tpl2 = HostTemplate("testtpl2")
        tpl2.add_parent("testtpl1")
        tpl2.add_attribute("TestAttr2", "TestVal")
        self.hosttemplatefactory.register(tpl2)
        # Reload the templates
        self.hosttemplatefactory.load_templates()
        tpldata = self.hosttemplatefactory.templates["testtpl1"]
        self.failIf(tpldata["attributes"].has_key("TestAttr2"),
                "inheritence taints parent templates")

    def test_defined_templates(self):
        self.hosttemplatefactory.load_templates()
        for tpl in self.hosttemplatefactory.templates.keys():
            self.hosttemplatefactory.apply(self.host, tpl)

    def test_parent_default(self):
        tpl1 = HostTemplate("testtpl2")
        tpl1.add_parent("testtpl1")
        self.hosttemplatefactory.register(tpl1)
        self.assertTrue("default" in
                self.hosttemplatefactory.templates["testtpl1"]["parent"],
                "The \"default\" template is not automatically added as "
                "parent to other templates")


    def test_add_nagios_hdirective(self):
        """Test for the add_nagios_directive method"""
        self.tpl.add_nagios_directive("max_check_attempts", "5")
        tpldata = self.hosttemplatefactory.templates["testtpl1"]
        self.assertEquals(
                tpldata["nagiosDirectives"]["host"]["max_check_attempts"],
                "5")


    def test_nagios_hdirs_apply_on_host(self):
        self.tpl.add_nagios_directive("retry_interval", "8")
        self.hosttemplatefactory.apply(self.host, "testtpl1")
        testserver1 = conf.hostsConf['testserver1']
        nagios_hdirs = testserver1.get('nagiosDirectives')["host"]
        self.assertEquals(nagios_hdirs['retry_interval'], "8",
                          "retry_interval=8")


    def test_nagios_sdirs_apply_on_all_service(self):
        """Nagios service directives for tests"""
        self.tpl.add_nagios_directive("retry_interval", "8", target="services")
        tpldata = self.hosttemplatefactory.templates["testtpl1"]
        self.assertEquals(
                tpldata["nagiosDirectives"]["services"]["retry_interval"],
                "8")


    def test_nagios_srvdirs_apply_on_service(self):
        """Nagios directives for tests"""
        self.tpl.add_test("UpTime", directives={"testdir": "testdirvalue"})
        self.hosttemplatefactory.apply(self.host, "testtpl1")
        ndirs = conf.hostsConf["testserver1"]["nagiosSrvDirs"]
        self.assertTrue("UpTime" in ndirs)
        self.assertTrue("testdir" in ndirs["UpTime"])
        self.assertEqual(ndirs["UpTime"]["testdir"], "testdirvalue")


    def test_nonexistant_test(self):
        """
        Une exception doit être levée si on cherche à ajouter un test inexistant.
        """
        self.tpl.add_test("NonExistant")
        self.assertRaises(ParsingError, self.hosttemplatefactory.apply,
                          self.host, "testtpl1")

    def test_attributes_hierarchy_order(self):
        """
        Les attributs doivent se faire surcharger dans l'ordre d'héritage
        """
        self.tpl.add_attribute("snmpCommunity", "comm1")
        self.hosttemplatefactory.apply(self.host, "testtpl1")
        self.assertEquals(conf.hostsConf['testserver1']['snmpCommunity'],
                "comm1", "La communauté SNMP doit être celle du dernier "
                "template et pas celle d'un de ses parents")

    def test_add_test_simple_active(self):
        """Ajout d'un service actif sur un hôte avec force-passive"""
        self.host.set_attribute("force-passive", True)
        self.tpl.add_test("HTTP")
        self.hosttemplatefactory.apply(self.host, "testtpl1")
        self.assertEqual("passive",
                conf.hostsConf["testserver1"]["services"]["HTTP"]["type"])