Beispiel #1
0
    def check_status(self):
        """Check RabbitMQ service by opening and closing a broker channel."""
        logger.debug("Checking for a broker_url on django settings...")

        broker_url = getattr(settings, "BROKER_URL", None)

        logger.debug("Got %s as the broker_url. Connecting to rabbit...",
                     broker_url)

        logger.debug("Attempting to connect to rabbit...")
        try:
            # conn is used as a context to release opened resources later
            with Connection(broker_url) as conn:
                conn.connect()  # exceptions may be raised upon calling connect
        except ConnectionRefusedError as e:
            self.add_error(
                ServiceUnavailable(
                    "Unable to connect to RabbitMQ: Connection was refused."),
                e)

        except AccessRefused as e:
            self.add_error(
                ServiceUnavailable(
                    "Unable to connect to RabbitMQ: Authentication error."), e)

        except IOError as e:
            self.add_error(ServiceUnavailable("IOError"), e)

        except BaseException as e:
            self.add_error(ServiceUnavailable("Unknown error"), e)
        else:
            logger.debug("Connection established. RabbitMQ is healthy.")
Beispiel #2
0
    def check_status(self):
        """Check Redis service by pinging the redis instance with a redis connection."""
        logger.debug("Got %s as the redis_url. Connecting to redis...",
                     self.redis_url)

        logger.debug("Attempting to connect to redis...")
        try:
            # conn is used as a context to release opened resources later
            with from_url(self.redis_url) as conn:
                conn.ping()  # exceptions may be raised upon ping
        except ConnectionRefusedError as e:
            self.add_error(
                ServiceUnavailable(
                    "Unable to connect to Redis: Connection was refused."), e)
        except exceptions.TimeoutError as e:
            self.add_error(
                ServiceUnavailable("Unable to connect to Redis: Timeout."), e)
        except exceptions.ConnectionError as e:
            self.add_error(
                ServiceUnavailable(
                    "Unable to connect to Redis: Connection Error"), e)
        except BaseException as e:
            self.add_error(ServiceUnavailable("Unknown error"), e)
        else:
            logger.debug("Connection established. Redis is healthy.")
Beispiel #3
0
    def check_status(self):
        """Check Redis service by pinging the redis instance with a redis connection."""
        logger.debug("Got %s as the redis_url. Connecting to redis...",
                     self.redis_host)

        logger.debug("Attempting to connect to redis...")
        try:
            # Keeping the timeout 2 sec, so that connection closes after health check
            conn = Redis(host=self.redis_host,
                         port=self.redis_port,
                         socket_connect_timeout=2)
            conn.ping()  # exceptions may be raised upon ping
        except ConnectionRefusedError as e:
            self.add_error(
                ServiceUnavailable(
                    "Unable to connect to Redis: Connection was refused."), e)
        except exceptions.TimeoutError as e:
            self.add_error(
                ServiceUnavailable("Unable to connect to Redis: Timeout."), e)
        except exceptions.ConnectionError as e:
            self.add_error(
                ServiceUnavailable(
                    "Unable to connect to Redis: Connection Error"), e)
        except BaseException as e:
            self.add_error(ServiceUnavailable("Unknown error"), e)
        else:
            logger.debug("Connection established. Redis is healthy.")
Beispiel #4
0
    def check_status(self):
        timeout = getattr(settings, 'HEALTHCHECK_CELERY_TIMEOUT', 3)
        result_timeout = getattr(settings, 'HEALTHCHECK_CELERY_RESULT_TIMEOUT', timeout)
        queue_timeout = getattr(settings, 'HEALTHCHECK_CELERY_QUEUE_TIMEOUT', timeout)

        try:
            result = add.apply_async(
                args=[4, 4],
                expires=queue_timeout,
                queue=self.queue
            )
            result.get(timeout=result_timeout)
            if result.result != 8:
                self.add_error(ServiceReturnedUnexpectedResult("Celery returned wrong result"))
        except IOError as e:
            self.add_error(ServiceUnavailable("IOError"), e)
        except NotImplementedError as e:
            self.add_error(ServiceUnavailable("NotImplementedError: Make sure CELERY_RESULT_BACKEND is set"), e)
        except TaskRevokedError as e:
            self.add_error(ServiceUnavailable("TaskRevokedError: The task was revoked, likely because it spent "
                                              "too long in the queue"), e)
        except TimeoutError as e:
            self.add_error(ServiceUnavailable("TimeoutError: The task took too long to return a result"), e)
        except BaseException as e:
            self.add_error(ServiceUnavailable("Unknown error"), e)
