network_inventory/docs/docs.org

21 KiB

Andreas Zweili

Models

Models define the database layout in a django application. Each class represents a table in the database. A lot the models in this project are very small because they exist mainly to keep the information unified.

Device

The "Device" class is only used as an abstract class.

from django.db import models


class Device(models.Model):
    name = models.CharField(max_length=50)
    description = models.TextField()

    def __str__(self):
        return self.name

GeneralDevice

The "GeneralDevice" model is used to describe devices which are very simple or I don't have much control over.

class GeneralDevice(Device):

    def __str__(self):
        return self.name

Weekday, DayOfMonth and Month

These models contain all the days of the week the days in a month and all month in a year.

class HoursInDay(models.Model):
    name = models.IntegerField()

    def __str__(self):
        return str(self.name)

    class Meta:
        verbose_name_plural = "Hours"
        ordering = ['name']


class MinutesInHour(models.Model):
    name = models.IntegerField()

    def __str__(self):
        return str(self.name)

    class Meta:
        verbose_name_plural = "Minutes"
        ordering = ['name']


class Weekday(models.Model):
    name = models.CharField(max_length=50)
    value = models.IntegerField()

    def __str__(self):
        return self.name

    class Meta:
        ordering = ['value']


class DayOfMonth(models.Model):
    name = models.IntegerField()

    def __str__(self):
        return str(self.name)

    class Meta:
        verbose_name_plural = "Days of Month"
        ordering = ['name']


class Month(models.Model):
    name = models.CharField(max_length=50)
    value = models.IntegerField()

    def __str__(self):
        return self.name

    class Meta:
        ordering = ['value']

RamType, Ram

"RamType" and "Ram" are ment to specify a ram module. "RamType" stands for the DDR verions.

