models.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035
  1. from collections import OrderedDict
  2. from django.conf import settings
  3. from django.core.exceptions import MultipleObjectsReturned, ValidationError
  4. from django.core.urlresolvers import reverse
  5. from django.core.validators import MinValueValidator
  6. from django.db import models
  7. from django.db.models import Count, Q, ObjectDoesNotExist
  8. from extras.rpc import RPC_CLIENTS
  9. from utilities.fields import NullableCharField
  10. from utilities.managers import NaturalOrderByManager
  11. from utilities.models import CreatedUpdatedModel
  12. from .fields import ASNField, MACAddressField
  13. RACK_FACE_FRONT = 0
  14. RACK_FACE_REAR = 1
  15. RACK_FACE_CHOICES = [
  16. [RACK_FACE_FRONT, 'Front'],
  17. [RACK_FACE_REAR, 'Rear'],
  18. ]
  19. SUBDEVICE_ROLE_PARENT = True
  20. SUBDEVICE_ROLE_CHILD = False
  21. SUBDEVICE_ROLE_CHOICES = (
  22. (None, 'None'),
  23. (SUBDEVICE_ROLE_PARENT, 'Parent'),
  24. (SUBDEVICE_ROLE_CHILD, 'Child'),
  25. )
  26. COLOR_TEAL = 'teal'
  27. COLOR_GREEN = 'green'
  28. COLOR_BLUE = 'blue'
  29. COLOR_PURPLE = 'purple'
  30. COLOR_YELLOW = 'yellow'
  31. COLOR_ORANGE = 'orange'
  32. COLOR_RED = 'red'
  33. COLOR_GRAY1 = 'light_gray'
  34. COLOR_GRAY2 = 'medium_gray'
  35. COLOR_GRAY3 = 'dark_gray'
  36. DEVICE_ROLE_COLOR_CHOICES = [
  37. [COLOR_TEAL, 'Teal'],
  38. [COLOR_GREEN, 'Green'],
  39. [COLOR_BLUE, 'Blue'],
  40. [COLOR_PURPLE, 'Purple'],
  41. [COLOR_YELLOW, 'Yellow'],
  42. [COLOR_ORANGE, 'Orange'],
  43. [COLOR_RED, 'Red'],
  44. [COLOR_GRAY1, 'Light Gray'],
  45. [COLOR_GRAY2, 'Medium Gray'],
  46. [COLOR_GRAY3, 'Dark Gray'],
  47. ]
  48. IFACE_FF_VIRTUAL = 0
  49. IFACE_FF_100M_COPPER = 800
  50. IFACE_FF_1GE_COPPER = 1000
  51. IFACE_FF_SFP = 1100
  52. IFACE_FF_10GE_COPPER = 1150
  53. IFACE_FF_SFP_PLUS = 1200
  54. IFACE_FF_XFP = 1300
  55. IFACE_FF_QSFP_PLUS = 1400
  56. IFACE_FF_CHOICES = [
  57. [IFACE_FF_VIRTUAL, 'Virtual'],
  58. [IFACE_FF_100M_COPPER, '10/100M (100BASE-TX)'],
  59. [IFACE_FF_1GE_COPPER, '1GE (1000BASE-T)'],
  60. [IFACE_FF_SFP, '1GE (SFP)'],
  61. [IFACE_FF_10GE_COPPER, '10GE (10GBASE-T)'],
  62. [IFACE_FF_SFP_PLUS, '10GE (SFP+)'],
  63. [IFACE_FF_XFP, '10GE (XFP)'],
  64. [IFACE_FF_QSFP_PLUS, '40GE (QSFP+)'],
  65. ]
  66. STATUS_ACTIVE = True
  67. STATUS_OFFLINE = False
  68. STATUS_CHOICES = [
  69. [STATUS_ACTIVE, 'Active'],
  70. [STATUS_OFFLINE, 'Offline'],
  71. ]
  72. CONNECTION_STATUS_PLANNED = False
  73. CONNECTION_STATUS_CONNECTED = True
  74. CONNECTION_STATUS_CHOICES = [
  75. [CONNECTION_STATUS_PLANNED, 'Planned'],
  76. [CONNECTION_STATUS_CONNECTED, 'Connected'],
  77. ]
  78. # For mapping platform -> NC client
  79. RPC_CLIENT_JUNIPER_JUNOS = 'juniper-junos'
  80. RPC_CLIENT_CISCO_IOS = 'cisco-ios'
  81. RPC_CLIENT_OPENGEAR = 'opengear'
  82. RPC_CLIENT_CHOICES = [
  83. [RPC_CLIENT_JUNIPER_JUNOS, 'Juniper Junos (NETCONF)'],
  84. [RPC_CLIENT_CISCO_IOS, 'Cisco IOS (SSH)'],
  85. [RPC_CLIENT_OPENGEAR, 'Opengear (SSH)'],
  86. ]
  87. def order_interfaces(queryset, sql_col, primary_ordering=tuple()):
  88. """
  89. Attempt to match interface names by their slot/position identifiers and order according. Matching is done using the
  90. following pattern:
  91. {a}/{b}/{c}:{d}
  92. Interfaces are ordered first by field a, then b, then c, and finally d. Leading text (which typically indicates the
  93. interface's type) is ignored. If any fields are not contained by an interface name, those fields are treated as
  94. None. 'None' is ordered after all other values. For example:
  95. et-0/0/0
  96. et-0/0/1
  97. et-0/1/0
  98. xe-0/1/1:0
  99. xe-0/1/1:1
  100. xe-0/1/1:2
  101. xe-0/1/1:3
  102. et-0/1/2
  103. ...
  104. et-0/1/9
  105. et-0/1/10
  106. et-0/1/11
  107. et-1/0/0
  108. et-1/0/1
  109. ...
  110. vlan1
  111. vlan10
  112. :param queryset: The base queryset to be ordered
  113. :param sql_col: Table and name of the SQL column which contains the interface name (ex: ''dcim_interface.name')
  114. :param primary_ordering: A tuple of fields which take ordering precedence before the interface name (optional)
  115. """
  116. ordering = primary_ordering + ('_id1', '_id2', '_id3', '_id4')
  117. return queryset.extra(select={
  118. '_id1': "CAST(SUBSTRING({} FROM '([0-9]+)\/[0-9]+\/[0-9]+(:[0-9]+)?$') AS integer)".format(sql_col),
  119. '_id2': "CAST(SUBSTRING({} FROM '([0-9]+)\/[0-9]+(:[0-9]+)?$') AS integer)".format(sql_col),
  120. '_id3': "CAST(SUBSTRING({} FROM '([0-9]+)(:[0-9]+)?$') AS integer)".format(sql_col),
  121. '_id4': "CAST(SUBSTRING({} FROM ':([0-9]+)$') AS integer)".format(sql_col),
  122. }).order_by(*ordering)
  123. class SiteManager(NaturalOrderByManager):
  124. def get_queryset(self):
  125. return self.natural_order_by('name')
  126. class Site(CreatedUpdatedModel):
  127. """
  128. A Site represents a geographic location within a network; typically a building or campus. The optional facility
  129. field can be used to include an external designation, such as a data center name (e.g. Equinix SV6).
  130. """
  131. name = models.CharField(max_length=50, unique=True)
  132. slug = models.SlugField(unique=True)
  133. facility = models.CharField(max_length=50, blank=True)
  134. asn = ASNField(blank=True, null=True, verbose_name='ASN')
  135. physical_address = models.CharField(max_length=200, blank=True)
  136. shipping_address = models.CharField(max_length=200, blank=True)
  137. comments = models.TextField(blank=True)
  138. objects = SiteManager()
  139. class Meta:
  140. ordering = ['name']
  141. def __unicode__(self):
  142. return self.name
  143. def get_absolute_url(self):
  144. return reverse('dcim:site', args=[self.slug])
  145. def to_csv(self):
  146. return ','.join([
  147. self.name,
  148. self.slug,
  149. self.facility,
  150. str(self.asn),
  151. ])
  152. @property
  153. def count_prefixes(self):
  154. return self.prefixes.count()
  155. @property
  156. def count_vlans(self):
  157. return self.vlans.count()
  158. @property
  159. def count_racks(self):
  160. return Rack.objects.filter(site=self).count()
  161. @property
  162. def count_devices(self):
  163. return Device.objects.filter(rack__site=self).count()
  164. @property
  165. def count_circuits(self):
  166. return self.circuits.count()
  167. class RackGroup(models.Model):
  168. """
  169. Racks can be grouped as subsets within a Site. The scope of a group will depend on how Sites are defined. For
  170. example, if a Site spans a corporate campus, a RackGroup might be defined to represent each building within that
  171. campus. If a Site instead represents a single building, a RackGroup might represent a single room or floor.
  172. """
  173. name = models.CharField(max_length=50)
  174. slug = models.SlugField()
  175. site = models.ForeignKey('Site', related_name='rack_groups')
  176. class Meta:
  177. ordering = ['site', 'name']
  178. unique_together = [
  179. ['site', 'name'],
  180. ['site', 'slug'],
  181. ]
  182. def __unicode__(self):
  183. return u'{} - {}'.format(self.site.name, self.name)
  184. def get_absolute_url(self):
  185. return "{}?group_id={}".format(reverse('dcim:rack_list'), self.pk)
  186. class RackManager(NaturalOrderByManager):
  187. def get_queryset(self):
  188. return self.natural_order_by('site__name', 'name')
  189. class Rack(CreatedUpdatedModel):
  190. """
  191. Devices are housed within Racks. Each rack has a defined height measured in rack units, and a front and rear face.
  192. Each Rack is assigned to a Site and (optionally) a RackGroup.
  193. """
  194. name = models.CharField(max_length=50)
  195. facility_id = NullableCharField(max_length=30, blank=True, null=True, verbose_name='Facility ID')
  196. site = models.ForeignKey('Site', related_name='racks', on_delete=models.PROTECT)
  197. group = models.ForeignKey('RackGroup', related_name='racks', blank=True, null=True, on_delete=models.SET_NULL)
  198. u_height = models.PositiveSmallIntegerField(default=42, verbose_name='Height (U)')
  199. comments = models.TextField(blank=True)
  200. objects = RackManager()
  201. class Meta:
  202. ordering = ['site', 'name']
  203. unique_together = [
  204. ['site', 'name'],
  205. ['site', 'facility_id'],
  206. ]
  207. def __unicode__(self):
  208. return self.display_name
  209. def get_absolute_url(self):
  210. return reverse('dcim:rack', args=[self.pk])
  211. def clean(self):
  212. # Validate that Rack is tall enough to house the installed Devices
  213. if self.pk:
  214. top_device = Device.objects.filter(rack=self).exclude(position__isnull=True).order_by('-position').first()
  215. if top_device:
  216. min_height = top_device.position + top_device.device_type.u_height - 1
  217. if self.u_height < min_height:
  218. raise ValidationError("Rack must be at least {}U tall with currently installed devices."
  219. .format(min_height))
  220. def to_csv(self):
  221. return ','.join([
  222. self.site.name,
  223. self.group.name if self.group else '',
  224. self.name,
  225. self.facility_id or '',
  226. str(self.u_height),
  227. ])
  228. @property
  229. def units(self):
  230. return reversed(range(1, self.u_height + 1))
  231. @property
  232. def display_name(self):
  233. if self.facility_id:
  234. return u"{} ({})".format(self.name, self.facility_id)
  235. return self.name
  236. def get_rack_units(self, face=RACK_FACE_FRONT, exclude=None, remove_redundant=False):
  237. """
  238. Return a list of rack units as dictionaries. Example: {'device': None, 'face': 0, 'id': 48, 'name': 'U48'}
  239. Each key 'device' is either a Device or None. By default, multi-U devices are repeated for each U they occupy.
  240. :param face: Rack face (front or rear)
  241. :param exclude: PK of a Device to exclude (optional); helpful when relocating a Device within a Rack
  242. :param remove_redundant: If True, rack units occupied by a device already listed will be omitted
  243. """
  244. elevation = OrderedDict()
  245. for u in reversed(range(1, self.u_height + 1)):
  246. elevation[u] = {'id': u, 'name': 'U{}'.format(u), 'face': face, 'device': None}
  247. # Add devices to rack units list
  248. if self.pk:
  249. for device in Device.objects.select_related('device_type__manufacturer', 'device_role')\
  250. .annotate(devicebay_count=Count('device_bays'))\
  251. .exclude(pk=exclude)\
  252. .filter(rack=self, position__gt=0)\
  253. .filter(Q(face=face) | Q(device_type__is_full_depth=True)):
  254. if remove_redundant:
  255. elevation[device.position]['device'] = device
  256. for u in range(device.position + 1, device.position + device.device_type.u_height):
  257. elevation.pop(u, None)
  258. else:
  259. for u in range(device.position, device.position + device.device_type.u_height):
  260. elevation[u]['device'] = device
  261. return [u for u in elevation.values()]
  262. def get_front_elevation(self):
  263. return self.get_rack_units(face=RACK_FACE_FRONT, remove_redundant=True)
  264. def get_rear_elevation(self):
  265. return self.get_rack_units(face=RACK_FACE_REAR, remove_redundant=True)
  266. def get_available_units(self, u_height=1, rack_face=None, exclude=list()):
  267. """
  268. Return a list of units within the rack available to accommodate a device of a given U height (default 1).
  269. Optionally exclude one or more devices when calculating empty units (needed when moving a device from one
  270. position to another within a rack).
  271. :param u_height: Minimum number of contiguous free units required
  272. :param rack_face: The face of the rack (front or rear) required; 'None' if device is full depth
  273. :param exclude: List of devices IDs to exclude (useful when moving a device within a rack)
  274. """
  275. # Gather all devices which consume U space within the rack
  276. devices = self.devices.select_related().filter(position__gte=1).exclude(pk__in=exclude)
  277. # Initialize the rack unit skeleton
  278. units = range(1, self.u_height + 1)
  279. # Remove units consumed by installed devices
  280. for d in devices:
  281. if rack_face is None or d.face == rack_face or d.device_type.is_full_depth:
  282. for u in range(d.position, d.position + d.device_type.u_height):
  283. try:
  284. units.remove(u)
  285. except ValueError:
  286. # Found overlapping devices in the rack!
  287. pass
  288. # Remove units without enough space above them to accommodate a device of the specified height
  289. available_units = []
  290. for u in units:
  291. if set(range(u, u + u_height)).issubset(units):
  292. available_units.append(u)
  293. return list(reversed(available_units))
  294. def get_0u_devices(self):
  295. return self.devices.filter(position=0)
  296. def get_utilization(self):
  297. """
  298. Determine the utilization rate of the rack and return it as a percentage.
  299. """
  300. if self.u_consumed is None:
  301. self.u_consumed = 0
  302. u_available = self.u_height - self.u_consumed
  303. return int(float(self.u_height - u_available) / self.u_height * 100)
  304. #
  305. # Device Types
  306. #
  307. class Manufacturer(models.Model):
  308. """
  309. A Manufacturer represents a company which produces hardware devices; for example, Juniper or Dell.
  310. """
  311. name = models.CharField(max_length=50, unique=True)
  312. slug = models.SlugField(unique=True)
  313. class Meta:
  314. ordering = ['name']
  315. def __unicode__(self):
  316. return self.name
  317. def get_absolute_url(self):
  318. return "{}?manufacturer={}".format(reverse('dcim:devicetype_list'), self.slug)
  319. class DeviceType(models.Model):
  320. """
  321. A DeviceType represents a particular make (Manufacturer) and model of device. It specifies rack height and depth, as
  322. well as high-level functional role(s).
  323. Each DeviceType can have an arbitrary number of component templates assigned to it, which define console, power, and
  324. interface objects. For example, a Juniper EX4300-48T DeviceType would have:
  325. * 1 ConsolePortTemplate
  326. * 2 PowerPortTemplates
  327. * 48 InterfaceTemplates
  328. When a new Device of this type is created, the appropriate console, power, and interface objects (as defined by the
  329. DeviceType) are automatically created as well.
  330. """
  331. manufacturer = models.ForeignKey('Manufacturer', related_name='device_types', on_delete=models.PROTECT)
  332. model = models.CharField(max_length=50)
  333. slug = models.SlugField()
  334. part_number = models.CharField(max_length=50, blank=True, help_text="Discrete part number (optional)")
  335. u_height = models.PositiveSmallIntegerField(verbose_name='Height (U)', default=1)
  336. is_full_depth = models.BooleanField(default=True, verbose_name="Is full depth",
  337. help_text="Device consumes both front and rear rack faces")
  338. is_console_server = models.BooleanField(default=False, verbose_name='Is a console server',
  339. help_text="This type of device has console server ports")
  340. is_pdu = models.BooleanField(default=False, verbose_name='Is a PDU',
  341. help_text="This type of device has power outlets")
  342. is_network_device = models.BooleanField(default=True, verbose_name='Is a network device',
  343. help_text="This type of device has network interfaces")
  344. subdevice_role = models.NullBooleanField(default=None, verbose_name='Parent/child status',
  345. choices=SUBDEVICE_ROLE_CHOICES,
  346. help_text="Parent devices house child devices in device bays. Select "
  347. "\"None\" if this device type is neither a parent nor a child.")
  348. class Meta:
  349. ordering = ['manufacturer', 'model']
  350. unique_together = [
  351. ['manufacturer', 'model'],
  352. ['manufacturer', 'slug'],
  353. ]
  354. def __unicode__(self):
  355. return u'{} {}'.format(self.manufacturer, self.model)
  356. def get_absolute_url(self):
  357. return reverse('dcim:devicetype', args=[self.pk])
  358. def clean(self):
  359. if not self.is_console_server and self.cs_port_templates.count():
  360. raise ValidationError("Must delete all console server port templates associated with this device before "
  361. "declassifying it as a console server.")
  362. if not self.is_pdu and self.power_outlet_templates.count():
  363. raise ValidationError("Must delete all power outlet templates associated with this device before "
  364. "declassifying it as a PDU.")
  365. if not self.is_network_device and self.interface_templates.filter(mgmt_only=False).count():
  366. raise ValidationError("Must delete all non-management-only interface templates associated with this device "
  367. "before declassifying it as a network device.")
  368. if self.subdevice_role != SUBDEVICE_ROLE_PARENT and self.device_bay_templates.count():
  369. raise ValidationError("Must delete all device bay templates associated with this device before "
  370. "declassifying it as a parent device.")
  371. if self.u_height and self.subdevice_role == SUBDEVICE_ROLE_CHILD:
  372. raise ValidationError("Child device types must be 0U.")
  373. @property
  374. def is_parent_device(self):
  375. return bool(self.subdevice_role)
  376. @property
  377. def is_child_device(self):
  378. return bool(self.subdevice_role is False)
  379. class ConsolePortTemplate(models.Model):
  380. """
  381. A template for a ConsolePort to be created for a new Device.
  382. """
  383. device_type = models.ForeignKey('DeviceType', related_name='console_port_templates', on_delete=models.CASCADE)
  384. name = models.CharField(max_length=30)
  385. class Meta:
  386. ordering = ['device_type', 'name']
  387. unique_together = ['device_type', 'name']
  388. def __unicode__(self):
  389. return self.name
  390. class ConsoleServerPortTemplate(models.Model):
  391. """
  392. A template for a ConsoleServerPort to be created for a new Device.
  393. """
  394. device_type = models.ForeignKey('DeviceType', related_name='cs_port_templates', on_delete=models.CASCADE)
  395. name = models.CharField(max_length=30)
  396. class Meta:
  397. ordering = ['device_type', 'name']
  398. unique_together = ['device_type', 'name']
  399. def __unicode__(self):
  400. return self.name
  401. class PowerPortTemplate(models.Model):
  402. """
  403. A template for a PowerPort to be created for a new Device.
  404. """
  405. device_type = models.ForeignKey('DeviceType', related_name='power_port_templates', on_delete=models.CASCADE)
  406. name = models.CharField(max_length=30)
  407. class Meta:
  408. ordering = ['device_type', 'name']
  409. unique_together = ['device_type', 'name']
  410. def __unicode__(self):
  411. return self.name
  412. class PowerOutletTemplate(models.Model):
  413. """
  414. A template for a PowerOutlet to be created for a new Device.
  415. """
  416. device_type = models.ForeignKey('DeviceType', related_name='power_outlet_templates', on_delete=models.CASCADE)
  417. name = models.CharField(max_length=30)
  418. class Meta:
  419. ordering = ['device_type', 'name']
  420. unique_together = ['device_type', 'name']
  421. def __unicode__(self):
  422. return self.name
  423. class InterfaceTemplateManager(models.Manager):
  424. def get_queryset(self):
  425. qs = super(InterfaceTemplateManager, self).get_queryset()
  426. return order_interfaces(qs, 'dcim_interfacetemplate.name', ('device_type',))
  427. class InterfaceTemplate(models.Model):
  428. """
  429. A template for a physical data interface on a new Device.
  430. """
  431. device_type = models.ForeignKey('DeviceType', related_name='interface_templates', on_delete=models.CASCADE)
  432. name = models.CharField(max_length=30)
  433. form_factor = models.PositiveSmallIntegerField(choices=IFACE_FF_CHOICES, default=IFACE_FF_SFP_PLUS)
  434. mgmt_only = models.BooleanField(default=False, verbose_name='Management only')
  435. objects = InterfaceTemplateManager()
  436. class Meta:
  437. ordering = ['device_type', 'name']
  438. unique_together = ['device_type', 'name']
  439. def __unicode__(self):
  440. return self.name
  441. class DeviceBayTemplate(models.Model):
  442. """
  443. A template for a DeviceBay to be created for a new parent Device.
  444. """
  445. device_type = models.ForeignKey('DeviceType', related_name='device_bay_templates', on_delete=models.CASCADE)
  446. name = models.CharField(max_length=30)
  447. class Meta:
  448. ordering = ['device_type', 'name']
  449. unique_together = ['device_type', 'name']
  450. def __unicode__(self):
  451. return self.name
  452. #
  453. # Devices
  454. #
  455. class DeviceRole(models.Model):
  456. """
  457. Devices are organized by functional role; for example, "Core Switch" or "File Server". Each DeviceRole is assigned a
  458. color to be used when displaying rack elevations.
  459. """
  460. name = models.CharField(max_length=50, unique=True)
  461. slug = models.SlugField(unique=True)
  462. color = models.CharField(max_length=30, choices=DEVICE_ROLE_COLOR_CHOICES)
  463. class Meta:
  464. ordering = ['name']
  465. def __unicode__(self):
  466. return self.name
  467. def get_absolute_url(self):
  468. return "{}?role={}".format(reverse('dcim:device_list'), self.slug)
  469. class Platform(models.Model):
  470. """
  471. Platform refers to the software or firmware running on a Device; for example, "Cisco IOS-XR" or "Juniper Junos".
  472. NetBox uses Platforms to determine how to interact with devices when pulling inventory data or other information by
  473. specifying an remote procedure call (RPC) client.
  474. """
  475. name = models.CharField(max_length=50, unique=True)
  476. slug = models.SlugField(unique=True)
  477. rpc_client = models.CharField(max_length=30, choices=RPC_CLIENT_CHOICES, blank=True, verbose_name='RPC client')
  478. class Meta:
  479. ordering = ['name']
  480. def __unicode__(self):
  481. return self.name
  482. def get_absolute_url(self):
  483. return "{}?platform={}".format(reverse('dcim:device_list'), self.slug)
  484. class DeviceManager(NaturalOrderByManager):
  485. def get_queryset(self):
  486. return self.natural_order_by('name')
  487. class Device(CreatedUpdatedModel):
  488. """
  489. A Device represents a piece of physical hardware mounted within a Rack. Each Device is assigned a DeviceType,
  490. DeviceRole, and (optionally) a Platform. Device names are not required, however if one is set it must be unique.
  491. Each Device must be assigned to a Rack, although associating it with a particular rack face or unit is optional (for
  492. example, vertically mounted PDUs do not consume rack units).
  493. When a new Device is created, console/power/interface components are created along with it as dictated by the
  494. component templates assigned to its DeviceType. Components can also be added, modified, or deleted after the
  495. creation of a Device.
  496. """
  497. device_type = models.ForeignKey('DeviceType', related_name='instances', on_delete=models.PROTECT)
  498. device_role = models.ForeignKey('DeviceRole', related_name='devices', on_delete=models.PROTECT)
  499. platform = models.ForeignKey('Platform', related_name='devices', blank=True, null=True, on_delete=models.SET_NULL)
  500. name = NullableCharField(max_length=50, blank=True, null=True, unique=True)
  501. serial = models.CharField(max_length=50, blank=True, verbose_name='Serial number')
  502. rack = models.ForeignKey('Rack', related_name='devices', on_delete=models.PROTECT)
  503. position = models.PositiveSmallIntegerField(blank=True, null=True, validators=[MinValueValidator(1)],
  504. verbose_name='Position (U)',
  505. help_text='Number of the lowest U position occupied by the device')
  506. face = models.PositiveSmallIntegerField(blank=True, null=True, choices=RACK_FACE_CHOICES, verbose_name='Rack face')
  507. status = models.BooleanField(choices=STATUS_CHOICES, default=STATUS_ACTIVE, verbose_name='Status')
  508. primary_ip4 = models.OneToOneField('ipam.IPAddress', related_name='primary_ip4_for', on_delete=models.SET_NULL,
  509. blank=True, null=True, verbose_name='Primary IPv4')
  510. primary_ip6 = models.OneToOneField('ipam.IPAddress', related_name='primary_ip6_for', on_delete=models.SET_NULL,
  511. blank=True, null=True, verbose_name='Primary IPv6')
  512. comments = models.TextField(blank=True)
  513. objects = DeviceManager()
  514. class Meta:
  515. ordering = ['name']
  516. unique_together = ['rack', 'position', 'face']
  517. def __unicode__(self):
  518. return self.display_name
  519. def get_absolute_url(self):
  520. return reverse('dcim:device', args=[self.pk])
  521. def clean(self):
  522. # Validate device type assignment
  523. if not hasattr(self, 'device_type'):
  524. raise ValidationError("Must specify device type.")
  525. # Child devices cannot be assigned to a rack face/unit
  526. if self.device_type.is_child_device and (self.face is not None or self.position):
  527. raise ValidationError("Child device types cannot be assigned a rack face or position.")
  528. # Validate position/face combination
  529. if self.position and self.face is None:
  530. raise ValidationError("Must specify rack face with rack position.")
  531. # Validate rack space
  532. rack_face = self.face if not self.device_type.is_full_depth else None
  533. exclude_list = [self.pk] if self.pk else []
  534. try:
  535. available_units = self.rack.get_available_units(u_height=self.device_type.u_height, rack_face=rack_face,
  536. exclude=exclude_list)
  537. if self.position and self.position not in available_units:
  538. raise ValidationError("U{} is already occupied or does not have sufficient space to accommodate a(n) "
  539. "{} ({}U).".format(self.position, self.device_type, self.device_type.u_height))
  540. except Rack.DoesNotExist:
  541. pass
  542. def save(self, *args, **kwargs):
  543. is_new = not bool(self.pk)
  544. super(Device, self).save(*args, **kwargs)
  545. # If this is a new Device, instantiate all of the related components per the DeviceType definition
  546. if is_new:
  547. ConsolePort.objects.bulk_create(
  548. [ConsolePort(device=self, name=template.name) for template in
  549. self.device_type.console_port_templates.all()]
  550. )
  551. ConsoleServerPort.objects.bulk_create(
  552. [ConsoleServerPort(device=self, name=template.name) for template in
  553. self.device_type.cs_port_templates.all()]
  554. )
  555. PowerPort.objects.bulk_create(
  556. [PowerPort(device=self, name=template.name) for template in
  557. self.device_type.power_port_templates.all()]
  558. )
  559. PowerOutlet.objects.bulk_create(
  560. [PowerOutlet(device=self, name=template.name) for template in
  561. self.device_type.power_outlet_templates.all()]
  562. )
  563. Interface.objects.bulk_create(
  564. [Interface(device=self, name=template.name, form_factor=template.form_factor,
  565. mgmt_only=template.mgmt_only) for template in self.device_type.interface_templates.all()]
  566. )
  567. DeviceBay.objects.bulk_create(
  568. [DeviceBay(device=self, name=template.name) for template in
  569. self.device_type.device_bay_templates.all()]
  570. )
  571. # Update Rack assignment for any child Devices
  572. Device.objects.filter(parent_bay__device=self).update(rack=self.rack)
  573. def to_csv(self):
  574. return ','.join([
  575. self.name or '',
  576. self.device_role.name,
  577. self.device_type.manufacturer.name,
  578. self.device_type.model,
  579. self.platform.name if self.platform else '',
  580. self.serial,
  581. self.rack.site.name,
  582. self.rack.name,
  583. str(self.position) if self.position else '',
  584. self.get_face_display() or '',
  585. ])
  586. @property
  587. def display_name(self):
  588. if self.name:
  589. return self.name
  590. elif self.position:
  591. return u"{} ({} U{})".format(self.device_type, self.rack.name, self.position)
  592. else:
  593. return u"{} ({})".format(self.device_type, self.rack.name)
  594. @property
  595. def identifier(self):
  596. """
  597. Return the device name if set; otherwise return the Device's primary key as {pk}
  598. """
  599. if self.name is not None:
  600. return self.name
  601. return '{{{}}}'.format(self.pk)
  602. @property
  603. def primary_ip(self):
  604. if settings.PREFER_IPV4 and self.primary_ip4:
  605. return self.primary_ip4
  606. elif self.primary_ip6:
  607. return self.primary_ip6
  608. elif self.primary_ip4:
  609. return self.primary_ip4
  610. else:
  611. return None
  612. def get_children(self):
  613. """
  614. Return the set of child Devices installed in DeviceBays within this Device.
  615. """
  616. return Device.objects.filter(parent_bay__device=self.pk)
  617. def get_rpc_client(self):
  618. """
  619. Return the appropriate RPC (e.g. NETCONF, ssh, etc.) client for this device's platform, if one is defined.
  620. """
  621. if not self.platform:
  622. return None
  623. return RPC_CLIENTS.get(self.platform.rpc_client)
  624. class ConsolePort(models.Model):
  625. """
  626. A physical console port within a Device. ConsolePorts connect to ConsoleServerPorts.
  627. """
  628. device = models.ForeignKey('Device', related_name='console_ports', on_delete=models.CASCADE)
  629. name = models.CharField(max_length=30)
  630. cs_port = models.OneToOneField('ConsoleServerPort', related_name='connected_console', on_delete=models.SET_NULL,
  631. verbose_name='Console server port', blank=True, null=True)
  632. connection_status = models.NullBooleanField(choices=CONNECTION_STATUS_CHOICES, default=CONNECTION_STATUS_CONNECTED)
  633. class Meta:
  634. ordering = ['device', 'name']
  635. unique_together = ['device', 'name']
  636. def __unicode__(self):
  637. return self.name
  638. # Used for connections export
  639. def to_csv(self):
  640. return ','.join([
  641. self.cs_port.device.identifier if self.cs_port else '',
  642. self.cs_port.name if self.cs_port else '',
  643. self.device.identifier,
  644. self.name,
  645. self.get_connection_status_display(),
  646. ])
  647. class ConsoleServerPortManager(models.Manager):
  648. def get_queryset(self):
  649. """
  650. Include the trailing numeric portion of each port name to allow for proper ordering.
  651. For example:
  652. Port 1, Port 2, Port 3 ... Port 9, Port 10, Port 11 ...
  653. Instead of:
  654. Port 1, Port 10, Port 11 ... Port 19, Port 2, Port 20 ...
  655. """
  656. return super(ConsoleServerPortManager, self).get_queryset().extra(select={
  657. 'name_as_integer': "CAST(substring(dcim_consoleserverport.name FROM '[0-9]+$') AS INTEGER)",
  658. }).order_by('device', 'name_as_integer')
  659. class ConsoleServerPort(models.Model):
  660. """
  661. A physical port within a Device (typically a designated console server) which provides access to ConsolePorts.
  662. """
  663. device = models.ForeignKey('Device', related_name='cs_ports', on_delete=models.CASCADE)
  664. name = models.CharField(max_length=30)
  665. objects = ConsoleServerPortManager()
  666. class Meta:
  667. unique_together = ['device', 'name']
  668. def __unicode__(self):
  669. return self.name
  670. class PowerPort(models.Model):
  671. """
  672. A physical power supply (intake) port within a Device. PowerPorts connect to PowerOutlets.
  673. """
  674. device = models.ForeignKey('Device', related_name='power_ports', on_delete=models.CASCADE)
  675. name = models.CharField(max_length=30)
  676. power_outlet = models.OneToOneField('PowerOutlet', related_name='connected_port', on_delete=models.SET_NULL,
  677. blank=True, null=True)
  678. connection_status = models.NullBooleanField(choices=CONNECTION_STATUS_CHOICES, default=CONNECTION_STATUS_CONNECTED)
  679. class Meta:
  680. ordering = ['device', 'name']
  681. unique_together = ['device', 'name']
  682. def __unicode__(self):
  683. return self.name
  684. # Used for connections export
  685. def to_csv(self):
  686. return ','.join([
  687. self.power_outlet.device.identifier if self.power_outlet else '',
  688. self.power_outlet.name if self.power_outlet else '',
  689. self.device.identifier,
  690. self.name,
  691. self.get_connection_status_display(),
  692. ])
  693. class PowerOutletManager(models.Manager):
  694. def get_queryset(self):
  695. return super(PowerOutletManager, self).get_queryset().extra(select={
  696. 'name_padded': "CONCAT(SUBSTRING(dcim_poweroutlet.name FROM '^[^0-9]+'), "
  697. "LPAD(SUBSTRING(dcim_poweroutlet.name FROM '[0-9\/]+$'), 8, '0'))",
  698. }).order_by('device', 'name_padded')
  699. class PowerOutlet(models.Model):
  700. """
  701. A physical power outlet (output) within a Device which provides power to a PowerPort.
  702. """
  703. device = models.ForeignKey('Device', related_name='power_outlets', on_delete=models.CASCADE)
  704. name = models.CharField(max_length=30)
  705. objects = PowerOutletManager()
  706. class Meta:
  707. unique_together = ['device', 'name']
  708. def __unicode__(self):
  709. return self.name
  710. class InterfaceManager(models.Manager):
  711. def get_queryset(self):
  712. qs = super(InterfaceManager, self).get_queryset()
  713. return order_interfaces(qs, 'dcim_interface.name', ('device',))
  714. def virtual(self):
  715. return self.get_queryset().filter(form_factor=IFACE_FF_VIRTUAL)
  716. def physical(self):
  717. return self.get_queryset().exclude(form_factor=IFACE_FF_VIRTUAL)
  718. class Interface(models.Model):
  719. """
  720. A physical data interface within a Device. An Interface can connect to exactly one other Interface via the creation
  721. of an InterfaceConnection.
  722. """
  723. device = models.ForeignKey('Device', related_name='interfaces', on_delete=models.CASCADE)
  724. name = models.CharField(max_length=30)
  725. form_factor = models.PositiveSmallIntegerField(choices=IFACE_FF_CHOICES, default=IFACE_FF_SFP_PLUS)
  726. mac_address = MACAddressField(null=True, blank=True, verbose_name='MAC Address')
  727. mgmt_only = models.BooleanField(default=False, verbose_name='OOB Management',
  728. help_text="This interface is used only for out-of-band management")
  729. description = models.CharField(max_length=100, blank=True)
  730. objects = InterfaceManager()
  731. class Meta:
  732. ordering = ['device', 'name']
  733. unique_together = ['device', 'name']
  734. def __unicode__(self):
  735. return self.name
  736. @property
  737. def is_physical(self):
  738. return self.form_factor != IFACE_FF_VIRTUAL
  739. @property
  740. def is_connected(self):
  741. try:
  742. return bool(self.circuit)
  743. except ObjectDoesNotExist:
  744. pass
  745. return bool(self.connection)
  746. @property
  747. def connection(self):
  748. try:
  749. return self.connected_as_a
  750. except ObjectDoesNotExist:
  751. pass
  752. try:
  753. return self.connected_as_b
  754. except ObjectDoesNotExist:
  755. pass
  756. return None
  757. def get_connected_interface(self):
  758. try:
  759. connection = InterfaceConnection.objects.select_related().get(Q(interface_a=self) | Q(interface_b=self))
  760. if connection.interface_a == self:
  761. return connection.interface_b
  762. else:
  763. return connection.interface_a
  764. except InterfaceConnection.DoesNotExist:
  765. return None
  766. except InterfaceConnection.MultipleObjectsReturned:
  767. raise MultipleObjectsReturned("Multiple connections found for {} interface {}!".format(self.device, self))
  768. class InterfaceConnection(models.Model):
  769. """
  770. An InterfaceConnection represents a symmetrical, one-to-one connection between two Interfaces. There is no
  771. significant difference between the interface_a and interface_b fields.
  772. """
  773. interface_a = models.OneToOneField('Interface', related_name='connected_as_a', on_delete=models.CASCADE)
  774. interface_b = models.OneToOneField('Interface', related_name='connected_as_b', on_delete=models.CASCADE)
  775. connection_status = models.BooleanField(choices=CONNECTION_STATUS_CHOICES, default=CONNECTION_STATUS_CONNECTED,
  776. verbose_name='Status')
  777. def clean(self):
  778. if self.interface_a == self.interface_b:
  779. raise ValidationError("Cannot connect an interface to itself")
  780. # Used for connections export
  781. def to_csv(self):
  782. return ','.join([
  783. self.interface_a.device.identifier,
  784. self.interface_a.name,
  785. self.interface_b.device.identifier,
  786. self.interface_b.name,
  787. self.get_connection_status_display(),
  788. ])
  789. class DeviceBay(models.Model):
  790. """
  791. An empty space within a Device which can house a child device
  792. """
  793. device = models.ForeignKey('Device', related_name='device_bays', on_delete=models.CASCADE)
  794. name = models.CharField(max_length=50, verbose_name='Name')
  795. installed_device = models.OneToOneField('Device', related_name='parent_bay', on_delete=models.SET_NULL, blank=True,
  796. null=True)
  797. class Meta:
  798. ordering = ['device', 'name']
  799. unique_together = ['device', 'name']
  800. def __unicode__(self):
  801. return u'{} - {}'.format(self.device.name, self.name)
  802. def clean(self):
  803. # Validate that the parent Device can have DeviceBays
  804. if not self.device.device_type.is_parent_device:
  805. raise ValidationError("This type of device ({}) does not support device bays."
  806. .format(self.device.device_type))
  807. # Cannot install a device into itself, obviously
  808. if self.device == self.installed_device:
  809. raise ValidationError("Cannot install a device into itself.")
  810. class Module(models.Model):
  811. """
  812. A Module represents a piece of hardware within a Device, such as a line card or power supply. Modules are used only
  813. for inventory purposes.
  814. """
  815. device = models.ForeignKey('Device', related_name='modules', on_delete=models.CASCADE)
  816. parent = models.ForeignKey('self', related_name='submodules', blank=True, null=True, on_delete=models.CASCADE)
  817. name = models.CharField(max_length=50, verbose_name='Name')
  818. part_id = models.CharField(max_length=50, verbose_name='Part ID', blank=True)
  819. serial = models.CharField(max_length=50, verbose_name='Serial number', blank=True)
  820. discovered = models.BooleanField(default=False, verbose_name='Discovered')
  821. class Meta:
  822. ordering = ['device__id', 'parent__id', 'name']
  823. unique_together = ['device', 'parent', 'name']
  824. def __unicode__(self):
  825. return self.name