Example #1
0
 def test_message_not_equal(self):
     """
     Test message not equal
     """
     message1 = Message('Service name', 'Message body', Message.ERROR)
     message2 = Message('Service name 2', 'Message body', Message.ERROR)
     self.assertTrue(message1 != message2)
Example #2
0
 def test_message_equality(self):
     """
     Test message equality
     2 Message objects with same values should be equal
     """
     message1 = Message('Service name', 'Message body', Message.ERROR)
     message2 = Message('Service name', 'Message body', Message.ERROR)
     self.assertTrue(message1 == message2)
Example #3
0
    def select_paste(self):
        try:
            self.ui.list_view.clear()

            self.files = getOpenFilesAndDirs()
            for path in self.files:
                self.ui.list_view.addItem(str(path))
        except Exception as error:
            msg = Message(self, str(error))
            msg.show()
Example #4
0
 def test_message_in_not_list(self):
     """
     Test 'in' primitive in Python is working as expected
     with Message object.
     """
     message = Message('Service name 0', 'Message body', Message.ERROR)
     messages = [
         Message('Service name 1', 'Message body 1', Message.ERROR),
         Message('Service name 2', 'Message body 2', Message.ERROR)
     ]
     self.assertTrue(message not in messages)
Example #5
0
def test(service):
    """
    See module docstring
    """

    domain = service['domain']
    ns_ips = service.get('ns_IPs', None)
    dnssec = service.get('dnssec', False)
    service_name = "[dns] {}:".format(domain)

    # Auto-discover NS servers if not given
    if ns_ips is None:
        ns_ips = get_ns_servers(domain)

    results = []

    for ns_ip in ns_ips:

        # request object
        request = dns.message.make_query(domain, dns.rdatatype.A)
        if dnssec:
            request.flags |= dns.flags.AD

        # UDP mode
        try:
            response = dns.query.udp(request, ns_ip)
            if response.rcode() != 0:
                raise Exception('rcode is not 0')
        except Exception as resolver_exception:
            results.append(
                Message(
                    service_name,
                    "Failed to resolv domain (UDP mode): {}".format(
                        resolver_exception), Message.ERROR))

        # TCP mode
        try:
            response = dns.query.tcp(request, ns_ip)
            if response.rcode() != 0:
                raise Exception('rcode is not 0')
        except Exception as resolver_exception:
            results.append(
                Message(
                    service_name,
                    "Failed to resolv domain (TCP mode): {}".format(
                        resolver_exception), Message.ERROR))

        return results
    def manage_notifications(self, notifications):
        """
        This method reorganizes notifications: don't send notification
        already sent and add notification for services back online.

        Parameters:
        notifications: (list of Message object) notifications from self.monitor

        Return:
        (list of Messages object) notification to send
        """

        notifications_to_send = []

        # Check if notification was already sent
        for message in notifications:
            if message not in self.down_services:
                notifications_to_send.append(message)
                self.down_services.append(message)

        # Add notification for services which are back online
        for sent_message in list(self.down_services):
            if sent_message not in notifications:
                notifications_to_send.append(
                    Message(sent_message.service,
                            sent_message.body,
                            sent_message.severity,
                            header='back online'))
                self.down_services.remove(sent_message)
                log.info("[service online] %s", str(sent_message))
            else:
                log.warning("[service down] %s", str(sent_message))

        return notifications_to_send
Example #7
0
    def test(self):
        """ test if the host responds to ping """
        args = ["ping", "-c", str(self.count), self.host]
        res = subprocess.run(args, capture_output=True)

        stdout = res.stdout.decode("ascii").split("\n")

        stats = self._parse_ping_stats(stdout[-4:])

        if stats["received"] is self.count:
            log.info("host %s is reachable with %s ms of latency", self.host,
                     stats["avg"])
            msg = []

        elif stats["received"] > 0:
            log.warning("host %s reachable, %s ms latency, %s percent of loss",
                        self.hostname, stats["avg"], stats["loss"])

            msg = []

        else:
            log.error("could not reach host %s", self.hostname)
            msg = [
                Message("Ping",
                        "Could not reach host {}".format(self.hostname),
                        Message.ERROR)
            ]

        return msg
