models.py 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476
  1. from __future__ import unicode_literals
  2. from collections import OrderedDict
  3. from itertools import count, groupby
  4. from django.conf import settings
  5. from django.contrib.auth.models import User
  6. from django.contrib.contenttypes.fields import GenericRelation
  7. from django.contrib.postgres.fields import ArrayField
  8. from django.core.exceptions import ValidationError
  9. from django.core.validators import MaxValueValidator, MinValueValidator
  10. from django.db import models
  11. from django.db.models import Count, Q, ObjectDoesNotExist
  12. from django.urls import reverse
  13. from django.utils.encoding import python_2_unicode_compatible
  14. from mptt.models import MPTTModel, TreeForeignKey
  15. from circuits.models import Circuit
  16. from extras.models import CustomFieldModel, CustomFieldValue, ImageAttachment
  17. from extras.rpc import RPC_CLIENTS
  18. from tenancy.models import Tenant
  19. from utilities.fields import ColorField, NullableCharField
  20. from utilities.managers import NaturalOrderByManager
  21. from utilities.models import CreatedUpdatedModel
  22. from utilities.utils import csv_format
  23. from .constants import *
  24. from .fields import ASNField, MACAddressField
  25. from .querysets import InterfaceQuerySet
  26. #
  27. # Regions
  28. #
  29. @python_2_unicode_compatible
  30. class Region(MPTTModel):
  31. """
  32. Sites can be grouped within geographic Regions.
  33. """
  34. parent = TreeForeignKey(
  35. 'self', null=True, blank=True, related_name='children', db_index=True, on_delete=models.CASCADE
  36. )
  37. name = models.CharField(max_length=50, unique=True)
  38. slug = models.SlugField(unique=True)
  39. csv_headers = [
  40. 'name', 'slug', 'parent',
  41. ]
  42. class MPTTMeta:
  43. order_insertion_by = ['name']
  44. def __str__(self):
  45. return self.name
  46. def get_absolute_url(self):
  47. return "{}?region={}".format(reverse('dcim:site_list'), self.slug)
  48. def to_csv(self):
  49. return csv_format([
  50. self.name,
  51. self.slug,
  52. self.parent.name if self.parent else None,
  53. ])
  54. #
  55. # Sites
  56. #
  57. class SiteManager(NaturalOrderByManager):
  58. def get_queryset(self):
  59. return self.natural_order_by('name')
  60. @python_2_unicode_compatible
  61. class Site(CreatedUpdatedModel, CustomFieldModel):
  62. """
  63. A Site represents a geographic location within a network; typically a building or campus. The optional facility
  64. field can be used to include an external designation, such as a data center name (e.g. Equinix SV6).
  65. """
  66. name = models.CharField(max_length=50, unique=True)
  67. slug = models.SlugField(unique=True)
  68. region = models.ForeignKey('Region', related_name='sites', blank=True, null=True, on_delete=models.SET_NULL)
  69. tenant = models.ForeignKey(Tenant, related_name='sites', blank=True, null=True, on_delete=models.PROTECT)
  70. facility = models.CharField(max_length=50, blank=True)
  71. asn = ASNField(blank=True, null=True, verbose_name='ASN')
  72. physical_address = models.CharField(max_length=200, blank=True)
  73. shipping_address = models.CharField(max_length=200, blank=True)
  74. contact_name = models.CharField(max_length=50, blank=True)
  75. contact_phone = models.CharField(max_length=20, blank=True)
  76. contact_email = models.EmailField(blank=True, verbose_name="Contact E-mail")
  77. comments = models.TextField(blank=True)
  78. custom_field_values = GenericRelation(CustomFieldValue, content_type_field='obj_type', object_id_field='obj_id')
  79. images = GenericRelation(ImageAttachment)
  80. objects = SiteManager()
  81. csv_headers = [
  82. 'name', 'slug', 'region', 'tenant', 'facility', 'asn', 'contact_name', 'contact_phone', 'contact_email',
  83. ]
  84. class Meta:
  85. ordering = ['name']
  86. def __str__(self):
  87. return self.name
  88. def get_absolute_url(self):
  89. return reverse('dcim:site', args=[self.slug])
  90. def to_csv(self):
  91. return csv_format([
  92. self.name,
  93. self.slug,
  94. self.region.name if self.region else None,
  95. self.tenant.name if self.tenant else None,
  96. self.facility,
  97. self.asn,
  98. self.contact_name,
  99. self.contact_phone,
  100. self.contact_email,
  101. ])
  102. @property
  103. def count_prefixes(self):
  104. return self.prefixes.count()
  105. @property
  106. def count_vlans(self):
  107. return self.vlans.count()
  108. @property
  109. def count_racks(self):
  110. return Rack.objects.filter(site=self).count()
  111. @property
  112. def count_devices(self):
  113. return Device.objects.filter(site=self).count()
  114. @property
  115. def count_circuits(self):
  116. return Circuit.objects.filter(terminations__site=self).count()
  117. #
  118. # Racks
  119. #
  120. @python_2_unicode_compatible
  121. class RackGroup(models.Model):
  122. """
  123. Racks can be grouped as subsets within a Site. The scope of a group will depend on how Sites are defined. For
  124. example, if a Site spans a corporate campus, a RackGroup might be defined to represent each building within that
  125. campus. If a Site instead represents a single building, a RackGroup might represent a single room or floor.
  126. """
  127. name = models.CharField(max_length=50)
  128. slug = models.SlugField()
  129. site = models.ForeignKey('Site', related_name='rack_groups', on_delete=models.CASCADE)
  130. csv_headers = [
  131. 'site', 'name', 'slug',
  132. ]
  133. class Meta:
  134. ordering = ['site', 'name']
  135. unique_together = [
  136. ['site', 'name'],
  137. ['site', 'slug'],
  138. ]
  139. def __str__(self):
  140. return self.name
  141. def get_absolute_url(self):
  142. return "{}?group_id={}".format(reverse('dcim:rack_list'), self.pk)
  143. def to_csv(self):
  144. return csv_format([
  145. self.site,
  146. self.name,
  147. self.slug,
  148. ])
  149. @python_2_unicode_compatible
  150. class RackRole(models.Model):
  151. """
  152. Racks can be organized by functional role, similar to Devices.
  153. """
  154. name = models.CharField(max_length=50, unique=True)
  155. slug = models.SlugField(unique=True)
  156. color = ColorField()
  157. class Meta:
  158. ordering = ['name']
  159. def __str__(self):
  160. return self.name
  161. def get_absolute_url(self):
  162. return "{}?role={}".format(reverse('dcim:rack_list'), self.slug)
  163. class RackManager(NaturalOrderByManager):
  164. def get_queryset(self):
  165. return self.natural_order_by('site__name', 'name')
  166. @python_2_unicode_compatible
  167. class Rack(CreatedUpdatedModel, CustomFieldModel):
  168. """
  169. Devices are housed within Racks. Each rack has a defined height measured in rack units, and a front and rear face.
  170. Each Rack is assigned to a Site and (optionally) a RackGroup.
  171. """
  172. name = models.CharField(max_length=50)
  173. facility_id = NullableCharField(max_length=50, blank=True, null=True, verbose_name='Facility ID')
  174. site = models.ForeignKey('Site', related_name='racks', on_delete=models.PROTECT)
  175. group = models.ForeignKey('RackGroup', related_name='racks', blank=True, null=True, on_delete=models.SET_NULL)
  176. tenant = models.ForeignKey(Tenant, blank=True, null=True, related_name='racks', on_delete=models.PROTECT)
  177. role = models.ForeignKey('RackRole', related_name='racks', blank=True, null=True, on_delete=models.PROTECT)
  178. serial = models.CharField(max_length=50, blank=True, verbose_name='Serial number')
  179. type = models.PositiveSmallIntegerField(choices=RACK_TYPE_CHOICES, blank=True, null=True, verbose_name='Type')
  180. width = models.PositiveSmallIntegerField(choices=RACK_WIDTH_CHOICES, default=RACK_WIDTH_19IN, verbose_name='Width',
  181. help_text='Rail-to-rail width')
  182. u_height = models.PositiveSmallIntegerField(default=42, verbose_name='Height (U)',
  183. validators=[MinValueValidator(1), MaxValueValidator(100)])
  184. desc_units = models.BooleanField(default=False, verbose_name='Descending units',
  185. help_text='Units are numbered top-to-bottom')
  186. comments = models.TextField(blank=True)
  187. custom_field_values = GenericRelation(CustomFieldValue, content_type_field='obj_type', object_id_field='obj_id')
  188. images = GenericRelation(ImageAttachment)
  189. objects = RackManager()
  190. csv_headers = [
  191. 'site', 'group_name', 'name', 'facility_id', 'tenant', 'role', 'type', 'serial', 'width', 'u_height',
  192. 'desc_units',
  193. ]
  194. class Meta:
  195. ordering = ['site', 'name']
  196. unique_together = [
  197. ['site', 'name'],
  198. ['site', 'facility_id'],
  199. ]
  200. def __str__(self):
  201. return self.display_name or super(Rack, self).__str__()
  202. def get_absolute_url(self):
  203. return reverse('dcim:rack', args=[self.pk])
  204. def clean(self):
  205. if self.pk:
  206. # Validate that Rack is tall enough to house the installed Devices
  207. top_device = Device.objects.filter(rack=self).exclude(position__isnull=True).order_by('-position').first()
  208. if top_device:
  209. min_height = top_device.position + top_device.device_type.u_height - 1
  210. if self.u_height < min_height:
  211. raise ValidationError({
  212. 'u_height': "Rack must be at least {}U tall to house currently installed devices.".format(
  213. min_height
  214. )
  215. })
  216. # Validate that Rack was assigned a group of its same site, if applicable
  217. if self.group:
  218. if self.group.site != self.site:
  219. raise ValidationError({
  220. 'group': "Rack group must be from the same site, {}.".format(self.site)
  221. })
  222. def save(self, *args, **kwargs):
  223. # Record the original site assignment for this rack.
  224. _site_id = None
  225. if self.pk:
  226. _site_id = Rack.objects.get(pk=self.pk).site_id
  227. super(Rack, self).save(*args, **kwargs)
  228. # Update racked devices if the assigned Site has been changed.
  229. if _site_id is not None and self.site_id != _site_id:
  230. Device.objects.filter(rack=self).update(site_id=self.site.pk)
  231. def to_csv(self):
  232. return csv_format([
  233. self.site.name,
  234. self.group.name if self.group else None,
  235. self.name,
  236. self.facility_id,
  237. self.tenant.name if self.tenant else None,
  238. self.role.name if self.role else None,
  239. self.get_type_display() if self.type else None,
  240. self.serial,
  241. self.width,
  242. self.u_height,
  243. self.desc_units,
  244. ])
  245. @property
  246. def units(self):
  247. if self.desc_units:
  248. return range(1, self.u_height + 1)
  249. else:
  250. return reversed(range(1, self.u_height + 1))
  251. @property
  252. def display_name(self):
  253. if self.facility_id:
  254. return "{} ({})".format(self.name, self.facility_id)
  255. elif self.name:
  256. return self.name
  257. return ""
  258. def get_rack_units(self, face=RACK_FACE_FRONT, exclude=None, remove_redundant=False):
  259. """
  260. Return a list of rack units as dictionaries. Example: {'device': None, 'face': 0, 'id': 48, 'name': 'U48'}
  261. Each key 'device' is either a Device or None. By default, multi-U devices are repeated for each U they occupy.
  262. :param face: Rack face (front or rear)
  263. :param exclude: PK of a Device to exclude (optional); helpful when relocating a Device within a Rack
  264. :param remove_redundant: If True, rack units occupied by a device already listed will be omitted
  265. """
  266. elevation = OrderedDict()
  267. for u in self.units:
  268. elevation[u] = {'id': u, 'name': 'U{}'.format(u), 'face': face, 'device': None}
  269. # Add devices to rack units list
  270. if self.pk:
  271. for device in Device.objects.select_related('device_type__manufacturer', 'device_role')\
  272. .annotate(devicebay_count=Count('device_bays'))\
  273. .exclude(pk=exclude)\
  274. .filter(rack=self, position__gt=0)\
  275. .filter(Q(face=face) | Q(device_type__is_full_depth=True)):
  276. if remove_redundant:
  277. elevation[device.position]['device'] = device
  278. for u in range(device.position + 1, device.position + device.device_type.u_height):
  279. elevation.pop(u, None)
  280. else:
  281. for u in range(device.position, device.position + device.device_type.u_height):
  282. elevation[u]['device'] = device
  283. return [u for u in elevation.values()]
  284. def get_front_elevation(self):
  285. return self.get_rack_units(face=RACK_FACE_FRONT, remove_redundant=True)
  286. def get_rear_elevation(self):
  287. return self.get_rack_units(face=RACK_FACE_REAR, remove_redundant=True)
  288. def get_available_units(self, u_height=1, rack_face=None, exclude=list()):
  289. """
  290. Return a list of units within the rack available to accommodate a device of a given U height (default 1).
  291. Optionally exclude one or more devices when calculating empty units (needed when moving a device from one
  292. position to another within a rack).
  293. :param u_height: Minimum number of contiguous free units required
  294. :param rack_face: The face of the rack (front or rear) required; 'None' if device is full depth
  295. :param exclude: List of devices IDs to exclude (useful when moving a device within a rack)
  296. """
  297. # Gather all devices which consume U space within the rack
  298. devices = self.devices.select_related('device_type').filter(position__gte=1).exclude(pk__in=exclude)
  299. # Initialize the rack unit skeleton
  300. units = list(range(1, self.u_height + 1))
  301. # Remove units consumed by installed devices
  302. for d in devices:
  303. if rack_face is None or d.face == rack_face or d.device_type.is_full_depth:
  304. for u in range(d.position, d.position + d.device_type.u_height):
  305. try:
  306. units.remove(u)
  307. except ValueError:
  308. # Found overlapping devices in the rack!
  309. pass
  310. # Remove units without enough space above them to accommodate a device of the specified height
  311. available_units = []
  312. for u in units:
  313. if set(range(u, u + u_height)).issubset(units):
  314. available_units.append(u)
  315. return list(reversed(available_units))
  316. def get_reserved_units(self):
  317. """
  318. Return a dictionary mapping all reserved units within the rack to their reservation.
  319. """
  320. reserved_units = {}
  321. for r in self.reservations.all():
  322. for u in r.units:
  323. reserved_units[u] = r
  324. return reserved_units
  325. def get_0u_devices(self):
  326. return self.devices.filter(position=0)
  327. def get_utilization(self):
  328. """
  329. Determine the utilization rate of the rack and return it as a percentage.
  330. """
  331. u_available = len(self.get_available_units())
  332. return int(float(self.u_height - u_available) / self.u_height * 100)
  333. @python_2_unicode_compatible
  334. class RackReservation(models.Model):
  335. """
  336. One or more reserved units within a Rack.
  337. """
  338. rack = models.ForeignKey('Rack', related_name='reservations', on_delete=models.CASCADE)
  339. units = ArrayField(models.PositiveSmallIntegerField())
  340. created = models.DateTimeField(auto_now_add=True)
  341. tenant = models.ForeignKey(Tenant, blank=True, null=True, related_name='rackreservations', on_delete=models.PROTECT)
  342. user = models.ForeignKey(User, on_delete=models.PROTECT)
  343. description = models.CharField(max_length=100)
  344. class Meta:
  345. ordering = ['created']
  346. def __str__(self):
  347. return "Reservation for rack {}".format(self.rack)
  348. def clean(self):
  349. if self.units:
  350. # Validate that all specified units exist in the Rack.
  351. invalid_units = [u for u in self.units if u not in self.rack.units]
  352. if invalid_units:
  353. raise ValidationError({
  354. 'units': "Invalid unit(s) for {}U rack: {}".format(
  355. self.rack.u_height,
  356. ', '.join([str(u) for u in invalid_units]),
  357. ),
  358. })
  359. # Check that none of the units has already been reserved for this Rack.
  360. reserved_units = []
  361. for resv in self.rack.reservations.exclude(pk=self.pk):
  362. reserved_units += resv.units
  363. conflicting_units = [u for u in self.units if u in reserved_units]
  364. if conflicting_units:
  365. raise ValidationError({
  366. 'units': 'The following units have already been reserved: {}'.format(
  367. ', '.join([str(u) for u in conflicting_units]),
  368. )
  369. })
  370. @property
  371. def unit_list(self):
  372. """
  373. Express the assigned units as a string of summarized ranges. For example:
  374. [0, 1, 2, 10, 14, 15, 16] => "0-2, 10, 14-16"
  375. """
  376. group = (list(x) for _, x in groupby(sorted(self.units), lambda x, c=count(): next(c) - x))
  377. return ', '.join('-'.join(map(str, (g[0], g[-1])[:len(g)])) for g in group)
  378. #
  379. # Device Types
  380. #
  381. @python_2_unicode_compatible
  382. class Manufacturer(models.Model):
  383. """
  384. A Manufacturer represents a company which produces hardware devices; for example, Juniper or Dell.
  385. """
  386. name = models.CharField(max_length=50, unique=True)
  387. slug = models.SlugField(unique=True)
  388. csv_headers = [
  389. 'name', 'slug',
  390. ]
  391. class Meta:
  392. ordering = ['name']
  393. def __str__(self):
  394. return self.name
  395. def get_absolute_url(self):
  396. return "{}?manufacturer={}".format(reverse('dcim:devicetype_list'), self.slug)
  397. def to_csv(self):
  398. return csv_format([
  399. self.name,
  400. self.slug,
  401. ])
  402. @python_2_unicode_compatible
  403. class DeviceType(models.Model, CustomFieldModel):
  404. """
  405. A DeviceType represents a particular make (Manufacturer) and model of device. It specifies rack height and depth, as
  406. well as high-level functional role(s).
  407. Each DeviceType can have an arbitrary number of component templates assigned to it, which define console, power, and
  408. interface objects. For example, a Juniper EX4300-48T DeviceType would have:
  409. * 1 ConsolePortTemplate
  410. * 2 PowerPortTemplates
  411. * 48 InterfaceTemplates
  412. When a new Device of this type is created, the appropriate console, power, and interface objects (as defined by the
  413. DeviceType) are automatically created as well.
  414. """
  415. manufacturer = models.ForeignKey('Manufacturer', related_name='device_types', on_delete=models.PROTECT)
  416. model = models.CharField(max_length=50)
  417. slug = models.SlugField()
  418. part_number = models.CharField(max_length=50, blank=True, help_text="Discrete part number (optional)")
  419. u_height = models.PositiveSmallIntegerField(verbose_name='Height (U)', default=1)
  420. is_full_depth = models.BooleanField(default=True, verbose_name="Is full depth",
  421. help_text="Device consumes both front and rear rack faces")
  422. interface_ordering = models.PositiveSmallIntegerField(choices=IFACE_ORDERING_CHOICES,
  423. default=IFACE_ORDERING_POSITION)
  424. is_console_server = models.BooleanField(default=False, verbose_name='Is a console server',
  425. help_text="This type of device has console server ports")
  426. is_pdu = models.BooleanField(default=False, verbose_name='Is a PDU',
  427. help_text="This type of device has power outlets")
  428. is_network_device = models.BooleanField(default=True, verbose_name='Is a network device',
  429. help_text="This type of device has network interfaces")
  430. subdevice_role = models.NullBooleanField(default=None, verbose_name='Parent/child status',
  431. choices=SUBDEVICE_ROLE_CHOICES,
  432. help_text="Parent devices house child devices in device bays. Select "
  433. "\"None\" if this device type is neither a parent nor a child.")
  434. comments = models.TextField(blank=True)
  435. custom_field_values = GenericRelation(CustomFieldValue, content_type_field='obj_type', object_id_field='obj_id')
  436. csv_headers = [
  437. 'manufacturer', 'model', 'slug', 'part_number', 'u_height', 'is_full_depth', 'is_console_server',
  438. 'is_pdu', 'is_network_device', 'subdevice_role', 'interface_ordering',
  439. ]
  440. class Meta:
  441. ordering = ['manufacturer', 'model']
  442. unique_together = [
  443. ['manufacturer', 'model'],
  444. ['manufacturer', 'slug'],
  445. ]
  446. def __str__(self):
  447. return self.model
  448. def __init__(self, *args, **kwargs):
  449. super(DeviceType, self).__init__(*args, **kwargs)
  450. # Save a copy of u_height for validation in clean()
  451. self._original_u_height = self.u_height
  452. def get_absolute_url(self):
  453. return reverse('dcim:devicetype', args=[self.pk])
  454. def to_csv(self):
  455. return csv_format([
  456. self.manufacturer.name,
  457. self.model,
  458. self.slug,
  459. self.part_number,
  460. self.u_height,
  461. self.is_full_depth,
  462. self.is_console_server,
  463. self.is_pdu,
  464. self.is_network_device,
  465. self.get_subdevice_role_display() if self.subdevice_role else None,
  466. self.get_interface_ordering_display(),
  467. ])
  468. def clean(self):
  469. # If editing an existing DeviceType to have a larger u_height, first validate that *all* instances of it have
  470. # room to expand within their racks. This validation will impose a very high performance penalty when there are
  471. # many instances to check, but increasing the u_height of a DeviceType should be a very rare occurrence.
  472. if self.pk is not None and self.u_height > self._original_u_height:
  473. for d in Device.objects.filter(device_type=self, position__isnull=False):
  474. face_required = None if self.is_full_depth else d.face
  475. u_available = d.rack.get_available_units(u_height=self.u_height, rack_face=face_required,
  476. exclude=[d.pk])
  477. if d.position not in u_available:
  478. raise ValidationError({
  479. 'u_height': "Device {} in rack {} does not have sufficient space to accommodate a height of "
  480. "{}U".format(d, d.rack, self.u_height)
  481. })
  482. if not self.is_console_server and self.cs_port_templates.count():
  483. raise ValidationError({
  484. 'is_console_server': "Must delete all console server port templates associated with this device before "
  485. "declassifying it as a console server."
  486. })
  487. if not self.is_pdu and self.power_outlet_templates.count():
  488. raise ValidationError({
  489. 'is_pdu': "Must delete all power outlet templates associated with this device before declassifying it "
  490. "as a PDU."
  491. })
  492. if not self.is_network_device and self.interface_templates.filter(mgmt_only=False).count():
  493. raise ValidationError({
  494. 'is_network_device': "Must delete all non-management-only interface templates associated with this "
  495. "device before declassifying it as a network device."
  496. })
  497. if self.subdevice_role != SUBDEVICE_ROLE_PARENT and self.device_bay_templates.count():
  498. raise ValidationError({
  499. 'subdevice_role': "Must delete all device bay templates associated with this device before "
  500. "declassifying it as a parent device."
  501. })
  502. if self.u_height and self.subdevice_role == SUBDEVICE_ROLE_CHILD:
  503. raise ValidationError({
  504. 'u_height': "Child device types must be 0U."
  505. })
  506. @property
  507. def full_name(self):
  508. return '{} {}'.format(self.manufacturer.name, self.model)
  509. @property
  510. def is_parent_device(self):
  511. return bool(self.subdevice_role)
  512. @property
  513. def is_child_device(self):
  514. return bool(self.subdevice_role is False)
  515. @python_2_unicode_compatible
  516. class ConsolePortTemplate(models.Model):
  517. """
  518. A template for a ConsolePort to be created for a new Device.
  519. """
  520. device_type = models.ForeignKey('DeviceType', related_name='console_port_templates', on_delete=models.CASCADE)
  521. name = models.CharField(max_length=50)
  522. class Meta:
  523. ordering = ['device_type', 'name']
  524. unique_together = ['device_type', 'name']
  525. def __str__(self):
  526. return self.name
  527. @python_2_unicode_compatible
  528. class ConsoleServerPortTemplate(models.Model):
  529. """
  530. A template for a ConsoleServerPort to be created for a new Device.
  531. """
  532. device_type = models.ForeignKey('DeviceType', related_name='cs_port_templates', on_delete=models.CASCADE)
  533. name = models.CharField(max_length=50)
  534. class Meta:
  535. ordering = ['device_type', 'name']
  536. unique_together = ['device_type', 'name']
  537. def __str__(self):
  538. return self.name
  539. @python_2_unicode_compatible
  540. class PowerPortTemplate(models.Model):
  541. """
  542. A template for a PowerPort to be created for a new Device.
  543. """
  544. device_type = models.ForeignKey('DeviceType', related_name='power_port_templates', on_delete=models.CASCADE)
  545. name = models.CharField(max_length=50)
  546. class Meta:
  547. ordering = ['device_type', 'name']
  548. unique_together = ['device_type', 'name']
  549. def __str__(self):
  550. return self.name
  551. @python_2_unicode_compatible
  552. class PowerOutletTemplate(models.Model):
  553. """
  554. A template for a PowerOutlet to be created for a new Device.
  555. """
  556. device_type = models.ForeignKey('DeviceType', related_name='power_outlet_templates', on_delete=models.CASCADE)
  557. name = models.CharField(max_length=50)
  558. class Meta:
  559. ordering = ['device_type', 'name']
  560. unique_together = ['device_type', 'name']
  561. def __str__(self):
  562. return self.name
  563. @python_2_unicode_compatible
  564. class InterfaceTemplate(models.Model):
  565. """
  566. A template for a physical data interface on a new Device.
  567. """
  568. device_type = models.ForeignKey('DeviceType', related_name='interface_templates', on_delete=models.CASCADE)
  569. name = models.CharField(max_length=64)
  570. form_factor = models.PositiveSmallIntegerField(choices=IFACE_FF_CHOICES, default=IFACE_FF_10GE_SFP_PLUS)
  571. mgmt_only = models.BooleanField(default=False, verbose_name='Management only')
  572. objects = InterfaceQuerySet.as_manager()
  573. class Meta:
  574. ordering = ['device_type', 'name']
  575. unique_together = ['device_type', 'name']
  576. def __str__(self):
  577. return self.name
  578. @python_2_unicode_compatible
  579. class DeviceBayTemplate(models.Model):
  580. """
  581. A template for a DeviceBay to be created for a new parent Device.
  582. """
  583. device_type = models.ForeignKey('DeviceType', related_name='device_bay_templates', on_delete=models.CASCADE)
  584. name = models.CharField(max_length=50)
  585. class Meta:
  586. ordering = ['device_type', 'name']
  587. unique_together = ['device_type', 'name']
  588. def __str__(self):
  589. return self.name
  590. #
  591. # Devices
  592. #
  593. @python_2_unicode_compatible
  594. class DeviceRole(models.Model):
  595. """
  596. Devices are organized by functional role; for example, "Core Switch" or "File Server". Each DeviceRole is assigned a
  597. color to be used when displaying rack elevations. The vm_role field determines whether the role is applicable to
  598. virtual machines as well.
  599. """
  600. name = models.CharField(max_length=50, unique=True)
  601. slug = models.SlugField(unique=True)
  602. color = ColorField()
  603. vm_role = models.BooleanField(
  604. default=True,
  605. verbose_name="VM Role",
  606. help_text="Virtual machines may be assigned to this role"
  607. )
  608. class Meta:
  609. ordering = ['name']
  610. def __str__(self):
  611. return self.name
  612. def get_absolute_url(self):
  613. return "{}?role={}".format(reverse('dcim:device_list'), self.slug)
  614. @python_2_unicode_compatible
  615. class Platform(models.Model):
  616. """
  617. Platform refers to the software or firmware running on a Device; for example, "Cisco IOS-XR" or "Juniper Junos".
  618. NetBox uses Platforms to determine how to interact with devices when pulling inventory data or other information by
  619. specifying an remote procedure call (RPC) client.
  620. """
  621. name = models.CharField(max_length=50, unique=True)
  622. slug = models.SlugField(unique=True)
  623. napalm_driver = models.CharField(max_length=50, blank=True, verbose_name='NAPALM driver',
  624. help_text="The name of the NAPALM driver to use when interacting with devices.")
  625. rpc_client = models.CharField(max_length=30, choices=RPC_CLIENT_CHOICES, blank=True,
  626. verbose_name='Legacy RPC client')
  627. class Meta:
  628. ordering = ['name']
  629. def __str__(self):
  630. return self.name
  631. def get_absolute_url(self):
  632. return "{}?platform={}".format(reverse('dcim:device_list'), self.slug)
  633. class DeviceManager(NaturalOrderByManager):
  634. def get_queryset(self):
  635. return self.natural_order_by('name')
  636. @python_2_unicode_compatible
  637. class Device(CreatedUpdatedModel, CustomFieldModel):
  638. """
  639. A Device represents a piece of physical hardware mounted within a Rack. Each Device is assigned a DeviceType,
  640. DeviceRole, and (optionally) a Platform. Device names are not required, however if one is set it must be unique.
  641. Each Device must be assigned to a site, and optionally to a rack within that site. Associating a device with a
  642. particular rack face or unit is optional (for example, vertically mounted PDUs do not consume rack units).
  643. When a new Device is created, console/power/interface/device bay components are created along with it as dictated
  644. by the component templates assigned to its DeviceType. Components can also be added, modified, or deleted after the
  645. creation of a Device.
  646. """
  647. device_type = models.ForeignKey('DeviceType', related_name='instances', on_delete=models.PROTECT)
  648. device_role = models.ForeignKey('DeviceRole', related_name='devices', on_delete=models.PROTECT)
  649. tenant = models.ForeignKey(Tenant, blank=True, null=True, related_name='devices', on_delete=models.PROTECT)
  650. platform = models.ForeignKey('Platform', related_name='devices', blank=True, null=True, on_delete=models.SET_NULL)
  651. name = NullableCharField(max_length=64, blank=True, null=True, unique=True)
  652. serial = models.CharField(max_length=50, blank=True, verbose_name='Serial number')
  653. asset_tag = NullableCharField(
  654. max_length=50, blank=True, null=True, unique=True, verbose_name='Asset tag',
  655. help_text='A unique tag used to identify this device'
  656. )
  657. site = models.ForeignKey('Site', related_name='devices', on_delete=models.PROTECT)
  658. rack = models.ForeignKey('Rack', related_name='devices', blank=True, null=True, on_delete=models.PROTECT)
  659. position = models.PositiveSmallIntegerField(
  660. blank=True, null=True, validators=[MinValueValidator(1)], verbose_name='Position (U)',
  661. help_text='The lowest-numbered unit occupied by the device'
  662. )
  663. face = models.PositiveSmallIntegerField(blank=True, null=True, choices=RACK_FACE_CHOICES, verbose_name='Rack face')
  664. status = models.PositiveSmallIntegerField(choices=STATUS_CHOICES, default=STATUS_ACTIVE, verbose_name='Status')
  665. primary_ip4 = models.OneToOneField(
  666. 'ipam.IPAddress', related_name='primary_ip4_for', on_delete=models.SET_NULL, blank=True, null=True,
  667. verbose_name='Primary IPv4'
  668. )
  669. primary_ip6 = models.OneToOneField(
  670. 'ipam.IPAddress', related_name='primary_ip6_for', on_delete=models.SET_NULL, blank=True, null=True,
  671. verbose_name='Primary IPv6'
  672. )
  673. cluster = models.ForeignKey(
  674. to='virtualization.Cluster',
  675. on_delete=models.SET_NULL,
  676. related_name='devices',
  677. blank=True,
  678. null=True
  679. )
  680. comments = models.TextField(blank=True)
  681. custom_field_values = GenericRelation(CustomFieldValue, content_type_field='obj_type', object_id_field='obj_id')
  682. images = GenericRelation(ImageAttachment)
  683. objects = DeviceManager()
  684. csv_headers = [
  685. 'name', 'device_role', 'tenant', 'manufacturer', 'model_name', 'platform', 'serial', 'asset_tag', 'status',
  686. 'site', 'rack_group', 'rack_name', 'position', 'face',
  687. ]
  688. class Meta:
  689. ordering = ['name']
  690. unique_together = ['rack', 'position', 'face']
  691. permissions = (
  692. ('napalm_read', 'Read-only access to devices via NAPALM'),
  693. ('napalm_write', 'Read/write access to devices via NAPALM'),
  694. )
  695. def __str__(self):
  696. return self.display_name or super(Device, self).__str__()
  697. def get_absolute_url(self):
  698. return reverse('dcim:device', args=[self.pk])
  699. def clean(self):
  700. # Validate site/rack combination
  701. if self.rack and self.site != self.rack.site:
  702. raise ValidationError({
  703. 'rack': "Rack {} does not belong to site {}.".format(self.rack, self.site),
  704. })
  705. if self.rack is None:
  706. if self.face is not None:
  707. raise ValidationError({
  708. 'face': "Cannot select a rack face without assigning a rack.",
  709. })
  710. if self.position:
  711. raise ValidationError({
  712. 'face': "Cannot select a rack position without assigning a rack.",
  713. })
  714. # Validate position/face combination
  715. if self.position and self.face is None:
  716. raise ValidationError({
  717. 'face': "Must specify rack face when defining rack position.",
  718. })
  719. if self.rack:
  720. try:
  721. # Child devices cannot be assigned to a rack face/unit
  722. if self.device_type.is_child_device and self.face is not None:
  723. raise ValidationError({
  724. 'face': "Child device types cannot be assigned to a rack face. This is an attribute of the "
  725. "parent device."
  726. })
  727. if self.device_type.is_child_device and self.position:
  728. raise ValidationError({
  729. 'position': "Child device types cannot be assigned to a rack position. This is an attribute of "
  730. "the parent device."
  731. })
  732. # Validate rack space
  733. rack_face = self.face if not self.device_type.is_full_depth else None
  734. exclude_list = [self.pk] if self.pk else []
  735. try:
  736. available_units = self.rack.get_available_units(
  737. u_height=self.device_type.u_height, rack_face=rack_face, exclude=exclude_list
  738. )
  739. if self.position and self.position not in available_units:
  740. raise ValidationError({
  741. 'position': "U{} is already occupied or does not have sufficient space to accommodate a(n) "
  742. "{} ({}U).".format(self.position, self.device_type, self.device_type.u_height)
  743. })
  744. except Rack.DoesNotExist:
  745. pass
  746. except DeviceType.DoesNotExist:
  747. pass
  748. # Validate primary IPv4 address
  749. if self.primary_ip4 and (
  750. self.primary_ip4.interface is None or
  751. self.primary_ip4.interface.device != self
  752. ) and (
  753. self.primary_ip4.nat_inside.interface is None or
  754. self.primary_ip4.nat_inside.interface.device != self
  755. ):
  756. raise ValidationError({
  757. 'primary_ip4': "The specified IP address ({}) is not assigned to this device.".format(self.primary_ip4),
  758. })
  759. # Validate primary IPv6 address
  760. if self.primary_ip6 and (
  761. self.primary_ip6.interface is None or
  762. self.primary_ip6.interface.device != self
  763. ) and (
  764. self.primary_ip6.nat_inside.interface is None or
  765. self.primary_ip6.nat_inside.interface.device != self
  766. ):
  767. raise ValidationError({
  768. 'primary_ip6': "The specified IP address ({}) is not assigned to this device.".format(self.primary_ip6),
  769. })
  770. # A Device can only be assigned to a Cluster in the same Site (or no Site)
  771. if self.cluster and self.cluster.site is not None and self.cluster.site != self.site:
  772. raise ValidationError({
  773. 'cluster': "The assigned cluster belongs to a different site ({})".format(self.cluster.site)
  774. })
  775. def save(self, *args, **kwargs):
  776. is_new = not bool(self.pk)
  777. super(Device, self).save(*args, **kwargs)
  778. # If this is a new Device, instantiate all of the related components per the DeviceType definition
  779. if is_new:
  780. ConsolePort.objects.bulk_create(
  781. [ConsolePort(device=self, name=template.name) for template in
  782. self.device_type.console_port_templates.all()]
  783. )
  784. ConsoleServerPort.objects.bulk_create(
  785. [ConsoleServerPort(device=self, name=template.name) for template in
  786. self.device_type.cs_port_templates.all()]
  787. )
  788. PowerPort.objects.bulk_create(
  789. [PowerPort(device=self, name=template.name) for template in
  790. self.device_type.power_port_templates.all()]
  791. )
  792. PowerOutlet.objects.bulk_create(
  793. [PowerOutlet(device=self, name=template.name) for template in
  794. self.device_type.power_outlet_templates.all()]
  795. )
  796. Interface.objects.bulk_create(
  797. [Interface(device=self, name=template.name, form_factor=template.form_factor,
  798. mgmt_only=template.mgmt_only) for template in self.device_type.interface_templates.all()]
  799. )
  800. DeviceBay.objects.bulk_create(
  801. [DeviceBay(device=self, name=template.name) for template in
  802. self.device_type.device_bay_templates.all()]
  803. )
  804. # Update Site and Rack assignment for any child Devices
  805. Device.objects.filter(parent_bay__device=self).update(site=self.site, rack=self.rack)
  806. def to_csv(self):
  807. return csv_format([
  808. self.name or '',
  809. self.device_role.name,
  810. self.tenant.name if self.tenant else None,
  811. self.device_type.manufacturer.name,
  812. self.device_type.model,
  813. self.platform.name if self.platform else None,
  814. self.serial,
  815. self.asset_tag,
  816. self.get_status_display(),
  817. self.site.name,
  818. self.rack.group.name if self.rack and self.rack.group else None,
  819. self.rack.name if self.rack else None,
  820. self.position,
  821. self.get_face_display(),
  822. ])
  823. @property
  824. def display_name(self):
  825. if self.name:
  826. return self.name
  827. elif hasattr(self, 'device_type'):
  828. return "{}".format(self.device_type)
  829. return ""
  830. @property
  831. def identifier(self):
  832. """
  833. Return the device name if set; otherwise return the Device's primary key as {pk}
  834. """
  835. if self.name is not None:
  836. return self.name
  837. return '{{{}}}'.format(self.pk)
  838. @property
  839. def primary_ip(self):
  840. if settings.PREFER_IPV4 and self.primary_ip4:
  841. return self.primary_ip4
  842. elif self.primary_ip6:
  843. return self.primary_ip6
  844. elif self.primary_ip4:
  845. return self.primary_ip4
  846. else:
  847. return None
  848. def get_children(self):
  849. """
  850. Return the set of child Devices installed in DeviceBays within this Device.
  851. """
  852. return Device.objects.filter(parent_bay__device=self.pk)
  853. def get_status_class(self):
  854. return DEVICE_STATUS_CLASSES[self.status]
  855. def get_rpc_client(self):
  856. """
  857. Return the appropriate RPC (e.g. NETCONF, ssh, etc.) client for this device's platform, if one is defined.
  858. """
  859. if not self.platform:
  860. return None
  861. return RPC_CLIENTS.get(self.platform.rpc_client)
  862. #
  863. # Console ports
  864. #
  865. @python_2_unicode_compatible
  866. class ConsolePort(models.Model):
  867. """
  868. A physical console port within a Device. ConsolePorts connect to ConsoleServerPorts.
  869. """
  870. device = models.ForeignKey('Device', related_name='console_ports', on_delete=models.CASCADE)
  871. name = models.CharField(max_length=50)
  872. cs_port = models.OneToOneField('ConsoleServerPort', related_name='connected_console', on_delete=models.SET_NULL,
  873. verbose_name='Console server port', blank=True, null=True)
  874. connection_status = models.NullBooleanField(choices=CONNECTION_STATUS_CHOICES, default=CONNECTION_STATUS_CONNECTED)
  875. csv_headers = ['console_server', 'cs_port', 'device', 'console_port', 'connection_status']
  876. class Meta:
  877. ordering = ['device', 'name']
  878. unique_together = ['device', 'name']
  879. def __str__(self):
  880. return self.name
  881. # Used for connections export
  882. def to_csv(self):
  883. return csv_format([
  884. self.cs_port.device.identifier if self.cs_port else None,
  885. self.cs_port.name if self.cs_port else None,
  886. self.device.identifier,
  887. self.name,
  888. self.get_connection_status_display(),
  889. ])
  890. #
  891. # Console server ports
  892. #
  893. class ConsoleServerPortManager(models.Manager):
  894. def get_queryset(self):
  895. """
  896. Include the trailing numeric portion of each port name to allow for proper ordering.
  897. For example:
  898. Port 1, Port 2, Port 3 ... Port 9, Port 10, Port 11 ...
  899. Instead of:
  900. Port 1, Port 10, Port 11 ... Port 19, Port 2, Port 20 ...
  901. """
  902. return super(ConsoleServerPortManager, self).get_queryset().extra(select={
  903. 'name_as_integer': "CAST(substring(dcim_consoleserverport.name FROM '[0-9]+$') AS INTEGER)",
  904. }).order_by('device', 'name_as_integer')
  905. @python_2_unicode_compatible
  906. class ConsoleServerPort(models.Model):
  907. """
  908. A physical port within a Device (typically a designated console server) which provides access to ConsolePorts.
  909. """
  910. device = models.ForeignKey('Device', related_name='cs_ports', on_delete=models.CASCADE)
  911. name = models.CharField(max_length=50)
  912. objects = ConsoleServerPortManager()
  913. class Meta:
  914. unique_together = ['device', 'name']
  915. def __str__(self):
  916. return self.name
  917. def clean(self):
  918. # Check that the parent device's DeviceType is a console server
  919. device_type = self.device.device_type
  920. if not device_type.is_console_server:
  921. raise ValidationError("The {} {} device type not support assignment of console server ports.".format(
  922. device_type.manufacturer, device_type
  923. ))
  924. #
  925. # Power ports
  926. #
  927. @python_2_unicode_compatible
  928. class PowerPort(models.Model):
  929. """
  930. A physical power supply (intake) port within a Device. PowerPorts connect to PowerOutlets.
  931. """
  932. device = models.ForeignKey('Device', related_name='power_ports', on_delete=models.CASCADE)
  933. name = models.CharField(max_length=50)
  934. power_outlet = models.OneToOneField('PowerOutlet', related_name='connected_port', on_delete=models.SET_NULL,
  935. blank=True, null=True)
  936. connection_status = models.NullBooleanField(choices=CONNECTION_STATUS_CHOICES, default=CONNECTION_STATUS_CONNECTED)
  937. csv_headers = ['pdu', 'power_outlet', 'device', 'power_port', 'connection_status']
  938. class Meta:
  939. ordering = ['device', 'name']
  940. unique_together = ['device', 'name']
  941. def __str__(self):
  942. return self.name
  943. # Used for connections export
  944. def to_csv(self):
  945. return csv_format([
  946. self.power_outlet.device.identifier if self.power_outlet else None,
  947. self.power_outlet.name if self.power_outlet else None,
  948. self.device.identifier,
  949. self.name,
  950. self.get_connection_status_display(),
  951. ])
  952. #
  953. # Power outlets
  954. #
  955. class PowerOutletManager(models.Manager):
  956. def get_queryset(self):
  957. return super(PowerOutletManager, self).get_queryset().extra(select={
  958. 'name_padded': "CONCAT(SUBSTRING(dcim_poweroutlet.name FROM '^[^0-9]+'), "
  959. "LPAD(SUBSTRING(dcim_poweroutlet.name FROM '[0-9\/]+$'), 8, '0'))",
  960. }).order_by('device', 'name_padded')
  961. @python_2_unicode_compatible
  962. class PowerOutlet(models.Model):
  963. """
  964. A physical power outlet (output) within a Device which provides power to a PowerPort.
  965. """
  966. device = models.ForeignKey('Device', related_name='power_outlets', on_delete=models.CASCADE)
  967. name = models.CharField(max_length=50)
  968. objects = PowerOutletManager()
  969. class Meta:
  970. unique_together = ['device', 'name']
  971. def __str__(self):
  972. return self.name
  973. def clean(self):
  974. # Check that the parent device's DeviceType is a PDU
  975. device_type = self.device.device_type
  976. if not device_type.is_pdu:
  977. raise ValidationError("The {} {} device type not support assignment of power outlets.".format(
  978. device_type.manufacturer, device_type
  979. ))
  980. #
  981. # Interfaces
  982. #
  983. @python_2_unicode_compatible
  984. class Interface(models.Model):
  985. """
  986. A network interface within a Device or VirtualMachine. A physical Interface can connect to exactly one other
  987. Interface via the creation of an InterfaceConnection.
  988. """
  989. device = models.ForeignKey(
  990. to='Device',
  991. on_delete=models.CASCADE,
  992. related_name='interfaces',
  993. null=True,
  994. blank=True
  995. )
  996. virtual_machine = models.ForeignKey(
  997. to='virtualization.VirtualMachine',
  998. on_delete=models.CASCADE,
  999. related_name='interfaces',
  1000. null=True,
  1001. blank=True
  1002. )
  1003. lag = models.ForeignKey(
  1004. to='self',
  1005. on_delete=models.SET_NULL,
  1006. related_name='member_interfaces',
  1007. null=True,
  1008. blank=True,
  1009. verbose_name='Parent LAG'
  1010. )
  1011. name = models.CharField(max_length=64)
  1012. form_factor = models.PositiveSmallIntegerField(choices=IFACE_FF_CHOICES, default=IFACE_FF_10GE_SFP_PLUS)
  1013. enabled = models.BooleanField(default=True)
  1014. mac_address = MACAddressField(null=True, blank=True, verbose_name='MAC Address')
  1015. mtu = models.PositiveSmallIntegerField(blank=True, null=True, verbose_name='MTU')
  1016. mgmt_only = models.BooleanField(
  1017. default=False,
  1018. verbose_name='OOB Management',
  1019. help_text="This interface is used only for out-of-band management"
  1020. )
  1021. description = models.CharField(max_length=100, blank=True)
  1022. mode = models.PositiveSmallIntegerField(choices=IFACE_MODE_CHOICES, default=IFACE_MODE_ACCESS)
  1023. untagged_vlan = models.ForeignKey(
  1024. to='ipam.VLAN',
  1025. null=True,
  1026. blank=True,
  1027. verbose_name='Untagged VLAN',
  1028. related_name='interfaces_as_untagged'
  1029. )
  1030. tagged_vlans = models.ManyToManyField(
  1031. to='ipam.VLAN',
  1032. blank=True,
  1033. verbose_name='Tagged VLANs',
  1034. related_name='interfaces_as_tagged'
  1035. )
  1036. objects = InterfaceQuerySet.as_manager()
  1037. class Meta:
  1038. ordering = ['device', 'name']
  1039. unique_together = ['device', 'name']
  1040. def __str__(self):
  1041. return self.name
  1042. def clean(self):
  1043. # Check that the parent device's DeviceType is a network device
  1044. device_type = self.device.device_type
  1045. if not device_type.is_network_device:
  1046. raise ValidationError("The {} {} device type not support assignment of network interfaces.".format(
  1047. device_type.manufacturer, device_type
  1048. ))
  1049. # An Interface must belong to a Device *or* to a VirtualMachine
  1050. if self.device and self.virtual_machine:
  1051. raise ValidationError("An interface cannot belong to both a device and a virtual machine.")
  1052. if not self.device and not self.virtual_machine:
  1053. raise ValidationError("An interface must belong to either a device or a virtual machine.")
  1054. # VM interfaces must be virtual
  1055. if self.virtual_machine and self.form_factor is not IFACE_FF_VIRTUAL:
  1056. raise ValidationError({
  1057. 'form_factor': "Virtual machines can only have virtual interfaces."
  1058. })
  1059. # Virtual interfaces cannot be connected
  1060. if self.form_factor in NONCONNECTABLE_IFACE_TYPES and self.is_connected:
  1061. raise ValidationError({
  1062. 'form_factor': "Virtual and wireless interfaces cannot be connected to another interface or circuit. "
  1063. "Disconnect the interface or choose a suitable form factor."
  1064. })
  1065. # An interface's LAG must belong to the same device
  1066. if self.lag and self.lag.device != self.device:
  1067. raise ValidationError({
  1068. 'lag': "The selected LAG interface ({}) belongs to a different device ({}).".format(
  1069. self.lag.name, self.lag.device.name
  1070. )
  1071. })
  1072. # A virtual interface cannot have a parent LAG
  1073. if self.form_factor in NONCONNECTABLE_IFACE_TYPES and self.lag is not None:
  1074. raise ValidationError({
  1075. 'lag': "{} interfaces cannot have a parent LAG interface.".format(self.get_form_factor_display())
  1076. })
  1077. # Only a LAG can have LAG members
  1078. if self.form_factor != IFACE_FF_LAG and self.member_interfaces.exists():
  1079. raise ValidationError({
  1080. 'form_factor': "Cannot change interface form factor; it has LAG members ({}).".format(
  1081. ", ".join([iface.name for iface in self.member_interfaces.all()])
  1082. )
  1083. })
  1084. # Validate untagged VLAN
  1085. if self.untagged_vlan and self.untagged_vlan.site not in [self.parent.site, None]:
  1086. raise ValidationError({
  1087. 'untagged_vlan': "The untagged VLAN ({}) must belong to the same site as the interface's parent "
  1088. "device/VM, or it must be global".format(self.untagged_vlan)
  1089. })
  1090. @property
  1091. def parent(self):
  1092. return self.device or self.virtual_machine
  1093. @property
  1094. def is_virtual(self):
  1095. return self.form_factor in VIRTUAL_IFACE_TYPES
  1096. @property
  1097. def is_wireless(self):
  1098. return self.form_factor in WIRELESS_IFACE_TYPES
  1099. @property
  1100. def is_lag(self):
  1101. return self.form_factor == IFACE_FF_LAG
  1102. @property
  1103. def is_connected(self):
  1104. try:
  1105. return bool(self.circuit_termination)
  1106. except ObjectDoesNotExist:
  1107. pass
  1108. return bool(self.connection)
  1109. @property
  1110. def connection(self):
  1111. try:
  1112. return self.connected_as_a
  1113. except ObjectDoesNotExist:
  1114. pass
  1115. try:
  1116. return self.connected_as_b
  1117. except ObjectDoesNotExist:
  1118. pass
  1119. return None
  1120. @property
  1121. def connected_interface(self):
  1122. try:
  1123. if self.connected_as_a:
  1124. return self.connected_as_a.interface_b
  1125. except ObjectDoesNotExist:
  1126. pass
  1127. try:
  1128. if self.connected_as_b:
  1129. return self.connected_as_b.interface_a
  1130. except ObjectDoesNotExist:
  1131. pass
  1132. return None
  1133. class InterfaceConnection(models.Model):
  1134. """
  1135. An InterfaceConnection represents a symmetrical, one-to-one connection between two Interfaces. There is no
  1136. significant difference between the interface_a and interface_b fields.
  1137. """
  1138. interface_a = models.OneToOneField('Interface', related_name='connected_as_a', on_delete=models.CASCADE)
  1139. interface_b = models.OneToOneField('Interface', related_name='connected_as_b', on_delete=models.CASCADE)
  1140. connection_status = models.BooleanField(choices=CONNECTION_STATUS_CHOICES, default=CONNECTION_STATUS_CONNECTED,
  1141. verbose_name='Status')
  1142. csv_headers = ['device_a', 'interface_a', 'device_b', 'interface_b', 'connection_status']
  1143. def clean(self):
  1144. try:
  1145. if self.interface_a == self.interface_b:
  1146. raise ValidationError({
  1147. 'interface_b': "Cannot connect an interface to itself."
  1148. })
  1149. except ObjectDoesNotExist:
  1150. pass
  1151. # Used for connections export
  1152. def to_csv(self):
  1153. return csv_format([
  1154. self.interface_a.device.identifier,
  1155. self.interface_a.name,
  1156. self.interface_b.device.identifier,
  1157. self.interface_b.name,
  1158. self.get_connection_status_display(),
  1159. ])
  1160. #
  1161. # Device bays
  1162. #
  1163. @python_2_unicode_compatible
  1164. class DeviceBay(models.Model):
  1165. """
  1166. An empty space within a Device which can house a child device
  1167. """
  1168. device = models.ForeignKey('Device', related_name='device_bays', on_delete=models.CASCADE)
  1169. name = models.CharField(max_length=50, verbose_name='Name')
  1170. installed_device = models.OneToOneField('Device', related_name='parent_bay', on_delete=models.SET_NULL, blank=True,
  1171. null=True)
  1172. class Meta:
  1173. ordering = ['device', 'name']
  1174. unique_together = ['device', 'name']
  1175. def __str__(self):
  1176. return '{} - {}'.format(self.device.name, self.name)
  1177. def clean(self):
  1178. # Validate that the parent Device can have DeviceBays
  1179. if not self.device.device_type.is_parent_device:
  1180. raise ValidationError("This type of device ({}) does not support device bays.".format(
  1181. self.device.device_type
  1182. ))
  1183. # Cannot install a device into itself, obviously
  1184. if self.device == self.installed_device:
  1185. raise ValidationError("Cannot install a device into itself.")
  1186. #
  1187. # Inventory items
  1188. #
  1189. @python_2_unicode_compatible
  1190. class InventoryItem(models.Model):
  1191. """
  1192. An InventoryItem represents a serialized piece of hardware within a Device, such as a line card or power supply.
  1193. InventoryItems are used only for inventory purposes.
  1194. """
  1195. device = models.ForeignKey('Device', related_name='inventory_items', on_delete=models.CASCADE)
  1196. parent = models.ForeignKey('self', related_name='child_items', blank=True, null=True, on_delete=models.CASCADE)
  1197. name = models.CharField(max_length=50, verbose_name='Name')
  1198. manufacturer = models.ForeignKey(
  1199. 'Manufacturer', models.PROTECT, related_name='inventory_items', blank=True, null=True
  1200. )
  1201. part_id = models.CharField(max_length=50, verbose_name='Part ID', blank=True)
  1202. serial = models.CharField(max_length=50, verbose_name='Serial number', blank=True)
  1203. asset_tag = NullableCharField(
  1204. max_length=50, blank=True, null=True, unique=True, verbose_name='Asset tag',
  1205. help_text='A unique tag used to identify this item'
  1206. )
  1207. discovered = models.BooleanField(default=False, verbose_name='Discovered')
  1208. description = models.CharField(max_length=100, blank=True)
  1209. class Meta:
  1210. ordering = ['device__id', 'parent__id', 'name']
  1211. unique_together = ['device', 'parent', 'name']
  1212. def __str__(self):
  1213. return self.name