Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6385445227 | ||
|
|
456bcb7c50 | ||
|
|
277fde9809 | ||
|
|
257b00be1b | ||
|
|
3659215a2f | ||
|
|
7b47e1d6d9 | ||
|
|
e17bf339e2 | ||
|
|
9d737dcd45 | ||
|
|
898578852d | ||
|
|
2a0744f602 | ||
|
|
15cde2cce4 | ||
|
|
d523b4ae99 | ||
|
|
fdb826d5ac | ||
|
|
bcb4b2e713 | ||
|
|
4daf775adb | ||
|
|
2df1f6ab36 | ||
|
|
5ece0c21f9 | ||
|
|
8946234b10 |
No files matched your search
+84
-14
@@ -1,8 +1,12 @@
|
||||
from django.contrib import admin, messages
|
||||
import ipaddress
|
||||
|
||||
from mdb.models import Ip6Address, Interface, Ip4Address, DhcpOption, DhcpCustomField, DomainSrvRecord, DomainTxtRecord, \
|
||||
DomainCnameRecord, DomainARecord, Domain, Host, Ip4Subnet, Ip6Subnet, Nameserver, MailExchange, OperatingSystem, \
|
||||
HostType, DhcpConfig, DomainAAAARecord
|
||||
from django.contrib import admin, messages
|
||||
from django.db.models import Count
|
||||
from mdb.forms import InterfaceForm
|
||||
from mdb.models import (
|
||||
Ip6Address, Interface, Ip4Address, DhcpOption, DhcpCustomField, DomainSrvRecord, DomainTxtRecord,
|
||||
DomainCnameRecord, DomainARecord, Domain, Host, Ip4Subnet, Ip6Subnet, Nameserver, MailExchange, OperatingSystem,
|
||||
HostType, DhcpConfig, DomainAAAARecord)
|
||||
|
||||
|
||||
class Ip6AddressInline(admin.TabularInline):
|
||||
@@ -14,6 +18,7 @@ class InterfaceInline(admin.TabularInline):
|
||||
inlines = [Ip6AddressInline]
|
||||
model = Interface
|
||||
extra = 0
|
||||
form = InterfaceForm
|
||||
|
||||
def get_queryset(self, request):
|
||||
return super(InterfaceInline, self).get_queryset(request).select_related()
|
||||
@@ -33,19 +38,42 @@ class HostAdmin(admin.ModelAdmin):
|
||||
'fields': ('owner', 'location', 'description')
|
||||
}),
|
||||
('Hardware and Software Information', {
|
||||
'fields': (('hostname', 'host_type'), ('pxe_key', 'pxe_installable'), ('brand', 'model'), 'serial_number', ('operating_system', 'virtual'))
|
||||
'fields': (
|
||||
('hostname', 'host_type'),
|
||||
('pxe_key', 'pxe_installable'),
|
||||
('brand', 'model'),
|
||||
'serial_number',
|
||||
('operating_system', 'virtual'))
|
||||
}),
|
||||
# FIXME: Not in use
|
||||
# ('Domain and Kerberos Information', {
|
||||
# 'description': 'If this host is a member of the LDAP domain, you need to tick the request kerberos principal checkbox. A principal will then be created for the host.',
|
||||
# 'classes': ['collapse'],
|
||||
# 'fields': ('request_kerberos_principal', 'kerberos_principal_created',
|
||||
# ('kerberos_principal_name', 'kerberos_principal_created_date'))
|
||||
# }),
|
||||
)
|
||||
actions = ['set_installable']
|
||||
|
||||
def _get_host_warning_message(self, host, ifs):
|
||||
@staticmethod
|
||||
def mac_addresses(host):
|
||||
addresses = host.interface_set.filter(macaddr__isnull=False).values_list('macaddr', flat=True)
|
||||
return ", ".join(addresses)
|
||||
|
||||
@staticmethod
|
||||
def ip_addresses(host):
|
||||
addresses = host.interface_set.filter(ip4address__isnull=False).values_list('ip4address__address', flat=True)
|
||||
return ", ".join(addresses)
|
||||
|
||||
@staticmethod
|
||||
def in_domain(host):
|
||||
domains = host.interface_set.values_list('domain__domain_name', flat=True)
|
||||
return ",".join(domains)
|
||||
|
||||
in_domain.short_description = "in domains"
|
||||
|
||||
@staticmethod
|
||||
def ipv6_enabled(host):
|
||||
ipv6_ifs = host.interface_set.annotate(num_ipv6=Count('ip6address')).filter(num_ipv6__gt=0)
|
||||
return ipv6_ifs.exists()
|
||||
|
||||
ipv6_enabled.boolean = True
|
||||
|
||||
@staticmethod
|
||||
def _get_host_warning_message(host, ifs):
|
||||
ifs_str = ', '.join([_if.name for _if in ifs])
|
||||
return 'Host {} might not be installable since interface(s) {} has no IP set.'.format(host, ifs_str)
|
||||
|
||||
@@ -73,6 +101,11 @@ class Ip4AddressInline(admin.TabularInline):
|
||||
extra = 0
|
||||
readonly_fields = ['address', 'assigned_to_host']
|
||||
|
||||
def assigned_to_host(self, addr):
|
||||
return addr.interface.host
|
||||
|
||||
assigned_to_host.short_description = "Assigned to Host"
|
||||
|
||||
|
||||
class DhcpOptionInline(admin.TabularInline):
|
||||
model = DhcpOption
|
||||
@@ -88,6 +121,31 @@ class SubnetAdmin(admin.ModelAdmin):
|
||||
list_display = ['name', 'network', 'netmask', 'num_addresses', 'broadcast_address', 'first_address', 'last_address']
|
||||
inlines = [DhcpOptionInline, DhcpCustomFieldInline, Ip4AddressInline]
|
||||
|
||||
@staticmethod
|
||||
def num_addresses(ip4subnet):
|
||||
subnet = ipaddress.IPv4Network(ip4subnet.network + "/" + ip4subnet.netmask)
|
||||
return subnet.num_addresses
|
||||
|
||||
@staticmethod
|
||||
def broadcast_address(ip4subnet):
|
||||
subnet = ipaddress.IPv4Network(ip4subnet.network + "/" + ip4subnet.netmask)
|
||||
return subnet.broadcast_address
|
||||
|
||||
@staticmethod
|
||||
def first_address(ip4subnet):
|
||||
subnet = ipaddress.IPv4Network(ip4subnet.network + "/" + ip4subnet.netmask)
|
||||
return next(subnet.hosts())
|
||||
|
||||
@staticmethod
|
||||
def last_address(ip4subnet):
|
||||
subnet = ipaddress.IPv4Network(ip4subnet.network + "/" + ip4subnet.netmask)
|
||||
return list(subnet.hosts())[-1]
|
||||
|
||||
broadcast_address.short_description = 'broadcast'
|
||||
num_addresses.short_description = '#addresses'
|
||||
first_address.short_description = 'first address'
|
||||
last_address.short_description = 'last address'
|
||||
|
||||
def get_queryset(self, request):
|
||||
# TODO: optimize
|
||||
return super(SubnetAdmin, self).get_queryset(request)
|
||||
@@ -124,13 +182,25 @@ class DomainAdmin(admin.ModelAdmin):
|
||||
list_display = ['domain_name', 'domain_soa', 'domain_admin', 'num_records', 'domain_ipaddr', 'domain_ip6addr']
|
||||
search_fields = ['domain_name']
|
||||
|
||||
def num_records(self, domain):
|
||||
host_a_records = Host.objects.filter(interface__domain=domain).count()
|
||||
size = {
|
||||
"CNAME": domain.domaincnamerecord_set.count(),
|
||||
"SRV": domain.domainsrvrecord_set.count(),
|
||||
"TXT": domain.domaintxtrecord_set.count(),
|
||||
"A": domain.domainarecord_set.count() + host_a_records
|
||||
}
|
||||
return ', '.join(['{}: {}'.format(k, v) for k, v in size.items()])
|
||||
|
||||
num_records.short_description = "Num Records"
|
||||
|
||||
|
||||
class HostTypeAdmin(admin.ModelAdmin):
|
||||
list_display = ['host_type', 'description', 'num_members']
|
||||
|
||||
|
||||
class OperatingSystemAdmin(admin.ModelAdmin):
|
||||
list_display = ['name', 'version', 'arch']
|
||||
list_display = ['name', 'version', 'arch', 'pxe_kernel', 'pxe_initrd', 'pxe_preseed_config_url']
|
||||
|
||||
|
||||
admin.site.register(Domain, DomainAdmin)
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
from mdb.models import Host
|
||||
from __future__ import unicode_literals
|
||||
from rest_framework import serializers
|
||||
from rest_framework.exceptions import ValidationError
|
||||
|
||||
from mdb.models import Host
|
||||
|
||||
|
||||
class HostPXEValidateSerializer(serializers.Serializer):
|
||||
certname = serializers.CharField(required=True)
|
||||
@@ -41,6 +43,7 @@ class HostPXEValidateSerializer(serializers.Serializer):
|
||||
def create(self, validated_data):
|
||||
# Make requests kind of idempotent by only allowing 1 request / installation
|
||||
self.host.pxe_installable = False
|
||||
self.host.pxe_key = ''
|
||||
self.host.save()
|
||||
|
||||
return self.host
|
||||
+1
-1
@@ -15,6 +15,6 @@ class HostPXEValidate(APIView):
|
||||
|
||||
serializer.is_valid(raise_exception=True)
|
||||
|
||||
host = serializer.save() # sets Host.pxe_installable=False
|
||||
serializer.save() # sets Host.pxe_installable=False
|
||||
|
||||
return Response({'valid_pxe_key': True})
|
||||
+1
-1
@@ -7,4 +7,4 @@ class MdbAppConfig(AppConfig):
|
||||
|
||||
def ready(self):
|
||||
# all models are loaded, now attach signals
|
||||
import mdb.signals
|
||||
import mdb.signals # noqa
|
||||
@@ -2738,6 +2738,18 @@
|
||||
"model": "mdb.operatingsystem",
|
||||
"pk": 1
|
||||
},
|
||||
{
|
||||
"fields": {
|
||||
"pxe_initrd": "path-to-initrd-for-os",
|
||||
"pxe_kernel": "path-to-kernel-for-os",
|
||||
"pxe_preseed_config_url": "http://url-to-preseed.config",
|
||||
"arch": "x86_64",
|
||||
"name": "Ubuntu",
|
||||
"version": "16.04-beta-final"
|
||||
},
|
||||
"model": "mdb.operatingsystem",
|
||||
"pk": 2
|
||||
},
|
||||
{
|
||||
"fields": {
|
||||
"kerberos_principal_name": "",
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
from django import forms
|
||||
from django.forms import ModelChoiceField
|
||||
|
||||
from mdb.models import Interface, Ip4Address
|
||||
|
||||
|
||||
class Ip4ModelChoiceField(ModelChoiceField):
|
||||
def label_from_instance(self, obj):
|
||||
if not hasattr(obj, 'interface'):
|
||||
return obj.address
|
||||
|
||||
return "{} ({})".format(obj.address, obj.interface.host.hostname)
|
||||
|
||||
|
||||
class InterfaceForm(forms.ModelForm):
|
||||
model = Interface
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super(InterfaceForm, self).__init__(*args, **kwargs)
|
||||
|
||||
# Join Ip4Address with tables interface and host,
|
||||
# before printing the select labels that walk those two relations.
|
||||
queryset = Ip4Address.objects.select_related('interface', 'interface__host')
|
||||
self.fields['ip4address'] = Ip4ModelChoiceField(queryset=queryset)
|
||||
@@ -46,7 +46,7 @@ class Command(BaseCommand):
|
||||
|
||||
# do the binaries exist?
|
||||
for f in (self.checkzone_bin, self.bind_bin):
|
||||
if not os.path.isfile(f):
|
||||
if not os.path.isfile(f) and not debug:
|
||||
print("ERROR: no such file %s, exiting..." % f)
|
||||
if not debug:
|
||||
sys.exit(1)
|
||||
@@ -59,7 +59,7 @@ class Command(BaseCommand):
|
||||
for zone in chain(Domain.objects.all(),
|
||||
Ip4Subnet.objects.all(),
|
||||
Ip6Subnet.objects.all()):
|
||||
if zone.domain_serial == zone.domain_active_serial or force:
|
||||
if zone.domain_serial == zone.domain_active_serial and not force:
|
||||
continue
|
||||
if self.update_zone(zone):
|
||||
self.changes[zone.domain_name]['success'] = True
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('mdb', '0010_auto_20151004_1709'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='operatingsystem',
|
||||
name='pxe_initrd',
|
||||
field=models.CharField(null=True, blank=True, max_length=255),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='operatingsystem',
|
||||
name='pxe_kernel',
|
||||
field=models.CharField(null=True, blank=True, max_length=255),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='operatingsystem',
|
||||
name='pxe_preseed_config_url',
|
||||
field=models.URLField(null=True, blank=True),
|
||||
),
|
||||
]
|
||||
+8
-67
@@ -1,8 +1,7 @@
|
||||
from django.db import models
|
||||
from django.db.models import Count
|
||||
from django.utils.encoding import python_2_unicode_compatible
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
from mdb.utils import host_as_pxe_files
|
||||
from mdb.pxe import host_as_pxe_files
|
||||
|
||||
from mdb.validators import validate_hostname, validate_macaddr
|
||||
|
||||
@@ -50,18 +49,6 @@ class Domain(models.Model):
|
||||
def __str__(self):
|
||||
return self.domain_name
|
||||
|
||||
def num_records(self):
|
||||
host_a_records = Host.objects.filter(interface__domain=self).count()
|
||||
size = {
|
||||
"CNAME": self.domaincnamerecord_set.count(),
|
||||
"SRV": self.domainsrvrecord_set.count(),
|
||||
"TXT": self.domaintxtrecord_set.count(),
|
||||
"A": self.domainarecord_set.count() + host_a_records
|
||||
}
|
||||
return ', '.join(['{}: {}'.format(k, v) for k, v in size.items()])
|
||||
|
||||
num_records.short_description = "Num Records"
|
||||
|
||||
def __eq__(self, other):
|
||||
if not other or not hasattr(other, 'domain_name'):
|
||||
return False
|
||||
@@ -93,7 +80,7 @@ class Domain(models.Model):
|
||||
if self.domain_ipaddr is not None:
|
||||
content += "@\tIN\tA\t%s\n" % self.domain_ipaddr
|
||||
|
||||
if self.domain_ip6addr is not None:
|
||||
if self.domain_ip6addr:
|
||||
content += "@\tIN\tAAAA\t%s\n" % self.domain_ip6addr
|
||||
|
||||
content += "; SRV records\n"
|
||||
@@ -332,7 +319,7 @@ class Ip6Subnet(models.Model):
|
||||
# content += "$ORIGIN " + ".".join(network.exploded.replace(":","")[:16])[::-1] + ".ip6.arpa.\n"
|
||||
|
||||
for addr in self.ip6address_set.all():
|
||||
#if addr.interface_set.count() == 0: continue
|
||||
# if addr.interface_set.count() == 0: continue
|
||||
|
||||
if addr.interface.domain is None:
|
||||
continue
|
||||
@@ -380,27 +367,6 @@ class Ip4Subnet(models.Model):
|
||||
def __str__(self):
|
||||
return self.network + " (" + self.name + ")"
|
||||
|
||||
def num_addresses(self):
|
||||
subnet = ipaddress.IPv4Network(self.network + "/" + self.netmask)
|
||||
return subnet.num_addresses
|
||||
|
||||
def broadcast_address(self):
|
||||
subnet = ipaddress.IPv4Network(self.network + "/" + self.netmask)
|
||||
return subnet.broadcast_address
|
||||
|
||||
def first_address(self):
|
||||
subnet = ipaddress.IPv4Network(self.network + "/" + self.netmask)
|
||||
return next(subnet.hosts())
|
||||
|
||||
def last_address(self):
|
||||
subnet = ipaddress.IPv4Network(self.network + "/" + self.netmask)
|
||||
return list(subnet.hosts())[-1]
|
||||
|
||||
broadcast_address.short_description = 'broadcast'
|
||||
num_addresses.short_description = '#addresses'
|
||||
first_address.short_description = 'first address'
|
||||
last_address.short_description = 'last address'
|
||||
|
||||
def zone_file_contents(self, generate_unassigned=False):
|
||||
content = ""
|
||||
content += "; zone file for %s\n" % self.domain_name
|
||||
@@ -472,16 +438,7 @@ class Ip4Address(models.Model):
|
||||
ping_avg_rtt = models.FloatField(null=True, blank=True)
|
||||
|
||||
def __str__(self):
|
||||
# FIXME: generates 2 SQL queries?
|
||||
if not hasattr(self, 'interface'):
|
||||
return self.address
|
||||
|
||||
return "{} ({})".format(self.address, self.interface.host.hostname)
|
||||
|
||||
def assigned_to_host(self):
|
||||
return self.interface.host
|
||||
|
||||
assigned_to_host.short_description = "Assigned to Host"
|
||||
return self.address
|
||||
|
||||
class Meta:
|
||||
verbose_name = 'IPv4 address'
|
||||
@@ -520,6 +477,10 @@ class OperatingSystem(models.Model):
|
||||
version = models.CharField(max_length=64)
|
||||
arch = models.CharField(max_length=255, choices=OS_ARCHITECTURES, blank=True, null=True)
|
||||
|
||||
pxe_kernel = models.CharField(max_length=255, blank=True, null=True)
|
||||
pxe_initrd = models.CharField(max_length=255, blank=True, null=True)
|
||||
pxe_preseed_config_url = models.URLField(blank=True, null=True)
|
||||
|
||||
def __str__(self):
|
||||
return self.name + " " + self.version + " (" + self.arch + ")"
|
||||
|
||||
@@ -552,26 +513,6 @@ class Host(models.Model):
|
||||
def __str__(self):
|
||||
return self.hostname
|
||||
|
||||
def in_domain(self):
|
||||
domains = self.interface_set.values_list('domain__domain_name', flat=True)
|
||||
return ",".join(domains)
|
||||
|
||||
in_domain.short_description = "in domains"
|
||||
|
||||
def ipv6_enabled(self):
|
||||
ipv6_ifs = self.interface_set.annotate(num_ipv6=Count('ip6address')).filter(num_ipv6__gt=0)
|
||||
return ipv6_ifs.exists()
|
||||
|
||||
ipv6_enabled.boolean = True
|
||||
|
||||
def mac_addresses(self):
|
||||
addresses = self.interface_set.filter(macaddr__isnull=False).values_list('macaddr', flat=True)
|
||||
return ", ".join(addresses)
|
||||
|
||||
def ip_addresses(self):
|
||||
addresses = self.interface_set.filter(ip4address__isnull=False).values_list('ip4address__address', flat=True)
|
||||
return ", ".join(addresses)
|
||||
|
||||
def as_pxe_files(self):
|
||||
return host_as_pxe_files(self)
|
||||
|
||||
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
from django.conf import settings
|
||||
from django.template.loader import render_to_string
|
||||
import ipaddress
|
||||
|
||||
|
||||
def render_pxelinux_cfg(_if, host):
|
||||
"""Renders pxelinux.cfg based on a host and the set of host interfaces,
|
||||
If the host is tied to an OS with PXE fields set, it will use these instead of defaults."""
|
||||
|
||||
# Default config
|
||||
context = {
|
||||
'kernel': settings.MDB_PXE_KERNEL,
|
||||
'initrd': settings.MDB_PXE_INITRD,
|
||||
'preseed_config_url': settings.MDB_PXE_PRESEED_URL,
|
||||
'host': host,
|
||||
'interface': _if
|
||||
}
|
||||
|
||||
# Per host config (via OS model)
|
||||
_os = host.operating_system
|
||||
required_pxe_attrs = [_os.pxe_initrd, _os.pxe_kernel]
|
||||
if None not in required_pxe_attrs and '' not in required_pxe_attrs:
|
||||
context['kernel'] = _os.pxe_kernel
|
||||
context['initrd'] = _os.pxe_initrd
|
||||
|
||||
# optional preseed URL
|
||||
if _os.pxe_preseed_config_url not in ['', None]:
|
||||
context['preseed_config_url'] = _os.pxe_preseed_config_url
|
||||
else:
|
||||
# Per OS config without preseed
|
||||
del context['preseed_config_url']
|
||||
|
||||
return render_to_string('pxelinux.cfg', context=context)
|
||||
|
||||
|
||||
def get_pxe_filename(interface, filename_format='mac_addr'):
|
||||
"""
|
||||
Mac or IP address based PXE filename
|
||||
Ref: http://www.syslinux.org/wiki/index.php/PXELINUX#Examples
|
||||
"""
|
||||
ip_addr_in_hex = '{:02X}'.format(int(ipaddress.IPv4Address(interface.ip4address.address)))
|
||||
formats = {
|
||||
'ip_addr': ip_addr_in_hex,
|
||||
'mac_addr': '01-{}'.format(interface.macaddr.lower().replace(':', '-'))
|
||||
}
|
||||
|
||||
return formats.get(filename_format, formats['mac_addr'])
|
||||
|
||||
|
||||
def host_as_pxe_files(host):
|
||||
"""Returns a list of filename,content for each host interface with an IPv4 address."""
|
||||
from mdb.models import Host
|
||||
assert isinstance(host, Host)
|
||||
|
||||
pxe_files = []
|
||||
for _if in host.interface_set.exclude(ip4address__isnull=True):
|
||||
filename = get_pxe_filename(_if)
|
||||
content = render_pxelinux_cfg(_if, host)
|
||||
pxe_files.append((filename, content))
|
||||
|
||||
return pxe_files
|
||||
@@ -98,9 +98,11 @@ def create_pxe_key_and_write_pxe_files_when_host_changes(sender, instance, creat
|
||||
for pxe_file_name, pxe_file in host.as_pxe_files():
|
||||
path = os.path.join(settings.MDB_PXE_TFTP_ROOT, pxe_file_name)
|
||||
if host.pxe_installable:
|
||||
# Write pxeconfig file to disk
|
||||
with open(path, 'w+') as f:
|
||||
f.write(pxe_file)
|
||||
logger.info("Created or updated {}".format(path))
|
||||
os.chmod(path, 0o644) # Not writeable for all
|
||||
|
||||
# Also set necessary fields for pxe installation
|
||||
interfaces = host.interface_set.exclude(ip4address__isnull=True)
|
||||
@@ -119,6 +121,7 @@ def create_pxe_key_and_write_pxe_files_when_host_changes(sender, instance, creat
|
||||
|
||||
else:
|
||||
if os.path.exists(path):
|
||||
# Delete pxeconfig file from disk
|
||||
os.unlink(path)
|
||||
logger.info("deleted {}".format(path))
|
||||
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
kernel {{kernel}}
|
||||
append ramdisk_size=14984 locale=en_US console-setup/ask_detect=false keyboard-configuration/layoutcode=no netcfg/wireless_wep= netcfg_choose_interface=eth0 netcfg/get_hostname= preseed/url={{preseed_config_url}} vga=normal initrd={{initrd}} -- snop={{host.pxe_key}}
|
||||
default ninja
|
||||
prompt 0
|
||||
timeout 0
|
||||
timeout 0
|
||||
|
||||
label ninja
|
||||
kernel {{kernel}}
|
||||
{% if preseed_config_url %}
|
||||
append ramdisk_size=14984 locale=en_US console-setup/ask_detect=false keyboard-configuration/layoutcode=no netcfg/wireless_wep= netcfg_choose_interface=eth0 netcfg/get_hostname= preseed/url={{preseed_config_url}} vga=normal snop={{host.pxe_key}} initrd={{initrd}} -- quiet
|
||||
{% else %}
|
||||
append locale=en_US console-setup/ask_detect=false keyboard-configuration/layoutcode=no netcfg/wireless_wep= vga=normal initrd={{initrd}} -- quiet
|
||||
{% endif %}
|
||||
+27
-3
@@ -1,12 +1,15 @@
|
||||
import io
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib.auth.models import User
|
||||
from django.core.management import call_command
|
||||
from django.core.urlresolvers import reverse
|
||||
from django.test import TestCase
|
||||
from mdb.pxe import render_pxelinux_cfg
|
||||
from rest_framework.authtoken.models import Token
|
||||
from rest_framework.test import APITestCase
|
||||
|
||||
from mdb.models import Host
|
||||
from mdb.models import Host, OperatingSystem
|
||||
|
||||
|
||||
class MyAPITestCases(APITestCase):
|
||||
@@ -35,6 +38,27 @@ class MyAPITestCases(APITestCase):
|
||||
class UnitTests(TestCase):
|
||||
fixtures = ['test_data']
|
||||
|
||||
def test_render_pxeconfig(self):
|
||||
host = Host.objects.first()
|
||||
interface = host.interface_set.exclude(ip4address__isnull=True).first()
|
||||
config = render_pxelinux_cfg(interface, host)
|
||||
|
||||
self.assertIn(settings.MDB_PXE_INITRD, config)
|
||||
self.assertIn(settings.MDB_PXE_KERNEL, config)
|
||||
self.assertIn(settings.MDB_PXE_PRESEED_URL, config)
|
||||
|
||||
def test_render_pxeconfig_with_os_pxe_config(self):
|
||||
_os = OperatingSystem.objects.get(pk=2) # OS with all pxe vars set
|
||||
Host.objects.filter(pk=Host.objects.first().pk).update(operating_system=_os)
|
||||
host = Host.objects.first()
|
||||
|
||||
interface = host.interface_set.exclude(ip4address__isnull=True).first()
|
||||
config = render_pxelinux_cfg(interface, host)
|
||||
|
||||
self.assertIn(_os.pxe_initrd, config)
|
||||
self.assertIn(_os.pxe_kernel, config)
|
||||
self.assertIn(_os.pxe_preseed_config_url, config)
|
||||
|
||||
def test_host_as_pxe_files(self):
|
||||
host = Host.objects.first()
|
||||
self.assertEqual(len(host.as_pxe_files()), 1)
|
||||
@@ -44,13 +68,13 @@ class RunManagementCommands(TestCase):
|
||||
fixtures = ['test_data']
|
||||
|
||||
def test_zone_sync(self):
|
||||
expected_zone_file = ''
|
||||
# expected_zone_file = ''
|
||||
with io.BytesIO() as f:
|
||||
call_command('zone-sync', debug=True, stdout=f)
|
||||
# TODO check expected_zone_file
|
||||
|
||||
def test_dhcp_sync(self):
|
||||
expected_dhcp_file = ''
|
||||
# expected_dhcp_file = ''
|
||||
with io.BytesIO() as f:
|
||||
call_command('dhcp-sync', stdout=f)
|
||||
# TODO check expected_dhcp_file
|
||||
+1
-48
@@ -1,7 +1,4 @@
|
||||
import datetime
|
||||
from django.conf import settings
|
||||
from django.template.loader import render_to_string
|
||||
import ipaddress
|
||||
import re
|
||||
|
||||
|
||||
@@ -20,7 +17,7 @@ def format_domain_serial_and_add_one(serial):
|
||||
""" The serial contains todays date, just update it. """
|
||||
try:
|
||||
number = int(res[0])
|
||||
except:
|
||||
except ValueError:
|
||||
number = 1
|
||||
if number >= 99:
|
||||
""" This is bad... Just keep the number on 99.
|
||||
@@ -35,47 +32,3 @@ def format_domain_serial_and_add_one(serial):
|
||||
""" Just return the first serial for today. """
|
||||
return "%4d%02d%02d%02d" % \
|
||||
(today.year, today.month, today.day, 1)
|
||||
|
||||
|
||||
def render_pxelinux_cfg(_if, host):
|
||||
# TODO add fields to os model and make dynamic per host
|
||||
distro = 'ubuntu/14_04/amd64/alternate/'
|
||||
kernel = distro + 'linux'
|
||||
initrd = distro + 'initrd.gz'
|
||||
preseed_config_url = settings.MDB_PXE_PRESEED_URL
|
||||
context = {
|
||||
'kernel': kernel,
|
||||
'initrd': initrd,
|
||||
'preseed_config_url': preseed_config_url,
|
||||
'host': host,
|
||||
'interface': _if
|
||||
}
|
||||
return render_to_string('pxelinux.cfg', context=context)
|
||||
|
||||
|
||||
def get_pxe_filename(interface, filename_format='mac_addr'):
|
||||
"""
|
||||
Mac or IP address based PXE filename
|
||||
Ref: http://www.syslinux.org/wiki/index.php/PXELINUX#Examples
|
||||
"""
|
||||
ip_addr_in_hex = '{:02X}'.format(int(ipaddress.IPv4Address(interface.ip4address.address)))
|
||||
formats = {
|
||||
'ip_addr': ip_addr_in_hex,
|
||||
'mac_addr': '01-{}'.format(interface.macaddr.lower().replace(':', '-'))
|
||||
}
|
||||
|
||||
return formats.get(filename_format, formats['mac_addr'])
|
||||
|
||||
|
||||
def host_as_pxe_files(host):
|
||||
""" Returns a list of filename,content for each host interface with an IPv4 address """
|
||||
from mdb.models import Host
|
||||
assert isinstance(host, Host)
|
||||
|
||||
pxe_files = []
|
||||
for _if in host.interface_set.exclude(ip4address__isnull=True):
|
||||
filename = get_pxe_filename(_if)
|
||||
content = render_pxelinux_cfg(_if, host)
|
||||
pxe_files.append((filename, content))
|
||||
|
||||
return pxe_files
|
||||
+4
-1
@@ -76,6 +76,7 @@ INSTALLED_APPS = (
|
||||
'django.contrib.admin',
|
||||
'rest_framework',
|
||||
'rest_framework.authtoken',
|
||||
'django_extensions',
|
||||
|
||||
'mdb',
|
||||
)
|
||||
@@ -115,7 +116,7 @@ SUIT_CONFIG = {
|
||||
),
|
||||
|
||||
# misc
|
||||
'LIST_PER_PAGE': 30
|
||||
'LIST_PER_PAGE': 35
|
||||
}
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',),
|
||||
@@ -123,6 +124,8 @@ REST_FRAMEWORK = {
|
||||
}
|
||||
|
||||
MDB_PXE_TFTP_ROOT = '/var/lib/tftpboot/pxelinux/pxelinux.cfg/'
|
||||
MDB_PXE_KERNEL = 'ubuntu/14_04/amd64/alternate/linux'
|
||||
MDB_PXE_INITRD = 'ubuntu/14_04/amd64/alternate/initrd.gz'
|
||||
MDB_PXE_PRESEED_URL = 'http://158.36.190.194/ubuntu/preseed_1404.cfg'
|
||||
|
||||
try:
|
||||
|
||||
+4
-3
@@ -1,5 +1,6 @@
|
||||
import os
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mdb.settings")
|
||||
|
||||
from django.core.wsgi import get_wsgi_application
|
||||
import os
|
||||
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mdbsite.settings")
|
||||
|
||||
application = get_wsgi_application()
|
||||
+6
-6
@@ -1,7 +1,7 @@
|
||||
Django>=1.8,<1.9
|
||||
django-auth-ldap
|
||||
django-extensions==1.5.7
|
||||
djangorestframework==3.2.4
|
||||
django-suit==0.2.15
|
||||
ipaddress==1.0.14
|
||||
mysqlclient==1.3.6
|
||||
django-auth-ldap==1.2.7
|
||||
django-extensions==1.6.1
|
||||
djangorestframework==3.3.3
|
||||
django-suit==0.2.18
|
||||
ipaddress==1.0.16
|
||||
mysqlclient==1.3.7
|
||||
Reference in new issue
Block a user