models.py 53 KB

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