Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 26 additions & 21 deletions ping/checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
from django.utils.importlib import import_module
from django.core.exceptions import ImproperlyConfigured

from ping.defaults import *
from ping.defaults import PING_DEFAULT_CHECKS, PING_CELERY_TIMEOUT


def checks(request):
"""
Expand All @@ -11,9 +12,9 @@ def checks(request):
for that check.
"""
response_dict = {}
#Taken straight from Django
#If there is a better way, I don't know it

# Taken straight from Django
# If there is a better way, I don't know it
for path in getattr(settings, 'PING_CHECKS', PING_DEFAULT_CHECKS):
i = path.rfind('.')
module, attr = path[:i], path[i+1:]
Expand All @@ -25,45 +26,49 @@ def checks(request):
func = getattr(mod, attr)
except AttributeError:
raise ImproperlyConfigured('Module "%s" does not define a "%s" callable' % (module, attr))

key, value = func(request)
response_dict[key] = value

return response_dict

#DEFAULT SYSTEM CHECKS

#Database
# DEFAULT SYSTEM CHECKS

# Database
def check_database_sessions(request):
from django.contrib.sessions.models import Session
try:
session = Session.objects.all()[0]
Session.objects.all()[0]
return 'db_sessions', True
except:
return 'db_sessions', False


def check_database_sites(request):
from django.contrib.sites.models import Site
try:
session = Site.objects.all()[0]
Site.objects.all()[0]
return 'db_site', True
except:
return 'db_site', False


#Caching
# Caching
CACHE_KEY = 'django-ping-test'
CACHE_VALUE = 'abc123'

def check_cache_set(request):

def check_cache_set(request):
from django.core.cache import cache
try:
cache.set(CACHE_KEY, CACHE_VALUE, 30)
return 'cache_set', True
except:
return 'cache_set', False

def check_cache_get(request):

def check_cache_get(request):
from django.core.cache import cache
try:
data = cache.get(CACHE_KEY)
Expand All @@ -75,18 +80,18 @@ def check_cache_get(request):
return 'cache_get', False


#User
def check_user_exists(request):
# User
def check_user_exists(request):
from django.contrib.auth.models import User
try:
username = request.GET.get('username')
u = User.objects.get(username=username)
User.objects.get(username=username)
return 'user_exists', True
except:
return 'user_exists', False


#Celery
# Celery
def check_celery(request):
from datetime import datetime, timedelta
from time import sleep, time
Expand All @@ -95,14 +100,14 @@ def check_celery(request):
now = time()
datetimenow = datetime.now()
expires = datetimenow + timedelta(seconds=getattr(settings, 'PING_CELERY_TIMEOUT', PING_CELERY_TIMEOUT))

try:
task = sample_task.apply_async(expires=expires)
while expires > datetime.now():
if task.ready() and task.result == True:
if task.ready() and task.result is True:
finished = str(time() - now)
return 'celery', { 'success': True, 'time':finished }
return 'celery', {'success': True, 'time': finished}
sleep(0.25)
return 'celery', { 'success': False }
return 'celery', {'success': False}
except Exception:
return 'celery', { 'success': False }
return 'celery', {'success': False}
11 changes: 5 additions & 6 deletions ping/decorators.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
from functools import wraps
import base64

from django.http import HttpResponse
from django.contrib.auth import authenticate, login
from django.conf import settings

from ping.defaults import PING_BASIC_AUTH


def http_basic_auth(func):
"""
Attempts to login user with u/p provided in HTTP_AUTHORIZATION header.
If successful, returns the view, otherwise returns a 401.
If PING_BASIC_AUTH is False, then just return the view function
If PING_BASIC_AUTH is False, then just return the view function

Modified code by:
http://djangosnippets.org/users/bthomas/
from
Expand All @@ -21,8 +21,7 @@ def http_basic_auth(func):
@wraps(func)
def _decorator(request, *args, **kwargs):
if getattr(settings, 'PING_BASIC_AUTH', PING_BASIC_AUTH):
from django.contrib.auth import authenticate, login
if request.META.has_key('HTTP_AUTHORIZATION'):
if 'HTTP_AUTHORIZATION' in request.META:
authmeth, auth = request.META['HTTP_AUTHORIZATION'].split(' ', 1)
if authmeth.lower() == 'basic':
auth = auth.strip().decode('base64')
Expand All @@ -37,4 +36,4 @@ def _decorator(request, *args, **kwargs):
return HttpResponse("No Credentials Provided", status=401)
else:
return func(request, *args, **kwargs)
return _decorator
return _decorator
2 changes: 1 addition & 1 deletion ping/defaults.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@

PING_BASIC_AUTH = False

PING_CELERY_TIMEOUT = 5
PING_CELERY_TIMEOUT = 5
2 changes: 1 addition & 1 deletion ping/models.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
from django.db import models
# empty
3 changes: 2 additions & 1 deletion ping/tasks.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from celery.task import task


@task()
def sample_task():
return True
return True
8 changes: 5 additions & 3 deletions ping/urls.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
from django.conf.urls.defaults import patterns, include, url
from django.conf.urls.defaults import patterns, url
from ping.views import status

urlpatterns = patterns('',

urlpatterns = patterns(
'',

url(r'^$', status, name='status'),
)

12 changes: 6 additions & 6 deletions ping/views.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
from django.http import HttpResponse
from django.conf import settings
from django.utils import simplejson
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt

from ping.defaults import *
from ping.defaults import PING_DEFAULT_RESPONSE, PING_DEFAULT_MIMETYPE
from ping.checks import checks
from ping.decorators import http_basic_auth


@csrf_exempt
@http_basic_auth
def status(request):
"""
Returns a simple HttpResponse
"""

response = "<h1>%s</h1>" % getattr(settings, 'PING_DEFAULT_RESPONSE', PING_DEFAULT_RESPONSE)
mimetype = getattr(settings, 'PING_DEFAULT_MIMETYPE', PING_DEFAULT_MIMETYPE)

if request.GET.get('checks') == 'true':
response_dict = checks(request)
response += "<dl>"
Expand All @@ -33,6 +33,6 @@ def status(request):
response_dict = checks(request)
response = simplejson.dumps(response_dict)
response = simplejson.dumps(response_dict, sort_keys=True)
mimetype = 'application/json'
mimetype = 'application/json'

return HttpResponse(response, mimetype=mimetype, status=200)
return HttpResponse(response, mimetype=mimetype, status=200)
49 changes: 25 additions & 24 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,28 @@

version = '0.2.0'

setup(name='django-ping',
version=version,
description="Django Monitoring and Availability Utility",
long_description="",
classifiers=[
"Development Status :: 3 - Alpha",
"Environment :: Web Environment",
"Intended Audience :: End Users/Desktop",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content :: CGI Tools/Libraries",
"Topic :: Utilities",
"License :: OSI Approved :: MIT License",
],
keywords='',
author='Garrett Pennington',
url='',
license='MIT',
packages=find_packages(),
install_requires = [],
include_package_data=True,
zip_safe=False,
)
setup(
name='django-ping',
version=version,
description="Django Monitoring and Availability Utility",
long_description="",
classifiers=[
"Development Status :: 3 - Alpha",
"Environment :: Web Environment",
"Intended Audience :: End Users/Desktop",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content :: CGI Tools/Libraries",
"Topic :: Utilities",
"License :: OSI Approved :: MIT License",
],
keywords='',
author='Garrett Pennington',
url='',
license='MIT',
packages=find_packages(),
install_requires=[],
include_package_data=True,
zip_safe=False,
)