From 3a03c142d76f30ed8fdf8200314b0c6807526569 Mon Sep 17 00:00:00 2001 From: Adrian Lopez Date: Fri, 25 Jan 2019 12:50:59 +0100 Subject: [PATCH] New function to recover active checks The new function get_active_checks() return a list of active items that a Zabbix Agent should execute. --- pyzabbix/sender.py | 31 +++++++++++++++++++++++++++++++ tests/test_sender.py | 17 +++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/pyzabbix/sender.py b/pyzabbix/sender.py index 6089c3d..67311f6 100644 --- a/pyzabbix/sender.py +++ b/pyzabbix/sender.py @@ -382,6 +382,18 @@ def _chunk_send(self, metrics): """ messages = self._create_messages(metrics) request = self._create_request(messages) + + return self._send_request(request) + + def _send_request(self, request): + """Send the formated zabbix request to zabbix server. + + :type request: str + :param request: formatted zabbix request + + :rtype: str + :return: Response from Zabbix Server + """ packet = self._create_packet(request) for host_addr in self.zabbix_uri: @@ -435,3 +447,22 @@ def send(self, metrics): for m in range(0, len(metrics), self.chunk_size): result.parse(self._chunk_send(metrics[m:m + self.chunk_size])) return result + + def get_active_checks(self, host): + """Send a request to retrieve active checks + + Format of returned items: + {'key': 'KEYITEM', 'delay': 30, 'lastlogsize': 0, 'mtime': 0} + + :type host: string + :param host: host name to retrive active checks + + :rtype: list + :return: List of active checks + """ + request = '{{"request":"active checks","host":"{host}"}}'.format(host=host) + request = request.encode("utf-8") + logger.debug('Request: %s', request) + + response = self._send_request(request) + return response.get("data") diff --git a/tests/test_sender.py b/tests/test_sender.py index 32962ba..1a0b811 100644 --- a/tests/test_sender.py +++ b/tests/test_sender.py @@ -222,3 +222,20 @@ def test_send_failed(self, mock_socket): zs = ZabbixSender() with self.assertRaises(Exception): zs.send([zm]) + + @patch('pyzabbix.sender.socket.socket', autospec=autospec) + def test_get_active_checks(self, mock_socket): + mock_data = b'\x01\\\x00\x00\x00\x00\x00\x00\x00' + mock_socket.return_value = mock_socket + mock_socket.recv.side_effect = (b'ZBXD', mock_data, b''' +{"response":"success","data":[{"key":"KEYITEM1","delay":30,"lastlogsize":0, \ +"mtime":0},{"key":"KEYITEM2","delay":300,"lastlogsize":10,"mtime":20}]} +''') + + zs = ZabbixSender() + result = zs.get_active_checks("host1") + self.assertIsInstance(result, list) + self.assertEqual(result[0], {"key": "KEYITEM1", "delay": 30, + "lastlogsize": 0, "mtime": 0}) + self.assertEqual(result[1], {"key": "KEYITEM2", "delay": 300, + "lastlogsize": 10, "mtime": 20})