Skip to content

Commit

Permalink
Initial commit.
Browse files Browse the repository at this point in the history
* Implemented views.
* Added Travis CI integration.
  • Loading branch information
audaciouscode committed Aug 4, 2017
1 parent e3b968f commit f47c30f
Show file tree
Hide file tree
Showing 13 changed files with 728 additions and 0 deletions.
426 changes: 426 additions & 0 deletions .pylintrc

Large diffs are not rendered by default.

43 changes: 43 additions & 0 deletions .travis.yml
@@ -0,0 +1,43 @@
dist: trusty

env:

language: python

python:
- 2.7

addons:
postgresql: 9.5
apt:
packages:
- spatialite-bin
- postgresql-9.5-postgis-2.3

before_install:
- export PYTHONPATH=$HOME/builds/audaciouscode/pdk

install:
- pip install -r requirements.txt
- pip install git+git://github.com/tinio/pysqlite.git@extension-enabled#egg=pysqlite

before_script:
- psql -U postgres -c "create extension postgis"
- psql -U postgres -c "CREATE DATABASE travisci;"
- psql -U postgres -c "CREATE EXTENSION postgis" -d travisci
- psql -U postgres -c "CREATE EXTENSION postgis_topology" -d travisci

script:
- cd ..
- mv Django-Nagios-Monitoring nagios_monitor
- mkdir django
- cd django
- django-admin.py startproject nm
- mv ../nagios_monitor nm
- cd nm
- cp nagios_monitor/travis_settings.py nm/settings.py
- python manage.py migrate
- python manage.py test
- cp nagios_monitor/.pylintrc .
- pylint nagios_monitor
- bandit -r .
Empty file added __init__.py
Empty file.
6 changes: 6 additions & 0 deletions admin.py
@@ -0,0 +1,6 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

# from django.contrib import admin

# Register your models here.
8 changes: 8 additions & 0 deletions apps.py
@@ -0,0 +1,8 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.apps import AppConfig


class NagiosMonitorConfig(AppConfig):
name = 'nagios_monitor'
Empty file added migrations/__init__.py
Empty file.
6 changes: 6 additions & 0 deletions models.py
@@ -0,0 +1,6 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

# from django.db import models

# Create your models here.
4 changes: 4 additions & 0 deletions requirements.txt
@@ -0,0 +1,4 @@
Django==1.11.1
psutil==5.2.2
pylint==1.7.1
bandit==1.4.0
6 changes: 6 additions & 0 deletions tests.py
@@ -0,0 +1,6 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

# from django.test import TestCase

# Create your tests here.
98 changes: 98 additions & 0 deletions travis_settings.py
@@ -0,0 +1,98 @@
# pylint: skip-file

"""
Settings.py for testing on Travis CI.
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
import sys

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

SECRET_KEY = 'foobar'

DEBUG = False
ADMINS = [('Chris Karr', 'chris@audacious-software.com')]

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.gis',
'nagios_monitor'
)

MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'passive_data_kit.travis_urls'

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

WSGI_APPLICATION = 'pdk.wsgi.application'

DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'travisci',
'USER': 'postgres',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '',
}
}

if 'test' in sys.argv or 'test_coverage' in sys.argv: #Covers regular testing and django-coverage
DATABASES['default']['ENGINE'] = 'django.contrib.gis.db.backends.spatialite'
# SPATIALITE_LIBRARY_PATH = 'mod_spatialite'

# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = 'static'

21 changes: 21 additions & 0 deletions travis_urls.py
@@ -0,0 +1,21 @@
"""Passive Data Kit URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^monitor/', include('nagios_monitor.urls')),
]
13 changes: 13 additions & 0 deletions urls.py
@@ -0,0 +1,13 @@
# pylint: disable=line-too-long

from django.conf.urls import url

from .views import cpu_load, current_users, disk_usage, total_processes, zombie_processes

urlpatterns = [
url(r'^cpu-load.json$', cpu_load, name='nagios_monitor_cpu_load'),
url(r'^current-users.json$', current_users, name='nagios_monitor_current_users'),
url(r'^disk-usage.json$', disk_usage, name='nagios_monitor_disk_usage'),
url(r'^total-processes.json$', total_processes, name='nagios_monitor_total_processes'),
url(r'^zombie-processes.json$', zombie_processes, name='nagios_monitor_zombie_processes'),
]
97 changes: 97 additions & 0 deletions views.py
@@ -0,0 +1,97 @@
import json

import psutil

from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.http import HttpResponse

def allowed_host(function):
def wrap(request, *args, **kwargs):
ip_address = None

x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')

if x_forwarded_for:
ip_address = x_forwarded_for.split(',')[0]
else:
ip_address = request.META.get('REMOTE_ADDR')

allowed = True

try:
allowed = (ip_address in settings.NAGIOS_MONITOR_ALLOWED_HOSTS)
except AttributeError:
pass

if allowed:
return function(request, *args, **kwargs)

raise PermissionDenied

wrap.__doc__ = function.__doc__
wrap.__name__ = function.__name__

return wrap

@allowed_host
def cpu_load(request): # pylint: disable=unused-argument
payload = {
'cpu_percentage': psutil.cpu_percent(interval=1)
}

return HttpResponse(json.dumps(payload, indent=2), \
content_type='application/json', \
status=201)

@allowed_host
def current_users(request): # pylint: disable=unused-argument
payload = {
'count': len(psutil.users())
}

return HttpResponse(json.dumps(payload, indent=2), \
content_type='application/json', \
status=201)

@allowed_host
def disk_usage(request): # pylint: disable=unused-argument
payload = {}

partitions = psutil.disk_partitions()

for partition in partitions:
usage = psutil.disk_usage(partition.mountpoint)

payload[partition.device] = usage.percent

return HttpResponse(json.dumps(payload, indent=2), \
content_type='application/json', \
status=201)

@allowed_host
def total_processes(request): # pylint: disable=unused-argument
payload = {
'count': len(psutil.pids())
}

return HttpResponse(json.dumps(payload, indent=2), \
content_type='application/json', \
status=201)
@allowed_host
def zombie_processes(request): # pylint: disable=unused-argument
zombie_count = 0

for pid in psutil.pids():
process = psutil.Process(pid=pid)

if process.status() == psutil.STATUS_ZOMBIE:
zombie_count += 1

payload = {
'count': zombie_count
}

return HttpResponse(json.dumps(payload, indent=2), \
content_type='application/json', \
status=201)

0 comments on commit f47c30f

Please sign in to comment.