Example #1
0
 def maintenance_get(self, maintenance_name):
     try:
         result = self.client.maintenance.get(filter={"name": maintenance_name})
         return result
     except ZabbixAPIException as e:
         raise ZabbixAPIException(("There was a problem searching for the maintenance window: "
                                 "{0}".format(e)))
Example #2
0
    def test_run_action_with_invalid_config_of_account(self, mock_client):
        # make an exception that means failure to authenticate with Zabbix-server.
        mock_client.side_effect = ZabbixAPIException('auth error')

        action = self.get_action_instance(self.full_config)

        with self.assertRaises(ZabbixAPIException):
            action.run(action='something')
Example #3
0
    def test_find_host_fail(self, mock_client):
        action = self.get_action_instance(self.full_config)
        test_dict = {'host_name': "test", 'hostid': "1"}
        mock_client.host.get.side_effect = ZabbixAPIException('host error')
        mock_client.host.get.return_value = [test_dict]
        action.client = mock_client

        with self.assertRaises(ZabbixAPIException):
            action.find_host(test_dict['host_name'])
Example #4
0
    def test_register_mediatype_with_invalid_authentication(self, mock_client):
        sys.argv += ['-z', 'http://invalid-zabbix-host', '-u', 'user', '-p', 'passwd']

        # make an exception that means failure to authenticate with Zabbix-server.
        mock_client.side_effect = ZabbixAPIException('auth error')

        with self.assertRaises(SystemExit):
            register_st2_config_to_zabbix.main()
            self.assertTrue(re.match(r"Failed to authenticate Zabbix", self.io_stderr.getvalue()))
Example #5
0
    def test_run_action_with_invalid_config_of_account(self, mock_client):
        # make an exception that means failure to authenticate with Zabbix-server.
        mock_client.side_effect = ZabbixAPIException('auth error')

        action = self.get_action_instance(self.full_config)
        result = action.run(action='something')

        self.assertFalse(result[0])
        self.assertTrue(
            re.match(r"Failed to authenticate with Zabbix", result[1]))
Example #6
0
 def test_run_host_error(self, mock_connect):
     action = self.get_action_instance(self.full_config)
     mock_connect.return_vaue = "connect return"
     test_dict = {'host': "test"}
     host_dict = {'name': "test", 'hostid': '1'}
     action.find_hosts = mock.MagicMock(return_value=host_dict['hostid'],
         side_effect=ZabbixAPIException('host error'))
     action.connect = mock_connect
     with self.assertRaises(ZabbixAPIException):
         action.run(**test_dict)
Example #7
0
    def test_maintenance_get_fail(self, mock_client):
        action = self.get_action_instance(self.full_config)
        test_dict = {'maintenance_name': "test", 'maintenanceid': "1"}
        mock_client.maintenance.get.side_effect = ZabbixAPIException(
            'maintenance error')
        mock_client.maintenance.get.return_value = [test_dict]
        action.client = mock_client

        with self.assertRaises(ZabbixAPIException):
            action.maintenance_get(test_dict['maintenance_name'])
Example #8
0
 def connect(self):
     try:
         self.client = ZabbixAPI(url=self.config['zabbix']['url'],
                                 user=self.config['zabbix']['username'],
                                 password=self.config['zabbix']['password'])
     except ZabbixAPIException as e:
         raise ZabbixAPIException("Failed to authenticate with Zabbix (%s)" % str(e))
     except URLError as e:
         raise URLError("Failed to connect to Zabbix Server (%s)" % str(e))
     except KeyError:
         raise KeyError("Configuration for Zabbix pack is not set yet")
Example #9
0
    def test_run_delete_error(self, mock_connect, mock_client):
        action = self.get_action_instance(self.full_config)
        mock_connect.return_vaue = "connect return"
        test_dict = {'maintenance_window_name': None, 'maintenance_id': '1'}
        action.connect = mock_connect
        mock_client.maintenance.delete.side_effect = ZabbixAPIException('maintenance error')
        mock_client.maintenance.delete.return_value = "delete return"
        action.client = mock_client

        with self.assertRaises(ZabbixAPIException):
            action.run(**test_dict)
Example #10
0
 def maintenance_create_or_update(self, maintenance_params):
     maintenance_result = self.maintenance_get(maintenance_params['name'])
     if len(maintenance_result) == 0:
         try:
             create_result = self.client.maintenance.create(**maintenance_params)
             return create_result
         except ZabbixAPIException as e:
             raise ZabbixAPIException(("There was a problem creating the "
                                     "maintenance window: {0}".format(e)))
     elif len(maintenance_result) == 1:
         try:
             maintenance_id = maintenance_result[0]['maintenanceid']
             update_result = self.client.maintenance.update(maintenanceid=maintenance_id,
                                                         **maintenance_params)
             return update_result
         except ZabbixAPIException as e:
             raise ZabbixAPIException(("There was a problem updating the "
                                     "maintenance window: {0}".format(e)))
     elif len(maintenance_result) >= 2:
         raise ValueError(("There are multiple maintenance windows with the "
                         "name: {0}").format(maintenance_params['name']))
    def test_run_update_error(self, mock_connect, mock_client):
        action = self.get_action_instance(self.full_config)
        mock_connect.return_vaue = "connect return"
        test_dict = {'host': "test", 'status': 1}
        host_dict = {'name': "test", 'hostid': '1'}
        action.connect = mock_connect
        action.find_host = mock.MagicMock(return_value=host_dict['hostid'])
        mock_client.host.update.side_effect = ZabbixAPIException('host error')
        mock_client.host.update.return_value = "update return"
        action.client = mock_client

        with self.assertRaises(ZabbixAPIException):
            action.run(**test_dict)