Beispiel #5
0
 def check_status(self):
     try:
         response = flower_get('metrics', timeout=2)
         if not response.ok:
             raise ServiceUnavailable('Flower Unavailable')
     except Exception as ex:
         raise ServiceUnavailable(ex.args)
Beispiel #6
0
 def check_status(self):
     last_beat_time = cache.get(CACHE_KEY, None)
     if last_beat_time is None:
         self.add_error(
             ServiceUnavailable("Celery beat is not scheduling tasks"))
     elif (datetime.now() -
           last_beat_time).seconds > TIMEOUT + DELAY_THRESHOLD:
         self.add_error(ServiceUnavailable("Celery beat tasks are delayed"))
Beispiel #7
0
 def check_save(self, file_name, file_content):
     storage = self.get_storage()
     # save the file
     file_name = storage.save(file_name, ContentFile(content=file_content))
     # read the file and compare
     if not storage.exists(file_name):
         raise ServiceUnavailable('File does not exist')
     with storage.open(file_name) as f:
         if not f.read() == file_content:
             raise ServiceUnavailable('File content does not match')
Beispiel #8
0
 def check_status(self):
     try:
         scheduler = get_scheduler('default')
         if not scheduler:
             self.add_error(ServiceUnavailable("No scheduler"))
         if scheduler.count() == 0:
             self.add_error(ServiceUnavailable("No jobs in scheduler"))
     except BaseException as e:
         self.add_error(ServiceUnavailable("Unknown error"), e)
         raise (e)
Beispiel #9
0
    def check_status(self):
        response = requests.get("http://localhost:8000/api/v1/articles/")

        # Check that the HTTP code was 200
        if response.status_code != 200:
            raise ServiceUnavailable("Articles did not return 200")

        # Check that the endpoint returns some results
        if len(response.json()["results"]) == 0:
            raise ServiceUnavailable("Articles did not return any articles")
Beispiel #10
0
 def check_status(self):
     from core.tasks import add
     timeout = getattr(settings, 'HEALTHCHECK_CELERY_TIMEOUT', 3)
     try:
         result = add.delay(4, 4)
         result.get(timeout=timeout)
         if result.result != 8:
             self.add_error(ServiceReturnedUnexpectedResult("Celery returned wrong result"))
     except IOError as e:
         self.add_error(ServiceUnavailable("IOError"), e)
     except BaseException as e:
         self.add_error(ServiceUnavailable("Unknown error"), e)
Beispiel #11
0
 def check_status(self):
     db_alias = getattr(settings, 'HEALTHCHECK_MIGRATIONS_DB',
                        DEFAULT_DB_ALIAS)
     try:
         executor = MigrationExecutor(connections[db_alias])
         plan = self.get_migration_plan(executor)
         if plan:
             self.add_error(
                 ServiceUnavailable("There are migrations to apply"))
     except DatabaseError as e:
         self.add_error(ServiceUnavailable("Database is not ready"), e)
     except Exception as e:
         self.add_error(ServiceUnavailable("Unexpected error"), e)
Beispiel #12
0
    def check_status(self):
        response = requests.get("http://localhost:8000/api/v1/site-meta/")

        # Check that the HTTP code was 200
        if response.status_code != 200:
            raise ServiceUnavailable("Site-Meta did not return 200")

        if len(response.json()["site"]) == 0:
            raise ServiceUnavailable("Site-Meta did not return any meta")

        if len(response.json()["isAllowed"]) == 0:
            raise ServiceUnavailable(
                "Site-Meta did not return any permissions")
