models.py 53 KB

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