Example #12
0
    def run(self, host=None, status=None):
        """ Updates the status of a Zabbix Host. Status needs to be
        1 or 0 for the call to succeed.
        """
        self.connect()

        host_id = self.find_host(host)

        try:
            self.client.host.update(hostid=host_id, status=status)
            return True
        except ZabbixAPIException as e:
            raise ZabbixAPIException("There was a problem updating the host: {0}".format(e))
    def run(self, host=None, host_id=None):
        """ Deletes a Zabbix Host.
        """
        self.connect()

        if not host_id:
            host_id = self.find_host(host)

        try:
            self.client.host.delete(host_id)
            return True
        except ZabbixAPIException as e:
            raise ZabbixAPIException("There was a problem deleting the host: {0}".format(e))
    def run(self, host_ids=None):
        """ Gets the inventory of one or more Zabbix Hosts.
        """
        self.connect()

        # Find inventory by host ids
        try:
            inventory = self.client.host.get(
                hostids=host_ids, selectInventory='extend', output=['hostid', 'inventory'])
        except ZabbixAPIException as e:
            raise ZabbixAPIException(("There was a problem searching for the host: "
                                      "{0}".format(e)))

        return inventory
Example #15
0
    def test_maintenance_create_or_update_create_fail(self, mock_client,
                                                      mock_maintenance_get):
        action = self.get_action_instance(self.full_config)
        test_dict = {'name': "test"}
        maintenance_dict = {'maintenance_name': "test", 'maintenanceid': "1"}
        mock_maintenance_get.return_value = []
        mock_client.maintenance.create.return_value = [
            maintenance_dict['maintenanceid']
        ]
        mock_client.maintenance.create.side_effect = ZabbixAPIException(
            'maintenance error')
        action.client = mock_client

        with self.assertRaises(ZabbixAPIException):
            action.maintenance_create_or_update(test_dict)
Example #16
0
    def find_host(self, host_name):
        try:
            zabbix_host = self.client.host.get(filter={"host": host_name})
        except ZabbixAPIException as e:
            raise ZabbixAPIException(("There was a problem searching for the host: "
                                    "{0}".format(e)))

        if len(zabbix_host) == 0:
            raise ValueError("Could not find any hosts named {0}".format(host_name))
        elif len(zabbix_host) >= 2:
            raise ValueError("Multiple hosts found with the name: {0}".format(host_name))

        self.zabbix_host = zabbix_host[0]

        return self.zabbix_host['hostid']
    def __init__(self):
        super().__init__()

        # Initiate vPoller
        try:
            self._vpoller = vPollerAPI(
                vpoller_endpoint=vfzsync.CONFIG["vpoller"]["endpoint"])
            self._vpoller.run(method="about",
                              vc_host=vfzsync.CONFIG["vpoller"]["vc_host"])
        except vPollerException:
            message = "vPoller initialization failed"
            logger.exception(message)
            raise vPollerException(message)

        # Initiate FNT API
        try:
            self._command = FNTCommandAPI(
                url=vfzsync.CONFIG["command"]["url"],
                username=vfzsync.CONFIG["command"]["username"],
                password=vfzsync.CONFIG["command"]["password"],
            )
        except FNTNotAuthorized:
            message = "FNT Command authorization failed"
            logger.exception(message)
            raise FNTNotAuthorized(message)

        # Initiate ZabbixAPI
        try:
            self._zapi = ZabbixAPI(
                url=vfzsync.CONFIG["zabbix"]["url"],
                user=vfzsync.CONFIG["zabbix"]["username"],
                password=vfzsync.CONFIG["zabbix"]["password"],
            )
            self._zapi.session.verify = False
            zabbix_hostgroup_name = vfzsync.CONFIG["zabbix"]["hostgroup"]
            zabbix_hostgroup_id = get_zabbix_hostgroupid_by_name(
                self._zapi, zabbix_hostgroup_name)
            if not zabbix_hostgroup_id:
                zabbix_hostgroup_id = self._zapi.hostgroup.create(
                    name=zabbix_hostgroup_name)
                logger.info(
                    f"Created Zabbix host group {zabbix_hostgroup_name}.")

        except ZabbixAPIException:
            message = "Zabbix authorization failed"
            logger.exception(message)
            raise ZabbixAPIException(message)
    def find_hosts(self, host_name):
        """ Queries the zabbix api for a host and returns just the
        ids of the hosts as a list. If a host could not be found it
        returns an empty list.
        """
        try:
            zabbix_hosts = self.client.host.get(filter={"host": host_name})
        except ZabbixAPIException as e:
            raise ZabbixAPIException(
                ("There was a problem searching for the host: "
                 "{0}".format(e)))

        zabbix_hosts_return = []
        if len(zabbix_hosts) > 0:
            for host in zabbix_hosts:
                zabbix_hosts_return.append(host['hostid'])

        return zabbix_hosts_return
Example #19
0
    def test_run_host_error(self, mock_connect):
        action = self.get_action_instance(self.full_config)
        mock_connect.return_vaue = "connect return"
        test_dict = {
            'host': "test",
            'time_type': 0,
            'maintenance_window_name': "test",
            'maintenance_type': 0,
            'start_date': "2017-11-14 10:40",
            'end_date': "2017-11-14 10:45"
        }
        host_dict = {'name': "test", 'hostid': '1'}
        action.find_host = mock.MagicMock(
            return_value=host_dict['hostid'],
            side_effect=ZabbixAPIException('host error'))
        action.connect = mock_connect

        with self.assertRaises(ZabbixAPIException):
            action.run(**test_dict)
Example #20
0
 def test_run_connection_error(self, mock_connect):
     action = self.get_action_instance(self.full_config)
     mock_connect.side_effect = ZabbixAPIException('login error')
     with self.assertRaises(ZabbixAPIException):
         action.run()