models.py 52 KB

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