Skip to content

Commit

Permalink
Added healthcheck endpoint /status (#185)
Browse files Browse the repository at this point in the history
  • Loading branch information
caronc authored May 11, 2024
1 parent 3a710fb commit 135dd4e
Show file tree
Hide file tree
Showing 10 changed files with 435 additions and 14 deletions.
39 changes: 39 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,45 @@ The following architectures are supported: `amd64`, `arm/v7`, and `arm64`. The f

## API Details

### Health Checks

You can perform status or health checks on your server configuration by accessing `/status`.

| Path | Method | Description |
|------------- | ------ | ----------- |
| `/status` | GET | Simply returns a server status. The server http response code is a `200` if the server is working correcty and a `417` if there was an unexpected issue. You can set the `Accept` header to `application/json` or `text/plain` for different response outputs.

Below is a sample of just a simple text response:
```bash
# Request a general text response
# Output will read `OK` if everything is fine, otherwise it will return
# one or more of the following separated by a comma:
# - ATTACH_PERMISSION_ISSUE: Can not write attachments (likely a permission issue)
# - CONFIG_PERMISSION_ISSUE: Can not write configuration (likely a permission issue)
curl -X GET http://localhost:8000/status
```

Below is a sample of a JSON response:
```bash
curl -X GET -H "Accept: application/json" http://localhost:8000/status
```
The above output may look like this:
```json
{
"config_lock": false,
"status": {
"can_write_config": true,
"can_write_attach": true,
"details": ["OK"]
}
}
```

- The `config_lock` always cross references if the `APPRISE_CONFIG_LOCK` is enabled or not.
- The `status.can_write_config` defines if the configuration directory is writable or not. If the environment variable `APPRISE_STATEFUL_MODE` is set to `disabled`, this value will always read `false` and it will not impact the `status.details`
- The `status.can_write_attach` defines if the attachment directory is writable or not. If the environment variable `APPRISE_ATTACH_SIZE` or `APPRISE_MAX_ATTACHMENTS` is set to `0` (zero) or lower, this value will always read `false` and it will not impact the `status.details`.
- The `status.details` identifies the overall status. If there is more then 1 issue to report here, they will all show in this list. In a working orderly environment, this will always be set to `OK` and the http response type will be `200`.

### Stateless Solution

Some people may wish to only have a sidecar solution that does require use of any persistent storage. The following API endpoint can be used to directly send a notification of your choice to any of the [supported services by Apprise](https://github.com/caronc/apprise/wiki) without any storage based requirements:
Expand Down
12 changes: 6 additions & 6 deletions apprise_api/api/templates/config.html
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,15 @@ <h4>{% trans "Management for Config ID:" %} <code class="config-id">{{ key }}</c
<h5>{% trans "Getting Started" %}</h5>
<ol>
<li>
{% blocktrans %}
Here is where you can store your Apprise configuration associated with the key <code>{{key}}</code>.
{% endblocktrans %}
For some examples on how to build a development environment around this, <strong><a href="{% url 'welcome'%}?key={{key}}">click here</a></strong>.
{% trans "Verify your Apprise API Status:" %} <strong><a href="{% url 'health' %}">click here</a></strong>
</li>
<li>
{% trans "Here is where you can store your Apprise configuration associated with the key:" %} <code>{{key}}</code>
{% trans "For some examples on how to build a development environment around this:" %} <strong><a href="{% url 'welcome'%}?key={{key}}">click here</a></strong>
</li>
<li>
{% blocktrans %}
In the future you can return to this configuration screen at any time by placing the following into your
browser:
In the future you can return to this configuration screen at any time by placing the following into your browser:
{% endblocktrans %}
<code>{{request.scheme}}://{{request.META.HTTP_HOST}}{{BASE_URL}}/cfg/{{key}}</code>
</li>
Expand Down
12 changes: 12 additions & 0 deletions apprise_api/api/tests/test_attachment.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,18 @@ def test_form_file_attachment_parsing(self):
with self.assertRaises(ValueError):
parse_attachments(None, files_request)

# Test Attachment Size seto t zer0
with override_settings(APPRISE_ATTACH_SIZE=0):
files_request = {
'file1': SimpleUploadedFile(
"attach.txt",
# More then 1 MB in size causing error to trip
("content" * 1024 * 1024).encode('utf-8'),
content_type="text/plain")
}
with self.assertRaises(ValueError):
parse_attachments(None, files_request)

# Bad data provided in filename field
files_request = {
'file1': SimpleUploadedFile(
Expand Down
223 changes: 223 additions & 0 deletions apprise_api/api/tests/test_healthecheck.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,223 @@
# -*- coding: utf-8 -*-
#
# Copyright (C) 2024 Chris Caron <[email protected]>
# All rights reserved.
#
# This code is licensed under the MIT License.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files(the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions :
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import mock
from django.test import SimpleTestCase
from json import loads
from django.test.utils import override_settings
from ..utils import healthcheck


class HealthCheckTests(SimpleTestCase):

def test_post_not_supported(self):
"""
Test POST requests
"""
response = self.client.post('/status')
# 405 as posting is not allowed
assert response.status_code == 405

def test_healthcheck_simple(self):
"""
Test retrieving basic successful health-checks
"""

# First Status Check
response = self.client.get('/status')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'OK')
assert response['Content-Type'].startswith('text/plain')

# Second Status Check (Lazy Mode kicks in)
response = self.client.get('/status')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'OK')
assert response['Content-Type'].startswith('text/plain')

# JSON Response
response = self.client.get(
'/status', content_type='application/json',
**{'HTTP_CONTENT_TYPE': 'application/json'})
self.assertEqual(response.status_code, 200)
content = loads(response.content)
assert content == {
'config_lock': False,
'status': {
'can_write_config': True,
'can_write_attach': True,
'details': ['OK']
}
}
assert response['Content-Type'].startswith('application/json')

with override_settings(APPRISE_CONFIG_LOCK=True):
# Status Check (Form based)
response = self.client.get('/status')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'OK')
assert response['Content-Type'].startswith('text/plain')

# JSON Response
response = self.client.get(
'/status', content_type='application/json',
**{'HTTP_CONTENT_TYPE': 'application/json'})
self.assertEqual(response.status_code, 200)
content = loads(response.content)
assert content == {
'config_lock': True,
'status': {
'can_write_config': False,
'can_write_attach': True,
'details': ['OK']
}
}

with override_settings(APPRISE_STATEFUL_MODE='disabled'):
# Status Check (Form based)
response = self.client.get('/status')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'OK')
assert response['Content-Type'].startswith('text/plain')

# JSON Response
response = self.client.get(
'/status', content_type='application/json',
**{'HTTP_CONTENT_TYPE': 'application/json'})
self.assertEqual(response.status_code, 200)
content = loads(response.content)
assert content == {
'config_lock': False,
'status': {
'can_write_config': False,
'can_write_attach': True,
'details': ['OK']
}
}

with override_settings(APPRISE_ATTACH_SIZE=0):
# Status Check (Form based)
response = self.client.get('/status')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'OK')
assert response['Content-Type'].startswith('text/plain')

# JSON Response
response = self.client.get(
'/status', content_type='application/json',
**{'HTTP_CONTENT_TYPE': 'application/json'})
self.assertEqual(response.status_code, 200)
content = loads(response.content)
assert content == {
'config_lock': False,
'status': {
'can_write_config': True,
'can_write_attach': False,
'details': ['OK']
}
}

with override_settings(APPRISE_MAX_ATTACHMENTS=0):
# Status Check (Form based)
response = self.client.get('/status')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'OK')
assert response['Content-Type'].startswith('text/plain')

# JSON Response
response = self.client.get(
'/status', content_type='application/json',
**{'HTTP_CONTENT_TYPE': 'application/json'})
self.assertEqual(response.status_code, 200)
content = loads(response.content)
assert content == {
'config_lock': False,
'status': {
'can_write_config': True,
'can_write_attach': False,
'details': ['OK']
}
}

def test_healthcheck_library(self):
"""
Test underlining healthcheck library
"""

result = healthcheck(lazy=True)
assert result == {
'can_write_config': True,
'can_write_attach': True,
'details': ['OK']
}

# A Double lazy check
result = healthcheck(lazy=True)
assert result == {
'can_write_config': True,
'can_write_attach': True,
'details': ['OK']
}

# Force a lazy check where we can't acquire the modify time
with mock.patch('os.path.getmtime') as mock_getmtime:
mock_getmtime.side_effect = FileNotFoundError()
result = healthcheck(lazy=True)
# We still succeed; we just don't leverage our lazy check
# which prevents addition (unnessisary) writes
assert result == {
'can_write_config': True,
'can_write_attach': True,
'details': ['OK'],
}

# Force a non-lazy check
with mock.patch('os.makedirs') as mock_makedirs:
mock_makedirs.side_effect = OSError()
result = healthcheck(lazy=False)
assert result == {
'can_write_config': False,
'can_write_attach': False,
'details': [
'CONFIG_PERMISSION_ISSUE',
'ATTACH_PERMISSION_ISSUE',
]}

mock_makedirs.side_effect = (None, OSError())
result = healthcheck(lazy=False)
assert result == {
'can_write_config': True,
'can_write_attach': False,
'details': [
'ATTACH_PERMISSION_ISSUE',
]}

mock_makedirs.side_effect = (OSError(), None)
result = healthcheck(lazy=False)
assert result == {
'can_write_config': False,
'can_write_attach': True,
'details': [
'CONFIG_PERMISSION_ISSUE',
]}
1 change: 0 additions & 1 deletion apprise_api/api/tests/test_payload_mapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,6 @@ def test_remap_fields(self):
'body': 'the message',
}


#
# mapping of fields don't align - test 6
#
Expand Down
2 changes: 1 addition & 1 deletion apprise_api/api/tests/test_stateless_notify.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ def test_notify(self, mock_notify):
# We sent the notification successfully (use our rule mapping)
# FORM
response = self.client.post(
f'/notify/?:payload=body&:fmt=format&:extra=urls',
'/notify/?:payload=body&:fmt=format&:extra=urls',
form_data)
assert response.status_code == 200
assert mock_notify.call_count == 1
Expand Down
18 changes: 16 additions & 2 deletions apprise_api/api/tests/test_webhook.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,15 +85,29 @@ def test_webhook_testing(self, mock_post):
mock_post.reset_mock()

with override_settings(APPRISE_WEBHOOK_URL='invalid'):
# Invalid wbhook defined
# Invalid webhook defined
send_webhook({})
assert mock_post.call_count == 0

mock_post.reset_mock()

with override_settings(APPRISE_WEBHOOK_URL=None):
# Invalid webhook defined
send_webhook({})
assert mock_post.call_count == 0

mock_post.reset_mock()

with override_settings(APPRISE_WEBHOOK_URL='http://$#@'):
# Invalid hostname defined
send_webhook({})
assert mock_post.call_count == 0

mock_post.reset_mock()

with override_settings(
APPRISE_WEBHOOK_URL='invalid://hostname'):
# Invalid wbhook defined
# Invalid webhook defined
send_webhook({})
assert mock_post.call_count == 0

Expand Down
3 changes: 3 additions & 0 deletions apprise_api/api/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@
re_path(
r'^$',
views.WelcomeView.as_view(), name='welcome'),
re_path(
r'^status/?$',
views.HealthCheckView.as_view(), name='health'),
re_path(
r'^details/?$',
views.DetailsView.as_view(), name='details'),
Expand Down
Loading

0 comments on commit 135dd4e

Please sign in to comment.