class RamType(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = "Types of RAM Modules"


class Ram(models.Model):
    type = models.ForeignKey(RamType, on_delete=models.CASCADE)
    size_in_gb = models.IntegerField()
    ecc = models.BooleanField(default=False)

    def __str__(self):
        return '{} {} GB'.format(self.type, self.size_in_gb)

    class Meta:
        verbose_name_plural = "RAM Modules"

DiskType, DiskSize, Disk

This three models together represent the various disk types I'm using. The idea is that you define the type then enter a common sizes you're using and then connect everything together in the "Disk" model. This way you have a set of disks you can "insert" into "Computer" models.

class DiskType(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = "Types of disks"


class DiskSize(models.Model):
    size = models.IntegerField()

    def __str__(self):
        return str(self.size) + " GB"

    class Meta:
        verbose_name_plural = "Disk sizes"


class Disk(models.Model):
    type = models.ForeignKey(DiskType, on_delete=models.CASCADE)
    size_in_gb = models.ForeignKey(DiskSize, on_delete=models.CASCADE)

    def __str__(self):
        return '{} {}'.format(self.type, self.size_in_gb)

Architecture, CpuManufacturer and Cpu

"Architecture", "CpuManufacturer" and "Cpu" are the models which together specifiy the properties of a CPU.

class Architecture(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return self.name


class CpuManufacturer(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = "CPU Manufacturers"


class Cpu(models.Model):
    name = models.CharField(max_length=50)
    manufacturer = models.ForeignKey(CpuManufacturer, on_delete=models.PROTECT)
    number_of_cores = models.IntegerField()
    frequency = models.FloatField()
    architecture = models.ForeignKey(Architecture, on_delete=models.PROTECT)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = "CPUs"

OperatingSystem

A simple model to save operating system names.

class OperatingSystem(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = "Operating Systems"

Raid

A model to store the various RAID configurations.

class Raid(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = "Types of RAID"

Computer

This model represents a complete computer, server or virtual machine. It's inheritated from the "Device" model. So that one can link it to a warranty.

class Computer(Device):
    os = models.ForeignKey(OperatingSystem, on_delete=models.PROTECT)
    cpu = models.ManyToManyField(Cpu, through='ComputerCpuRelation')
    ram = models.ManyToManyField(Ram, through='ComputerRamRelation')
    ip = models.CharField(max_length=15)
    disks = models.ManyToManyField(Disk, through='ComputerDiskRelation')
    host = models.ForeignKey('self', null=True, blank=True,
                             on_delete=models.PROTECT)

    def __str__(self):
        return str(self.name)

ComputerDiskRelation, ComputerRamRelation and ComputerCpuRelation

These models are required to link RAM modules, disks and CPUs to a computer. Without these models it wouldn't be possible to specifiy the used amount.

class ComputerDiskRelation(models.Model):
    disk = models.ForeignKey(Disk, on_delete=models.CASCADE)
    computer = models.ForeignKey(Computer, on_delete=models.CASCADE)
    amount = models.IntegerField()
    raid = models.ForeignKey(Raid, null=True, blank=True,
                             on_delete=models.PROTECT)

    def __str__(self):
        return self.computer.name

    class Meta:
        verbose_name_plural = "Disks in Computer"


class ComputerRamRelation(models.Model):
    ram = models.ForeignKey(Ram, on_delete=models.CASCADE)
    computer = models.ForeignKey(Computer, on_delete=models.CASCADE)
    amount = models.IntegerField()

    def __str__(self):
        return self.computer.name

    class Meta:
        verbose_name_plural = "RAM Modules in Computer"


class ComputerCpuRelation(models.Model):
    cpu = models.ForeignKey(Cpu, on_delete=models.CASCADE)
    computer = models.ForeignKey(Computer, on_delete=models.CASCADE)
    amount = models.IntegerField()

    def __str__(self):
        return self.computer.name

    class Meta:
        verbose_name_plural = "CPUs in Computer"

Warranty

As the name suggests this model is for storing warranty informations. In addition it has an attribute for a file so that one can attach a scan of the warranty paper.

class Warranty(models.Model):
    device = models.ForeignKey(Device, on_delete=models.CASCADE)
    files = models.FileField()
    valid_until = models.DateField()

    def __str__(self):
        return self.device

    class Meta:
        verbose_name_plural = "Warranties"

CronJob

This model represents a cron job running on a host. It contains all the information that one would write in a crontab file.

class CronJob(models.Model):
    name = models.CharField(max_length=50)
    host = models.ForeignKey(Computer, on_delete=models.CASCADE)
    command = models.CharField(max_length=50)
    minutes = models.ForeignKey(MinutesInHour, on_delete=models.CASCADE,
                                null=True, blank=True,)
    hours = models.ForeignKey(HoursInDay, on_delete=models.CASCADE,
                              null=True, blank=True,)
    weekday = models.ForeignKey(Weekday, on_delete=models.CASCADE,
                                null=True, blank=True,)
    day = models.ForeignKey(DayOfMonth, on_delete=models.CASCADE,
                            null=True, blank=True,)
    month = models.ForeignKey(Month, on_delete=models.CASCADE,
                              null=True, blank=True,)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = "Cron Jobs"

Admin

The admin file specifies which models are visible and in which way the get shown in the admin interface.

We have to import each model we want to use.

from django.contrib import admin
from inventory.models import (GeneralDevice, HoursInDay,
                              MinutesInHour, Weekday, DayOfMonth,
                              Month, RamType, Ram, DiskType, DiskSize,
                              Disk, Architecture, CpuManufacturer,
                              Cpu, OperatingSystem, Raid, Computer,
                              ComputerDiskRelation,
                              ComputerCpuRelation,
                              ComputerRamRelation, Warranty, CronJob)

InLine classes

I made an inline class for RAM, disks and CPUs and extended the "Computer" admin form with them. This makes it easier to add theme to a computer.

class RamInLine(admin.StackedInline):
    model = ComputerRamRelation
    extra = 0
    verbose_name_plural = 'RAM Modules'


class DiskInLine(admin.StackedInline):
    model = ComputerDiskRelation
    extra = 0
    verbose_name_plural = 'Disks'


class CpusInLine(admin.StackedInline):
    model = ComputerCpuRelation
    extra = 0
    verbose_name_plural = 'CPUs'

Extended Admin Interfaces

This section contains the classes which extend the admin interface for certain models in cases where the default form might not work for the task.

ComputerAdmin

The "ComputerAdmin" class extends the default "Computer" admin interface. For one it adds some columns to the list and adds three inline models which allows to add them directly from the "Computer" form.

class ComputerAdmin(admin.ModelAdmin):
    list_display = ('name', 'ip', 'host')
    inlines = (CpusInLine, RamInLine, DiskInLine,)

CronJobAdmin

The "CronJobAdmin" extends the cron job admin list with two columns to show to which host they belong.

class CronJobAdmin(admin.ModelAdmin):
    list_display = ('name', 'host')

Registering models

In order for the models to show up in the admin interface we have to register them in addition to importing them in the admin.py file. In addition we have to define which admin form they should use if we want to use something different than the default one.

admin.site.register(GeneralDevice)
admin.site.register(HoursInDay)
admin.site.register(MinutesInHour)
admin.site.register(Weekday)
admin.site.register(DayOfMonth)
admin.site.register(Month)
admin.site.register(RamType)
admin.site.register(Ram)
admin.site.register(DiskType)
admin.site.register(DiskSize)
admin.site.register(Disk)
admin.site.register(Architecture)
admin.site.register(CpuManufacturer)
admin.site.register(Cpu)
admin.site.register(OperatingSystem)
admin.site.register(Raid)
admin.site.register(Computer, ComputerAdmin)
admin.site.register(Warranty)
admin.site.register(CronJob, CronJobAdmin)

Views

Views are used to get information from the database and send them to the templates.

#!/usr/bin/python3
from django.shortcuts import get_object_or_404, render
from .models import (GeneralDevice, Computer, CronJob,
                     ComputerRamRelation,
                     ComputerDiskRelation,
                     ComputerCpuRelation)


def index(request):
    device_list = GeneralDevice.objects.all()
    computer_list = Computer.objects.all().order_by('ip')
    cronjob_list = CronJob.objects.all().order_by('host')

    return render(request,
                  'inventory/index.html',
                  {'device_list': device_list,
                   'computer_list': computer_list,
                   'cronjob_list': cronjob_list})


def device_details(request, device_id):
        device = get_object_or_404(GeneralDevice, pk=device_id)
        return render(request, 'inventory/device_details.html',
                      {'device': device})


def computer_details(request, computer_id):
        computer = get_object_or_404(Computer, pk=computer_id)
        disks_list = ComputerDiskRelation.objects.filter(computer=computer_id)
        ram = ComputerRamRelation.objects.get(computer=computer_id)
        cpu = ComputerCpuRelation.objects.get(computer=computer_id)
        cronjob_list = CronJob.objects.filter(host=computer_id)
        return render(request, 'inventory/computer_details.html',
                      {'computer': computer,
                       'disks_list': disks_list,
                       'ram': ram,
                       'cpu': cpu,
                       'cronjob_list': cronjob_list})


def cronjob_details(request, cronjob_id):
        cronjob = get_object_or_404(CronJob, pk=cronjob_id)
        return render(request, 'inventory/cronjob_details.html',
                      {'cronjob': cronjob})

URLs

The urls.py files contain the definitions for the URLs. This means you can define how your various pages get accessed.

network_inventory/urls.py

This is the main URLs file. All the urls.py files need to get registered in here in order to work.

"""network_inventory URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.urls import path

urlpatterns = [
    url(r'', include('inventory.urls')),
    path('admin/', admin.site.urls),
]

inventory/urls.py

Contains the url definitions for the inventory application. For the moment the inventory is my only application so all the URLs will start from the root.

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^device/(?P<device_id>[0-9]+)/$',
        views.device_details,
        name='device'),
    url(r'^computer/(?P<computer_id>[0-9]+)/$',
        views.computer_details,
        name='computer'),
    url(r'^cronjob/(?P<cronjob_id>[0-9]+)/$',
        views.cronjob_details,
        name='cronjob'),
 ]

Templates

Templates define the look of the application and where things get positioned on the page.

base.html

The base.html file is the basis for all other html files and gets extended by them.

{% load staticfiles %}
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="{% static 'css/inventory.css' %}">
</head>
<body>
        <a href="{% url 'index' %}">Home</a>
        <h1>{% block section_title %}Device Inventory{% endblock %}</h1>
        {% block content %}{% endblock %}
</body>
<footer>
    {% block footer %}
    <p><font size="1">Created by Andreas Zweili licensed under GPL v3.0</font></p>
    {% endblock %}
</footer>
</html>

index.html

index.html is the landing page of the project. It gives a list overview over the active devices. In addition it shows some useful information about the devices like IP addresses and similar information.

{% extends "inventory/base.html" %}
{% block content %}
        {% if device_list or computer_list %}
        <h3>Device List</h3>
        <ul>
            {% for device in device_list %}
                <li><a href="{% url 'device' device.id %}">{{ device.name }}</a></li>
            {% endfor %}
        </ul>
        <h3>Computer List</h3>
        <table cellpadding="10">
            <tr>
                <th>Hostname</th>
                <th>IP</th>
            </tr>
            {% for computer in computer_list %}
            <tr>
                <td><a href="{% url 'computer' computer.id %}">{{ computer.name }}</a></td>
                <td>{{ computer.ip }}</td>
            </tr>
            {% endfor %}
        </table>
        {% endif %}
        {% if cronjob_list %}
        <h3>Cron Job List</h3>
        <table cellpadding="10">
            <tr>
                <th>Name</th>
                <th>Hostname</th>
                <th>Minute</th>
                <th>Hour</th>
                <th>Day of Week</th>
                <th>Day of Month</th>
                <th>Month</th>
            </tr>
            {% for cronjob in cronjob_list %}
            <tr>
                <td><a href="{% url 'cronjob' cronjob.id %}">{{ cronjob.name }}</a></td>
                <td>{{ cronjob.host }}</td>
                <td>{{ cronjob.minutes }}</td>
                <td>{{ cronjob.hours }}</td>
                <td>{{ cronjob.weekday }}</td>
                <td>{{ cronjob.day }}</td>
                <td>{{ cronjob.month }}</td>
            </tr>
            {% endfor %}
        </table>
        {% endif %}
{% endblock %}

device_details.html

{% extends "inventory/base.html" %}
{% block section_title %}{{ device.name }}{% endblock %}
{% block content %}
    <h3>Description</h3>
    <p>{{ device.description }}</p>
{% endblock %}

computer_details.html

The computer details show all the known information about the selected computer.

{% extends "inventory/base.html" %}
{% block section_title %}{{ computer.name }}{% endblock %}
{% block content %}
    <h3>Description</h3>
    <p>{{ computer.description }}</p>
    <p><b>OS:</b> {{ computer.os }}</p>
    <p><b>CPU:</b> {{ cpu.cpu }}</p>
    <p><b>RAM Modules: </b>{{ ram.amount }}x {{ ram.ram }}</p>
    <p><b>IP:</b> {{ computer.ip }}</p>
    {% if disks_list %}
    <p><b>Disks:</b></p>
    <p>
        <ul>
            {% for disk in disks_list %}
                <li>{{ disk.amount }}x {{ disk.disk }}</li>
            {% endfor %}
        </ul>
    </p>
    {% endif %}
    <p><b>Host:</b> {{ computer.host }}</p>

The list of cron jobs running on the computer get's only displayed if there are any cron jobs.

    {% if cronjob_list %}
    <p><b>Cron Jobs:</b></p>
    <p>
        <ul>
            {% for cronjob in cronjob_list %}
                <li><a href="{% url 'cronjob' cronjob.id %}">{{ cronjob.name }}
                    {{ cronjob.time }} {{ cronjob.weekday }} {{ cronjob.month }}</a></li>
            {% endfor %}
        </ul>
    </p>
    {% endif %}
{% endblock %}

cronjob_details.html

The cron job details page shows all the information related to a cron job.

{% extends "inventory/base.html" %}
{% block section_title %}{{ cronjob.name }}{% endblock %}
{% block content %}
<h3>Description</h3>
<p><b>Host:</b> {{ cronjob.host }}</p>
<p><b>Command: </b>{{ cronjob.command }}</p>
<table cellpadding="10">
  <tr>
    <th>Minute</th>
    <th>Hour</th>
    <th>Day of Week</th>
    <th>Day of Month</th>
    <th>Month</th>
  </tr>
  <tr>
    <td>{{ cronjob.minutes }}</td>
    <td>{{ cronjob.hours }}</td>
    <td>{{ cronjob.weekday }}</td>
    <td>{{ cronjob.day }}</td>
    <td>{{ cronjob.month }}</td>
  </tr>
</table>
{% endblock %}