forked from Uninett/nav
/
manage.py
2825 lines (2332 loc) · 90.9 KB
/
manage.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2015 Uninett AS
# Copyright (C) 2022 Sikt
#
# This file is part of Network Administration Visualized (NAV).
#
# NAV is free software: you can redistribute it and/or modify it under the
# terms of the GNU General Public License version 3 as published by the Free
# Software Foundation.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details. You should have received a copy of the GNU General Public
# License along with NAV. If not, see <http://www.gnu.org/licenses/>.
#
"""Django ORM wrapper for the NAV manage database"""
# pylint: disable=R0903
import base64
import datetime as dt
import pickle
import warnings
from functools import partial
from itertools import count, groupby
import logging
import math
import re
from typing import Set
import IPy
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import models
from django.db.models import JSONField, Q
from django.db.models.expressions import RawSQL
from django.urls import reverse
from nav import util
from nav.adapters import HStoreField
from nav.bitvector import BitVector
from nav.metrics.data import get_netboxes_availability
from nav.metrics.graphs import get_simple_graph_url, Graph
from nav.metrics.names import get_all_leaves_below
from nav.metrics.templates import (
metric_prefix_for_interface,
metric_prefix_for_ports,
metric_prefix_for_device,
metric_prefix_for_sensors,
metric_path_for_sensor,
metric_path_for_prefix,
metric_path_for_power,
)
import nav.natsort
from nav.models.fields import DateTimeInfinityField, VarcharField, PointField
from nav.models.fields import CIDRField
import nav.models.event
_logger = logging.getLogger(__name__)
#######################################################################
### Netbox-related models
class UpsManager(models.Manager):
"""Manager for finding UPS netboxes"""
def get_queryset(self):
"""Filter out UPSes"""
return (
super(UpsManager, self)
.get_queryset()
.filter(category='POWER', sensor__internal_name__startswith='ups')
.distinct()
)
class NetboxQuerySet(models.QuerySet):
chassis_serialnum_sql = (
"SELECT device.serial FROM device "
"JOIN netboxentity ne USING (deviceid) "
"WHERE ne.netboxid=netbox.netboxid AND ne.physical_class=%s "
"ORDER BY index ASC "
"LIMIT 1"
)
def on_maintenance(self, on_maintenance):
"""Filter on whether a netbox is in maintenance mode or not"""
on_maintenance = bool(on_maintenance)
alerts = nav.models.event.AlertHistory.objects.unresolved(
'maintenanceState'
).filter(variables__variable='netbox')
netboxes = self.filter(
id__in=(
alerts.filter(netbox__isnull=False).values_list('netbox_id', flat=True)
)
)
if on_maintenance:
return netboxes
return self.difference(netboxes)
def with_chassis_serials(self):
"""Annotates every Netbox with the serial number of its chassis,
if applicable. Stacked netboxes will typically have multiple chassis - in
this case, the one with the lowest index is considered the "master", and its
serial number is used.
Each object will be annotated with the attribute `chassis_serial`
"""
return self.annotate(
chassis_serial=RawSQL(
self.chassis_serialnum_sql, (NetboxEntity.CLASS_CHASSIS,)
)
)
class ManagementProfile(models.Model):
"""Management connection profiles shared between multiple netboxes. These
may include protocols, credentials etc.
"""
id = models.AutoField(db_column='management_profileid', primary_key=True)
name = VarcharField(unique=True)
description = VarcharField(blank=True, null=True)
PROTOCOL_DEBUG = 0
PROTOCOL_SNMP = 1
PROTOCOL_NAPALM = 2
PROTOCOL_CHOICES = [
(PROTOCOL_SNMP, "SNMP"),
(PROTOCOL_NAPALM, "NAPALM"),
]
if settings.DEBUG:
PROTOCOL_CHOICES.insert(0, (PROTOCOL_DEBUG, 'debug'))
protocol = models.IntegerField(choices=PROTOCOL_CHOICES)
configuration = JSONField(default=dict)
class Meta(object):
db_table = 'management_profile'
verbose_name = 'management profile'
verbose_name_plural = 'management profiles'
ordering = ('protocol', 'name')
def __str__(self):
return self.name
@property
def is_snmp(self):
return self.protocol == self.PROTOCOL_SNMP
@property
def snmp_version(self):
"""Returns the configured SNMP version as an integer"""
if self.is_snmp:
value = self.configuration['version']
if value == "2c":
return 2
return int(value)
raise ValueError(
"Getting snmp protocol version for non-snmp management profile"
)
@property
def snmp_community(self):
if self.is_snmp:
return self.configuration['community']
raise ValueError("Getting snmp community for non-snmp management profile")
class NetboxProfile(models.Model):
"""Stores the relation between Netboxes and their management profiles"""
id = models.AutoField(primary_key=True, db_column='netbox_profileid')
netbox = models.ForeignKey('Netbox', on_delete=models.CASCADE, db_column='netboxid')
profile = models.ForeignKey(
'ManagementProfile', on_delete=models.CASCADE, db_column='profileid'
)
class Meta(object):
db_table = 'netbox_profile'
unique_together = (('netbox', 'profile'),)
def __str__(self):
return self.netbox.sysname
class Netbox(models.Model):
"""From NAV Wiki: The netbox table is the heart of the heart so to speak,
the most central table of them all. The netbox tables contains information
on all IP devices that NAV manages with adhering information and
relations."""
UP_UP = 'y'
UP_DOWN = 'n'
UP_SHADOW = 's'
UP_CHOICES = (
(UP_UP, 'up'),
(UP_DOWN, 'down'),
(UP_SHADOW, 'shadow'),
)
id = models.AutoField(db_column='netboxid', primary_key=True)
ip = models.GenericIPAddressField(unique=True)
room = models.ForeignKey('Room', on_delete=models.CASCADE, db_column='roomid')
type = models.ForeignKey(
'NetboxType',
on_delete=models.CASCADE,
db_column='typeid',
blank=True,
null=True,
)
sysname = VarcharField(unique=True, blank=False)
category = models.ForeignKey(
'Category', on_delete=models.CASCADE, db_column='catid'
)
groups = models.ManyToManyField('NetboxGroup', through='NetboxCategory', blank=True)
groups.help_text = ''
organization = models.ForeignKey(
'Organization', on_delete=models.CASCADE, db_column='orgid'
)
profiles = models.ManyToManyField(
'ManagementProfile', through='NetboxProfile', blank=True
)
up = models.CharField(max_length=1, choices=UP_CHOICES, default=UP_UP)
up_since = models.DateTimeField(db_column='upsince', auto_now_add=True)
up_to_date = models.BooleanField(db_column='uptodate', default=False)
discovered = models.DateTimeField(auto_now_add=True)
deleted_at = models.DateTimeField(blank=True, null=True, default=None)
master = models.ForeignKey(
'Netbox',
on_delete=models.CASCADE,
db_column='masterid',
null=True,
blank=True,
default=None,
related_name='instances',
)
data = HStoreField(blank=True, null=True, default=dict)
objects = NetboxQuerySet.as_manager()
ups_objects = UpsManager()
class Meta(object):
db_table = 'netbox'
verbose_name = 'ip device'
verbose_name_plural = 'ip devices'
ordering = ('sysname',)
def __str__(self):
return self.get_short_sysname()
def clean(self):
"""Custom validation"""
# Make sure master cannot be set to self
if self.master and self.pk == self.master.pk:
raise ValidationError('You cannot be your own master')
# Make sure sysname is set
if not self.sysname:
self.sysname = str(self.ip)
@property
def device(self):
"""Property to access the former device-field
Returns the first chassis device if any
"""
for chassis in self.get_chassis().order_by('index'):
return chassis.device
@property
def read_only(self):
"""Returns the read-only SNMP community"""
warnings.warn(
"The Netbox.read_only attribute will be removed in a future release",
category=DeprecationWarning,
stacklevel=2,
)
return self._get_snmp_config('community', writeable=False)
@property
def read_write(self):
"""Returns the read-write SNMP community"""
warnings.warn(
"The Netbox.read_write attribute will be removed in a future release",
category=DeprecationWarning,
stacklevel=2,
)
return self._get_snmp_config('community', writeable=True)
@property
def snmp_version(self):
"""Returns the configured SNMP version as an integer"""
warnings.warn(
"The Netbox.snmp_version attribute will be removed in the next "
"feature release",
category=DeprecationWarning,
stacklevel=2,
)
value = self._get_snmp_config('version')
if value or value == 0:
if value == "2c":
return 2
return int(value)
def _get_snmp_config(self, variable='community', writeable=None):
"""Returns SNMP profile configuration variables, preferring the profile
with the highest available SNMP version.
"""
# TODO: This method can be removed when the SNMP properties above are removed
query = Q(protocol=ManagementProfile.PROTOCOL_SNMP)
if writeable:
query = query & Q(configuration__write=True)
elif writeable is not None:
query = query & (
Q(configuration__write=False) | ~Q(configuration__has_key='write')
)
profiles = sorted(
self.profiles.filter(query),
key=lambda p: str(p.configuration.get('version') or 0),
reverse=True,
)
if profiles:
return profiles[0].configuration.get(variable)
def get_preferred_snmp_management_profile(self, writeable=None):
"""
Returns the snmp management profile with the highest available
SNMP version.
"""
query = Q(protocol=ManagementProfile.PROTOCOL_SNMP)
if writeable:
query = query & Q(configuration__write=True)
elif writeable is not None:
query = query & (
Q(configuration__write=False) | ~Q(configuration__has_key='write')
)
profiles = sorted(
self.profiles.filter(query),
key=lambda p: str(p.configuration.get('version') or 0),
reverse=True,
)
if profiles:
return profiles[0]
def is_up(self):
"""Returns True if the Netbox isn't known to be down or in shadow"""
return self.up == self.UP_UP
def is_snmp_down(self):
"""
Returns True if this netbox has any unresolved snmp agent state alerts
"""
return self.get_unresolved_alerts('snmpAgentState').count() > 0
def get_absolute_url(self):
kwargs = {
'name': self.sysname,
}
return reverse('ipdevinfo-details-by-name', kwargs=kwargs)
def last_updated(self, job='inventory'):
"""Returns the last updated timestamp of a particular job as a
datetime object.
"""
try:
log = self.job_log.filter(success=True, job_name=job).order_by('-end_time')[
0
]
return log.end_time
except IndexError:
return None
def get_last_jobs(self):
"""Returns the last log entry for all jobs"""
query = """
SELECT
ijl.*
FROM ipdevpoll_job_log AS ijl
JOIN (
SELECT
netboxid,
job_name,
MAX(end_time) AS end_time
FROM
ipdevpoll_job_log
GROUP BY netboxid, job_name
) AS foo USING (netboxid, job_name, end_time)
JOIN netbox ON (ijl.netboxid = netbox.netboxid)
WHERE ijl.netboxid = %s
ORDER BY end_time
"""
logs = IpdevpollJobLog.objects.raw(query, [self.id])
return list(logs)
def get_gwport_count(self):
"""Returns the number of all interfaces that have IP addresses."""
return self.get_gwports().count()
def get_gwports(self):
"""Returns all interfaces that have IP addresses."""
return Interface.objects.filter(
netbox=self, gwportprefix__isnull=False
).distinct()
def get_gwports_sorted(self):
"""Returns gwports naturally sorted by interface name"""
ports = self.get_gwports().select_related('module', 'netbox')
return Interface.sort_ports_by_ifname(ports)
def get_swport_count(self):
"""Returns the number of all interfaces that are switch ports."""
return self.get_swports().count()
def get_swports(self):
"""Returns all interfaces that are switch ports."""
return Interface.objects.filter(netbox=self, baseport__isnull=False).distinct()
def get_swports_sorted(self):
"""Returns swports naturally sorted by interface name"""
ports = self.get_swports().select_related('module', 'netbox')
return Interface.sort_ports_by_ifname(ports)
def get_physical_ports(self):
"""Return all ports that are present."""
return Interface.objects.filter(netbox=self, ifconnectorpresent=True).distinct()
def get_physical_ports_sorted(self):
"""Return all ports that are present sorted by interface name."""
ports = self.get_physical_ports().select_related('module', 'netbox')
return Interface.sort_ports_by_ifname(ports)
def get_sensors(self):
"""Returns sensors associated with this netbox"""
return Sensor.objects.filter(netbox=self)
def get_availability(self):
"""Calculates and returns an availability data structure."""
result = get_netboxes_availability([self])
return result.get(self.pk)
def get_week_availability(self):
"""Gets the availability for this netbox for the last week"""
avail = self.get_availability()
try:
return "%.2f%%" % avail["availability"]["week"]
except (KeyError, TypeError):
return "N/A"
def get_uplinks(self):
"""Returns a list of uplinks on this netbox. Requires valid vlan."""
result = []
for iface in self.connected_to_interface.all():
if iface.swport_vlans.filter(direction=SwPortVlan.DIRECTION_DOWN).count():
result.append(
{
'other': iface,
'this': iface.to_interface,
}
)
return result
def get_uplinks_regarding_of_vlan(self):
result = []
for iface in self.connected_to_interface.all():
result.append(
{
'other': iface,
'this': iface.to_interface,
}
)
return result
def get_function(self):
"""Returns the function description of this netbox."""
try:
return self.info_set.get(variable='function').value
except NetboxInfo.DoesNotExist:
return None
def get_prefix(self):
"""Returns the prefix address for this netbox' IP address."""
try:
return self.netboxprefix.prefix
except models.ObjectDoesNotExist:
return None
def get_filtered_prefix(self):
"""Returns the netbox' prefix address only when the prefix is not a
scope, private or reserved prefix.
"""
prefix = self.get_prefix()
if prefix and prefix.vlan.net_type.description in (
'scope',
'private',
'reserved',
):
return None
else:
return prefix
def get_short_sysname(self):
"""Returns sysname without the domain suffix if specified in the
DOMAIN_SUFFIX setting in nav.conf"""
if settings.DOMAIN_SUFFIX is not None and self.sysname.endswith(
settings.DOMAIN_SUFFIX
):
return self.sysname[: -len(settings.DOMAIN_SUFFIX)]
else:
return self.sysname or self.ip
def is_on_maintenance(self):
"""Returns True if this netbox is currently on maintenance"""
states = self.get_unresolved_alerts('maintenanceState').filter(
variables__variable='netbox'
)
return states.count() > 0
def last_downtime_ended(self):
"""
Returns the end_time of the last known boxState alert.
:returns: A datetime object if a serviceState alert was found,
otherwise None
"""
try:
lastdown = self.alert_history_set.filter(
event_type__id='boxState', end_time__isnull=False
).order_by("-end_time")[0]
except IndexError:
return
else:
return lastdown.end_time
def get_unresolved_alerts(self, kind=None):
"""Returns a queryset of unresolved alert states"""
return self.alert_history_set.unresolved(kind)
def get_powersupplies(self):
return self.powersupplyorfan_set.filter(physical_class='powerSupply').order_by(
'name'
)
def get_fans(self):
return self.powersupplyorfan_set.filter(physical_class='fan').order_by('name')
def get_system_metrics(self):
"""Gets a list of available Graphite metrics related to this Netbox,
except for ports and sensors, which are seen as separate.
:returns: A list of dicts describing the metrics, e.g.:
{id:"nav.devices.some-gw.cpu.cpu1.loadavg1min",
group="cpu",
suffix="cpu1.loadavg1min"}
"""
ports_exclude = metric_prefix_for_ports(self.sysname)
sensors_exclude = metric_prefix_for_sensors(self.sysname)
base = metric_prefix_for_device(self.sysname)
nodes = get_all_leaves_below(base, [ports_exclude, sensors_exclude])
result = []
for node in nodes:
suffix = node.replace(base + '.', '')
elements = suffix.split('.')
group = elements[0]
suffix = '.'.join(elements[1:])
result.append(dict(id=node, group=group, suffix=suffix))
return result
def has_unignored_unrecognized_neighbors(self):
"""Returns true if this netbox has unignored unrecognized neighbors"""
return self.unrecognizedneighbor_set.filter(ignored_since=None).count() > 0
def get_chassis(self):
"""Returns a QuerySet of chassis devices seen on this netbox"""
return self.entity_set.filter(
device__isnull=False,
physical_class=NetboxEntity.CLASS_CHASSIS,
).select_related('device')
def get_environment_sensors(self):
"""Returns the sensors to be displayed on the Environment Sensor tab"""
return self.sensor_set.filter(
Q(unit_of_measurement__icontains='celsius')
| Q(unit_of_measurement__icontains='percent')
)
@property
def mac_addresses(self) -> Set[str]:
"""Returns a set of collected chassis MAC addresses for this Netbox"""
macinfo_match = (Q(key="bridge_info") & Q(variable="base_address")) | (
Q(key="lldp") & Q(variable="chassis_mac")
)
macs = self.info_set.filter(macinfo_match).distinct("value").only("value")
return set(mac.value for mac in macs)
class NetboxInfo(models.Model):
"""From NAV Wiki: The netboxinfo table is the place
to store additional info on a netbox."""
id = models.AutoField(db_column='netboxinfoid', primary_key=True)
netbox = models.ForeignKey(
'Netbox',
on_delete=models.CASCADE,
db_column='netboxid',
related_name='info_set',
)
key = VarcharField()
variable = VarcharField(db_column='var')
value = models.TextField(db_column='val')
class Meta(object):
db_table = 'netboxinfo'
unique_together = (('netbox', 'key', 'variable', 'value'),)
def __str__(self):
return u'%s="%s"' % (self.variable, self.value)
@classmethod
def cache_set(cls, netbox, key, variable, value):
"""Attempts to cache a serialized Python value as a NetboxInfo record"""
cache, _ = cls.objects.get_or_create(
netbox_id=netbox.id, key=key, variable=variable
)
cache.value = base64.encodebytes(pickle.dumps(value))
cache.save()
@classmethod
def cache_get(cls, netbox, key, variable):
"""Attempts to fetch and unserialize a cached Python value from a NetboxInfo
record. Returns None if unsucessful for any reason.
"""
try:
cache = cls.objects.get(netbox_id=netbox.id, key=key, variable=variable)
except cls.DoesNotExist:
return None
try:
value = cache.value.encode("utf-8")
remote_table = pickle.loads(base64.decodebytes(value))
return remote_table
except Exception as error:
_logger.debug(
"Unable to unpickle cache value for (%r, %r, %r): %s",
netbox.sysname,
key,
variable,
error,
)
# Broken cache values don't matter, just re-calculate
return None
class NetboxEntity(models.Model):
"""
Represents a physical Entity within a Netbox. Largely modeled after
ENTITY-MIB::entPhysicalTable. See RFC 4133 (and RFC 6933), but may be
filled from other sources where applicable.
"""
# Class choices, extracted from RFC 6933
CLASS_OTHER = 1
CLASS_UNKNOWN = 2
CLASS_CHASSIS = 3
CLASS_BACKPLANE = 4
CLASS_CONTAINER = 5 # e.g., chassis slot or daughter-card holder
CLASS_POWERSUPPLY = 6
CLASS_FAN = 7
CLASS_SENSOR = 8
CLASS_MODULE = 9 # e.g., plug-in card or daughter-card
CLASS_PORT = 10
CLASS_STACK = 11 # e.g., stack of multiple chassis entities
CLASS_CPU = 12
CLASS_ENERGYOBJECT = 13
CLASS_BATTERY = 14
CLASS_CHOICES = (
(CLASS_OTHER, 'other'),
(CLASS_UNKNOWN, 'unknown'),
(CLASS_CHASSIS, 'chassis'),
(CLASS_BACKPLANE, 'backplane'),
(CLASS_CONTAINER, 'container'),
(CLASS_POWERSUPPLY, 'powerSupply'),
(CLASS_FAN, 'fan'),
(CLASS_SENSOR, 'sensor'),
(CLASS_MODULE, 'module'),
(CLASS_PORT, 'port'),
(CLASS_STACK, 'stack'),
(CLASS_CPU, 'cpu'),
(CLASS_ENERGYOBJECT, 'energyObject'),
(CLASS_BATTERY, 'battery'),
)
id = models.AutoField(db_column='netboxentityid', primary_key=True)
netbox = models.ForeignKey(
'Netbox',
on_delete=models.CASCADE,
db_column='netboxid',
related_name='entity_set',
)
index = models.IntegerField()
source = VarcharField(default='ENTITY-MIB')
descr = VarcharField(null=True)
vendor_type = VarcharField(null=True)
contained_in = models.ForeignKey(
'NetboxEntity', on_delete=models.CASCADE, null=True
)
physical_class = models.IntegerField(choices=CLASS_CHOICES, null=True)
parent_relpos = models.IntegerField(null=True)
name = VarcharField(null=True)
hardware_revision = VarcharField(null=True)
firmware_revision = VarcharField(null=True)
software_revision = VarcharField(null=True)
device = models.ForeignKey(
'Device', on_delete=models.CASCADE, null=True, db_column='deviceid'
)
mfg_name = VarcharField(null=True)
model_name = VarcharField(null=True)
alias = VarcharField(null=True)
asset_id = VarcharField(null=True)
fru = models.BooleanField(null=True, verbose_name='Is a field replaceable unit')
mfg_date = models.DateTimeField(null=True)
uris = VarcharField(null=True)
gone_since = models.DateTimeField(null=True)
data = HStoreField(default=dict)
class Meta:
db_table = 'netboxentity'
unique_together = (('netbox', 'index'),)
def __str__(self):
klass = (self.get_physical_class_display() or '').capitalize()
title = self.name or '(Unnamed entity)'
if klass and not title.strip().lower().startswith(klass.lower()):
title = "%s %s" % (klass, title)
try:
netbox = self.netbox
except Netbox.DoesNotExist:
netbox = '(Unknown netbox)'
return "{title} at {netbox}".format(title=title, netbox=netbox)
def is_chassis(self):
"""Returns True if this is a chassis type entity"""
return self.physical_class == self.CLASS_CHASSIS
def get_software_revision(self):
"""Returns the software revision applicable to this entity"""
if not self.is_chassis():
return
if not self.software_revision:
return self._get_applicable_software_revision()
return self.software_revision
def _get_applicable_software_revision(self):
"""Gets an aggregated software revision for this entity"""
from nav.enterprise.ids import VENDOR_ID_CISCOSYSTEMS
if (
self.netbox.type
and self.netbox.type.get_enterprise_id() == VENDOR_ID_CISCOSYSTEMS
):
return self._get_cisco_sup_software_version()
def _get_cisco_sup_software_version(self):
"""Returns the supervisors software version
Finds all modules in the netbox that matches supervisor patterns and has
this entity as a parent. Returns the software version of the first one
in that list.
"""
supervisor_patterns = [
re.compile(r'supervisor', re.I),
re.compile('\bSup\b'),
re.compile(r'WS-SUP'),
]
sup_candidates = []
modules = NetboxEntity.objects.filter(
physical_class=NetboxEntity.CLASS_MODULE, netbox=self.netbox
)
for pattern in supervisor_patterns:
for module in modules:
if pattern.search(module.model_name):
sup_candidates.append(module)
for sup in sup_candidates:
parents = sup.get_parents()
if self in parents and sup.software_revision:
return sup.software_revision
def get_parents(self):
"""Gets the parents of this entity
:rtype: list<NetboxEntity>
"""
parents = []
if self.contained_in:
parents.append(self.contained_in)
parents += self.contained_in.get_parents()
return parents
class NetboxPrefix(models.Model):
"""Which prefix a netbox is connected to.
This models the read-only netboxprefix view.
"""
netbox = models.OneToOneField(
'Netbox', on_delete=models.CASCADE, db_column='netboxid', primary_key=True
)
prefix = models.ForeignKey(
'Prefix',
on_delete=models.CASCADE,
db_column='prefixid',
related_name='netbox_set',
)
class Meta(object):
db_table = 'netboxprefix'
unique_together = (('netbox', 'prefix'),)
def __str__(self):
return u'%s at %s' % (self.netbox.sysname, self.prefix.net_address)
def save(self, *_args, **_kwargs):
"""Does nothing, since this models a database view."""
raise Exception("Cannot save to a view.")
class Device(models.Model):
"""From NAV Wiki: The device table contains all physical devices in the
network. As opposed to the netbox table, the device table focuses on the
physical box with its serial number. The device may appear as different net
boxes or may appear in different modules throughout its lifetime."""
id = models.AutoField(db_column='deviceid', primary_key=True)
serial = VarcharField(unique=True, null=True)
hardware_version = VarcharField(db_column='hw_ver', null=True)
firmware_version = VarcharField(db_column='fw_ver', null=True)
software_version = VarcharField(db_column='sw_ver', null=True)
discovered = models.DateTimeField(default=dt.datetime.now)
class Meta(object):
db_table = 'device'
def __str__(self):
return self.serial or ''
def get_related_objects(self):
"""
Returns the related modules/power supplies/fans/netbox
entities of a device.
"""
modules = self.module_set.all()
power_supplies_or_fans = self.powersupplyorfan_set.all()
netbox_entities = self.netboxentity_set.all()
return modules or power_supplies_or_fans or netbox_entities
def get_preferred_related_object(self):
"""
Returns the first related module/power supply/fan/netbox
entity of a device.
"""
related_objects = self.get_related_objects()
if not related_objects:
return None
if len(related_objects) > 1:
_logger.info(
"Device.get_related_objects(): %s weirdly appears to have "
"duplicate related objects, returning just one",
self,
)
return related_objects[0]
def get_extended_description(self):
"""
Returns the extended description of a device. This is usually
the string representation of an related object.
"""
related_object = self.get_preferred_related_object()
if related_object:
return str(related_object)
return str(self)
class Module(models.Model):
"""From NAV Wiki: The module table defines modules. A module is a part of a
netbox of category GW, SW and GSW. A module has ports; i.e router ports
and/or switch ports. A module is also a physical device with a serial
number."""
UP_UP = 'y'
UP_DOWN = 'n'
UP_CHOICES = (
(UP_UP, 'up'),
(UP_DOWN, 'down'),
)
id = models.AutoField(db_column='moduleid', primary_key=True)
device = models.ForeignKey('Device', on_delete=models.CASCADE, db_column='deviceid')
netbox = models.ForeignKey('Netbox', on_delete=models.CASCADE, db_column='netboxid')
module_number = models.IntegerField(db_column='module')
name = VarcharField()
model = VarcharField()
description = VarcharField(db_column='descr')
up = models.CharField(max_length=1, choices=UP_CHOICES, default=UP_UP)
down_since = models.DateTimeField(db_column='downsince')
class Meta(object):
db_table = 'module'
verbose_name = 'module'
ordering = ('netbox', 'module_number', 'name')
unique_together = (('netbox', 'name'),)
def __str__(self):
return u'{name} at {netbox}'.format(
name=self.name or self.module_number, netbox=self.netbox
)
def get_absolute_url(self):
kwargs = {
'netbox_sysname': self.netbox.sysname,
'module_name': self.name,
}
return reverse('ipdevinfo-module-details', kwargs=kwargs)
def get_gwports(self):
"""Returns all interfaces that have IP addresses."""
return Interface.objects.filter(
module=self, gwportprefix__isnull=False
).distinct()
def get_gwports_sorted(self):
"""Returns gwports naturally sorted by interface name"""
ports = self.get_gwports()
return Interface.sort_ports_by_ifname(ports)
def get_swports(self):
"""Returns all interfaces that are switch ports."""
return Interface.objects.select_related().filter(
module=self, baseport__isnull=False
)
def get_swports_sorted(self):
"""Returns swports naturally sorted by interface name"""
ports = self.get_swports()
return Interface.sort_ports_by_ifname(ports)
def get_physical_ports(self):
"""Return all ports that are present."""
return Interface.objects.filter(module=self, ifconnectorpresent=True).distinct()
def get_physical_ports_sorted(self):
"""Return all ports that are present sorted by interface name."""
ports = self.get_physical_ports()
return Interface.sort_ports_by_ifname(ports)
def is_on_maintenace(self):
"""Returns True if the owning Netbox is on maintenance"""
return self.netbox.is_on_maintenance()
def get_entity(self):
"""
Attempts to find the NetboxEntity entry that corresponds to this module.
:returns: Either a NetboxEntity object or None.
"""
entities = NetboxEntity.objects.filter(netbox=self.netbox, device=self.device)
if entities:
if len(entities) > 1: