├── .bumpversion.cfg ├── .editorconfig ├── .github └── workflows │ ├── python-release.yml │ └── python-test.yml ├── .gitignore ├── CHANGES ├── LICENSE ├── Makefile ├── README.rst ├── docs ├── Makefile ├── _templates │ └── sidebar-intro.html ├── conf.py ├── index.rst ├── make.bat └── requirements.txt ├── pyproject.toml ├── sandbox ├── __init__.py ├── manage.py ├── settings.py ├── urls.py └── wsgi.py ├── setup.cfg ├── setup.py ├── src └── django_healthchecks │ ├── __init__.py │ ├── admin.py │ ├── checker.py │ ├── contrib.py │ ├── heartbeats.py │ ├── migrations │ ├── 0001_initial.py │ └── __init__.py │ ├── models.py │ ├── urls.py │ └── views.py ├── tests ├── conftest.py ├── test_checker.py ├── test_contrib.py ├── test_heartbeats.py ├── test_urls.py └── test_views.py └── tox.ini /.bumpversion.cfg: -------------------------------------------------------------------------------- 1 | [bumpversion] 2 | current_version = 1.5.0 3 | commit = true 4 | tag = true 5 | tag_name = {new_version} 6 | 7 | [bumpversion:file:setup.py] 8 | 9 | [bumpversion:file:docs/conf.py] 10 | 11 | [bumpversion:file:src/django_healthchecks/__init__.py] 12 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*.py] 4 | line_length = 89 5 | multi_line_output = 4 6 | balanced_wrapping = true 7 | known_first_party = django_healthchecks,tests 8 | use_parentheses = true 9 | 10 | [*.yml] 11 | indent_size = 2 12 | 13 | 14 | [Makefile] 15 | indent_style = tab 16 | indent_size = 4 17 | -------------------------------------------------------------------------------- /.github/workflows/python-release.yml: -------------------------------------------------------------------------------- 1 | name: Release to PyPi 2 | 3 | on: 4 | release: 5 | types: [created] 6 | 7 | jobs: 8 | release: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v2 12 | - name: Set up Python 3.7 13 | uses: actions/setup-python@v1 14 | with: 15 | python-version: 3.7 16 | - name: Install build requirements 17 | run: python -m pip install wheel 18 | - name: Build package 19 | run: python setup.py sdist bdist_wheel 20 | - name: Publish package 21 | uses: pypa/gh-action-pypi-publish@master 22 | with: 23 | user: __token__ 24 | password: ${{ secrets.pypi_password }} 25 | -------------------------------------------------------------------------------- /.github/workflows/python-test.yml: -------------------------------------------------------------------------------- 1 | name: Python Tests 2 | 3 | on: [push] 4 | 5 | jobs: 6 | 7 | format: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v2 11 | - name: Set up Python 3.10 12 | uses: actions/setup-python@v1 13 | with: 14 | python-version: "3.10" 15 | - name: Install dependencies 16 | run: pip install tox 17 | - name: Validate formatting 18 | run: tox -e format 19 | 20 | test: 21 | runs-on: ubuntu-latest 22 | strategy: 23 | max-parallel: 4 24 | matrix: 25 | tox_env: 26 | - py38-django32 27 | - py39-django32 28 | - py310-django32 29 | - py38-django40 30 | - py39-django40 31 | - py310-django40 32 | include: 33 | - python-version: "3.8" 34 | tox_env: py38-django32 35 | - python-version: "3.9" 36 | tox_env: py39-django32 37 | - python-version: "3.10" 38 | tox_env: py310-django32 39 | - python-version: "3.8" 40 | tox_env: py38-django40 41 | - python-version: "3.9" 42 | tox_env: py39-django40 43 | - python-version: "3.10" 44 | tox_env: py310-django40 45 | steps: 46 | - uses: actions/checkout@v2 47 | - name: Set up Python ${{ matrix.python-version }} 48 | uses: actions/setup-python@v1 49 | with: 50 | python-version: ${{ matrix.python-version }} 51 | - name: Install dependencies 52 | run: | 53 | python -m pip install --upgrade pip 54 | pip install tox[toml] 55 | - name: Test with tox 56 | run: tox -e ${{ matrix.tox_env }} 57 | - name: Prepare artifacts 58 | run: mkdir .coverage-data && mv .coverage.* .coverage-data/ 59 | - uses: actions/upload-artifact@master 60 | with: 61 | name: coverage-data 62 | path: .coverage-data/ 63 | 64 | coverage: 65 | runs-on: ubuntu-latest 66 | needs: [test] 67 | steps: 68 | - uses: actions/checkout@v2 69 | - uses: actions/download-artifact@master 70 | with: 71 | name: coverage-data 72 | path: . 73 | - name: Set up Python 3.10 74 | uses: actions/setup-python@v1 75 | with: 76 | python-version: "3.10" 77 | - name: Install dependencies 78 | run: | 79 | python -m pip install --upgrade pip 80 | pip install tox 81 | - name: Prepare Coverage report 82 | run: tox -e coverage-report 83 | - name: Upload to codecov 84 | uses: codecov/codecov-action@v1.0.6 85 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.egg-info 2 | *.pyc 3 | *.sqlite* 4 | .tox 5 | .coverage 6 | .coverage.* 7 | .eggs 8 | .cache 9 | .python-version 10 | .venv 11 | .pytest_cache/ 12 | 13 | /build/ 14 | /dist/ 15 | /docs/_build/ 16 | /htmlcov/ 17 | 18 | 19 | # Editors 20 | .idea/ 21 | .vscode/ 22 | -------------------------------------------------------------------------------- /CHANGES: -------------------------------------------------------------------------------- 1 | 2.0.0 (unreleased) 2 | ================== 3 | - This version now only supports Python 3.5+ and Django > 2.2, although earlier 4 | versions might still work. 5 | - Implemented heartbeat support. With this healthcheck you can write add 6 | 'last active' flag to the database which is then used by a healthcheck 7 | endpoint to see if it was updated recently. This is for example really 8 | useful for background tasks (e.g. celery) 9 | - Allow passing in the a custom status code for errors via an HTTP header, by 10 | default 'X-HEALTHCHECK-ERROR-CODE'. This is helpful for kubernetes 11 | healthchecks which can only act on http status codes. 12 | 13 | 14 | 1.4.2 (2018-03-08) 15 | ================== 16 | - Fix bumpversion error 17 | 18 | 19 | 1.4.1 (2018-03-08) 20 | ================== 21 | - Fix returning non-bool data from the HealthCheckServiceView 22 | 23 | 24 | 1.4.0 (2018-03-08) 25 | ================== 26 | - Add support for nested remote healthchecks (#10) 27 | 28 | 29 | 1.3.0 (2018-02-14) 30 | ================== 31 | - Add Django 2.0 support (#9) 32 | - Correctly close the db cursor (#6) 33 | 34 | 35 | 1.2.0 (2018-01-30) 36 | ================== 37 | - Wrap the basic auth header value in force_text() 38 | 39 | 40 | 1.1.0 (2016-10-09) 41 | ================== 42 | - Fix healthcheck detail view page (#4) 43 | 44 | 45 | 1.0.0 (2016-08-13) 46 | ================== 47 | - 1.0.0 release (including docs) 48 | 49 | 50 | 0.7.1 (2016-04-02) 51 | ================== 52 | - Minor release to fix readme on pypi 53 | 54 | 55 | 0.7.0 (2016-04-01) 56 | ================== 57 | - Introduce the `HEALTH_CHECKS_BASIC_AUTH` setting. This allows setting 58 | authentication for specific (or all) healthcheck endpoints 59 | 60 | 61 | 0.6.0 (2016-02-02) 62 | ================== 63 | - Optionally allow checks to receive the request. This allows the remote_addr 64 | check which allows you to check if the proxy / x-forwarded-for is correctly 65 | set. 66 | 67 | 68 | 0.5.0 (2016-01-16) 69 | ================== 70 | - Allow setting a HTTP status code for failures (`HEALTH_CHECKS_ERROR_CODE`) 71 | 72 | 73 | 0.4.1 (2015-11-24) 74 | ================== 75 | - Make the wheel file universal (py2/py3) 76 | 77 | 0.4.0 (2015-11-24) 78 | ================== 79 | - Add support for Python 3.4 and Python 3.5 (Arthur Skowronek) 80 | 81 | 82 | 0.3.1 (2015-11-12) 83 | ================== 84 | - Release 0.3.0 was broken (didn't test..), add unittests and fix issue 85 | 86 | 87 | 0.3.0 (2015-11-12) 88 | ================== 89 | - Add simple cache checker in contrib 90 | 91 | 92 | 0.2.0 (2015-08-05) 93 | ================== 94 | - Set proper caching headers (no-cache, no-store, max-age=0) 95 | 96 | 97 | 0.1.2 (2015-07-13) 98 | ================== 99 | - Return raw status value instead of forcing it to a boolean on the 100 | detail page. 101 | 102 | 103 | 0.1.1 (2015-05-12) 104 | ================== 105 | - Use status code 200 instead of 500 for failing checks 106 | 107 | 108 | 0.1.0 (2015-03-10) 109 | ================== 110 | - Initial release 111 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Michael 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: install test upload docs 2 | 3 | 4 | install: 5 | pip install -e .[docs,test] 6 | 7 | format: 8 | isort src tests 9 | black src/ tests/ 10 | 11 | test: 12 | py.test 13 | 14 | retest: 15 | py.test -vvv --lf 16 | 17 | coverage: 18 | py.test --cov=django_healthchecks --cov-report=term-missing --cov-report=html 19 | 20 | docs: 21 | $(MAKE) -C docs html 22 | 23 | release: 24 | rm -rf dist/* 25 | python setup.py sdist bdist_wheel 26 | twine upload dist/* 27 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | =================== 2 | django-healthchecks 3 | =================== 4 | 5 | Simple Django app/framework to publish health check for monitoring purposes 6 | 7 | Features: 8 | 9 | * Custom checks via Python functions 10 | * Remote healthchecks 11 | * Heartbeat monitoring 12 | 13 | 14 | Status 15 | ====== 16 | .. image:: https://github.com/mvantellingen/django-healthchecks/workflows/Python%20Tests/badge.svg 17 | :target: https://github.com/mvantellingen/django-healthchecks/actions?query=workflow%3A%22Python+Tests%22 18 | 19 | .. image:: http://codecov.io/github/mvantellingen/django-healthchecks/coverage.svg?branch=master 20 | :target: http://codecov.io/github/mvantellingen/django-healthchecks?branch=master 21 | 22 | .. image:: https://img.shields.io/pypi/v/django-healthchecks.svg 23 | :target: https://pypi.python.org/pypi/django-healthchecks/ 24 | 25 | Installation 26 | ============ 27 | 28 | .. code-block:: shell 29 | 30 | pip install django_healthchecks 31 | 32 | 33 | Usage 34 | ===== 35 | 36 | Add the following to your urls.py: 37 | 38 | 39 | .. code-block:: python 40 | 41 | url(r'^healthchecks/', include('django_healthchecks.urls')), 42 | 43 | 44 | Add a setting with the available healthchecks: 45 | 46 | .. code-block:: python 47 | 48 | HEALTH_CHECKS = { 49 | 'postgresql': 'django_healthchecks.contrib.check_database', 50 | 'cache_default': 'django_healthchecks.contrib.check_cache_default', 51 | 'solr': 'your_project.lib.healthchecks.check_solr', 52 | } 53 | 54 | 55 | You can also include healthchecks over http. This is useful when you want to 56 | monitor if depending services are up: 57 | 58 | .. code-block:: python 59 | 60 | HEALTH_CHECKS = { 61 | ... 62 | 'my_microservice': 'https://my-service.services.internal/healthchecks/', 63 | ... 64 | } 65 | 66 | 67 | By default, http health checks will time out after 500ms. You can override this 68 | as follows: 69 | 70 | .. code-block:: python 71 | 72 | HEALTH_CHECKS_HTTP_TIMEOUT = 0.5 73 | 74 | 75 | By default the status code is always 200, you can change this to something 76 | else by using the `HEALTH_CHECKS_ERROR_CODE` setting: 77 | 78 | .. code-block:: python 79 | 80 | HEALTH_CHECKS_ERROR_CODE = 503 81 | 82 | 83 | You can also add some simple protection to your healthchecks via basic auth. 84 | This can be specified per check or a wildcard can be used `*`. 85 | 86 | .. code-block:: python 87 | 88 | HEALTH_CHECKS_BASIC_AUTH = { 89 | '*': [('admin', 'pass')], 90 | 'solr': [], 91 | } 92 | 93 | 94 | Using heartbeats 95 | ================ 96 | 97 | Heartbeats give a periodic update, to see whether an service was recently active. 98 | When the service doesn't report back within timeout, a healthcheck can be triggered. 99 | To use heartbeats, add the application to the ``INSTALLED_APPS``: 100 | 101 | .. code-block:: python 102 | 103 | INSTALLED_APPS = [ 104 | ... 105 | "django_healthchecks", 106 | ] 107 | 108 | Include one of these checks: 109 | 110 | .. code-block:: python 111 | 112 | HEALTH_CHECKS = { 113 | ... 114 | 'heartbeats': 'django_healthchecks.contrib.check_heartbeats' 115 | ... 116 | 'expired_heartbeats': 'django_healthchecks.contrib.check_expired_heartbeats', 117 | ... 118 | } 119 | 120 | Optionally, define an initial timeout: 121 | 122 | .. code-block:: python 123 | 124 | HEALTHCHECKS_DEFAULT_HEARTBEAT_TIMEOUT = timedelta(days=1) 125 | 126 | Let your code track the beats: 127 | 128 | .. code-block:: python 129 | 130 | from datetime import timedelta 131 | from django_healthchecks.heartbeats import update_heartbeat 132 | 133 | update_heartbeat("myservice.name", default_timeout=timedelta(days=2)) 134 | 135 | Or use the decorator: 136 | 137 | .. code-block:: python 138 | 139 | from django_healthchecks.heartbeats import update_heartbeat_on_success 140 | 141 | @update_heartbeat_on_success("myservice.name", default_timeout=...) 142 | def long_running_task(): 143 | .... 144 | 145 | Each time ``update_heartbeat()`` is called, the heartbeat is reset. 146 | When a heartbeat didn't receive an update before it's ``timeout``, 147 | the service name be mentioned in the ``check_expired_heartbeats`` check. 148 | 149 | Updating timeouts 150 | ~~~~~~~~~~~~~~~~~ 151 | 152 | The ``default_timeout`` parameter is only assigned upon creation. Any updates 153 | happen through the Django admin. To update the timeout automatically on 154 | code deployment, use the ``timeout`` parameter instead. This will replace the 155 | stored timeout value each time the ``update_heartbeat()`` function 156 | is called, erasing any changes made in the Django admin. 157 | 158 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # Internal variables. 11 | PAPEROPT_a4 = -D latex_paper_size=a4 12 | PAPEROPT_letter = -D latex_paper_size=letter 13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 14 | # the i18n builder cannot share the environment and doctrees with the others 15 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 16 | 17 | .PHONY: help 18 | help: 19 | @echo "Please use \`make ' where is one of" 20 | @echo " html to make standalone HTML files" 21 | @echo " dirhtml to make HTML files named index.html in directories" 22 | @echo " singlehtml to make a single large HTML file" 23 | @echo " pickle to make pickle files" 24 | @echo " json to make JSON files" 25 | @echo " htmlhelp to make HTML files and a HTML help project" 26 | @echo " qthelp to make HTML files and a qthelp project" 27 | @echo " applehelp to make an Apple Help Book" 28 | @echo " devhelp to make HTML files and a Devhelp project" 29 | @echo " epub to make an epub" 30 | @echo " epub3 to make an epub3" 31 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 32 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 33 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 34 | @echo " text to make text files" 35 | @echo " man to make manual pages" 36 | @echo " texinfo to make Texinfo files" 37 | @echo " info to make Texinfo files and run them through makeinfo" 38 | @echo " gettext to make PO message catalogs" 39 | @echo " changes to make an overview of all changed/added/deprecated items" 40 | @echo " xml to make Docutils-native XML files" 41 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 42 | @echo " linkcheck to check all external links for integrity" 43 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 44 | @echo " coverage to run coverage check of the documentation (if enabled)" 45 | @echo " dummy to check syntax errors of document sources" 46 | 47 | .PHONY: clean 48 | clean: 49 | rm -rf $(BUILDDIR)/* 50 | 51 | .PHONY: html 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | .PHONY: dirhtml 58 | dirhtml: 59 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 60 | @echo 61 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 62 | 63 | .PHONY: singlehtml 64 | singlehtml: 65 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 66 | @echo 67 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 68 | 69 | .PHONY: pickle 70 | pickle: 71 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 72 | @echo 73 | @echo "Build finished; now you can process the pickle files." 74 | 75 | .PHONY: json 76 | json: 77 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 78 | @echo 79 | @echo "Build finished; now you can process the JSON files." 80 | 81 | .PHONY: htmlhelp 82 | htmlhelp: 83 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 84 | @echo 85 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 86 | ".hhp project file in $(BUILDDIR)/htmlhelp." 87 | 88 | .PHONY: qthelp 89 | qthelp: 90 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 91 | @echo 92 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 93 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 94 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/DjangoHealthchecks.qhcp" 95 | @echo "To view the help file:" 96 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/DjangoHealthchecks.qhc" 97 | 98 | .PHONY: applehelp 99 | applehelp: 100 | $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp 101 | @echo 102 | @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." 103 | @echo "N.B. You won't be able to view it unless you put it in" \ 104 | "~/Library/Documentation/Help or install it in your application" \ 105 | "bundle." 106 | 107 | .PHONY: devhelp 108 | devhelp: 109 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 110 | @echo 111 | @echo "Build finished." 112 | @echo "To view the help file:" 113 | @echo "# mkdir -p $$HOME/.local/share/devhelp/DjangoHealthchecks" 114 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/DjangoHealthchecks" 115 | @echo "# devhelp" 116 | 117 | .PHONY: epub 118 | epub: 119 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 120 | @echo 121 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 122 | 123 | .PHONY: epub3 124 | epub3: 125 | $(SPHINXBUILD) -b epub3 $(ALLSPHINXOPTS) $(BUILDDIR)/epub3 126 | @echo 127 | @echo "Build finished. The epub3 file is in $(BUILDDIR)/epub3." 128 | 129 | .PHONY: latex 130 | latex: 131 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 132 | @echo 133 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 134 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 135 | "(use \`make latexpdf' here to do that automatically)." 136 | 137 | .PHONY: latexpdf 138 | latexpdf: 139 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 140 | @echo "Running LaTeX files through pdflatex..." 141 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 142 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 143 | 144 | .PHONY: latexpdfja 145 | latexpdfja: 146 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 147 | @echo "Running LaTeX files through platex and dvipdfmx..." 148 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 149 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 150 | 151 | .PHONY: text 152 | text: 153 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 154 | @echo 155 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 156 | 157 | .PHONY: man 158 | man: 159 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 160 | @echo 161 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 162 | 163 | .PHONY: texinfo 164 | texinfo: 165 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 166 | @echo 167 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 168 | @echo "Run \`make' in that directory to run these through makeinfo" \ 169 | "(use \`make info' here to do that automatically)." 170 | 171 | .PHONY: info 172 | info: 173 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 174 | @echo "Running Texinfo files through makeinfo..." 175 | make -C $(BUILDDIR)/texinfo info 176 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 177 | 178 | .PHONY: gettext 179 | gettext: 180 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 181 | @echo 182 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 183 | 184 | .PHONY: changes 185 | changes: 186 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 187 | @echo 188 | @echo "The overview file is in $(BUILDDIR)/changes." 189 | 190 | .PHONY: linkcheck 191 | linkcheck: 192 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 193 | @echo 194 | @echo "Link check complete; look for any errors in the above output " \ 195 | "or in $(BUILDDIR)/linkcheck/output.txt." 196 | 197 | .PHONY: doctest 198 | doctest: 199 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 200 | @echo "Testing of doctests in the sources finished, look at the " \ 201 | "results in $(BUILDDIR)/doctest/output.txt." 202 | 203 | .PHONY: coverage 204 | coverage: 205 | $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage 206 | @echo "Testing of coverage in the sources finished, look at the " \ 207 | "results in $(BUILDDIR)/coverage/python.txt." 208 | 209 | .PHONY: xml 210 | xml: 211 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 212 | @echo 213 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 214 | 215 | .PHONY: pseudoxml 216 | pseudoxml: 217 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 218 | @echo 219 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 220 | 221 | .PHONY: dummy 222 | dummy: 223 | $(SPHINXBUILD) -b dummy $(ALLSPHINXOPTS) $(BUILDDIR)/dummy 224 | @echo 225 | @echo "Build finished. Dummy builder generates no files." 226 | -------------------------------------------------------------------------------- /docs/_templates/sidebar-intro.html: -------------------------------------------------------------------------------- 1 |

