From fe0fa743c4dcae694a16ba5337c4e41620258dd4 Mon Sep 17 00:00:00 2001 From: Jason Ross Date: Fri, 9 Sep 2016 10:18:14 -0500 Subject: [PATCH] Add Utilization to PrefixTable --- netbox/ipam/models.py | 31 +++++++++++++++++++++++++++++++ netbox/ipam/tables.py | 3 ++- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/netbox/ipam/models.py b/netbox/ipam/models.py index 0b8b09049..ba4c80455 100644 --- a/netbox/ipam/models.py +++ b/netbox/ipam/models.py @@ -300,7 +300,38 @@ class Prefix(CreatedUpdatedModel, CustomFieldModel): def get_status_class(self): return STATUS_CHOICE_CLASSES[self.status] + + def get_utilization(self): + """ + Determine the utilization rate of the aggregate prefix and return it as a percentage. + """ + if self.vrf: + # If the prefix is in a VRF, show child prefixes only within that VRF. + child_prefixes = Prefix.objects.filter(vrf=self.vrf) + else: + # If the prefix is in the global table, show child prefixes from all VRFs. + child_prefixes = Prefix.objects.all() + child_prefixes = child_prefixes.filter(prefix__net_contained=str(self.prefix))\ + .select_related('site', 'role').annotate_depth(limit=0) + child_ips = IPAddress.objects.filter(vrf=self.vrf, address__net_contained_or_equal=str(self.prefix)) + # Remove overlapping prefixes from list of children + if child_prefixes: + networks = cidr_merge([c.prefix for c in child_prefixes]) + children_size = float(0) + for p in networks: + children_size += p.size + return int(children_size / self.prefix.size * 100) + elif child_ips: + # code to calculate IP Utilization + ipaddress_count = child_ips.count() + + if self.prefix.version == 4 and self.prefix.prefixlen < 31: + return int(((float(ipaddress_count) + 2 )/self.prefix.size) * 100) + else: + return int((float(ipaddress_count) / self.prefix.size ) * 100) + else: + return 0 class IPAddressManager(models.Manager): diff --git a/netbox/ipam/tables.py b/netbox/ipam/tables.py index c669362c5..e39a90f23 100644 --- a/netbox/ipam/tables.py +++ b/netbox/ipam/tables.py @@ -164,10 +164,11 @@ class PrefixTable(BaseTable): site = tables.LinkColumn('dcim:site', args=[Accessor('site.slug')], verbose_name='Site') role = tables.Column(verbose_name='Role') description = tables.Column(orderable=False, verbose_name='Description') + utilization = tables.TemplateColumn(UTILIZATION_GRAPH, orderable=False, verbose_name='Utilization') class Meta(BaseTable.Meta): model = Prefix - fields = ('pk', 'prefix', 'status', 'vrf', 'tenant', 'site', 'role', 'description') + fields = ('pk', 'prefix', 'status', 'utilization', 'vrf', 'tenant', 'site', 'role', 'description') row_attrs = { 'class': lambda record: 'success' if not record.pk else '', }