[Python-modules-commits] [django-prometheus] 01/10: Import django-prometheus_1.0.6.orig.tar.gz

Christopher Baines cbaines-guest at moszumanska.debian.org
Sun Feb 28 01:59:56 UTC 2016


This is an automated email from the git hooks/post-receive script.

cbaines-guest pushed a commit to branch master
in repository django-prometheus.

commit f86a69bf199609840ce396d187c097044c42d0fb
Author: Christopher Baines <mail at cbaines.net>
Date:   Sat Feb 27 16:25:17 2016 +0000

    Import django-prometheus_1.0.6.orig.tar.gz
---
 .gitignore                                        |  95 ++++++++++
 .travis.yml                                       |  36 ++++
 CONTRIBUTING.md                                   |  56 ++++++
 LICENSE                                           | 202 ++++++++++++++++++++++
 README.md                                         | 131 ++++++++++++++
 django_prometheus/__init__.py                     |  19 ++
 django_prometheus/apps.py                         |  22 +++
 django_prometheus/db/__init__.py                  |   2 +
 django_prometheus/db/backends/README.md           |  35 ++++
 django_prometheus/db/backends/__init__.py         |   0
 django_prometheus/db/backends/mysql/__init__.py   |   0
 django_prometheus/db/backends/mysql/base.py       |  11 ++
 django_prometheus/db/backends/sqlite3/__init__.py |   0
 django_prometheus/db/backends/sqlite3/base.py     |  11 ++
 django_prometheus/db/common.py                    |  72 ++++++++
 django_prometheus/db/metrics.py                   |  31 ++++
 django_prometheus/exports.py                      | 108 ++++++++++++
 django_prometheus/middleware.py                   | 154 +++++++++++++++++
 django_prometheus/migrations.py                   |  47 +++++
 django_prometheus/models.py                       |  44 +++++
 django_prometheus/testutils.py                    | 126 ++++++++++++++
 django_prometheus/urls.py                         |   7 +
 django_prometheus/utils.py                        |  31 ++++
 documentation/exports.md                          |  77 +++++++++
 examples/django-promdash.png                      | Bin 0 -> 154391 bytes
 examples/prometheus/README.md                     |  18 ++
 examples/prometheus/consoles/django.html          | 194 +++++++++++++++++++++
 examples/prometheus/django.rules                  |  57 ++++++
 examples/prometheus/prometheus.yml                |  14 ++
 requirements.txt                                  |   5 +
 setup.py                                          |  38 ++++
 tests/__init__.py                                 |   0
 tests/end2end/manage.py                           |  10 ++
 tests/end2end/testapp/__init__.py                 |   0
 tests/end2end/testapp/models.py                   |  12 ++
 tests/end2end/testapp/settings.py                 | 144 +++++++++++++++
 tests/end2end/testapp/templates/help.html         |  72 ++++++++
 tests/end2end/testapp/templates/index.html        |   1 +
 tests/end2end/testapp/templates/lawn.html         |   1 +
 tests/end2end/testapp/templates/slow.html         |  37 ++++
 tests/end2end/testapp/templates/sql.html          |  22 +++
 tests/end2end/testapp/test_db.py                  |  52 ++++++
 tests/end2end/testapp/test_middleware.py          | 102 +++++++++++
 tests/end2end/testapp/test_migrations.py          |  47 +++++
 tests/end2end/testapp/test_models.py              |  61 +++++++
 tests/end2end/testapp/urls.py                     |  15 ++
 tests/end2end/testapp/views.py                    |  68 ++++++++
 tests/end2end/testapp/wsgi.py                     |  16 ++
 tests/test_django_prometheus.py                   |  24 +++
 tests/test_testutils.py                           | 150 ++++++++++++++++
 50 files changed, 2477 insertions(+)

diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..03676e4
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,95 @@
+# Byte-compiled / optimized / DLL files
+__pycache__/
+*.py[cod]
+
+# C extensions
+*.so
+
+# Distribution / packaging
+.Python
+env*/
+build/
+develop-eggs/
+dist/
+downloads/
+eggs/
+.eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+*.egg-info/
+.installed.cfg
+*.egg
+
+# PyInstaller
+#  Usually these files are written by a python script from a template
+#  before PyInstaller builds the exe, so as to inject date/other infos into it.
+*.manifest
+*.spec
+
+# Installer logs
+pip-log.txt
+pip-delete-this-directory.txt
+
+# Unit test / coverage reports
+htmlcov/
+.tox/
+.coverage
+.coverage.*
+.cache
+nosetests.xml
+coverage.xml
+*,cover
+
+# Translations
+*.mo
+*.pot
+
+# Django stuff:
+*.log
+*.sqlite3
+
+# Sphinx documentation
+docs/_build/
+
+# PyBuilder
+target/
+
+### Emacs ###
+# -*- mode: gitignore; -*-
+*~
+\#*\#
+/.emacs.desktop
+/.emacs.desktop.lock
+*.elc
+auto-save-list
+tramp
+.\#*
+
+# Org-mode
+.org-id-locations
+*_archive
+
+# flymake-mode
+*_flymake.*
+
+# eshell files
+/eshell/history
+/eshell/lastdir
+
+# elpa packages
+/elpa/
+
+# reftex files
+*.rel
+
+# AUCTeX auto folder
+/auto/
+
+# cask packages
+.cask/
+
+### Prometheus ###
+examples/prometheus/data
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 0000000..b73344e
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,36 @@
+language: python
+python:
+  - "3.5"
+  - "3.4"
+  - "3.3"
+  - "2.7"
+env:
+  - DJANGO_VERSION=1.9
+  - DJANGO_VERSION=1.8
+  - DJANGO_VERSION=1.7
+  - DJANGO_VERSION=1.6
+  - DJANGO_VERSION=1.5
+  - DJANGO_VERSION=1.4
+matrix:
+  exclude:
+    - python: "3.3"
+      env: DJANGO_VERSION=1.4
+    - python: "3.3"
+      env: DJANGO_VERSION=1.9
+    - python: "3.4"
+      env: DJANGO_VERSION=1.4
+    - python: "3.5"
+      env: DJANGO_VERSION=1.4
+    - python: "3.5"
+      env: DJANGO_VERSION=1.5
+    - python: "3.5"
+      env: DJANGO_VERSION=1.6
+    - python: "3.5"
+      env: DJANGO_VERSION=1.7
+install:
+  - pip install -r requirements.txt
+  - pip install -q Django==$DJANGO_VERSION
+before_script: pep8 .
+script:
+  - python setup.py test
+  - (cd tests/end2end; PYTHONPATH=../.. python manage.py test)
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000..aae7bd7
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,56 @@
+# Contributing
+
+## Git
+
+Feel free to send pull requests, even for the tiniest things. Watch
+for Travis' opinion on them ([![Build
+Status](https://travis-ci.org/korfuri/django-prometheus.svg?branch=master)](https://travis-ci.org/korfuri/django-prometheus)).
+
+Travis will also make sure your code is pep8 compliant, and it's a
+good idea to run flake8 as well (on django_prometheus/ and on
+tests/). The code contains "unused" imports on purpose so flake8 isn't
+run automatically.
+
+## Tests
+
+Please write unit tests for your change. There are two kinds of tests:
+
+  * Regular unit tests that test the code directly, without loading
+    Django. This is limited to pieces of the code that don't depend on
+    Django, since a lot of the Django code will require a full Django
+    environment (anything that interacts with models, for instance,
+    needs a full database configuration).
+  * End-to-end tests are Django unit tests in a test application. The
+    test application doubles as an easy way to interactively test your
+    changes. It uses most of the basic Django features and a few
+    advanced features, so you can test things for yourself.
+
+### Running all tests
+
+```shell
+$ python setup.py test
+$ (cd tests/end2end/; PYTHONPATH=../.. ./manage.py test)
+```
+
+The former runs the regular unit tests, the latter runs the Django
+unit test.
+
+To avoid setting PYTHONPATH every time, you can also run `python
+setup.py install`.
+
+### Running the test Django app
+
+```shell
+$ (cd tests/end2end/; PYTHONPATH=../.. ./manage.py runserver)
+```
+
+By default, this will start serving on http://localhost:8000/. Metrics
+are available at `/metrics`.
+
+## Running Prometheus
+
+See http://prometheus.io/docs/ for instructions on installing
+Prometheus. Once you have Prometheus installed, you can use the
+example rules and dashboard in `examples/prometheus/`. See
+`examples/prometheus/README.md` to run Prometheus and view the example
+dashboard.
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..8f71f43
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,202 @@
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "{}"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright {yyyy} {name of copyright owner}
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..e82e0c1
--- /dev/null
+++ b/README.md
@@ -0,0 +1,131 @@
+# django-prometheus
+Export Django monitoring metrics for Prometheus.io
+
+[![PyPI version](https://badge.fury.io/py/django-prometheus.svg)](http://badge.fury.io/py/django-prometheus)
+[![Build Status](https://travis-ci.org/korfuri/django-prometheus.svg?branch=master)](https://travis-ci.org/korfuri/django-prometheus)
+
+## Usage
+
+### Requirements
+
+* Django >= 1.4 (>= 1.8 is recommended)
+
+### Installation
+
+Install with:
+```shell
+pip install django-prometheus
+```
+
+Or, if you're using a development version cloned from this repository:
+```shell
+python path-to-where-you-cloned-django-prometheus/setup.py install
+```
+
+This will install [prometheus_client](https://github.com/prometheus/client_python) as a dependency.
+
+### Quickstart
+
+In your settings.py:
+
+```python
+INSTALLED_APPS = (
+   ...
+   'django_prometheus',
+   ...
+)
+
+MIDDLEWARE_CLASSES = (
+    'django_prometheus.middleware.PrometheusBeforeMiddleware',
+    # All your other middlewares go here, including the default
+    # middlewares like SessionMiddleware, CommonMiddleware,
+    # CsrfViewmiddleware, SecurityMiddleware, etc.
+    'django_prometheus.middleware.PrometheusAfterMiddleware',
+)
+```
+
+In your urls.py:
+
+```python
+urlpatterns = [
+    ...
+    url('', include('django_prometheus.urls')),
+]
+```
+
+### Monitoring your databases
+
+Currently, only SQLite and MySQL databases can be monitored. Just
+replace the `ENGINE` property of your database, replacing
+`django.db.backends` with `django_prometheus.db.backends`.
+
+```python
+DATABASES = {
+    'default': {
+        'ENGINE': 'django_prometheus.db.backends.sqlite3',
+        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
+    },
+}
+```
+
+### Monitoring your models
+
+You may want to monitor the creation/deletion/update rate for your
+model. This can be done by adding a mixin to them. This is safe to do
+on existing models (it does not require a migration).
+
+If your model is:
+
+```python
+class Dog(models.Model):
+    name = models.CharField(max_length=100, unique=True)
+    breed = models.CharField(max_length=100, blank=True, null=True)
+    age = models.PositiveIntegerField(blank=True, null=True)
+```
+
+Just add the `ExportModelOperationsMixin` as such:
+
+```python
+from django_prometheus.models import ExportModelOperationsMixin
+
+class Dog(ExportModelOperationsMixin('dog'), models.Model):
+    name = models.CharField(max_length=100, unique=True)
+    breed = models.CharField(max_length=100, blank=True, null=True)
+    age = models.PositiveIntegerField(blank=True, null=True)
+```
+
+This will export 3 metrics, `django_model_inserts_total{model="dog"}`,
+`django_model_updates_total{model="dog"}` and
+`django_model_deletes_total{model="dog"}`.
+
+Note that the exported metrics are counters of creations,
+modifications and deletions done in the current process. They are not
+gauges of the number of objects in the model.
+
+Starting with Django 1.7, migrations are also monitored. Two gauges
+are exported, `django_migrations_applied_by_connection` and
+`django_migrations_unapplied_by_connection`. You may want to alert if
+there are unapplied migrations.
+
+### Monitoring and aggregating the metrics
+
+Prometheus is quite easy to set up. An example prometheus.conf to
+scrape `127.0.0.1:8001` can be found in `examples/prometheus`.
+
+Here's an example of a PromDash displaying some of the metrics
+collected by django-prometheus:
+
+![Example dashboard](https://raw.githubusercontent.com/korfuri/django-prometheus/master/examples/django-promdash.png)
+
+## Adding your own metrics
+
+You can add application-level metrics in your code by using
+[prometheus_client](https://github.com/prometheus/client_python)
+directly. The exporter is global and will pick up your metrics.
+
+To add metrics to the Django internals, the easiest way is to extend
+django-prometheus' classes. Please consider contributing your metrics,
+pull requests are welcome. Make sure to read the Prometheus best
+practices on
+[instrumentation](http://prometheus.io/docs/practices/instrumentation/)
+and [naming](http://prometheus.io/docs/practices/naming/).
diff --git a/django_prometheus/__init__.py b/django_prometheus/__init__.py
new file mode 100644
index 0000000..39458ec
--- /dev/null
+++ b/django_prometheus/__init__.py
@@ -0,0 +1,19 @@
+"""Django-Prometheus
+
+https://github.com/korfuri/django-prometheus
+"""
+
+# Import all files that define metrics. This has the effect that
+# `import django_prometheus` will always instanciate all metric
+# objects right away.
+import django_prometheus.middleware
+import django_prometheus.models
+
+# Import pip_prometheus to export the pip metrics automatically.
+try:
+    import pip_prometheus
+except ImportError:
+    # If people don't have pip, don't export anything.
+    pass
+
+default_app_config = 'django_prometheus.apps.DjangoPrometheusConfig'
diff --git a/django_prometheus/apps.py b/django_prometheus/apps.py
new file mode 100644
index 0000000..a973336
--- /dev/null
+++ b/django_prometheus/apps.py
@@ -0,0 +1,22 @@
+from django.apps import AppConfig
+from django_prometheus.exports import SetupPrometheusExportsFromConfig
+from django_prometheus.migrations import ExportMigrations
+# unused import to force instantiating the metric objects at startup.
+import django_prometheus
+
+
+class DjangoPrometheusConfig(AppConfig):
+    name = 'django_prometheus'
+    verbose_name = 'Django-Prometheus'
+
+    def ready(self):
+        """Initializes the Prometheus exports if they are enabled in the config.
+
+        Note that this is called even for other management commands
+        than `runserver`. As such, it is possible to scrape the
+        metrics of a running `manage.py test` or of another command,
+        which shouldn't be done for real monitoring (since these jobs
+        are usually short-lived), but can be useful for debugging.
+        """
+        SetupPrometheusExportsFromConfig()
+        ExportMigrations()
diff --git a/django_prometheus/db/__init__.py b/django_prometheus/db/__init__.py
new file mode 100644
index 0000000..5593d7d
--- /dev/null
+++ b/django_prometheus/db/__init__.py
@@ -0,0 +1,2 @@
+# Import all metrics
+from django_prometheus.db.metrics import *
diff --git a/django_prometheus/db/backends/README.md b/django_prometheus/db/backends/README.md
new file mode 100644
index 0000000..ef53478
--- /dev/null
+++ b/django_prometheus/db/backends/README.md
@@ -0,0 +1,35 @@
+# Adding new database wrapper types
+
+Unfortunately, I don't have the resources to create wrappers for all
+database vendors. Doing so should be straightforward, but testing that
+it works and maintaining it is a lot of busywork, or is impossible for
+me for commercial databases.
+
+This document should be enough for people who wish to implement a new
+database wrapper.
+
+## Structure
+
+A database engine in Django requires 3 classes (it really requires 2,
+but the 3rd one is required for our purposes):
+
+* A DatabaseFeatures class, which describes what features the database
+  supports. For our usage, we can simply extend the existing
+  DatabaseFeatures class without any changes.
+* A DatabaseWrapper class, which abstracts the interface to the
+  database.
+* A CursorWrapper class, which abstracts the interface to a cursor. A
+  cursor is the object that can execute SQL statements via an open
+  connection.
+
+An easy example can be found in the sqlite3 module. Here are a few tips:
+
+* The `self.alias` and `self.vendor` properties are present in all
+  DatabaseWrappers.
+* The CursorWrapper doesn't have access to the alias and vendor, so we
+  generate the class in a function that accepts them as arguments.
+* Most methods you overload should just increment a counter, forward
+  all arguments to the original method and return the
+  result. `execute` and `execute_many` should also wrap the call to
+  the parent method in a `try...except` block to increment the
+  `errors_total` counter as appropriate.
diff --git a/django_prometheus/db/backends/__init__.py b/django_prometheus/db/backends/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/django_prometheus/db/backends/mysql/__init__.py b/django_prometheus/db/backends/mysql/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/django_prometheus/db/backends/mysql/base.py b/django_prometheus/db/backends/mysql/base.py
new file mode 100644
index 0000000..2e0f393
--- /dev/null
+++ b/django_prometheus/db/backends/mysql/base.py
@@ -0,0 +1,11 @@
+from django_prometheus.db.common import DatabaseWrapperMixin
+from django.db.backends.mysql import base
+
+
+class DatabaseFeatures(base.DatabaseFeatures):
+    """Our database has the exact same features as the base one."""
+    pass
+
+
+class DatabaseWrapper(DatabaseWrapperMixin, base.DatabaseWrapper):
+    CURSOR_CLASS = base.CursorWrapper
diff --git a/django_prometheus/db/backends/sqlite3/__init__.py b/django_prometheus/db/backends/sqlite3/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/django_prometheus/db/backends/sqlite3/base.py b/django_prometheus/db/backends/sqlite3/base.py
new file mode 100644
index 0000000..66db95f
--- /dev/null
+++ b/django_prometheus/db/backends/sqlite3/base.py
@@ -0,0 +1,11 @@
+from django_prometheus.db.common import DatabaseWrapperMixin
+from django.db.backends.sqlite3 import base
+
+
+class DatabaseFeatures(base.DatabaseFeatures):
+    """Our database has the exact same features as the base one."""
+    pass
+
+
+class DatabaseWrapper(DatabaseWrapperMixin, base.DatabaseWrapper):
+    CURSOR_CLASS = base.SQLiteCursorWrapper
diff --git a/django_prometheus/db/common.py b/django_prometheus/db/common.py
new file mode 100644
index 0000000..1d31003
--- /dev/null
+++ b/django_prometheus/db/common.py
@@ -0,0 +1,72 @@
+from django_prometheus.db import (
+    connections_total, execute_total, execute_many_total, errors_total,
+    connection_errors_total)
+
+
+class ExceptionCounterByType(object):
+    """A context manager that counts exceptions by type.
+
+    Exceptions increment the provided counter, whose last label's name
+    must match the `type_label` argument.
+
+    In other words:
+
+    c = Counter('http_request_exceptions_total', 'Counter of exceptions',
+                ['method', 'type'])
+    with ExceptionCounterByType(c, extra_labels={'method': 'GET'}):
+        handle_get_request()
+    """
+
+    def __init__(self, counter, type_label='type', extra_labels=None):
+        self._counter = counter
+        self._type_label = type_label
+        self._labels = extra_labels
+
+    def __enter__(self):
+        pass
+
+    def __exit__(self, typ, value, traceback):
+        if typ is not None:
+            self._labels.update({self._type_label: typ.__name__})
+            self._counter.labels(self._labels).inc()
+
+
+class DatabaseWrapperMixin(object):
+    """Extends the DatabaseWrapper to count connections and cursors."""
+
+    def get_new_connection(self, *args, **kwargs):
+        connections_total.labels(self.alias, self.vendor).inc()
+        try:
+            return super(DatabaseWrapperMixin, self).get_new_connection(
+                *args, **kwargs)
+        except:
+            connection_errors_total.labels(self.alias, self.vendor).inc()
+            raise
+
+    def create_cursor(self):
+        return self.connection.cursor(factory=ExportingCursorWrapper(
+            self.CURSOR_CLASS, self.alias, self.vendor))
+
+
+def ExportingCursorWrapper(cursor_class, alias, vendor):
+    """Returns a CursorWrapper class that knows its database's alias and
+    vendor name.
+    """
+
+    class CursorWrapper(cursor_class):
+        """Extends the base CursorWrapper to count events."""
+
+        def execute(self, *args, **kwargs):
+            execute_total.labels(alias, vendor).inc()
+            with ExceptionCounterByType(errors_total, extra_labels={
+                    'alias': alias, 'vendor': vendor}):
+                return super(CursorWrapper, self).execute(*args, **kwargs)
+
+        def executemany(self, query, param_list, *args, **kwargs):
+            execute_total.labels(alias, vendor).inc(len(param_list))
+            execute_many_total.labels(alias, vendor).inc(len(param_list))
+            with ExceptionCounterByType(errors_total, extra_labels={
+                    'alias': alias, 'vendor': vendor}):
+                return super(CursorWrapper, self).executemany(
+                    query=query, param_list=param_list, *args, **kwargs)
+    return CursorWrapper
diff --git a/django_prometheus/db/metrics.py b/django_prometheus/db/metrics.py
new file mode 100644
index 0000000..a5370f5
--- /dev/null
+++ b/django_prometheus/db/metrics.py
@@ -0,0 +1,31 @@
+from prometheus_client import Counter
+
+
+connections_total = Counter(
+    'django_db_new_connections_total',
+    'Counter of created connections by database and by vendor.',
+    ['alias', 'vendor'])
+
+connection_errors_total = Counter(
+    'django_db_new_connection_errors_total',
+    'Counter of connection failures by database and by vendor.',
+    ['alias', 'vendor'])
+
+execute_total = Counter(
+    'django_db_execute_total',
+    ('Counter of executed statements by database and by vendor, including'
+     ' bulk executions.'),
+    ['alias', 'vendor'])
+
+
+execute_many_total = Counter(
+    'django_db_execute_many_total',
+    ('Counter of executed statements in bulk operations by database and'
+     ' by vendor.'),
+    ['alias', 'vendor'])
+
+
+errors_total = Counter(
+    'django_db_errors_total',
+    ('Counter of execution errors by database, vendor and exception type.'),
+    ['alias', 'vendor', 'type'])
diff --git a/django_prometheus/exports.py b/django_prometheus/exports.py
new file mode 100644
index 0000000..184bacf
--- /dev/null
+++ b/django_prometheus/exports.py
@@ -0,0 +1,108 @@
+from django.http import HttpResponse
+from django.conf import settings
+try:
+    # Python 2
+    from BaseHTTPServer import HTTPServer
+except ImportError:
+    # Python 3
+    from http.server import HTTPServer
+import logging
+import os
+import prometheus_client
+import threading
+
+
+logger = logging.getLogger(__name__)
+
+
+def SetupPrometheusEndpointOnPort(port, addr=''):
+    """Exports Prometheus metrics on an HTTPServer running in its own thread.
+
+    The server runs on the given port and is by default listenning on
+    all interfaces. This HTTPServer is fully independent of Django and
+    its stack. This offers the advantage that even if Django becomes
+    unable to respond, the HTTPServer will continue to function and
+    export metrics. However, this also means that the features
+    offered by Django (like middlewares or WSGI) can't be used.
+
+    Now here's the really weird part. When Django runs with the
+    auto-reloader enabled (which is the default, you can disable it
+    with `manage.py runserver --noreload`), it forks and executes
+    manage.py twice. That's wasteful but usually OK. It starts being a
+    problem when you try to open a port, like we do. We can detect
+    that we're running under an autoreloader through the presence of
+    the RUN_MAIN environment variable, so we abort if we're trying to
+    export under an autoreloader and trying to open a port.
+    """
+    assert os.environ.get('RUN_MAIN') != 'true', (
+        'The thread-based exporter can\'t be safely used when django\'s '
+        'autoreloader is active. Use the URL exporter, or start django '
+        'with --noreload. See documentation/exports.md.')
+    prometheus_client.start_http_server(port, addr=addr)
+
+
+class PrometheusEndpointServer(threading.Thread):
+    """A thread class that holds an http and makes it serve_forever()."""
+    def __init__(self, httpd, *args, **kwargs):
+        self.httpd = httpd
+        super(PrometheusEndpointServer, self).__init__(*args, **kwargs)
+
+    def run(self):
+        self.httpd.serve_forever()
+
+
+def SetupPrometheusEndpointOnPortRange(port_range, addr=''):
+    """Like SetupPrometheusEndpointOnPort, but tries several ports.
+
+    This is useful when you're running Django as a WSGI application
+    with multiple processes and you want Prometheus to discover all
+    workers. Each worker will grab a port and you can use Prometheus
+    to aggregate accross workers.
+
+    port_range may be any iterable object that contains a list of
+    ports. Typically this would be an xrange of contiguous ports.
+
+    As soon as one port is found that can serve, use this one and stop
+    trying.
+
+    The same caveats regarding autoreload apply. Do not use this when
+    Django's autoreloader is active.
+
+    """
+    assert os.environ.get('RUN_MAIN') != 'true', (
+        'The thread-based exporter can\'t be safely used when django\'s '
+        'autoreloader is active. Use the URL exporter, or start django '
+        'with --noreload. See documentation/exports.md.')
+    for port in port_range:
+        try:
+            httpd = HTTPServer((addr, port), prometheus_client.MetricsHandler)
+        except OSError:
+            continue  # Try next port
+        thread = PrometheusEndpointServer(httpd)
+        thread.daemon = True
+        thread.start()
+        logger.info('Exporting Prometheus /metrics/ on port %s' % port)
+        return  # Stop trying ports at this point
+
+
+def SetupPrometheusExportsFromConfig():
+    """Exports metrics so Prometheus can collect them."""
+    port = getattr(settings, 'PROMETHEUS_METRICS_EXPORT_PORT', None)
+    port_range = getattr(
+        settings, 'PROMETHEUS_METRICS_EXPORT_PORT_RANGE', None)
+    addr = getattr(settings, 'PROMETHEUS_METRICS_EXPORT_ADDRESS', '')
+    if port_range:
+        SetupPrometheusEndpointOnPortRange(port_range, addr)
+    elif port:
+        SetupPrometheusEndpointOnPort(port, addr)
+
+
+def ExportToDjangoView(request):
+    """Exports /metrics as a Django view.
+
+    You can use django_prometheus.urls to map /metrics to this view.
+    """
+    metrics_page = prometheus_client.generate_latest()
+    return HttpResponse(
+        metrics_page,
+        content_type=prometheus_client.CONTENT_TYPE_LATEST)
diff --git a/django_prometheus/middleware.py b/django_prometheus/middleware.py
new file mode 100644
index 0000000..6196e47
--- /dev/null
+++ b/django_prometheus/middleware.py
@@ -0,0 +1,154 @@
+from prometheus_client import Counter, Histogram
+from django_prometheus.utils import Time, TimeSince, PowersOf
+
+requests_total = Counter(
+    'django_http_requests_before_middlewares_total',
+    'Total count of requests before middlewares run.')
+responses_total = Counter(
+    'django_http_responses_before_middlewares_total',
+    'Total count of responses before middlewares run.')
+requests_latency_before = Histogram(
+    'django_http_requests_latency_including_middlewares_seconds',
+    ('Histogram of requests processing time (including middleware '
... 1818 lines suppressed ...

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/python-modules/packages/django-prometheus.git



More information about the Python-modules-commits mailing list