Esempio n. 1
0
 def test_add_collector_service_reroute(self):
     """Test for the add_collector_service host method with rerouting"""
     host2 = Host(conf.hostsConf, "dummy", "testserver2", "192.168.1.2", "Servers")
     host2.add_collector_service(
         "TestAddCSReRoute",
         "TestAddCSReRouteFunction",
         ["fake arg 1"],
         ["GET/.1.3.6.1.2.1.1.3.0"],
         reroutefor={
             'host': "testserver1",
             "service": "TestAddCSReRoute",
         },
     )
     hdata1 = conf.hostsConf["testserver1"]
     hdata2 = conf.hostsConf["testserver2"]
     self.assertEqual(hdata1["services"]["TestAddCSReRoute"]["type"],
         "passive", "add_collector_service rerouting does not work "
         "with the services sub-hashmap")
     self.assertEqual(hdata2["SNMPJobs"][("TestAddCSReRoute", "service")],
             { 'function': "TestAddCSReRouteFunction",
               'params': ["fake arg 1"],
               'vars': ["GET/.1.3.6.1.2.1.1.3.0"],
               'reRouteFor': {
                 'host': "testserver1",
                 "service": "TestAddCSReRoute"
               },
             }, "add_collector_service rerouting does not work "
             "with the SNMPJobs sub-hashmap")
Esempio n. 2
0
 def test_add_nagios_sdirective(self):
     """Test for the add_nagios_directive method"""
     host = Host(conf.hostsConf, "dummy", u"test2",
                 u"192.168.1.2", "Servers")
     host.add_nagios_directive("max_check_attempts", "5", target="services")
     nagios_sdirs = conf.hostsConf["test2"]["nagiosDirectives"]["services"]
     self.assertEquals(nagios_sdirs["max_check_attempts"], "5")
class ConnectorMetroTest(unittest.TestCase):

    def setUp(self):
        self.tmpdir = setup_tmpdir()
        self.basedir = os.path.join(self.tmpdir, "deploy")
        self.host = Host(conf.hostsConf, "dummy.xml", "testserver1",
                         "192.168.1.1", "Servers")
        self.host.add_perfdata("dummy", "dummy")

    def tearDown(self):
        """Call after every test case."""
        shutil.rmtree(self.tmpdir)

    def test_add_missing_servers(self):
        app = ConnectorMetro()
        ventilation = {"testserver1":
                {"connector-metro": "localhost"}
            }
        app.generate(ventilation)
        self.assertTrue("localhost" in app.servers)
        self.assertEqual(app.servers["localhost"].name, "localhost")
        self.assertEqual(app.actions, {"localhost": ["stop", "start"]})

    def test_generated(self):
        app = ConnectorMetro()
        ventilation = {"testserver1":
                {"connector-metro": "localhost"}
            }
        app.generate(ventilation)
        db_path = os.path.join(self.basedir, "localhost",
                               "connector-metro.db")
        self.assertTrue(os.path.exists(db_path))
        db = sqlite3.connect(db_path)
        cur = db.cursor()
        cur.execute("SELECT * FROM perfdatasource")
        pds = cur.fetchall()
        cur.execute("SELECT * FROM rra")
        rra = cur.fetchall()
        cur.execute("SELECT * FROM pdsrra")
        pdsrra = cur.fetchall()
        cur.close()
        db.close()
        self.assertEqual(pds, [
            (1, 'dummy', 'testserver1', 'GAUGE', 300, 600, None,
             None, 1.0, None, None, None, u'localhost') ])
        self.assertEqual(rra, [
            (1, 'AVERAGE', 0.5, 1, 600),  (2, 'AVERAGE', 0.5, 6,   700),
            (3, 'AVERAGE', 0.5, 24, 775), (4, 'AVERAGE', 0.5, 288, 732)
            ])
        self.assertEqual(pdsrra, [
            (1, 1, 0),
            (1, 2, 1),
            (1, 3, 2),
            (1, 4, 3),
            ])
Esempio n. 4
0
 def test_generator_com(self):
     """Test the generation in C.E."""
     host = Host(conf.hostsConf, "dummy.xml", "testserver1",
                 "192.168.1.1", "Servers")
     testfactory = TestFactory(confdir=os.path.join(self.tmpdir, "conf"))
     test_list = testfactory.get_test("UpTime", host.classes)
     host.add_tests(test_list)
     nagios = Nagios()
     genmanager = GeneratorManager([nagios])
     genmanager.generate(DummyRevMan())
     self.assert_(os.path.exists(os.path.join(self.basedir, "localhost",
                  "nagios", "nagios.cfg")))
Esempio n. 5
0
 def setUp(self):
     setup_db()
     conf.hostsConf = {}
     # Prepare temporary directory
     self.tmpdir = setup_tmpdir()
     self.basedir = os.path.join(self.tmpdir, "deploy")
     self.old_conf_path = settings["vigiconf"]["confdir"]
     settings["vigiconf"]["confdir"] = os.path.join(self.tmpdir, "conf.d")
     os.mkdir(settings["vigiconf"]["confdir"])
     self.testfactory = TestFactory(confdir=settings["vigiconf"]["confdir"])
     self.host = Host(conf.hostsConf, "dummy.xml", "testserver1",
                      "192.168.1.1", "Servers")
     self.host.set_attribute("collectorTimeout", "3")
     # attention, le fichier dummy.xml doit exister ou l'hôte sera supprimé
     # juste après avoir été inséré
     open(os.path.join(self.tmpdir, "conf.d", "dummy.xml"), "w").close()
     conffile = ConfFile.get_or_create("dummy.xml")
     add_host("testserver1", conffile)
     self.apps = self._get_apps()
     self.genmanager = GeneratorManager(self.apps.values())
     self.substitutions = {
         'nagios_bin': 'nagios',
         'nagios_init': '/etc/init.d/nagios',
         'targetconfdir': '/etc/vigilo/vigiconf/',
         'nagios_cfg': '/etc/nagios/nagios.cfg',
     }
 def setUp(self):
     self.tmpdir = setup_tmpdir()
     os.mkdir(os.path.join(self.tmpdir, "deploy"))
     self.host = Host(conf.hostsConf, "dummy.xml", "testserver1",
                      "192.168.1.1", "Servers")
     self.vigirrd = VigiRRD()
     ventilation = {"testserver1": {"vigirrd": "sup.example.com"}}
     self.generator = self.vigirrd.generator(self.vigirrd, ventilation)
Esempio n. 7
0
 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")
Esempio n. 8
0
class TestLoader(unittest.TestCase):

    def setUp(self):
        setup_db()
        self.tmpdir = setup_tmpdir()
        # attention, le fichier dummy.xml doit exister ou l'hôte sera supprimé
        # juste après avoir été inséré
        self.old_conf_dir = settings["vigiconf"]["confdir"]
        settings["vigiconf"]["confdir"] = self.tmpdir
        open(os.path.join(self.tmpdir, "dummy.xml"), "w").close() # == touch
        self.host = ConfHost(
            conf.hostsConf,
            os.path.join(self.tmpdir, "dummy.xml"),
            "testserver1",
            "192.168.1.1",
            "Servers",
        )
        self.rm = DummyRevMan()
        grouploader = GroupLoader()
        self.hostloader = HostLoader(grouploader, self.rm)

    def tearDown(self):
        teardown_db()
        shutil.rmtree(self.tmpdir)
        settings["vigiconf"]["confdir"] = self.old_conf_dir

    def test_warning_weight_forbidden(self):
        """Valeur de warning_weight < weight est interdite."""
        self.host.add_external_sup_service("Interface eth0")
        host_dict = conf.hostsConf[u'testserver1']
        host_dict["default_service_weight"] = 1
        host_dict["default_service_warning_weight"] = 3
        print host_dict
        try:
            self.hostloader.load()
        except ParsingError, e:
            pass
        except Exception, e:
            self.fail("Excepted a ParsingError, got %s" % type(e))