Example #8
0
 def test_message_creation(self):
     """
     Test message creation
     """
     message = Message('Service name', 'Message body', Message.ERROR)
     self.assertTrue(message.service == 'Service name')
     self.assertTrue(message.body == 'Message body')
     self.assertTrue(message.severity == Message.ERROR)
Example #9
0
 def test_str_header(self):
     """
     Test __str__ method with header set
     """
     message = Message('Service name 0',
                       'Message body',
                       Message.ERROR,
                       header='Header')
     self.assertTrue(
         str(message) == "[Header] Service name 0: Message body")
    def test_back_online(self):
        """
        Test if a service was down but it's now up
        """
        message1 = Message('Service 1', 'Message 1', Message.ERROR)
        expected_notifications = [
            Message(
                'Service 1',
                'Message 1',
                Message.ERROR,
                'back online'
            )
        ]
        notifications = []
        self.services_monitoring.down_services = [message1]

        notifications_to_send = \
            self.services_monitoring.manage_notifications(notifications)

        self.assertTrue(notifications_to_send == expected_notifications)
        self.assertTrue(not self.services_monitoring.down_services)
    def test_one_notification(self):
        """
        Test with one notification
        """
        message1 = Message('Service 1', 'Message 1', Message.ERROR)
        notifications = [message1]
        self.services_monitoring.down_services = []

        notifications_to_send = \
            self.services_monitoring.manage_notifications(notifications)

        self.assertTrue(notifications_to_send == [message1])
        self.assertTrue(
            self.services_monitoring.down_services == [message1]
        )
    def test_still_down(self):
        """
        Test if a service is still down
        """
        message1 = Message('Service 1', 'Message 1', Message.ERROR)
        notifications = [message1]
        self.services_monitoring.down_services = [message1]

        notifications_to_send = \
            self.services_monitoring.manage_notifications(notifications)

        self.assertTrue(not notifications_to_send)
        self.assertTrue(
            self.services_monitoring.down_services == [message1]
        )
Example #13
0
def test(service):
    """
    See module docstring
    """
    host = service['host']
    port = service['port']
    timeout = service.get('timeout', 1)

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(timeout)
    try:
        sock.connect((host, port))
        sock.close()
    except Exception as socket_exception:
        return [
            Message(body="{}".format(socket_exception),
                    severity=Message.ERROR,
                    service="[raw_tcp] {}:{}".format(host, port))
        ]
    return []
Example #14
0
def test(service):
    """
    See module docstring
    """

    url = service['url']
    verify_certificate = service.get('verify_certificate', True)
    # check_tlsa = service.get('check_tlsa', False)  # check 'tlsa' branch
    redirection = service.get('redirection', False)
    service_name = "[https] {}".format(url)

    results = []

    try:
        request = requests.get(
            url,
            verify=verify_certificate,
            headers={
                'user-agent': 'services-monitoring/v1'
            },
            timeout=5
        )

    # Handle timeout
    except requests.exceptions.Timeout:
        results.append(Message(
            service_name,
            "Time out",
            Message.ERROR
        ))
        return results

    except Exception as request_exception:
        results.append(Message(
            service_name,
            "Exception: {}".format(request_exception),
            Message.ERROR
        ))
        return results

    # Fail if error code is not 2XX/3XX or TLS error
    if not request.ok:
        results.append(Message(
            service_name,
            "Request failed (status code: {})"
            .format(request.status_code),
            Message.ERROR
        ))

    # Check if url redirects to another url (3XX codes)
    if redirection:
        first_response = request.history[0] if request.history else request
        if not first_response.is_redirect:
            results.append(Message(
                service_name,
                "Not a redirection",
                Message.ERROR
            ))

    # For https check certificate expiration date and TLSA (if requested)
    parsed_url = urllib3.util.parse_url(url)
    if parsed_url.scheme == 'https':

        # Get certificate
        port = parsed_url.port if parsed_url.port is not None else 443
        cert = tls.get_certificate(parsed_url.host, port)

        # Check if certificate has expired or will expire soon
        not_before = datetime.strptime(
            cert.get_notBefore().decode('ascii'),
            '%Y%m%d%H%M%SZ'
        )

        not_after = datetime.strptime(
            cert.get_notAfter().decode('ascii'),
            '%Y%m%d%H%M%SZ'
        )
        log.debug(
            "Certificate: not_before: %s, not_after: %s",
            str(not_before),
            str(not_after)
        )

        now = datetime.utcnow()

        if now < not_before or now > not_after:
            results.append(Message(
                service_name,
                "Certificate has expired",
                Message.ERROR
            ))
        elif now + timedelta(hours=48) > not_after:
            results.append(Message(
                service_name,
                "Certificate will expire in less than 48 hours",
                Message.ERROR
            ))
        elif now + timedelta(days=7) > not_after:
            results.append(Message(
                service_name,
                "Certificate will expire in less than 7 days",
                Message.WARNING
            ))

    return results