Beispiel #13
0
 def check_status(self):
     logger.debug("Checking status of API url...")
     try:
         assert_bwv_health()
     except ConnectionRefusedError as e:
         self.add_error(
             ServiceUnavailable(
                 "Unable to connect to BWV database: Connection was refused."
             ),
             e,
         )
     except BaseException as e:
         self.add_error(ServiceUnavailable("Unknown error"), e)
     else:
         logger.debug("Connection established. BWV database is healthy.")
    def check_status(self):
        timeout = getattr(settings, 'HEALTHCHECK_CELERY_TIMEOUT', 3)

        try:
            result = add.apply_async(
                args=[4, 4],
                expires=timeout
            )
            result.get(timeout=timeout)
            if result.result != 8:
                self.add_error(ServiceReturnedUnexpectedResult("Celery returned wrong result"))
        except IOError as e:
            self.add_error(ServiceUnavailable("IOError"), e)
        except BaseException as e:
            self.add_error(ServiceUnavailable("Unknown error"), e)
 def check_status(self):
     try:
         check_geoserver_is_up()
         return True
     except AssertionError:
         logger.exception("Unknown Error")
         raise ServiceUnavailable("Unknown error")
Beispiel #16
0
    def check_status(self):

        try:
            registration = get_vakantieverhuur_registration(
                settings.VAKANTIEVERHUUR_REGISTRATIE_API_HEALTH_CHECK_REGISTRATION_NUMBER
            )
            assert bool(
                registration
            ), "The registration data is empty and could not be retrieved"

            bsn_registrations = get_bsn_vakantieverhuur_registrations(
                settings.VAKANTIEVERHUUR_REGISTRATIE_API_HEALTH_CHECK_BSN
            )
            assert (
                len(bsn_registrations) > 0
            ), "The registration data is empty and could not be retrieved using the BSN number"

            bag_registrations = get_bag_vakantieverhuur_registrations(
                settings.VAKANTIEVERHUUR_REGISTRATIE_API_HEALTH_CHECK_BAG_ID
            )
            assert (
                len(bag_registrations) > 0
            ), "The registration data is empty and could not be retrieved using the BAG id"

        except Exception as e:
            logger.error(e)
            self.add_error(ServiceUnavailable("Failed"), e)
        else:
            logger.info(
                "Connection established. Vakantieverhuur Registratie API connection is healthy."
            )
Beispiel #17
0
 def check_status(self):
     client = mqtt.Client(client_id="django-hc")
     try:
         client.connect(MQTT_HOST, port=MQTT_PORT)
         client.disconnect()
     except (socket.gaierror, ConnectionRefusedError):
         self.add_error(ServiceUnavailable("Connection refused"))
Beispiel #18
0
    def check_status(self):
        from apps.fines.api_queries_belastingen import get_fines

        try:
            # The id doesn't matter, as long an authenticated request is succesful.
            get_fines("foo-id")
        except Exception as e:
            self.add_error(ServiceUnavailable("Failed"), e)
Beispiel #19
0
 def check_status(self):
     try:
         res = requests.get(settings.ELASTIC_SEARCH_HOST)
         if res.status_code != 200:
             self.add_error(ServiceReturnedUnexpectedResult(
                 "ElasticSearch service return status code: %s" % res.status_code))
     except requests.exceptions.RequestException as e:
         self.add_error(ServiceUnavailable("Unknown error"), e)
Beispiel #20
0
 def check_status(self):
     try:
         res = requests.get('https://www.rest.co.il/restaurants/israel/?kw=zozobra')
         if res.status_code != 200:
             self.add_error(ServiceReturnedUnexpectedResult(
                 "Logo finder service return status code: %s" % res.status_code))
     except requests.exceptions.RequestException as e:
         self.add_error(ServiceUnavailable("Unknown error"), e)
Beispiel #21
0
 def check_status(self):
     try:
         res = requests.get('http://www.purgomalum.com/service/containsprofanity?text=kickass')
         if res.status_code != 200:
             self.add_error(ServiceReturnedUnexpectedResult(
                 "Profanity service return status code: %s" % res.status_code))
     except requests.exceptions.RequestException as e:
         self.add_error(ServiceUnavailable("Unknown error"), e)
 def check_status(self):
     try:
         for opt, value in settings.AUTH_LDAP_GLOBAL_OPTIONS.items():
             ldap.set_option(opt, value)
         conn = ldap.initialize(settings.AUTH_LDAP_SERVER_URI)
         conn.bind_s(settings.AUTH_LDAP_BIND_DN,
                     settings.AUTH_LDAP_BIND_PASSWORD)
     except ldap.SERVER_DOWN as e:
         self.add_error(ServiceUnavailable("LDAP Server is not available."),
                        e)
     except ldap.NO_SUCH_OBJECT as e:
         self.add_error(ServiceUnavailable("Bind user does not exist."), e)
     except ldap.INVALID_CREDENTIALS as e:
         self.add_error(
             ServiceUnavailable("Invalid bind user credentials."), e)
     except ldap.LDAPError as e:
         self.add_error(ServiceUnavailable("Unknown error"), e)