Esempio n. 9
0
 def test_add_collector_metro_reroute(self):
     """Test for the add_collector_metro host method with rerouting"""
     host2 = Host(conf.hostsConf, "dummy", u"testserver2",
                  u"192.168.1.2", "Servers")
     host2.add_collector_metro("TestAddCSReRoute", "TestAddCSRRMFunction",
             ["fake arg 1"], ["GET/.1.3.6.1.2.1.1.3.0"],
             "GAUGE", label="TestAddCSReRouteLabel",
             reroutefor={'host': "testserver1",
                         "service": "TestAddCSReRoute"} )
     t1ds = conf.hostsConf["testserver1"]["dataSources"]
     t2snmp = conf.hostsConf["testserver2"]["SNMPJobs"]
     self.assertEqual(t1ds["TestAddCSReRoute"],
         {'dsType':"GAUGE", 'label': "TestAddCSReRouteLabel",
          "max": None, "min": None, "rra_template": None},
         "add_collector_metro rerouting does not work with the "
         "dataSources sub-hashmap")
     self.assertEqual(t2snmp[("TestAddCSReRoute","perfData")],
         {'function': "TestAddCSRRMFunction", 'params': ["fake arg 1"],
          'vars': ["GET/.1.3.6.1.2.1.1.3.0"], 'reRouteFor':
          {'host':"testserver1", "service" : "TestAddCSReRoute"}},
         "add_collector_service ReRouting does not work with the "
         "SNMPJobs sub-hashmap")
Esempio n. 10
0
 def setUp(self):
     setup_db()
     self.testfactory = TestFactory(confdir=settings["vigiconf"]["confdir"])
     self.host = Host(conf.hostsConf, "dummy", u"testserver1",
                      u"192.168.1.1", u"Servers")
     self.expected = {
         "metrosrv": {
             "type": "passive",
             "weight": None,
             "warning_weight": None,
             "directives": {},
             "reRoutedBy": None,
         },
     }
Esempio n. 11
0
 def setUp(self):
     setup_db()
     self.tmpdir = setup_tmpdir()
     # attention, le fichier dummy.xml doit exister ou l'hôte sera supprimé
     # juste après avoir été inséré
     self.old_conf_dir = settings["vigiconf"]["confdir"]
     settings["vigiconf"]["confdir"] = self.tmpdir
     open(os.path.join(self.tmpdir, "dummy.xml"), "w").close() # == touch
     self.host = ConfHost(
         conf.hostsConf,
         os.path.join(self.tmpdir, "dummy.xml"),
         "testserver1",
         "192.168.1.1",
         "Servers",
     )
     self.rm = DummyRevMan()
     grouploader = GroupLoader()
     self.hostloader = HostLoader(grouploader, self.rm)
Esempio n. 12
0
class VigiRRDTest(unittest.TestCase):

    def setUp(self):
        self.tmpdir = setup_tmpdir()
        os.mkdir(os.path.join(self.tmpdir, "deploy"))
        self.host = Host(conf.hostsConf, "dummy.xml", "testserver1",
                         "192.168.1.1", "Servers")
        self.vigirrd = VigiRRD()
        ventilation = {"testserver1": {"vigirrd": "sup.example.com"}}
        self.generator = self.vigirrd.generator(self.vigirrd, ventilation)

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

    def test_graph_order(self):
        for i in range(7):
            self.host.add_perfdata("test_ds_%d" % i, "dummy")
        self.host.add_graph("test graph 1",
                [ "test_ds_%d" % i for i in range(7) ],
                "lines", "dummy")
        self.host.add_graph("test graph 2",
                [ "test_ds_%d" % i for i in range(6, -1, -1) ],
                "lines", "dummy")
        self.generator.generate()
        db = sqlite3.connect(os.path.join(self.tmpdir, "deploy",
                                          "sup.example.com", "vigirrd.db"))
        c = db.cursor()
        c.execute("""SELECT pds.name FROM perfdatasource pds
                     JOIN graphperfdatasource gpds
                       ON pds.idperfdatasource = gpds.idperfdatasource
                     JOIN graph g
                       ON g.idgraph = gpds.idgraph
                     WHERE g.name = ? ORDER BY gpds.`order`""",
                  ("test graph 1", ))
        ds_in_graph_1 = [ r[0] for r in c.fetchall() ]
        self.assertEqual(ds_in_graph_1, [ "test_ds_%d" % i for i in range(7) ])
        c.execute("""SELECT pds.name FROM perfdatasource pds
                     JOIN graphperfdatasource gpds
                       ON pds.idperfdatasource = gpds.idperfdatasource
                     JOIN graph g
                       ON g.idgraph = gpds.idgraph
                     WHERE g.name = ? ORDER BY gpds.`order`""",
                  ("test graph 2", ))
        ds_in_graph_2 = [ r[0] for r in c.fetchall() ]
        self.assertEqual(ds_in_graph_2,
                         [ "test_ds_%d" % i for i in range(6, -1, -1) ])
Esempio n. 13
0
    def setUp(self):
        setup_db()
        self.tmpdir = setup_tmpdir()
        self.old_conf_path = settings["vigiconf"]["confdir"]
        settings["vigiconf"]["confdir"] = os.path.join(self.tmpdir, "conf.d")
        os.mkdir(settings["vigiconf"]["confdir"])

        # Prepare necessary directories
        # TODO: commenter les divers repertoires
        setup_deploy_dir()
        self.host = Host(conf.hostsConf, "dummy", u"testserver1",
                         u"192.168.1.1", u"Servers")
        testfactory = TestFactory(confdir=settings["vigiconf"]["confdir"])
        test_list = testfactory.get_test("UpTime", self.host.classes)
        self.host.add_tests(test_list)
        self.dispatchator = make_dispatchator()
        # Disable qualification, validation, stop and start scripts
        for app in self.dispatchator.apps_mgr.applications:
            app.validation = None
            app.start_command = None
            app.stop_command = None
        # Don't check the installed revisions
        self.dispatchator.force = ("deploy", "db-sync")
Esempio n. 14
0
class DispatchatorTest(unittest.TestCase):

    def setUp(self):
        setup_db()
        self.tmpdir = setup_tmpdir()
        self.old_conf_path = settings["vigiconf"]["confdir"]
        settings["vigiconf"]["confdir"] = os.path.join(self.tmpdir, "conf.d")
        os.mkdir(settings["vigiconf"]["confdir"])

        # Prepare necessary directories
        # TODO: commenter les divers repertoires
        setup_deploy_dir()
        self.host = Host(conf.hostsConf, "dummy", u"testserver1",
                         u"192.168.1.1", u"Servers")
        testfactory = TestFactory(confdir=settings["vigiconf"]["confdir"])
        test_list = testfactory.get_test("UpTime", self.host.classes)
        self.host.add_tests(test_list)
        self.dispatchator = make_dispatchator()
        # Disable qualification, validation, stop and start scripts
        for app in self.dispatchator.apps_mgr.applications:
            app.validation = None
            app.start_command = None
            app.stop_command = None
        # Don't check the installed revisions
        self.dispatchator.force = ("deploy", "db-sync")

    def tearDown(self):
        teardown_db()
        teardown_deploy_dir()
        settings["vigiconf"]["confdir"] = self.old_conf_path

    def test_deploy(self):
        """Globally test the deployment"""
        self.dispatchator.deploy()

    def test_restart(self):
        """Globally test the restart"""
        # Create necessary file
        revs = open(os.path.join(conf.baseConfDir, "new", "revisions.txt"), "w")
        revs.close()
        self.dispatchator.restart()

    def test_conf_reactivation(self):
        """ Test de réactivation d'une conf versionnée.
        Chaque configuration doit être mise en version et doit pouvoir être
        réactivée par passage d'une commande particulière.
        VIGILO_EXIG_VIGILO_CONFIGURATION_0020
        """
        settings["vigiconf"]["svnusername"] = "******"
        settings["vigiconf"]["svnpassword"] = "******"
        rev_mgr = self.dispatchator.rev_mgr
        rev_mgr.deploy_revision = 1234
        rev_mgr.command_class = DummyCommand
        svn_cmd = rev_mgr.update()

        self.assertEquals(svn_cmd,
                    ["svn", "update", "--username", "user1",
                     "--password", "pass1", "-r", "1234",
                     settings["vigiconf"]["confdir"]],
                    "Invalid svn update command")

    def test_get_state(self):
        """Test de la récupération de l'état (par la commande vigiconf info)"""
        locale.setlocale(locale.LC_ALL, 'C')
        self.dispatchator.rev_mgr.last_revision = lambda: 43
        state = self.dispatchator.getState()
        print state
        self.assertEqual(len(state), 2)