Links

2 |

3 | 5 |

6 | 11 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Django Healthchecks documentation build configuration file, created by 4 | # sphinx-quickstart on Wed Aug 10 17:06:14 2016. 5 | # 6 | # This file is execfile()d with the current directory set to its 7 | # containing dir. 8 | # 9 | # Note that not all possible configuration values are present in this 10 | # autogenerated file. 11 | # 12 | # All configuration values have a default; values that are commented out 13 | # serve to show the default. 14 | 15 | # If extensions (or modules to document with autodoc) are in another directory, 16 | # add these directories to sys.path here. If the directory is relative to the 17 | # documentation root, use os.path.abspath to make it absolute, like shown here. 18 | # 19 | # import os 20 | # import sys 21 | # sys.path.insert(0, os.path.abspath('.')) 22 | 23 | # -- General configuration ------------------------------------------------ 24 | 25 | # If your documentation needs a minimal Sphinx version, state it here. 26 | # 27 | # needs_sphinx = '1.0' 28 | 29 | # Add any Sphinx extension module names here, as strings. They can be 30 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 31 | # ones. 32 | extensions = ['sphinx.ext.autodoc'] 33 | 34 | # Add any paths that contain templates here, relative to this directory. 35 | templates_path = ['_templates'] 36 | 37 | # The suffix(es) of source filenames. 38 | # You can specify multiple suffix as a list of string: 39 | # 40 | # source_suffix = ['.rst', '.md'] 41 | source_suffix = '.rst' 42 | 43 | # The encoding of source files. 44 | # 45 | # source_encoding = 'utf-8-sig' 46 | 47 | # The master toctree document. 48 | master_doc = 'index' 49 | 50 | # General information about the project. 51 | project = u'Django Healthchecks' 52 | project = u'Zeep' 53 | copyright = u'2016, Michael van Tellingen' 54 | author = u'Michael van Tellingen' 55 | 56 | # The version info for the project you're documenting, acts as replacement for 57 | # |version| and |release|, also used in various other places throughout the 58 | # built documents. 59 | # 60 | version = '1.5.0' 61 | release = version 62 | 63 | # The language for content autogenerated by Sphinx. Refer to documentation 64 | # for a list of supported languages. 65 | # 66 | # This is also used if you do content translation via gettext catalogs. 67 | # Usually you set "language" from the command line for these cases. 68 | language = None 69 | 70 | # There are two options for replacing |today|: either, you set today to some 71 | # non-false value, then it is used: 72 | # 73 | # today = '' 74 | # 75 | # Else, today_fmt is used as the format for a strftime call. 76 | # 77 | # today_fmt = '%B %d, %Y' 78 | 79 | # List of patterns, relative to source directory, that match files and 80 | # directories to ignore when looking for source files. 81 | # This patterns also effect to html_static_path and html_extra_path 82 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] 83 | 84 | # The reST default role (used for this markup: `text`) to use for all 85 | # documents. 86 | # 87 | # default_role = None 88 | 89 | # If true, '()' will be appended to :func: etc. cross-reference text. 90 | # 91 | # add_function_parentheses = True 92 | 93 | # If true, the current module name will be prepended to all description 94 | # unit titles (such as .. function::). 95 | # 96 | # add_module_names = True 97 | 98 | # If true, sectionauthor and moduleauthor directives will be shown in the 99 | # output. They are ignored by default. 100 | # 101 | # show_authors = False 102 | 103 | # The name of the Pygments (syntax highlighting) style to use. 104 | pygments_style = 'sphinx' 105 | 106 | # A list of ignored prefixes for module index sorting. 107 | # modindex_common_prefix = [] 108 | 109 | # If true, keep warnings as "system message" paragraphs in the built documents. 110 | # keep_warnings = False 111 | 112 | # If true, `todo` and `todoList` produce output, else they produce nothing. 113 | todo_include_todos = False 114 | 115 | 116 | # -- Options for HTML output ---------------------------------------------- 117 | 118 | # The theme to use for HTML and HTML Help pages. See the documentation for 119 | # a list of builtin themes. 120 | # 121 | html_theme = 'alabaster' 122 | 123 | # Theme options are theme-specific and customize the look and feel of a theme 124 | # further. For a list of options available for each theme, see the 125 | # documentation. 126 | # 127 | # html_theme_options = {} 128 | html_theme_options = { 129 | 'github_user': 'mvantellingen', 130 | 'github_banner': True, 131 | 'github_repo': 'django-healthchecks', 132 | 'travis_button': True, 133 | 'codecov_button': True, 134 | 'analytics_id': 'UA-75907833-3', 135 | } 136 | 137 | # Add any paths that contain custom themes here, relative to this directory. 138 | # html_theme_path = [] 139 | 140 | # The name for this set of Sphinx documents. 141 | # " v documentation" by default. 142 | # 143 | # html_title = u'Django Healthchecks v0.1.0' 144 | 145 | # A shorter title for the navigation bar. Default is the same as html_title. 146 | # 147 | # html_short_title = None 148 | 149 | # The name of an image file (relative to this directory) to place at the top 150 | # of the sidebar. 151 | # 152 | # html_logo = None 153 | 154 | # The name of an image file (relative to this directory) to use as a favicon of 155 | # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 156 | # pixels large. 157 | # 158 | # html_favicon = None 159 | 160 | # Add any paths that contain custom static files (such as style sheets) here, 161 | # relative to this directory. They are copied after the builtin static files, 162 | # so a file named "default.css" will overwrite the builtin "default.css". 163 | html_static_path = ['_static'] 164 | 165 | # Add any extra paths that contain custom files (such as robots.txt or 166 | # .htaccess) here, relative to this directory. These files are copied 167 | # directly to the root of the documentation. 168 | # 169 | # html_extra_path = [] 170 | 171 | # If not None, a 'Last updated on:' timestamp is inserted at every page 172 | # bottom, using the given strftime format. 173 | # The empty string is equivalent to '%b %d, %Y'. 174 | # 175 | # html_last_updated_fmt = None 176 | 177 | # If true, SmartyPants will be used to convert quotes and dashes to 178 | # typographically correct entities. 179 | # 180 | # html_use_smartypants = True 181 | 182 | # Custom sidebar templates, maps document names to template names. 183 | # 184 | # html_sidebars = {} 185 | # Custom sidebar templates, maps document names to template names. 186 | html_sidebars = { 187 | '*': [ 188 | 'sidebar-intro.html', 189 | ] 190 | } 191 | 192 | 193 | # Additional templates that should be rendered to pages, maps page names to 194 | # template names. 195 | # 196 | # html_additional_pages = {} 197 | 198 | # If false, no module index is generated. 199 | # 200 | # html_domain_indices = True 201 | 202 | # If false, no index is generated. 203 | # 204 | # html_use_index = True 205 | 206 | # If true, the index is split into individual pages for each letter. 207 | # 208 | # html_split_index = False 209 | 210 | # If true, links to the reST sources are added to the pages. 211 | # 212 | # html_show_sourcelink = True 213 | 214 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 215 | # 216 | # html_show_sphinx = True 217 | 218 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 219 | # 220 | # html_show_copyright = True 221 | 222 | # If true, an OpenSearch description file will be output, and all pages will 223 | # contain a tag referring to it. The value of this option must be the 224 | # base URL from which the finished HTML is served. 225 | # 226 | # html_use_opensearch = '' 227 | 228 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 229 | # html_file_suffix = None 230 | 231 | # Language to be used for generating the HTML full-text search index. 232 | # Sphinx supports the following languages: 233 | # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' 234 | # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh' 235 | # 236 | # html_search_language = 'en' 237 | 238 | # A dictionary with options for the search language support, empty by default. 239 | # 'ja' uses this config value. 240 | # 'zh' user can custom change `jieba` dictionary path. 241 | # 242 | # html_search_options = {'type': 'default'} 243 | 244 | # The name of a javascript file (relative to the configuration directory) that 245 | # implements a search results scorer. If empty, the default will be used. 246 | # 247 | # html_search_scorer = 'scorer.js' 248 | 249 | # Output file base name for HTML help builder. 250 | htmlhelp_basename = 'DjangoHealthchecksdoc' 251 | 252 | # -- Options for LaTeX output --------------------------------------------- 253 | 254 | latex_elements = { 255 | # The paper size ('letterpaper' or 'a4paper'). 256 | # 257 | # 'papersize': 'letterpaper', 258 | 259 | # The font size ('10pt', '11pt' or '12pt'). 260 | # 261 | # 'pointsize': '10pt', 262 | 263 | # Additional stuff for the LaTeX preamble. 264 | # 265 | # 'preamble': '', 266 | 267 | # Latex figure (float) alignment 268 | # 269 | # 'figure_align': 'htbp', 270 | } 271 | 272 | # Grouping the document tree into LaTeX files. List of tuples 273 | # (source start file, target name, title, 274 | # author, documentclass [howto, manual, or own class]). 275 | latex_documents = [ 276 | (master_doc, 'DjangoHealthchecks.tex', u'Django Healthchecks Documentation', 277 | u'Michael van Tellingen', 'manual'), 278 | ] 279 | 280 | # The name of an image file (relative to this directory) to place at the top of 281 | # the title page. 282 | # 283 | # latex_logo = None 284 | 285 | # For "manual" documents, if this is true, then toplevel headings are parts, 286 | # not chapters. 287 | # 288 | # latex_use_parts = False 289 | 290 | # If true, show page references after internal links. 291 | # 292 | # latex_show_pagerefs = False 293 | 294 | # If true, show URL addresses after external links. 295 | # 296 | # latex_show_urls = False 297 | 298 | # Documents to append as an appendix to all manuals. 299 | # 300 | # latex_appendices = [] 301 | 302 | # It false, will not define \strong, \code, itleref, \crossref ... but only 303 | # \sphinxstrong, ..., \sphinxtitleref, ... To help avoid clash with user added 304 | # packages. 305 | # 306 | # latex_keep_old_macro_names = True 307 | 308 | # If false, no module index is generated. 309 | # 310 | # latex_domain_indices = True 311 | 312 | 313 | # -- Options for manual page output --------------------------------------- 314 | 315 | # One entry per manual page. List of tuples 316 | # (source start file, name, description, authors, manual section). 317 | man_pages = [ 318 | (master_doc, 'wsgibasicauth', u'Django Healthchecks Documentation', 319 | [author], 1) 320 | ] 321 | 322 | # If true, show URL addresses after external links. 323 | # 324 | # man_show_urls = False 325 | 326 | 327 | # -- Options for Texinfo output ------------------------------------------- 328 | 329 | # Grouping the document tree into Texinfo files. List of tuples 330 | # (source start file, target name, title, author, 331 | # dir menu entry, description, category) 332 | texinfo_documents = [ 333 | (master_doc, 'DjangoHealthchecks', u'Django Healthchecks Documentation', 334 | author, 'DjangoHealthchecks', 'One line description of project.', 335 | 'Miscellaneous'), 336 | ] 337 | 338 | # Documents to append as an appendix to all manuals. 339 | # 340 | # texinfo_appendices = [] 341 | 342 | # If false, no module index is generated. 343 | # 344 | # texinfo_domain_indices = True 345 | 346 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 347 | # 348 | # texinfo_show_urls = 'footnote' 349 | 350 | # If true, do not generate a @detailmenu in the "Top" node's menu. 351 | # 352 | # texinfo_no_detailmenu = False 353 | 354 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | =================== 2 | django-healthchecks 3 | =================== 4 | 5 | Simple Django app/framework to publish health check for monitoring purposes 6 | 7 | Installation 8 | ============ 9 | 10 | .. code-block:: shell 11 | 12 | pip install django_healthchecks 13 | 14 | Usage 15 | ===== 16 | 17 | Add the following to your urls.py: 18 | 19 | 20 | .. code-block:: python 21 | 22 | url(r'^healthchecks/', include('django_healthchecks.urls')), 23 | 24 | Add a setting with the available healthchecks: 25 | 26 | .. code-block:: python 27 | 28 | HEALTH_CHECKS = { 29 | 'postgresql': 'django_healthchecks.contrib.check_database', 30 | 'cache_default': 'django_healthchecks.contrib.check_cache_default', 31 | 'solr': 'your_project.lib.healthchecks.check_solr', 32 | } 33 | 34 | By default the status code is always 200, you can change this to something 35 | else by using the `HEALTH_CHECKS_ERROR_CODE` setting: 36 | 37 | 38 | .. code-block:: python 39 | 40 | HEALTH_CHECKS_ERROR_CODE = 503 41 | 42 | 43 | You can also add some simple protection to your healthchecks via basic auth. 44 | This can be specified per check or a wildcard can be used `*`. 45 | 46 | .. code-block:: python 47 | 48 | HEALTH_CHECKS_BASIC_AUTH = { 49 | '*': [('admin', 'pass')], 50 | 'solr': [], 51 | } 52 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. epub3 to make an epub3 31 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 32 | echo. text to make text files 33 | echo. man to make manual pages 34 | echo. texinfo to make Texinfo files 35 | echo. gettext to make PO message catalogs 36 | echo. changes to make an overview over all changed/added/deprecated items 37 | echo. xml to make Docutils-native XML files 38 | echo. pseudoxml to make pseudoxml-XML files for display purposes 39 | echo. linkcheck to check all external links for integrity 40 | echo. doctest to run all doctests embedded in the documentation if enabled 41 | echo. coverage to run coverage check of the documentation if enabled 42 | echo. dummy to check syntax errors of document sources 43 | goto end 44 | ) 45 | 46 | if "%1" == "clean" ( 47 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 48 | del /q /s %BUILDDIR%\* 49 | goto end 50 | ) 51 | 52 | 53 | REM Check if sphinx-build is available and fallback to Python version if any 54 | %SPHINXBUILD% 1>NUL 2>NUL 55 | if errorlevel 9009 goto sphinx_python 56 | goto sphinx_ok 57 | 58 | :sphinx_python 59 | 60 | set SPHINXBUILD=python -m sphinx.__init__ 61 | %SPHINXBUILD% 2> nul 62 | if errorlevel 9009 ( 63 | echo. 64 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 65 | echo.installed, then set the SPHINXBUILD environment variable to point 66 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 67 | echo.may add the Sphinx directory to PATH. 68 | echo. 69 | echo.If you don't have Sphinx installed, grab it from 70 | echo.http://sphinx-doc.org/ 71 | exit /b 1 72 | ) 73 | 74 | :sphinx_ok 75 | 76 | 77 | if "%1" == "html" ( 78 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 79 | if errorlevel 1 exit /b 1 80 | echo. 81 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 82 | goto end 83 | ) 84 | 85 | if "%1" == "dirhtml" ( 86 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 87 | if errorlevel 1 exit /b 1 88 | echo. 89 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 90 | goto end 91 | ) 92 | 93 | if "%1" == "singlehtml" ( 94 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 95 | if errorlevel 1 exit /b 1 96 | echo. 97 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 98 | goto end 99 | ) 100 | 101 | if "%1" == "pickle" ( 102 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 103 | if errorlevel 1 exit /b 1 104 | echo. 105 | echo.Build finished; now you can process the pickle files. 106 | goto end 107 | ) 108 | 109 | if "%1" == "json" ( 110 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 111 | if errorlevel 1 exit /b 1 112 | echo. 113 | echo.Build finished; now you can process the JSON files. 114 | goto end 115 | ) 116 | 117 | if "%1" == "htmlhelp" ( 118 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 119 | if errorlevel 1 exit /b 1 120 | echo. 121 | echo.Build finished; now you can run HTML Help Workshop with the ^ 122 | .hhp project file in %BUILDDIR%/htmlhelp. 123 | goto end 124 | ) 125 | 126 | if "%1" == "qthelp" ( 127 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 128 | if errorlevel 1 exit /b 1 129 | echo. 130 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 131 | .qhcp project file in %BUILDDIR%/qthelp, like this: 132 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\DjangoHealthchecks.qhcp 133 | echo.To view the help file: 134 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\DjangoHealthchecks.ghc 135 | goto end 136 | ) 137 | 138 | if "%1" == "devhelp" ( 139 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 140 | if errorlevel 1 exit /b 1 141 | echo. 142 | echo.Build finished. 143 | goto end 144 | ) 145 | 146 | if "%1" == "epub" ( 147 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 148 | if errorlevel 1 exit /b 1 149 | echo. 150 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 151 | goto end 152 | ) 153 | 154 | if "%1" == "epub3" ( 155 | %SPHINXBUILD% -b epub3 %ALLSPHINXOPTS% %BUILDDIR%/epub3 156 | if errorlevel 1 exit /b 1 157 | echo. 158 | echo.Build finished. The epub3 file is in %BUILDDIR%/epub3. 159 | goto end 160 | ) 161 | 162 | if "%1" == "latex" ( 163 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 164 | if errorlevel 1 exit /b 1 165 | echo. 166 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 167 | goto end 168 | ) 169 | 170 | if "%1" == "latexpdf" ( 171 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 172 | cd %BUILDDIR%/latex 173 | make all-pdf 174 | cd %~dp0 175 | echo. 176 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 177 | goto end 178 | ) 179 | 180 | if "%1" == "latexpdfja" ( 181 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 182 | cd %BUILDDIR%/latex 183 | make all-pdf-ja 184 | cd %~dp0 185 | echo. 186 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 187 | goto end 188 | ) 189 | 190 | if "%1" == "text" ( 191 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 192 | if errorlevel 1 exit /b 1 193 | echo. 194 | echo.Build finished. The text files are in %BUILDDIR%/text. 195 | goto end 196 | ) 197 | 198 | if "%1" == "man" ( 199 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 200 | if errorlevel 1 exit /b 1 201 | echo. 202 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 203 | goto end 204 | ) 205 | 206 | if "%1" == "texinfo" ( 207 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 208 | if errorlevel 1 exit /b 1 209 | echo. 210 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 211 | goto end 212 | ) 213 | 214 | if "%1" == "gettext" ( 215 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 216 | if errorlevel 1 exit /b 1 217 | echo. 218 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 219 | goto end 220 | ) 221 | 222 | if "%1" == "changes" ( 223 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 224 | if errorlevel 1 exit /b 1 225 | echo. 226 | echo.The overview file is in %BUILDDIR%/changes. 227 | goto end 228 | ) 229 | 230 | if "%1" == "linkcheck" ( 231 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 232 | if errorlevel 1 exit /b 1 233 | echo. 234 | echo.Link check complete; look for any errors in the above output ^ 235 | or in %BUILDDIR%/linkcheck/output.txt. 236 | goto end 237 | ) 238 | 239 | if "%1" == "doctest" ( 240 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 241 | if errorlevel 1 exit /b 1 242 | echo. 243 | echo.Testing of doctests in the sources finished, look at the ^ 244 | results in %BUILDDIR%/doctest/output.txt. 245 | goto end 246 | ) 247 | 248 | if "%1" == "coverage" ( 249 | %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage 250 | if errorlevel 1 exit /b 1 251 | echo. 252 | echo.Testing of coverage in the sources finished, look at the ^ 253 | results in %BUILDDIR%/coverage/python.txt. 254 | goto end 255 | ) 256 | 257 | if "%1" == "xml" ( 258 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 259 | if errorlevel 1 exit /b 1 260 | echo. 261 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 262 | goto end 263 | ) 264 | 265 | if "%1" == "pseudoxml" ( 266 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 267 | if errorlevel 1 exit /b 1 268 | echo. 269 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 270 | goto end 271 | ) 272 | 273 | if "%1" == "dummy" ( 274 | %SPHINXBUILD% -b dummy %ALLSPHINXOPTS% %BUILDDIR%/dummy 275 | if errorlevel 1 exit /b 1 276 | echo. 277 | echo.Build finished. Dummy builder generates no files. 278 | goto end 279 | ) 280 | 281 | :end 282 | -------------------------------------------------------------------------------- /docs/requirements.txt: -------------------------------------------------------------------------------- 1 | -e .[docs] 2 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | 2 | [build-system] 3 | requires = ["setuptools>=40.6.0", "wheel"] 4 | build-backend = "setuptools.build_meta" 5 | 6 | [tool.coverage.run] 7 | branch = true 8 | source = ["django_healthchecks"] 9 | 10 | [tool.coverage.paths] 11 | source = ["src", "*/.tox/*/site-packages"] 12 | 13 | [tool.coverage.report] 14 | show_missing = true 15 | 16 | [tool.isort] 17 | line_length = 88 18 | multi_line_output = 3 19 | include_trailing_comma = true 20 | balanced_wrapping = true 21 | default_section = "THIRDPARTY" 22 | known_first_party = ["django_healthchecks", "tests"] 23 | use_parentheses = true 24 | -------------------------------------------------------------------------------- /sandbox/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/labd/django-healthchecks/37e548e8ee2bf15b1afb98f078ee54ec63f1e621/sandbox/__init__.py -------------------------------------------------------------------------------- /sandbox/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") 7 | 8 | from django.core.management import execute_from_command_line 9 | 10 | execute_from_command_line(sys.argv) 11 | -------------------------------------------------------------------------------- /sandbox/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for sandbox project. 3 | 4 | Generated by 'django-admin startproject' using Django 1.9.4. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.9/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/1.9/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'qk1t#3&b0@vntk9r($_i1^6%9-9_jonad@clifp4htm$$_lj36' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | ] 41 | 42 | MIDDLEWARE_CLASSES = [ 43 | 'django.middleware.security.SecurityMiddleware', 44 | 'django.contrib.sessions.middleware.SessionMiddleware', 45 | 'django.middleware.common.CommonMiddleware', 46 | 'django.middleware.csrf.CsrfViewMiddleware', 47 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 48 | 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 49 | 'django.contrib.messages.middleware.MessageMiddleware', 50 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 51 | ] 52 | 53 | ROOT_URLCONF = 'urls' 54 | 55 | TEMPLATES = [ 56 | { 57 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 58 | 'DIRS': [], 59 | 'APP_DIRS': True, 60 | 'OPTIONS': { 61 | 'context_processors': [ 62 | 'django.template.context_processors.debug', 63 | 'django.template.context_processors.request', 64 | 'django.contrib.auth.context_processors.auth', 65 | 'django.contrib.messages.context_processors.messages', 66 | ], 67 | }, 68 | }, 69 | ] 70 | 71 | WSGI_APPLICATION = 'wsgi.application' 72 | 73 | 74 | # Database 75 | # https://docs.djangoproject.com/en/1.9/ref/settings/#databases 76 | 77 | DATABASES = { 78 | 'default': { 79 | 'ENGINE': 'django.db.backends.sqlite3', 80 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 81 | } 82 | } 83 | 84 | 85 | # Password validation 86 | # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators 87 | 88 | AUTH_PASSWORD_VALIDATORS = [ 89 | { 90 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 91 | }, 92 | { 93 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 94 | }, 95 | { 96 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 97 | }, 98 | { 99 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 100 | }, 101 | ] 102 | 103 | 104 | # Internationalization 105 | # https://docs.djangoproject.com/en/1.9/topics/i18n/ 106 | 107 | LANGUAGE_CODE = 'en-us' 108 | 109 | TIME_ZONE = 'UTC' 110 | 111 | USE_I18N = True 112 | 113 | USE_L10N = True 114 | 115 | USE_TZ = True 116 | 117 | 118 | # Static files (CSS, JavaScript, Images) 119 | # https://docs.djangoproject.com/en/1.9/howto/static-files/ 120 | 121 | STATIC_URL = '/static/' 122 | 123 | 124 | HEALTH_CHECKS = { 125 | 'public': 'django_healthchecks.contrib.check_dummy_true', 126 | 'private': 'django_healthchecks.contrib.check_dummy_false', 127 | 'remote': 'https://lfd-tst.labd.io/api/healthchecks/', 128 | 'callable': lambda: True, 129 | } 130 | 131 | HEALTH_CHECKS_BASIC_AUTH = { 132 | # '*': [('admin', 'pass')], 133 | 'public': [], 134 | } 135 | -------------------------------------------------------------------------------- /sandbox/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import url, include 2 | 3 | urlpatterns = [ 4 | url(r'^healthchecks/', include('django_healthchecks.urls')), 5 | ] 6 | -------------------------------------------------------------------------------- /sandbox/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for sandbox project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [wheel] 2 | universal = 1 3 | 4 | [tool:pytest] 5 | minversion = 3.0 6 | strict = true 7 | testpaths = tests 8 | django_find_project = false 9 | addopts = --nomigrations --reuse-db 10 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import find_packages, setup 2 | 3 | docs_require = [ 4 | "sphinx>=1.4.0", 5 | ] 6 | 7 | tests_require = [ 8 | "coverage[toml]==5.2", 9 | "pytest==6.2.5", 10 | "pytest-django==3.9.0", 11 | "requests-mock==1.8.0", 12 | "freezegun==0.3.15", 13 | # Linting 14 | "isort==5.0.6", 15 | "flake8==3.8.3", 16 | "flake8-blind-except==0.1.1", 17 | "flake8-debugger==3.2.1", 18 | ] 19 | 20 | setup( 21 | name="django-healthchecks", 22 | version="1.5.0", 23 | description="Simple Django app/framework to publish health checks", 24 | long_description=open("README.rst", "r").read(), 25 | url="https://github.com/mvantellingen/django-healthchecks", 26 | author="Michael van Tellingen", 27 | author_email="michaelvantellingen@gmail.com", 28 | install_requires=[ 29 | "Django>=3.2", 30 | "requests>=2.24.0", 31 | "certifi>=2020.6.20", 32 | ], 33 | tests_require=tests_require, 34 | extras_require={"docs": docs_require, "test": tests_require,}, 35 | use_scm_version=True, 36 | entry_points={}, 37 | package_dir={"": "src"}, 38 | packages=find_packages("src"), 39 | include_package_data=True, 40 | license="MIT", 41 | classifiers=[ 42 | "Development Status :: 5 - Production/Stable", 43 | "Environment :: Web Environment", 44 | "Framework :: Django", 45 | "Framework :: Django :: 3.2", 46 | "Framework :: Django :: 4.0", 47 | "License :: OSI Approved :: MIT License", 48 | "Programming Language :: Python", 49 | "Programming Language :: Python :: 3.8", 50 | "Programming Language :: Python :: 3.9", 51 | "Programming Language :: Python :: 3.10", 52 | ], 53 | zip_safe=False, 54 | ) 55 | -------------------------------------------------------------------------------- /src/django_healthchecks/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = "1.5.0" 2 | -------------------------------------------------------------------------------- /src/django_healthchecks/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from django.templatetags.static import static 3 | from django.utils.formats import localize 4 | from django.utils.html import format_html 5 | from django.utils.timesince import timeuntil 6 | from django.utils.timezone import is_aware, localtime 7 | from django.utils.translation import gettext_lazy as _ 8 | 9 | from django_healthchecks.models import HeartbeatMonitor 10 | 11 | 12 | @admin.register(HeartbeatMonitor) 13 | class HeartbeatMonitorAdmin(admin.ModelAdmin): 14 | """Give an overview of heartbeats.""" 15 | 16 | list_display = ("name", "enabled", "timeout", "last_beat_column") 17 | list_filter = ("enabled",) 18 | readonly_fields = ("last_beat_column", "remaining_time") 19 | fieldsets = ( 20 | ( 21 | None, 22 | { 23 | "fields": ( 24 | "name", 25 | "timeout", 26 | "enabled", 27 | ("last_beat_column", "remaining_time"), 28 | ) 29 | }, 30 | ), 31 | ) 32 | 33 | def has_add_permission(self, request): 34 | # Only code calling HeartbeatMonitor.update() can add objects 35 | return False 36 | 37 | def last_beat_column(self, object): 38 | last_beat = object.last_beat 39 | if is_aware(last_beat): 40 | # Only for USE_TZ=True 41 | last_beat = localtime(last_beat) 42 | 43 | last_beat_str = localize(last_beat) 44 | if object.is_expired: 45 | # Make clearly visible 46 | alert_icon = static("admin/img/icon-alert.svg") 47 | return format_html( 48 | '
' 49 | ' ' 50 | ' {}' 51 | "
", 52 | alert_icon, 53 | last_beat_str, 54 | ) 55 | else: 56 | return last_beat_str 57 | 58 | last_beat_column.admin_order_field = "last_beat" 59 | last_beat_column.short_description = _("Last beat") 60 | 61 | def remaining_time(self, object): 62 | return timeuntil(object.expires_at) 63 | 64 | remaining_time.short_description = _("Time remaining") 65 | -------------------------------------------------------------------------------- /src/django_healthchecks/checker.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import functools 3 | import inspect 4 | 5 | import requests 6 | from django.conf import settings 7 | from django.utils.encoding import force_str 8 | from django.utils.module_loading import import_string 9 | 10 | 11 | class PermissionDenied(Exception): 12 | pass 13 | 14 | 15 | def create_report(request=None): 16 | """Run all checks and return a tuple containing results and boolean to 17 | indicate to indicate if all things are healthy. 18 | 19 | """ 20 | report = {} 21 | has_error = False 22 | 23 | for service, check_func in _get_check_functions(request=request): 24 | report[service] = check_func() or False 25 | 26 | if not report[service]: 27 | has_error = True 28 | return report, not has_error 29 | 30 | 31 | def create_service_result(service, request=None): 32 | functions = list(_get_check_functions(name=service, request=request)) 33 | if not functions: 34 | return 35 | 36 | check_func = functions[0][1] 37 | result = check_func() or False 38 | return result 39 | 40 | 41 | def _get_check_functions(name=None, request=None): 42 | checks = _get_registered_health_checks() 43 | if not checks or (name and name not in checks): 44 | return 45 | 46 | checks = _filter_checks_on_permission(request, checks) 47 | if not checks or (name and name not in checks): 48 | raise PermissionDenied() 49 | 50 | for service, func_string in checks.items(): 51 | if name and name != service: 52 | continue 53 | 54 | if callable(func_string): 55 | check_func = func_string 56 | elif func_string.startswith(("https://", "http://")): 57 | check_func = _http_healthcheck_func(func_string) 58 | else: 59 | check_func = import_string(func_string) 60 | 61 | spec = inspect.getfullargspec(check_func) 62 | if spec.args == ["request"]: 63 | check_func = functools.partial(check_func, request) 64 | 65 | yield service, check_func 66 | 67 | 68 | def _get_registered_health_checks(): 69 | return getattr(settings, "HEALTH_CHECKS", {}) 70 | 71 | 72 | def _http_healthcheck_func(url): 73 | def handle_remote_request(): 74 | try: 75 | response = requests.get(url, timeout=_get_http_healthcheck_timeout()) 76 | except requests.exceptions.RequestException: 77 | return False 78 | 79 | if response.ok: 80 | return response.json() 81 | return False 82 | 83 | return handle_remote_request 84 | 85 | 86 | def _get_http_healthcheck_timeout(): 87 | return getattr(settings, "HEALTH_CHECKS_HTTP_TIMEOUT", 0.5) 88 | 89 | 90 | def _filter_checks_on_permission(request, checks): 91 | permissions = getattr(settings, "HEALTH_CHECKS_BASIC_AUTH", {}) 92 | if not permissions: 93 | return checks 94 | 95 | allowed = {} 96 | for name in checks.keys(): 97 | required_credentials = permissions.get(name, permissions.get("*")) 98 | 99 | if required_credentials: 100 | credentials = _get_basic_auth(request) 101 | if not credentials or credentials not in required_credentials: 102 | continue 103 | 104 | allowed[name] = checks[name] 105 | return allowed 106 | 107 | 108 | def _get_basic_auth(request): 109 | auth = request.META.get("HTTP_AUTHORIZATION") 110 | if not auth: 111 | return 112 | 113 | auth = auth.split() 114 | if len(auth) == 2 and force_str(auth[0]).lower() == "basic": 115 | credentials = base64.b64decode(auth[1]).decode("latin-1") 116 | return tuple(credentials.split(":")) 117 | -------------------------------------------------------------------------------- /src/django_healthchecks/contrib.py: -------------------------------------------------------------------------------- 1 | import uuid 2 | 3 | from django.core.cache import cache 4 | from django.db import connection 5 | 6 | MIGRATION_CACHE = False 7 | 8 | 9 | def check_database(): 10 | """Check if the application can perform a dummy sql query""" 11 | with connection.cursor() as cursor: 12 | cursor.execute("SELECT 1; -- Healthcheck") 13 | row = cursor.fetchone() 14 | return row[0] == 1 15 | 16 | 17 | def check_cache_default(): 18 | """Check if the application can connect to the default cached and 19 | read/write some dummy data. 20 | 21 | """ 22 | dummy = str(uuid.uuid4()) 23 | key = "healthcheck:%s" % dummy 24 | cache.set(key, dummy, timeout=5) 25 | cached_value = cache.get(key) 26 | return cached_value == dummy 27 | 28 | 29 | def check_dummy_true(): 30 | return True 31 | 32 | 33 | def check_dummy_false(request): 34 | return False 35 | 36 | 37 | def check_remote_addr(request): 38 | return request.META["REMOTE_ADDR"] 39 | 40 | 41 | def check_expired_heartbeats(): 42 | """Check which heartbeats have expired.""" 43 | from django_healthchecks.heartbeats import get_expired_heartbeats 44 | 45 | return get_expired_heartbeats() or None 46 | 47 | 48 | def check_heartbeats(): 49 | """Give a dict of each check and it's status.""" 50 | from django_healthchecks.heartbeats import get_heartbeat_statuses 51 | 52 | return get_heartbeat_statuses() or None 53 | 54 | 55 | def check_open_migrations(): 56 | """ 57 | Check if all migrations have run. 58 | 59 | Cache this check on succesfull run as to reduce disk io. 60 | """ 61 | global MIGRATION_CACHE 62 | if MIGRATION_CACHE: 63 | return True 64 | 65 | from django.conf import ImproperlyConfigured 66 | from django.db.migrations.executor import MigrationExecutor 67 | 68 | try: 69 | executor = MigrationExecutor(connection) 70 | except ImproperlyConfigured: 71 | # No databases are configured (or the dummy one) 72 | return None 73 | 74 | plan = executor.migration_plan(executor.loader.graph.leaf_nodes()) 75 | if plan: 76 | return False 77 | 78 | if not MIGRATION_CACHE: 79 | MIGRATION_CACHE = True 80 | return MIGRATION_CACHE 81 | -------------------------------------------------------------------------------- /src/django_healthchecks/heartbeats.py: -------------------------------------------------------------------------------- 1 | """API functions to update heartbeats. 2 | 3 | This module exists to keep external code decoupled from our model-based 4 | implementation. This allows extending the functionality later to support 5 | different mechanisms for tracking heartbeats (e.g. external services). 6 | """ 7 | from functools import wraps 8 | 9 | from django.utils.timezone import now 10 | 11 | from django_healthchecks.models import HeartbeatMonitor 12 | 13 | 14 | def get_expired_heartbeats(): 15 | """Provide a list of all heartbeats that expired. 16 | 17 | :rtype: list 18 | """ 19 | return HeartbeatMonitor.objects.enabled().expired_names() 20 | 21 | 22 | def get_heartbeat_statuses(): 23 | """Provide a dict of ``name: status`` for every heartbeat. 24 | 25 | :rtype: dict 26 | """ 27 | data = HeartbeatMonitor.objects.enabled().status_by_name() 28 | data["__all__"] = all(data.values()) 29 | return data 30 | 31 | 32 | def update_heartbeat(name, default_timeout=None, timeout=None): 33 | """Update a heartbeat monitor. 34 | This tracks a new pulse, so the timer is reset. 35 | 36 | Upon the first call, the ``default_timeout`` can be assigned. 37 | To tune the timeout later, use the Django admin interface, 38 | or make a call that provides the ``timeout`` value. 39 | 40 | :param name: Name of the check. 41 | :type name: str 42 | :param default_timeout: The timeout to use by default on registration. 43 | :type default_timeout: datetime.timedelta 44 | :param timeout: The timeout to be forcefully updated. 45 | :type timeout: datetime.timedelta 46 | """ 47 | HeartbeatMonitor._update( 48 | name=name, default_timeout=default_timeout, timeout=timeout 49 | ) 50 | 51 | 52 | def update_heartbeat_on_success(name, default_timeout=None, timeout=None): 53 | """Decorator to update a heartbeat when a function was successful. 54 | 55 | Usage: 56 | 57 | .. code-block:: 58 | 59 | @update_heartbeat_on_success("some.check.name") 60 | def your_function(): 61 | pass 62 | """ 63 | 64 | def _inner(func): 65 | @wraps(func) 66 | def _update_heartbeat_decorator(*args, **kwargs): 67 | value = func(*args, **kwargs) 68 | update_heartbeat(name, default_timeout=default_timeout, timeout=timeout) 69 | return value 70 | 71 | return _update_heartbeat_decorator 72 | 73 | return _inner 74 | -------------------------------------------------------------------------------- /src/django_healthchecks/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.11.7 on 2018-05-03 11:24 3 | from __future__ import unicode_literals 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | 10 | initial = True 11 | 12 | dependencies = [] 13 | 14 | operations = [ 15 | migrations.CreateModel( 16 | name="HeartbeatMonitor", 17 | fields=[ 18 | ( 19 | "id", 20 | models.AutoField( 21 | auto_created=True, 22 | primary_key=True, 23 | serialize=False, 24 | verbose_name="ID", 25 | ), 26 | ), 27 | ( 28 | "name", 29 | models.CharField( 30 | db_index=True, max_length=200, unique=True, verbose_name="Name" 31 | ), 32 | ), 33 | ( 34 | "enabled", 35 | models.BooleanField( 36 | db_index=True, default=True, verbose_name="Enabled" 37 | ), 38 | ), 39 | ("timeout", models.DurationField(verbose_name="Timeout")), 40 | ( 41 | "last_beat", 42 | models.DateTimeField(null=True, verbose_name="Last Beat"), 43 | ), 44 | ], 45 | options={ 46 | "verbose_name": "Heartbeat Monitor", 47 | "verbose_name_plural": "Heartbeat Monitors", 48 | "ordering": ("name",), 49 | }, 50 | ), 51 | ] 52 | -------------------------------------------------------------------------------- /src/django_healthchecks/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/labd/django-healthchecks/37e548e8ee2bf15b1afb98f078ee54ec63f1e621/src/django_healthchecks/migrations/__init__.py -------------------------------------------------------------------------------- /src/django_healthchecks/models.py: -------------------------------------------------------------------------------- 1 | from datetime import timedelta 2 | 3 | from django.conf import settings 4 | from django.db import models 5 | from django.db.models import ExpressionWrapper, F 6 | from django.utils.timezone import now 7 | from django.utils.translation import gettext_lazy as _ 8 | 9 | EXPIRES_COLUMN_TYPE = models.DateTimeField() 10 | IS_EXPIRED_COLUMN_TYPE = models.BooleanField() 11 | 12 | 13 | def _get_default_timeout(): 14 | return getattr( 15 | settings, "HEALTHCHECKS_DEFAULT_HEARTBEAT_TIMEOUT", timedelta(days=1) 16 | ) 17 | 18 | 19 | class HeartbeatMonitorQuerySet(models.QuerySet): 20 | def enabled(self): 21 | """Filter on enabled checks only.""" 22 | return self.filter(enabled=True) 23 | 24 | def annotate_expires_at(self): 25 | """Add an ``expires_at`` field to the queryset results.""" 26 | return self.annotate( 27 | expires_at=ExpressionWrapper( 28 | (F("last_beat") + F("timeout")), output_field=EXPIRES_COLUMN_TYPE 29 | ) 30 | ) 31 | 32 | def expired(self): 33 | """Tell which services no longer appear to send heartbeats.""" 34 | return self.annotate_expires_at().filter(expires_at__lt=now()) 35 | 36 | def expired_names(self): 37 | """Return a list of all heartbeats names that are expired.""" 38 | return list(self.expired().values_list("name", flat=True)) 39 | 40 | def status_by_name(self): 41 | """Return the expired status for every heartbeat.""" 42 | # Sadly, tests like (F('last_beat') + F('timeout')) < now() aren't supported in Django. 43 | # Even this fails: .annotate(is_expired=RawSQL("(last_beat + timeout) < %s", [now()])) 44 | # Thus, have to make the comparison in Python instead. 45 | t = now() 46 | monitors = self.annotate_expires_at().values_list("name", "expires_at") 47 | return {name: (expires_at < t) for name, expires_at in monitors} 48 | 49 | 50 | class HeartbeatMonitor(models.Model): 51 | """Monitoring the heartbeat of a task 52 | 53 | When a service is no longer sending out heartbeats, the 54 | ``check_expired_heartbeats`` check will be triggered. 55 | """ 56 | 57 | name = models.CharField(_("Name"), max_length=200, db_index=True, unique=True) 58 | enabled = models.BooleanField(_("Enabled"), db_index=True, default=True) 59 | timeout = models.DurationField(_("Timeout")) 60 | last_beat = models.DateTimeField(_("Last Beat"), null=True) 61 | 62 | objects = HeartbeatMonitorQuerySet.as_manager() 63 | 64 | def __str__(self): 65 | return self.name 66 | 67 | class Meta: 68 | ordering = ("name",) 69 | verbose_name = _("Heartbeat Monitor") 70 | verbose_name_plural = _("Heartbeat Monitors") 71 | 72 | @property 73 | def expires_at(self): 74 | """Tell when the object will expire""" 75 | return self.last_beat + self.timeout 76 | 77 | @property 78 | def is_expired(self): 79 | """Tell whether the last beat expired.""" 80 | return self.expires_at < now() 81 | 82 | @property 83 | def remaining_time(self): 84 | return self.expires_at - now() 85 | 86 | @classmethod 87 | def _update(cls, name, default_timeout=None, timeout=None): 88 | """Internal function to update a heartbeat. 89 | Use :func:`django_healthchecks.heartbeats.update_heartbeat` instead. 90 | """ 91 | extra_updates = {} 92 | if timeout is not None: 93 | extra_updates["timeout"] = timeout 94 | 95 | rows = cls.objects.filter(name=name).update(last_beat=now(), **extra_updates) 96 | if not rows: 97 | return cls.objects.create( 98 | name=name, 99 | enabled=True, 100 | timeout=timeout or default_timeout or _get_default_timeout(), 101 | last_beat=now(), 102 | ) 103 | -------------------------------------------------------------------------------- /src/django_healthchecks/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path 2 | 3 | from django_healthchecks import views 4 | 5 | urlpatterns = [ 6 | path(r"", views.HealthCheckView.as_view(), name="index"), 7 | path(r"/", views.HealthCheckServiceView.as_view(), name="service"), 8 | ] 9 | -------------------------------------------------------------------------------- /src/django_healthchecks/views.py: -------------------------------------------------------------------------------- 1 | import six 2 | from django.conf import settings 3 | from django.http import HttpResponse, JsonResponse 4 | from django.http.response import Http404 5 | from django.views.decorators.cache import cache_control 6 | from django.views.generic import View 7 | 8 | from django_healthchecks.checker import ( 9 | PermissionDenied, 10 | create_report, 11 | create_service_result, 12 | ) 13 | 14 | 15 | class NoCacheMixin(object): 16 | @classmethod 17 | def as_view(cls, **kwargs): 18 | view = super(NoCacheMixin, cls).as_view(**kwargs) 19 | return cache_control(private=True, no_cache=True, no_store=True, max_age=0)( 20 | view 21 | ) 22 | 23 | 24 | class GetErrorStatusCodeMixin(object): 25 | def get_error_stats_code(self, request): 26 | """override status code based on header but only allow int and within 27 | 100-599 range. 28 | 29 | """ 30 | status_header = getattr( 31 | settings, "HEALTH_CHECKS_ERROR_CODE_HEADER", "X-HEALTHCHECK-ERROR-CODE" 32 | ) 33 | 34 | requested_status_code = request.headers.get(status_header) 35 | if requested_status_code: 36 | try: 37 | # validate status code can be used 38 | status_code = int(requested_status_code) 39 | if 100 <= status_code <= 599: 40 | return status_code 41 | 42 | except (TypeError, ValueError): 43 | pass 44 | 45 | # current default behaviour 46 | return getattr(settings, "HEALTH_CHECKS_ERROR_CODE", 200) 47 | 48 | 49 | class HealthCheckView(NoCacheMixin, GetErrorStatusCodeMixin, View): 50 | def get(self, request, *args, **kwargs): 51 | try: 52 | report, is_healthy = create_report(request=request) 53 | except PermissionDenied: 54 | response = HttpResponse(status=401) 55 | response["WWW-Authenticate"] = 'Basic realm="Healthchecks"' 56 | return response 57 | status_code = 200 if is_healthy else self.get_error_stats_code(request) 58 | return JsonResponse(report, status=status_code) 59 | 60 | 61 | class HealthCheckServiceView(NoCacheMixin, GetErrorStatusCodeMixin, View): 62 | def get(self, request, service, *args, **kwargs): 63 | service_path = list(filter(lambda s: s, service.split("/"))) 64 | service = service_path.pop(0) 65 | 66 | try: 67 | result = create_service_result(service=service, request=request) 68 | except PermissionDenied: 69 | response = HttpResponse(status=401) 70 | response["WWW-Authenticate"] = 'Basic realm="Healthchecks"' 71 | return response 72 | 73 | return self.create_result_response(request, service, result, service_path) 74 | 75 | def create_result_response(self, request, service, result, service_path): 76 | for nested in service_path: 77 | result = result.get(nested, None) 78 | if result is None: 79 | break 80 | 81 | if result is None: 82 | raise Http404() 83 | 84 | if result in (True, False): 85 | status_code = 200 if result else self.get_error_stats_code(request) 86 | return HttpResponse(str(result).lower(), status=status_code) 87 | elif isinstance(result, six.string_types) or isinstance(result, bytes): 88 | return HttpResponse(result) 89 | else: 90 | # Django requires safe=False for non-dict values. 91 | return JsonResponse(result, safe=False) 92 | -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | from django.conf import settings 2 | 3 | 4 | def pytest_configure(): 5 | settings.configure( 6 | SECRET_KEY="KZ6ae1ZfI0BL36beMzReajDLWLb5O8bw", 7 | HEALTH_CHECKS={}, 8 | MIDDLEWARE_CLASSES=[], 9 | INSTALLED_APPS=[ 10 | "django.contrib.admin", 11 | "django.contrib.contenttypes", 12 | "django.contrib.auth", 13 | "django.contrib.sessions", 14 | "django_healthchecks", 15 | ], 16 | CACHES={ 17 | "default": { 18 | "BACKEND": "django.core.cache.backends.locmem.LocMemCache", 19 | "LOCATION": "unique-snowflake", 20 | } 21 | }, 22 | DATABASES={ 23 | "default": { 24 | "ENGINE": "django.db.backends.sqlite3", 25 | "NAME": "db.sqlite", 26 | }, 27 | }, 28 | MIDDLEWARE=( 29 | "django.contrib.sessions.middleware.SessionMiddleware", 30 | "django.contrib.auth.middleware.AuthenticationMiddleware", 31 | ), 32 | TEMPLATES=[ 33 | { 34 | "BACKEND": "django.template.backends.django.DjangoTemplates", 35 | "OPTIONS": { 36 | "loaders": ("django.template.loaders.app_directories.Loader",), 37 | }, 38 | }, 39 | ], 40 | USE_TZ=True, 41 | ROOT_URLCONF="test_urls", 42 | ) 43 | -------------------------------------------------------------------------------- /tests/test_checker.py: -------------------------------------------------------------------------------- 1 | import base64 2 | 3 | import requests 4 | import requests_mock 5 | 6 | from django_healthchecks import checker 7 | 8 | 9 | def test_create_report(settings): 10 | settings.HEALTH_CHECKS = { 11 | "database": "django_healthchecks.contrib.check_dummy_true", 12 | "remote_service": "https://test.com/api/healthchecks/", 13 | } 14 | 15 | with requests_mock.Mocker() as mock: 16 | mock.get("https://test.com/api/healthchecks/", text='{"cache_default": true}') 17 | result, is_healthy = checker.create_report() 18 | 19 | expected = { 20 | "database": True, 21 | "remote_service": {"cache_default": True}, 22 | } 23 | 24 | assert result == expected 25 | assert is_healthy is True 26 | 27 | 28 | def test_service_timeout(settings): 29 | settings.HEALTH_CHECKS = { 30 | "database": "django_healthchecks.contrib.check_dummy_true", 31 | "timeout_service": "http://timeout.com/api/healthchecks/", 32 | } 33 | 34 | with requests_mock.Mocker() as mock: 35 | mock.register_uri( 36 | "GET", 37 | "http://timeout.com/api/healthchecks/", 38 | exc=requests.exceptions.Timeout, 39 | ) 40 | result, is_healthy = checker.create_report() 41 | 42 | expected = {"database": True, "timeout_service": False} 43 | 44 | assert result == expected 45 | assert is_healthy is False 46 | 47 | 48 | def test_create_report_err(settings): 49 | settings.HEALTH_CHECKS = { 50 | "database": "django_healthchecks.contrib.check_dummy_true", 51 | "i_fail": "django_healthchecks.contrib.check_dummy_false", 52 | } 53 | result, is_healthy = checker.create_report() 54 | expected = { 55 | "database": True, 56 | "i_fail": False, 57 | } 58 | 59 | assert result == expected 60 | assert is_healthy is False 61 | 62 | 63 | def test_create_service_result(settings): 64 | settings.HEALTH_CHECKS = { 65 | "database": "django_healthchecks.contrib.check_dummy_true" 66 | } 67 | result = checker.create_service_result("database") 68 | assert result is True 69 | 70 | 71 | def test_create_service_result_unknown(settings): 72 | result = checker.create_service_result("database") 73 | assert result is None 74 | 75 | 76 | def test_create_with_request(rf, settings): 77 | settings.HEALTH_CHECKS = { 78 | "remote_addr": "django_healthchecks.contrib.check_remote_addr" 79 | } 80 | request = rf.get("/") 81 | result = checker.create_service_result("remote_addr", request) 82 | assert result == "127.0.0.1" 83 | 84 | 85 | def test_filter_checks_on_permission(rf, settings): 86 | checks = { 87 | "public": "django_healthchecks.contrib.check_dummy_true", 88 | "private": "django_healthchecks.contrib.check_dummy_true", 89 | } 90 | 91 | settings.HEALTH_CHECKS_BASIC_AUTH = { 92 | "*": [("user", "password")], 93 | "public": [], 94 | } 95 | 96 | request = rf.get("/") 97 | result = checker._filter_checks_on_permission(request, checks) 98 | assert result == { 99 | "public": "django_healthchecks.contrib.check_dummy_true", 100 | } 101 | 102 | request = rf.get( 103 | "/", HTTP_AUTHORIZATION=b"Basic " + base64.b64encode(b"user:password") 104 | ) 105 | 106 | result = checker._filter_checks_on_permission(request, checks) 107 | assert result == { 108 | "public": "django_healthchecks.contrib.check_dummy_true", 109 | "private": "django_healthchecks.contrib.check_dummy_true", 110 | } 111 | -------------------------------------------------------------------------------- /tests/test_contrib.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from django.core import cache 3 | 4 | from django_healthchecks import contrib 5 | 6 | 7 | @pytest.mark.django_db 8 | def test_check_database(): 9 | assert contrib.check_database() 10 | 11 | 12 | def test_check_cache_default(): 13 | assert contrib.check_cache_default() 14 | 15 | 16 | def test_check_cache_default_down(settings): 17 | """Check if the application can connect to the default cached and 18 | read/write some dummy data. 19 | 20 | """ 21 | settings.CACHES = { 22 | "default": { 23 | "BACKEND": "django.core.cache.backends.dummy.DummyCache", 24 | } 25 | } 26 | assert not contrib.check_cache_default() 27 | 28 | 29 | @pytest.mark.django_db 30 | def test_check_heartbeats(): 31 | assert not contrib.MIGRATION_CACHE 32 | assert contrib.check_open_migrations() 33 | assert contrib.MIGRATION_CACHE 34 | -------------------------------------------------------------------------------- /tests/test_heartbeats.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime, timedelta 2 | 3 | import pytest 4 | from django.urls import reverse 5 | from django.utils.timezone import utc 6 | from freezegun import freeze_time 7 | 8 | from django_healthchecks.contrib import check_expired_heartbeats, check_heartbeats 9 | from django_healthchecks.heartbeats import update_heartbeat, update_heartbeat_on_success 10 | from django_healthchecks.models import HeartbeatMonitor 11 | 12 | NOON = datetime(2018, 5, 3, 12, 0, 0, tzinfo=utc) 13 | ONE_HOUR_LATER = datetime(2018, 5, 3, 13, 1, 0, tzinfo=utc) 14 | 15 | 16 | @pytest.fixture 17 | @freeze_time(NOON) 18 | def beat1(): 19 | # Should be expired one hour later 20 | return HeartbeatMonitor.objects.create( 21 | name="testing.beat1", enabled=True, timeout=timedelta(hours=1), last_beat=NOON 22 | ) 23 | 24 | 25 | @pytest.fixture 26 | @freeze_time(NOON) 27 | def beat2(): 28 | # Should not be expired one hour later 29 | return HeartbeatMonitor.objects.create( 30 | name="testing.beat2", 31 | enabled=True, 32 | timeout=timedelta(hours=1, minutes=8), 33 | last_beat=NOON, 34 | ) 35 | 36 | 37 | @pytest.fixture 38 | @freeze_time(NOON) 39 | def beat3(): 40 | # Should be ignored in all tests 41 | return HeartbeatMonitor.objects.create( 42 | name="testing.beat3", 43 | enabled=False, 44 | timeout=timedelta(minutes=1), 45 | last_beat=NOON, 46 | ) 47 | 48 | 49 | @pytest.mark.django_db 50 | def test_check_empty_db(): 51 | """See that an empty database doesn't crash.""" 52 | assert check_expired_heartbeats() is None 53 | assert check_heartbeats() == {"__all__": True} 54 | 55 | 56 | @pytest.mark.django_db 57 | @freeze_time(ONE_HOUR_LATER) 58 | def test_check_expired(beat1, beat2, beat3): 59 | """See that the checks themselves return proper data.""" 60 | assert check_expired_heartbeats() == ["testing.beat1"] 61 | assert check_heartbeats() == { 62 | "__all__": False, 63 | "testing.beat1": True, 64 | "testing.beat2": False, 65 | } 66 | 67 | 68 | @pytest.mark.django_db 69 | @freeze_time(ONE_HOUR_LATER) 70 | def test_expired_names(beat1, beat2, beat3): 71 | assert HeartbeatMonitor.objects.expired_names() == [ 72 | "testing.beat1", 73 | "testing.beat3", 74 | ] 75 | assert HeartbeatMonitor.objects.enabled().expired_names() == ["testing.beat1"] 76 | 77 | 78 | @pytest.mark.django_db 79 | @freeze_time(ONE_HOUR_LATER) 80 | def test_update_heartbeat(beat1): 81 | """See that ``last_beat`` is properly updated.""" 82 | assert beat1.is_expired 83 | update_heartbeat(beat1.name) 84 | 85 | # Should not have created new objects, but update existing. 86 | assert HeartbeatMonitor.objects.count() == 1 87 | 88 | beat1.refresh_from_db() 89 | assert not beat1.is_expired 90 | 91 | 92 | @pytest.mark.django_db 93 | def test_update_heartbeat_auto_creates(): 94 | """See that the first call to update_heartbeat() auto-creates.""" 95 | assert HeartbeatMonitor.objects.count() == 0 96 | 97 | update_heartbeat("testing.autocreate1", default_timeout=timedelta(days=1)) 98 | update_heartbeat("testing.autocreate1", default_timeout=timedelta(days=2)) 99 | 100 | # Should not have created new objects, but update existing. 101 | assert HeartbeatMonitor.objects.count() == 1 102 | 103 | # Should only assign default_timeout in the first call. 104 | beat = HeartbeatMonitor.objects.get(name="testing.autocreate1") 105 | assert beat.timeout == timedelta(days=1) 106 | 107 | 108 | @pytest.mark.django_db 109 | @freeze_time(ONE_HOUR_LATER) 110 | def test_update_heartbeat_timeout(beat1): 111 | assert beat1.is_expired 112 | update_heartbeat(beat1.name, timeout=timedelta(days=3)) 113 | 114 | # Should not have created new objects, but update existing. 115 | assert HeartbeatMonitor.objects.count() == 1 116 | 117 | beat1.refresh_from_db() 118 | assert not beat1.is_expired 119 | assert beat1.timeout == timedelta(days=3) 120 | 121 | 122 | @pytest.mark.django_db 123 | @freeze_time(ONE_HOUR_LATER) 124 | def test_update_heartbeat_on_success(beat1): 125 | assert beat1.is_expired 126 | 127 | @update_heartbeat_on_success(beat1.name) 128 | def foo(x=1): 129 | return x 130 | 131 | assert foo(x=2) == 2 132 | beat1.refresh_from_db() 133 | assert not beat1.is_expired 134 | 135 | 136 | @pytest.mark.django_db 137 | @freeze_time(ONE_HOUR_LATER) 138 | def test_update_heartbeat_on_success_exception(beat1): 139 | assert beat1.is_expired 140 | 141 | @update_heartbeat_on_success(beat1.name) 142 | def foo(): 143 | raise ValueError() 144 | 145 | with pytest.raises(ValueError): 146 | foo() 147 | 148 | beat1.refresh_from_db() 149 | assert beat1.is_expired 150 | 151 | 152 | @pytest.mark.django_db 153 | @pytest.mark.django_db 154 | @freeze_time(ONE_HOUR_LATER) 155 | def test_is_expired(beat1, beat2, beat3): 156 | assert beat1.is_expired 157 | assert not beat2.is_expired 158 | assert beat3.is_expired 159 | 160 | 161 | @pytest.mark.django_db 162 | @freeze_time(ONE_HOUR_LATER) 163 | def test_remaining_time(beat1, beat2): 164 | assert beat1.remaining_time == timedelta(minutes=-1) 165 | assert beat2.remaining_time == timedelta(minutes=7) 166 | 167 | 168 | @pytest.mark.django_db 169 | @freeze_time(ONE_HOUR_LATER) 170 | def test_admin_list_view(admin_client, beat1, beat2, beat3): 171 | """See that the admin list renders and displays the status. 172 | 173 | By adding ?o=1.2.3.4 the ordering of all columns is tested too. 174 | This makes sure the 'admin_order_field' also works. 175 | """ 176 | url = ( 177 | reverse("admin:django_healthchecks_heartbeatmonitor_changelist") + "?o=1.2.3.4" 178 | ) 179 | response = admin_client.get(url) 180 | assert response.status_code == 200 181 | content = response.render().content # make sure template rendering works 182 | assert b"icon-alert.svg" in content 183 | 184 | 185 | @pytest.mark.django_db 186 | @freeze_time(ONE_HOUR_LATER) 187 | def test_admin_change_view(admin_client, beat1): 188 | """See that the admin page renders without fieldset issues.""" 189 | url = reverse("admin:django_healthchecks_heartbeatmonitor_change", args=(beat1.pk,)) 190 | response = admin_client.get(url) 191 | assert response.status_code == 200 192 | content = response.render().content # make sure template rendering works 193 | assert b"icon-alert.svg" in content 194 | -------------------------------------------------------------------------------- /tests/test_urls.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from django.urls import include, path 3 | 4 | import django_healthchecks.urls 5 | 6 | urlpatterns = [ 7 | path("^admin/", admin.site.urls), 8 | path("^healthchecks", include(django_healthchecks.urls)), 9 | ] 10 | -------------------------------------------------------------------------------- /tests/test_views.py: -------------------------------------------------------------------------------- 1 | import json 2 | from collections import OrderedDict 3 | 4 | import pytest 5 | import requests_mock 6 | from django.http import Http404 7 | 8 | from django_healthchecks import views 9 | 10 | 11 | def check_int(): 12 | return 2 13 | 14 | 15 | def check_float(): 16 | return 1.5 17 | 18 | 19 | def test_index_view(rf, settings): 20 | settings.HEALTH_CHECKS = { 21 | "database": "django_healthchecks.contrib.check_dummy_true", 22 | "redis": "django_healthchecks.contrib.check_dummy_false", 23 | } 24 | 25 | request = rf.get("/") 26 | view = views.HealthCheckView() 27 | result = view.dispatch(request) 28 | 29 | data = json.loads(result.content.decode(result.charset)) 30 | assert data == { 31 | "database": True, 32 | "redis": False, 33 | } 34 | 35 | 36 | def test_service_view_bool(rf, settings): 37 | settings.HEALTH_CHECKS = OrderedDict( 38 | [ 39 | ("redis", "django_healthchecks.contrib.check_dummy_false"), 40 | ("database", "django_healthchecks.contrib.check_dummy_true"), 41 | ] 42 | ) 43 | 44 | request = rf.get("/") 45 | view = views.HealthCheckServiceView() 46 | result = view.dispatch(request, service="database") 47 | 48 | assert result.status_code == 200 49 | assert result.content == b"true" 50 | 51 | 52 | def test_service_view_bytes(rf, settings): 53 | # This tests the serilization contraints 54 | settings.HEALTH_CHECKS = OrderedDict( 55 | [ 56 | ("ip", "django_healthchecks.contrib.check_remote_addr"), 57 | ] 58 | ) 59 | 60 | request = rf.get("/") 61 | view = views.HealthCheckServiceView() 62 | result = view.dispatch(request, service="ip") 63 | 64 | assert result.status_code == 200 65 | assert result.content == b"127.0.0.1" 66 | 67 | 68 | def test_service_view_int(rf, settings): 69 | # This tests the serilization contraints 70 | settings.HEALTH_CHECKS = OrderedDict( 71 | [ 72 | ("val", check_int), 73 | ] 74 | ) 75 | 76 | request = rf.get("/") 77 | view = views.HealthCheckServiceView() 78 | result = view.dispatch(request, service="val") 79 | 80 | assert result.status_code == 200 81 | assert result["Content-Type"] == "application/json" 82 | assert result.content == b"2" 83 | 84 | 85 | def test_service_view_float(rf, settings): 86 | # This tests the serilization contraints 87 | settings.HEALTH_CHECKS = OrderedDict( 88 | [ 89 | ("val", check_float), 90 | ] 91 | ) 92 | 93 | request = rf.get("/") 94 | view = views.HealthCheckServiceView() 95 | result = view.dispatch(request, service="val") 96 | 97 | assert result.status_code == 200 98 | assert result["Content-Type"] == "application/json" 99 | assert result.content == b"1.5" 100 | 101 | 102 | def test_service_view_remote(rf, settings): 103 | settings.HEALTH_CHECKS = { 104 | "remote_service": "https://test.com/api/healthchecks/", 105 | } 106 | 107 | with requests_mock.Mocker() as mock: 108 | mock.get("https://test.com/api/healthchecks/", json={"cache_default": True}) 109 | 110 | request = rf.get("/") 111 | view = views.HealthCheckServiceView() 112 | result = view.dispatch(request, service="remote_service") 113 | 114 | expected = {"cache_default": True} 115 | data = json.loads(result.content.decode(result.charset)) 116 | 117 | assert result.status_code == 200 118 | assert result["Content-Type"] == "application/json" 119 | assert data == expected 120 | 121 | 122 | def test_service_view_err(rf, settings): 123 | settings.HEALTH_CHECKS = { 124 | "database": "django_healthchecks.contrib.check_dummy_false" 125 | } 126 | 127 | request = rf.get("/") 128 | view = views.HealthCheckServiceView() 129 | 130 | result = view.dispatch(request, service="database") 131 | assert result.status_code == 200 132 | assert result.content == b"false" 133 | 134 | 135 | def test_service_view_err_custom_code(rf, settings): 136 | settings.HEALTH_CHECKS_ERROR_CODE = 500 137 | settings.HEALTH_CHECKS = { 138 | "database": "django_healthchecks.contrib.check_dummy_false" 139 | } 140 | 141 | request = rf.get("/") 142 | view = views.HealthCheckServiceView() 143 | 144 | result = view.dispatch(request, service="database") 145 | assert result.status_code == 500 146 | assert result.content == b"false" 147 | 148 | 149 | def test_service_view_err_custom_code_header(rf, settings): 150 | settings.HEALTH_CHECKS_ERROR_CODE = 200 151 | settings.HEALTH_CHECKS = { 152 | "database": "django_healthchecks.contrib.check_dummy_false" 153 | } 154 | 155 | request = rf.get("/", HTTP_X_HEALTHCHECK_ERROR_CODE=500) 156 | view = views.HealthCheckServiceView() 157 | 158 | result = view.dispatch(request, service="database") 159 | assert result.status_code == 500 160 | assert result.content == b"false" 161 | 162 | 163 | def test_service_view_err_custom_code_header_override(rf, settings): 164 | settings.HEALTH_CHECKS_ERROR_CODE = 200 165 | settings.HEALTH_CHECKS_ERROR_CODE_HEADER = "X-ERROR-CODE" 166 | settings.HEALTH_CHECKS = { 167 | "database": "django_healthchecks.contrib.check_dummy_false" 168 | } 169 | 170 | request = rf.get("/", HTTP_X_ERROR_CODE=500) 171 | view = views.HealthCheckServiceView() 172 | 173 | result = view.dispatch(request, service="database") 174 | assert result.status_code == 500 175 | assert result.content == b"false" 176 | 177 | 178 | def test_service_view_404(rf): 179 | request = rf.get("/") 180 | view = views.HealthCheckServiceView() 181 | 182 | with pytest.raises(Http404): 183 | view.dispatch(request, service="database") 184 | 185 | 186 | def test_service_require_auth(rf, settings): 187 | settings.HEALTH_CHECKS = { 188 | "database": "django_healthchecks.contrib.check_dummy_true" 189 | } 190 | settings.HEALTH_CHECKS_BASIC_AUTH = { 191 | "*": [("user", "password")], 192 | } 193 | 194 | request = rf.get("/") 195 | view = views.HealthCheckServiceView() 196 | 197 | result = view.dispatch(request, service="database") 198 | assert result.status_code == 401 199 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py{38,39,310}-django{32,40} 3 | 4 | [testenv] 5 | commands = coverage run --parallel -m pytest {posargs} 6 | deps = 7 | django32: Django>=3.2,<4.0 8 | django40: Django>=4.0,<4.1 9 | extras = test 10 | 11 | [testenv:coverage-report] 12 | deps = coverage[toml] 13 | skip_install = true 14 | commands = 15 | coverage combine 16 | coverage report 17 | 18 | [testenv:format] 19 | basepython = python3.10 20 | deps = 21 | black 22 | isort 23 | skip_install = true 24 | commands = 25 | isort --check-only src tests 26 | black --check src/ tests/ 27 | --------------------------------------------------------------------------------