models.py 35 KB

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