Esempio n. 15
0
class GeneratorBaseTestCase(TestCase):
    """Classe de base pour les tests de génération"""

    def setUp(self):
        setup_db()
        conf.hostsConf = {}
        # Prepare temporary directory
        self.tmpdir = setup_tmpdir()
        self.basedir = os.path.join(self.tmpdir, "deploy")
        self.old_conf_path = settings["vigiconf"]["confdir"]
        settings["vigiconf"]["confdir"] = os.path.join(self.tmpdir, "conf.d")
        os.mkdir(settings["vigiconf"]["confdir"])
        self.testfactory = TestFactory(confdir=settings["vigiconf"]["confdir"])
        self.host = Host(conf.hostsConf, "dummy.xml", "testserver1",
                         "192.168.1.1", "Servers")
        self.host.set_attribute("collectorTimeout", "3")
        # attention, le fichier dummy.xml doit exister ou l'hôte sera supprimé
        # juste après avoir été inséré
        open(os.path.join(self.tmpdir, "conf.d", "dummy.xml"), "w").close()
        conffile = ConfFile.get_or_create("dummy.xml")
        add_host("testserver1", conffile)
        self.apps = self._get_apps()
        self.genmanager = GeneratorManager(self.apps.values())
        self.substitutions = {
            'nagios_bin': 'nagios',
            'nagios_init': '/etc/init.d/nagios',
            'targetconfdir': '/etc/vigilo/vigiconf/',
            'nagios_cfg': '/etc/nagios/nagios.cfg',
        }

    def tearDown(self):
        DBSession.expunge_all()
        teardown_db()
        shutil.rmtree(self.tmpdir)
        settings["vigiconf"]["confdir"] = self.old_conf_path
        conf.hostsConf = {}

    def _get_apps(self):
        """
        Dictionnaire des instances d'applications à tester.
        Exemple: {"nagios": Nagios(), "vigimap": VigiMap()}
        """
        return {}

    def _generate(self):
        self.genmanager.generate(DummyRevMan())

    def _validate(self):
        deploydir = os.path.join(self.basedir, "localhost")
        for appname, app in self.apps.iteritems():
            __import__(app.__module__)
            module = sys.modules[app.__module__]
            validation_script = os.path.join(
                    os.path.dirname(module.__file__),
                    "validate.sh")
            fh = open(validation_script, 'r')
            contents = fh.read()
            fh.close()
            contents = contents % {
            }
            validation_script = os.path.join(self.tmpdir, "validate.sh")
            fh = open(validation_script, 'w')
            fh.write(contents % self.substitutions)
            fh.close()
            print appname
            proc = Popen(["sh", validation_script, deploydir],
                        stdout=PIPE, stderr=STDOUT)
            print proc.communicate()[0]
            self.assertEqual(proc.returncode, 0)
 def setUp(self):
     self.tmpdir = setup_tmpdir()
     self.basedir = os.path.join(self.tmpdir, "deploy")
     self.host = Host(conf.hostsConf, "dummy.xml", "testserver1",
                      "192.168.1.1", "Servers")
     self.host.add_perfdata("dummy", "dummy")
