Beispiel #1
0
 def test_update_zabbix_host(self):
     host = self.connector.zabbix_api.host.get(
         {"filter": {
             "host": "vsphere_uuid"
         }})[0]
     node = self.driver.list_nodes(ex_node_ids=["vsphere_uuid"])[0]
     node.name = "vSphereVM_Updated"
     node.public_ips = ["127.0.0.1", "192.168.0.1", "localhost"]
     result = self.connector.update_zabbix_host("ESXi", "vsphere_uuid",
                                                node, host)
     self.assertTrue(result)
     self.assertEqual(host["name"], "ESXi_vSphereVM_Updated")
     self.connector.zabbix_api.host.update = Mock(
         side_effect=ZabbixAPIException())
     result = self.connector.update_zabbix_host("ESXi", "vsphere_uuid",
                                                node, host)
     self.assertFalse(result)
     self.connector.zabbix_api.hostinterface.update = Mock(
         side_effect=ZabbixAPIException())
     host = self.connector.zabbix_api.host.get(
         {"filter": {
             "host": "dummy_uuid"
         }})[0]
     result = self.connector.update_zabbix_host("ESXi", "vsphere_uuid",
                                                node, host)
     self.assertFalse(result)
Beispiel #2
0
    def _diff_interfaces(cls, obj, host, interface):
        params = {}

        # There should be one zabbix agent interface
        hi = None
        try:
            interfaces = cls._parse_host_interfaces(host)

            for i, iface in enumerate(interfaces):
                if int(iface['type']) == cls.HOSTINTERFACE_AGENT and int(iface['main']) == cls.YES:
                    if hi:
                        # noinspection PyProtectedMember
                        raise ZabbixAPIException('Zabbix host ID "%s" for %s %s has multiple Zabbix Agent '
                                                 'configurations' % (host['hostid'], obj._meta.verbose_name_raw, obj))

                    # Zabbix host interface found, let's check it out
                    hi = iface

                    if (iface['dns'] != interface['dns']
                            or iface['ip'] != interface['ip']
                            or str(iface['port']) != str(interface['port'])
                            or str(iface['useip']) != str(interface['useip'])):
                        # Host ip or dns changed -> update host interface
                        interface['interfaceid'] = iface['interfaceid']
                        interfaces[i] = interface
                        params['interfaces'] = interfaces

        except (IndexError, KeyError):
            pass

        if not hi:
            # noinspection PyProtectedMember
            raise ZabbixAPIException('Zabbix host ID "%s" for %s %s is missing a valid main '
                                     'Zabbix Agent configuration' % (host['hostid'], obj._meta.verbose_name_raw, obj))
        return params
Beispiel #3
0
 def test_create_zabbix_host(self):
     node = MockNode(
         **{
             "id": "new_uuid",
             "name": "New Host",
             "state": 0,
             "public_ips": [],
             "private_ips": [],
             "driver": MockVSphereNodeDriver("key", "secret"),
             "extra": {
                 "vmpath": "[datastore1] /hoge/hoge.vmx",
                 "platform": "CentOS 4/5/6 (64bit)",
             }
         })
     result = self.connector.create_zabbix_host("ESXi", "new_uuid", node)
     self.assertTrue(result)
     host = self.connector.zabbix_api.host.get(
         {"filter": {
             "host": node.id
         }})[0]
     self.assertEqual(host["host"], node.id)
     self.connector.zabbix_api.host.update = Mock(
         side_effect=ZabbixAPIException())
     result = self.connector.create_zabbix_host("ESXi", "new_uuid", node)
     self.assertFalse(result)
     self.connector.zabbix_api.host.create = Mock(
         side_effect=ZabbixAPIException())
     result = self.connector.create_zabbix_host("ESXi", "new_uuid", node)
     self.assertFalse(result)
Beispiel #4
0
 def _hostinterface_update(self, params):
     if "interfaceid" not in params:
         raise ZabbixAPIException("interfaceid does not specified")
     interfaces = [host["interfaces"] for host in self.mock_hosts]
     interfaces = reduce(lambda a, b: dict(a.items() + b.items()),
                         interfaces)
     if params["interfaceid"] not in interfaces:
         raise ZabbixAPIException("interface '%s' does not exist" %
                                  params["interfaceid"])
     interface = interfaces[params["interfaceid"]]
     for key, value in params.items():
         interface[key] = value
     return {"interfaceids": [interface["interfaceid"]]}
