models.py 51 KB

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