Esempio n. 17
0
class HostMethods(unittest.TestCase):

    def setUp(self):
        setup_db()
        self.testfactory = TestFactory(confdir=settings["vigiconf"]["confdir"])
        self.host = Host(conf.hostsConf, "dummy", u"testserver1",
                         u"192.168.1.1", u"Servers")
        self.expected = {
            "metrosrv": {
                "type": "passive",
                "weight": None,
                "warning_weight": None,
                "directives": {},
                "reRoutedBy": None,
            },
        }

    def tearDown(self):
        teardown_db()

    def test_add_metro_service(self):
        """Test for the add_metro_service host method"""
        test_list = self.testfactory.get_test("Interface", self.host.classes)
        self.host.add_tests(test_list, {"label":"eth1", "ifname":"eth1"})
        self.host.add_metro_service("Traffic in eth1", "ineth1", 10, 20)
        self.assertEqual(
            conf.hostsConf["testserver1"]["services"]["Traffic in eth1"],
            self.expected["metrosrv"])
        self.assert_('ineth1' in conf.hostsConf["testserver1"]["metro_services"])
        self.assertEqual(
            conf.hostsConf["testserver1"]["metro_services"]['ineth1'],
            {
                'servicename': 'Traffic in eth1',
                'warning': 10,
                'critical': 20,
                'factor': 1.0,
            }
        )

    def test_priority_host_hosttemplate(self):
        """Test priorite du parametrage des hosts sur les hosttemplates"""
        test_list = self.testfactory.get_test("Interface", self.host.classes)
        self.host.add_tests(test_list, {"label":"eth0", "ifname":"eth0"})
        self.host.add_metro_service("Traffic in eth0", "ineth0", 10, 20)
        self.assertEqual(
            conf.hostsConf["testserver1"]["services"]["Traffic in eth0"],
            self.expected["metrosrv"])

    def test_add_metro_service_INTF(self):
        """Test for the add_metro_service function in the Interface test"""
        test_list = self.testfactory.get_test("Interface", self.host.classes)
        self.host.add_tests(test_list, {"label":"eth0", "ifname":"eth0",
                                        "warn": (10, 20), "crit": (30, 40)})
        self.assertEqual(
            conf.hostsConf["testserver1"]["services"]["Traffic in eth0"],
            self.expected["metrosrv"])
        self.assert_('ineth0' in conf.hostsConf["testserver1"]["metro_services"])
        self.assertEqual(
            conf.hostsConf["testserver1"]["metro_services"]['ineth0'],
            {
                'servicename': 'Traffic in eth0',
                'warning': 10,
                'critical': 30,
                'factor': 8,
            }
        )

        self.assertEqual(
            conf.hostsConf["testserver1"]["services"]["Traffic out eth0"],
            self.expected["metrosrv"])
        self.assert_('outeth0' in conf.hostsConf["testserver1"]["metro_services"])
        self.assertEqual(
            conf.hostsConf["testserver1"]["metro_services"]['outeth0'],
            {
                'servicename': 'Traffic out eth0',
                'warning': 20,
                'critical': 40,
                'factor': 8,
            }
        )

    def test_invalid_INTF_admin_value(self):
        """Valeurs autorisées pour le paramètre 'admin' du test Interface."""
        test_list = self.testfactory.get_test("Interface", self.host.classes)

        # Les valeurs i/w/c doivent être acceptées.
        for value in ('i', 'w', 'c'):
            self.host.add_tests(test_list, {"label":"eth0", "ifname":"eth0",
                                            "admin": value})
            self.assertEqual(
                conf.hostsConf["testserver1"]["SNMPJobs"]\
                    [ ("Interface eth0", "service") ]['params'],
                # 'c' correspond à la valeur par défaut de "dormant".
                ['eth0', 'eth0', value, 'c'])

        # Les autres valeurs doivent être rejetées.
        self.assertRaises(ParsingError, self.host.add_tests,
            test_list, {"label":"eth0", "ifname":"eth0", "admin": ''})

    def test_invalid_INTF_dormant_value(self):
        """Valeurs autorisées pour le paramètre 'dormant' du test Interface."""
        test_list = self.testfactory.get_test("Interface", self.host.classes)

        # Les valeurs i/w/c doivent être acceptées.
        for value in ('i', 'w', 'c'):
            self.host.add_tests(test_list, {"label":"eth0", "ifname":"eth0",
                                            "dormant": value})
            self.assertEqual(
                conf.hostsConf["testserver1"]["SNMPJobs"]\
                    [ ("Interface eth0", "service") ]['params'],
                # 'i' correspond à la valeur par défaut de "admin".
                ['eth0', 'eth0', 'i', value])

        # Les autres valeurs doivent être rejetées.
        self.assertRaises(ParsingError, self.host.add_tests,
            test_list, {"label":"eth0", "ifname":"eth0", "dormant": ''})

    def test_add_tag_hosts(self):
        """Test for the add_tag method on hosts"""
        self.host.add_tag("Host", "important", 2)
        self.assertEqual(conf.hostsConf["testserver1"]["tags"],
                         {"important": 2})

    def test_add_tag_services(self):
        """Test for the add_tag method on services"""
        test_list = self.testfactory.get_test("UpTime", self.host.classes)
        self.host.add_tests(test_list)
        self.host.add_tag("UpTime", "security", 1)
        self.assertEqual({"security": 1},
                conf.hostsConf["testserver1"]["services"]["UpTime"]["tags"])

    def test_add_trap(self):
        """Test for the add_trap method on hosts"""
        data = {}
        data["command"] = "test_path_to_script"
        data["service"] = "test_serv"
        data["label"] = "test.label"
        self.host.add_trap("test_serv", "1.2.3.4.5.6.7.8.9", data)
        trapdata = conf.hostsConf["testserver1"]["snmpTrap"]["test_serv"]
        self.assertEqual(trapdata["1.2.3.4.5.6.7.8.9"]["label"], "test.label")

    def test_add_group(self):
        """Test for the add_group method on hosts"""
        self.host.add_group("/Test Group")
        self.assertTrue("/Test Group" in
                conf.hostsConf["testserver1"]["otherGroups"],
                "add_group does not work")

    def test_add_collector_service(self):
        """Test for the add_collector_service method on hosts"""
        self.host.add_collector_service(
            "TestAddCS",
            "TestAddCSFunction",
            ["fake arg 1"],
            ["GET/.1.3.6.1.2.1.1.3.0"]
        )
        hostdata = conf.hostsConf["testserver1"]
        self.assertEqual(hostdata["services"]["TestAddCS"]["type"],
                "passive", "add_collector_service does not fill the "
                "services sub-hashmap")
        self.assertEqual(hostdata["SNMPJobs"][("TestAddCS", "service")],
                { 'function': "TestAddCSFunction",
                  'params': ["fake arg 1"],
                  'vars': ["GET/.1.3.6.1.2.1.1.3.0"],
                  'reRouteFor': None },
                "add_collector_service does not fill the SNMPJobs sub-hashmap")

    def test_add_collector_service_reroute(self):
        """Test for the add_collector_service host method with rerouting"""
        host2 = Host(conf.hostsConf, "dummy", "testserver2", "192.168.1.2", "Servers")
        host2.add_collector_service(
            "TestAddCSReRoute",
            "TestAddCSReRouteFunction",
            ["fake arg 1"],
            ["GET/.1.3.6.1.2.1.1.3.0"],
            reroutefor={
                'host': "testserver1",
                "service": "TestAddCSReRoute",
            },
        )
        hdata1 = conf.hostsConf["testserver1"]
        hdata2 = conf.hostsConf["testserver2"]
        self.assertEqual(hdata1["services"]["TestAddCSReRoute"]["type"],
            "passive", "add_collector_service rerouting does not work "
            "with the services sub-hashmap")
        self.assertEqual(hdata2["SNMPJobs"][("TestAddCSReRoute", "service")],
                { 'function': "TestAddCSReRouteFunction",
                  'params': ["fake arg 1"],
                  'vars': ["GET/.1.3.6.1.2.1.1.3.0"],
                  'reRouteFor': {
                    'host': "testserver1",
                    "service": "TestAddCSReRoute"
                  },
                }, "add_collector_service rerouting does not work "
                "with the SNMPJobs sub-hashmap")

    def test_add_collector_metro(self):
        """Test for the add_collector_metro host method"""
        self.host.add_collector_metro("TestAddCS", "TestAddCSMFunction",
                            ["fake arg 1"], ["GET/.1.3.6.1.2.1.1.3.0"],
                            "GAUGE", label="TestAddCSLabel")
        self.assertEqual(
            conf.hostsConf["testserver1"]["dataSources"]["TestAddCS"],
            {'dsType':"GAUGE", 'label': "TestAddCSLabel",
             "max": None, "min": None, "rra_template": None},
            "add_collector_metro does not fill the dataSources sub-hashmap")
        self.assertEqual(
            conf.hostsConf["testserver1"]["SNMPJobs"][("TestAddCS","perfData")],
            {'function': "TestAddCSMFunction", 'params': ["fake arg 1"],
             'vars': ["GET/.1.3.6.1.2.1.1.3.0"], 'reRouteFor': None},
            "add_collector_metro does not fill the SNMPJobs sub-hashmap")

    def test_add_collector_metro_reroute(self):
        """Test for the add_collector_metro host method with rerouting"""
        host2 = Host(conf.hostsConf, "dummy", u"testserver2",
                     u"192.168.1.2", "Servers")
        host2.add_collector_metro("TestAddCSReRoute", "TestAddCSRRMFunction",
                ["fake arg 1"], ["GET/.1.3.6.1.2.1.1.3.0"],
                "GAUGE", label="TestAddCSReRouteLabel",
                reroutefor={'host': "testserver1",
                            "service": "TestAddCSReRoute"} )
        t1ds = conf.hostsConf["testserver1"]["dataSources"]
        t2snmp = conf.hostsConf["testserver2"]["SNMPJobs"]
        self.assertEqual(t1ds["TestAddCSReRoute"],
            {'dsType':"GAUGE", 'label': "TestAddCSReRouteLabel",
             "max": None, "min": None, "rra_template": None},
            "add_collector_metro rerouting does not work with the "
            "dataSources sub-hashmap")
        self.assertEqual(t2snmp[("TestAddCSReRoute","perfData")],
            {'function': "TestAddCSRRMFunction", 'params': ["fake arg 1"],
             'vars': ["GET/.1.3.6.1.2.1.1.3.0"], 'reRouteFor':
             {'host':"testserver1", "service" : "TestAddCSReRoute"}},
            "add_collector_service ReRouting does not work with the "
            "SNMPJobs sub-hashmap")

    def test_add_nagios_hdirective(self):
        """Test for the add_nagios_directive method"""
        host = Host(conf.hostsConf, "dummy", u"testserver2",
                    u"192.168.1.2", "Servers")
        host.add_nagios_directive("max_check_attempts", "5")
        nagios_hdirs = conf.hostsConf["testserver2"]["nagiosDirectives"]["host"]
        self.assertEquals(nagios_hdirs["max_check_attempts"], "5")

    def test_add_nagios_sdirective(self):
        """Test for the add_nagios_directive method"""
        host = Host(conf.hostsConf, "dummy", u"test2",
                    u"192.168.1.2", "Servers")
        host.add_nagios_directive("max_check_attempts", "5", target="services")
        nagios_sdirs = conf.hostsConf["test2"]["nagiosDirectives"]["services"]
        self.assertEquals(nagios_sdirs["max_check_attempts"], "5")

    def test_add_nagios_service_directive_INTF(self):
        """Nagios directives for tests"""
        test_list = self.testfactory.get_test("Interface", self.host.classes)
        self.host.add_tests(test_list, {"label":"eth0", "ifname":"eth0"},
                            directives={"testdirective": "testdirvalue"})
        nsd = conf.hostsConf["testserver1"]["nagiosSrvDirs"]
        self.assertEquals(nsd["Interface eth0"]["testdirective"],
                          "testdirvalue")

    def test_add_graph(self):
        self.host.add(self.host.name, "dataSources", "dummyds", {})
        graph = self.host.add_graph("testgraph", ["dummyds"], "lines", "test")
        self.assertTrue("testgraph" in
                        conf.hostsConf["testserver1"]["graphItems"])

    def test_make_cdef(self):
        cdef = self.host.make_rrd_cdef("testcdef", "1,1,+")
        self.assertTrue("testcdef" in
                        conf.hostsConf["testserver1"]["dataSources"])
        graph = self.host.add_graph("testgraph", [cdef], "lines", "test")
        print conf.hostsConf["testserver1"]["graphItems"]["testgraph"]["cdefs"]
        self.assertEqual(conf.hostsConf["testserver1"]["graphItems"][
                "testgraph"]["cdefs"], [{"name": "testcdef", "cdef": "1,1,+"}])

    def test_make_cdef_unicode(self):
        self.assertRaises(VigiConfError, self.host.make_rrd_cdef,
                          u"test éèçà", "1,1,+")

    def test_make_cdef_8bit(self):
        self.assertRaises(VigiConfError, self.host.make_rrd_cdef,
                          "test éèçà", "1,1,+")
Esempio n. 18
0
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"])