Beispiel #5
0
 def test_get_group_ids(self):
     test_data = [
         {
             "params": {
                 "owner_hostname": "AWS",
                 "key": "{$VM_GROUPS}"
             },
             "expect": [{
                 "groupid": 2
             }]
         },
         {
             "params": {
                 "owner_hostname": "AWS",
                 "key": "{$NOT_EXIST}"
             },
             "expect": []
         },
         {
             "params": {
                 "owner_hostname": "AWS",
                 "key": "{$GLOBAL}"
             },
             "expect": [{
                 "groupid": 3
             }]
         },
     ]
     for data in test_data:
         result = self.connector.get_group_ids(**data["params"])
         self.assertEqual(result, data["expect"])
     self.connector.zabbix_api.hostgroup.create = Mock(
         side_effect=ZabbixAPIException())
     result = self.connector.get_group_ids("AWS", "{$GLOBAL2}")
     self.assertListEqual(result, [])
Beispiel #6
0
 def _host_update(self, params):
     if "hostid" not in params:
         raise ZabbixAPIException("hostid does not specified")
     elif params["hostid"] not in [
             host["hostid"] for host in self.mock_hosts
     ]:
         raise ZabbixAPIException("host '%s' does not exist" %
                                  params["hostid"])
     host = [
         host for host in self.mock_hosts
         if host["hostid"] == params["hostid"]
     ][0]
     for key, value in params.items():
         if key == "interfaces":
             continue
         host[key] = value
     return {"hostids": [host["hostid"]]}
Beispiel #7
0
    def get_history(self, hosts, items, history, since, until, items_search=None):
        """Return monitoring history for selected zabbix host, items and period"""
        res = {'history': [], 'items': []}

        now = int(datetime.now().strftime('%s'))
        max_period = self.settings.MON_ZABBIX_GRAPH_MAX_PERIOD
        max_history = now - self.settings.MON_ZABBIX_GRAPH_MAX_HISTORY
        period = until - since
        since_history = None
        until_history = None
        since_trend = None
        until_trend = None
        itemids = set()

        if until < max_history or period > max_period:  # trends only
            until_trend = until
            since_trend = since
        else:  # history only
            until_history = until
            since_history = since

        try:
            for host in hosts:
                host_items = self._zabbix_get_items(host, items, search_params=items_search)

                if not host_items:
                    raise ZabbixAPIException('Cannot find items for host "%s" in Zabbix' % host)

                itemids.update(i['itemid'] for i in host_items)
                res['items'].extend(host_items)

            # noinspection PyTypeChecker
            params = {
                'itemids': list(itemids),
                'history': history,
                'sortfield': 'clock',
                'sortorder': 'ASC',
                'output': 'extend',
            }

            if since_trend and until_trend:
                params['time_from'] = since_trend
                params['time_till'] = until_trend
                # Zabbix trend.get does not support sorting -> https://support.zabbix.com/browse/ZBXNEXT-3974
                res['history'] = sorted(self.zapi.trend.get(params), key=itemgetter('clock'))

            if since_history and until_history:
                params['time_from'] = since_history
                params['time_till'] = until_history
                res['history'] += self.zapi.history.get(params)

        except ZabbixAPIException as exc:
            self.log(ERROR, 'Zabbix API Error in get_history(%s, %s): %s', hosts, items, exc)
            raise InternalMonitoringError('Zabbix API Error while retrieving history (%s)' % exc)

        else:
            return res
Beispiel #8
0
 def test_create_zabbix_host(self):
     node = self.driver.list_nodes(ex_node_ids=["i-aaaaaaaa"])[0]
     node.extra["platform"] = None
     self.assertTrue(
         self.connector.create_zabbix_host(owner_hostname="AWS",
                                           hostname="i-aaaaaaaa",
                                           node=node))
     self.connector.zabbix_api.host.update = Mock(
         side_effect=ZabbixAPIException())
     self.assertFalse(
         self.connector.create_zabbix_host(owner_hostname="AWS",
                                           hostname="i-aaaaaaaa",
                                           node=node))
     self.connector.zabbix_api.host.create = Mock(
         side_effect=ZabbixAPIException())
     self.assertFalse(
         self.connector.create_zabbix_host(owner_hostname="AWS",
                                           hostname="i-aaaaaaaa",
                                           node=node))