Beispiel #23
0
    def check_status(self):
        timeout = time.time() + getattr(settings,
                                        'HEALTHCHECK_RQWORKER_TIMEOUT', 4)

        try:
            job = enqueue(add, 5, 6)
            while True:
                if job.result or time.time() > timeout:
                    break
            if not job.result:
                self.add_error(
                    ServiceUnavailable("No result, are workers running?"))
            elif job.result == '11':
                self.add_error(
                    ServiceReturnedUnexpectedResult("Invalid result"))
        except BaseException as e:
            self.add_error(ServiceUnavailable("Unknown error"), e)
Beispiel #24
0
    def check_status(self):
        from apps.permits.api_queries_decos_join import DecosJoinRequest

        try:
            # The address doesn't matter, as long an authenticated request is succesful.
            response = DecosJoinRequest().get_decos_object_with_address("foo")
            assert response, "Could not reach Decos Join"
        except Exception as e:
            self.add_error(ServiceUnavailable("Failed"), e)
Beispiel #25
0
 def check_status(self):
     try:
         res = requests.get('https://maps.googleapis.com/maps/api/distancematrix/json?origins=jerusalem&'
                            'destinations=Tel-Aviv&mode=driving&key=AIzaSyBuVvbfu_0nMgFmagXaWdIsVyXrL41OV-U')
         if res.status_code != 200:
             self.add_error(ServiceReturnedUnexpectedResult(
                 "Google distance api service return status code: %s" % res.status_code))
     except requests.exceptions.RequestException as e:
         self.add_error(ServiceUnavailable("Unknown error"), e)
    def check_status(self):
        if not (settings.HEROKU_AUTH_TOKEN
                and settings.HEROKU_CONNECT_APP_NAME):
            raise ServiceUnavailable(
                'Both App Name and Auth Token are required')

        try:
            connections = utils.get_connections(
                settings.HEROKU_CONNECT_APP_NAME)
        except requests.HTTPError as e:
            raise ServiceReturnedUnexpectedResult(
                "Unable to retrieve connection state") from e
        for connection in connections:
            if connection['state'] not in utils.ConnectionStates.OK_STATES:
                self.add_error(
                    ServiceUnavailable(
                        "Connection state for '%s' is '%s'" %
                        (connection['name'], connection['state'])))
 def check_status(self):
     try:
         cache.set('djangohealtcheck_test', 'itworks', 1)
         if not cache.get("djangohealtcheck_test") == "itworks":
             raise ServiceUnavailable("Cache key does not match")
     except CacheKeyWarning as e:
         self.add_error(ServiceReturnedUnexpectedResult("Cache key warning"), e)
     except ValueError as e:
         self.add_error(ServiceReturnedUnexpectedResult("ValueError"), e)
 def check_status(self):
     logger.debug("Checking status of Decos Join API url...")
     response = DecosJoinRequest().get()
     if not response:
         self.add_error(
             ServiceUnavailable(
                 "Unable to connect to Decos Join: Connection was refused.")
         )
     else:
         logger.debug("Decos Join API connection established.")
Beispiel #29
0
 def check_status(self):
     try:
         # write the file to the storage backend
         file_name = self.get_file_name()
         file_content = self.get_file_content()
         file_name = self.check_save(file_name, file_content)
         self.check_delete(file_name)
         return True
     except Exception:
         raise ServiceUnavailable('Unknown exception')
 def check_status(self):
     try:
         response = sso_api_client.ping()
     except Exception as error:
         raise ServiceUnavailable('(SSO proxy) ' + str(error))
     else:
         if response.status_code != 200:
             raise ServiceReturnedUnexpectedResult(
                 self.message_bad_status.format(response))
     return True