Example #15
0
 def test_str(self):
     """
     Test __str__ method
     """
     message = Message('Service name 0', 'Message body', Message.ERROR)
     self.assertTrue(str(message) == "Service name 0: Message body")
Example #16
0
def test(service):
    """
    See module docstring
    """

    host = service['host']
    port = service.get('port', 25)
    # check_tlsa = service.get('check_tlsa', False)  # check 'tlsa' branch
    service_name = "[smtp] {}:{}".format(host, port)

    # This list will store warnings or errors.
    results = []

    # Fetch certificate
    try:
        connection = smtplib.SMTP('{}:{}'.format(host, port), timeout=2)
        connection.starttls()
    except Exception as connection_exception:
        results.append(
            Message(service_name,
                    "Failed to connect: {}".format(connection_exception),
                    Message.ERROR))

        return results  # Future tests will necessarily fail

    # Parse peer certificate
    cert = OpenSSL.crypto.load_certificate(
        OpenSSL.crypto.FILETYPE_ASN1,
        connection.sock.getpeercert(binary_form=True))

    connection.quit()

    # Check if hostname is correct
    common_name = dict(
        cert.get_subject().get_components())[b'CN'].decode('ascii')

    if '*' in common_name:  # wildcard cert
        if match('.{}$'.format(common_name), host) is None:
            results.append(
                Message(
                    service_name,
                    "Common name {} does not match host {}".format(
                        common_name, host), Message.ERROR))
    else:
        if common_name != host:
            results.append(
                Message(
                    service_name,
                    "Common name {} does not match host {}".format(
                        common_name, host), Message.ERROR))

    # Check if certificate has expired or will expire soon
    not_before = datetime.strptime(cert.get_notBefore().decode('ascii'),
                                   '%Y%m%d%H%M%SZ')

    not_after = datetime.strptime(cert.get_notAfter().decode('ascii'),
                                  '%Y%m%d%H%M%SZ')

    now = datetime.utcnow()

    if now < not_before or now > not_after:
        results.append(
            Message(service_name, "Certificate has expired", Message.ERROR))
    elif now + timedelta(hours=72) > not_after:
        results.append(
            Message(service_name,
                    "Certificate will expire in less than 72 hours",
                    Message.ERROR))

    return results
Example #17
0
    def compact_to_zip(self):
        try:
            if self.ui.list_view.count() != 0:

                path_save = QtWidgets.QFileDialog.getSaveFileName(
                    filter='*.zip')
                zip_dir = pathlib.Path(os.path.split(path_save[0])[1]).stem
                files_to_compact = list()

                for index in range(self.ui.list_view.count()):
                    files_to_compact.append(
                        self.ui.list_view.item(index).text())

                part_progress = 100 / len(files_to_compact)

                # function create zip
                create_zip(path_save[0], files_to_compact, zip_dir)

                msg = Message(self,
                              'Successfully created file!',
                              type_m='info')
                msg.show()
                self.ui.list_view.clear()
            else:
                msg_add = Message(self,
                                  'Select files to compress',
                                  type_m='info')
                msg_add.show()
        except FileNotFoundError:
            pass
        except Exception as error:
            msg = Message(self, str(error))
            msg.show()