Beispiel #9
0
 def _hostinterface_delete(self, params):
     if not isinstance(params, list):
         raise ZabbixAPIException("invalid format")
     deleted = []
     for host in self.mock_hosts:
         interfaces = host["interfaces"]
         for interfaceid in params:
             if interfaceid in interfaces:
                 del interfaces[interfaceid]
                 deleted.append(interfaceid)
     return {"interfaceids": deleted}
Beispiel #10
0
 def _host_delete(self, params):
     if not isinstance(params, list):
         raise ZabbixAPIException("invalid format")
     deleted = []
     for hostid in params:
         id = hostid["hostid"] if isinstance(hostid, dict) else hostid
         host = [host for host in self.mock_hosts
                 if host["hostid"] == id][0]
         self.mock_hosts.remove(host)
         deleted.append(id)
     return {"hostids": deleted}
Beispiel #11
0
 def _hostinterface_create(self, params):
     interface = params
     if interface["hostid"]:
         hosts = [
             host for host in self.mock_hosts
             if host["hostid"] == interface["hostid"]
         ]
         if hosts:
             interface["interfaceid"] = self.interfaceid_seq
             index = self.interfaceid_seq
             self.interfaceid_seq += 1
             hosts[0]["interfaces"][index] = interface
             return {"interfaceids": [interface["interfaceid"]]}
     raise ZabbixAPIException()
Beispiel #12
0
    def test_init(self):
        self.assertIsInstance(self.connector.config, configobj.ConfigObj)
        self.assertIsInstance(self.connector.logger, logging.Logger)
        self.assertEqual(self.connector.zabbix_server, '127.0.0.1')
        self.assertEqual(self.connector.zabbix_port, '10051')
        self.assertEqual(self.connector.zabbix_sender_path,
                         '/usr/bin/zabbix_sender')
        self.assertIsInstance(self.connector.zabbix_api, MockZabbixAPI)

        with self.assertRaises(KeyError):
            connector = BaseConnector(config=configobj.ConfigObj("wrong_path"))
        with patch('hyclops.connector.base.ZabbixAPI.login') as m:
            m.side_effect = ZabbixAPIException()
            with self.assertRaises(ZabbixAPIException):
                connector = BaseConnector(config=self.config)
            m.side_effect = Exception()
            with self.assertRaises(Exception):
                connector = BaseConnector(config=self.config)
Beispiel #13
0
 def test_update_zabbix_host(self):
     node = self.driver.list_nodes(ex_node_ids=["i-aaaaaaaa"])[0]
     node.name = "a" * 62
     host = self.connector.zabbix_api.host.get(
         {"filter": {
             "host": "i-aaaaaaaa"
         }})[0]
     self.assertTrue(
         self.connector.update_zabbix_host(owner_hostname="AWS",
                                           hostname="i-aaaaaaaa",
                                           node=node,
                                           host=host))
     self.assertEqual(
         host["name"], "AWS_" + "a" *
         (64 - len("AWS_") - len(".._i-aaaaaaaa")) + ".._i-aaaaaaaa")
     host = self.connector.zabbix_api.host.get(
         {"filter": {
             "host": "i-aaaaaaaa"
         }})[0]
     self.assertEqual(len(host["interfaces"]),
                      len(node.private_ips) * 2 + 2)
     node.public_ips = []
     node.private_ips = []
     self.assertTrue(
         self.connector.update_zabbix_host(owner_hostname="AWS",
                                           hostname="i-aaaaaaaa",
                                           node=node,
                                           host=host))
     host = self.connector.zabbix_api.host.get(
         {"filter": {
             "host": "i-aaaaaaaa"
         }})[0]
     self.assertEqual(len(host["interfaces"]),
                      len(node.private_ips) * 2 + 2)
     self.connector.zabbix_api.host.update = Mock(
         side_effect=ZabbixAPIException())
     self.assertFalse(
         self.connector.update_zabbix_host(owner_hostname="AWS",
                                           hostname="i-aaaaaaaa",
                                           node=node,
                                           host=host))
Beispiel #14
0
 def login(self, user='', password='', save=True):
     if user == 'Admin' and password == 'zabbix':
         return True
     else:
         raise ZabbixAPIException()