models.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  1. from __future__ import unicode_literals
  2. import netaddr
  3. from django.conf import settings
  4. from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
  5. from django.contrib.contenttypes.models import ContentType
  6. from django.core.exceptions import ValidationError
  7. from django.core.validators import MaxValueValidator, MinValueValidator
  8. from django.db import models
  9. from django.db.models import Q
  10. from django.db.models.expressions import RawSQL
  11. from django.urls import reverse
  12. from django.utils.encoding import python_2_unicode_compatible
  13. from dcim.models import Interface
  14. from extras.models import CustomFieldModel, CustomFieldValue
  15. from tenancy.models import Tenant
  16. from utilities.models import CreatedUpdatedModel
  17. from utilities.sql import NullsFirstQuerySet
  18. from utilities.utils import csv_format
  19. from .constants import *
  20. from .fields import IPNetworkField, IPAddressField
  21. @python_2_unicode_compatible
  22. class VRF(CreatedUpdatedModel, CustomFieldModel):
  23. """
  24. A virtual routing and forwarding (VRF) table represents a discrete layer three forwarding domain (e.g. a routing
  25. table). Prefixes and IPAddresses can optionally be assigned to VRFs. (Prefixes and IPAddresses not assigned to a VRF
  26. are said to exist in the "global" table.)
  27. """
  28. name = models.CharField(max_length=50)
  29. rd = models.CharField(max_length=21, unique=True, verbose_name='Route distinguisher')
  30. tenant = models.ForeignKey(Tenant, related_name='vrfs', blank=True, null=True, on_delete=models.PROTECT)
  31. enforce_unique = models.BooleanField(default=True, verbose_name='Enforce unique space',
  32. help_text="Prevent duplicate prefixes/IP addresses within this VRF")
  33. description = models.CharField(max_length=100, blank=True)
  34. custom_field_values = GenericRelation(CustomFieldValue, content_type_field='obj_type', object_id_field='obj_id')
  35. csv_headers = ['name', 'rd', 'tenant', 'enforce_unique', 'description']
  36. class Meta:
  37. ordering = ['name']
  38. verbose_name = 'VRF'
  39. verbose_name_plural = 'VRFs'
  40. def __str__(self):
  41. return self.display_name or super(VRF, self).__str__()
  42. def get_absolute_url(self):
  43. return reverse('ipam:vrf', args=[self.pk])
  44. def to_csv(self):
  45. return csv_format([
  46. self.name,
  47. self.rd,
  48. self.tenant.name if self.tenant else None,
  49. self.enforce_unique,
  50. self.description,
  51. ])
  52. @property
  53. def display_name(self):
  54. if self.name and self.rd:
  55. return "{} ({})".format(self.name, self.rd)
  56. return None
  57. @python_2_unicode_compatible
  58. class RIR(models.Model):
  59. """
  60. A Regional Internet Registry (RIR) is responsible for the allocation of a large portion of the global IP address
  61. space. This can be an organization like ARIN or RIPE, or a governing standard such as RFC 1918.
  62. """
  63. name = models.CharField(max_length=50, unique=True)
  64. slug = models.SlugField(unique=True)
  65. is_private = models.BooleanField(default=False, verbose_name='Private',
  66. help_text='IP space managed by this RIR is considered private')
  67. class Meta:
  68. ordering = ['name']
  69. verbose_name = 'RIR'
  70. verbose_name_plural = 'RIRs'
  71. def __str__(self):
  72. return self.name
  73. def get_absolute_url(self):
  74. return "{}?rir={}".format(reverse('ipam:aggregate_list'), self.slug)
  75. @python_2_unicode_compatible
  76. class Aggregate(CreatedUpdatedModel, CustomFieldModel):
  77. """
  78. An aggregate exists at the root level of the IP address space hierarchy in NetBox. Aggregates are used to organize
  79. the hierarchy and track the overall utilization of available address space. Each Aggregate is assigned to a RIR.
  80. """
  81. family = models.PositiveSmallIntegerField(choices=AF_CHOICES)
  82. prefix = IPNetworkField()
  83. rir = models.ForeignKey('RIR', related_name='aggregates', on_delete=models.PROTECT, verbose_name='RIR')
  84. date_added = models.DateField(blank=True, null=True)
  85. description = models.CharField(max_length=100, blank=True)
  86. custom_field_values = GenericRelation(CustomFieldValue, content_type_field='obj_type', object_id_field='obj_id')
  87. csv_headers = ['prefix', 'rir', 'date_added', 'description']
  88. class Meta:
  89. ordering = ['family', 'prefix']
  90. def __str__(self):
  91. return str(self.prefix)
  92. def get_absolute_url(self):
  93. return reverse('ipam:aggregate', args=[self.pk])
  94. def clean(self):
  95. if self.prefix:
  96. # Clear host bits from prefix
  97. self.prefix = self.prefix.cidr
  98. # Ensure that the aggregate being added is not covered by an existing aggregate
  99. covering_aggregates = Aggregate.objects.filter(prefix__net_contains_or_equals=str(self.prefix))
  100. if self.pk:
  101. covering_aggregates = covering_aggregates.exclude(pk=self.pk)
  102. if covering_aggregates:
  103. raise ValidationError({
  104. 'prefix': "Aggregates cannot overlap. {} is already covered by an existing aggregate ({}).".format(
  105. self.prefix, covering_aggregates[0]
  106. )
  107. })
  108. # Ensure that the aggregate being added does not cover an existing aggregate
  109. covered_aggregates = Aggregate.objects.filter(prefix__net_contained=str(self.prefix))
  110. if self.pk:
  111. covered_aggregates = covered_aggregates.exclude(pk=self.pk)
  112. if covered_aggregates:
  113. raise ValidationError({
  114. 'prefix': "Aggregates cannot overlap. {} covers an existing aggregate ({}).".format(
  115. self.prefix, covered_aggregates[0]
  116. )
  117. })
  118. def save(self, *args, **kwargs):
  119. if self.prefix:
  120. # Infer address family from IPNetwork object
  121. self.family = self.prefix.version
  122. super(Aggregate, self).save(*args, **kwargs)
  123. def to_csv(self):
  124. return csv_format([
  125. self.prefix,
  126. self.rir.name,
  127. self.date_added.isoformat() if self.date_added else None,
  128. self.description,
  129. ])
  130. def get_utilization(self):
  131. """
  132. Determine the prefix utilization of the aggregate and return it as a percentage.
  133. """
  134. queryset = Prefix.objects.filter(prefix__net_contained_or_equal=str(self.prefix))
  135. child_prefixes = netaddr.IPSet([p.prefix for p in queryset])
  136. return int(float(child_prefixes.size) / self.prefix.size * 100)
  137. @python_2_unicode_compatible
  138. class Role(models.Model):
  139. """
  140. A Role represents the functional role of a Prefix or VLAN; for example, "Customer," "Infrastructure," or
  141. "Management."
  142. """
  143. name = models.CharField(max_length=50, unique=True)
  144. slug = models.SlugField(unique=True)
  145. weight = models.PositiveSmallIntegerField(default=1000)
  146. class Meta:
  147. ordering = ['weight', 'name']
  148. def __str__(self):
  149. return self.name
  150. @property
  151. def count_prefixes(self):
  152. return self.prefixes.count()
  153. @property
  154. def count_vlans(self):
  155. return self.vlans.count()
  156. class PrefixQuerySet(NullsFirstQuerySet):
  157. def annotate_depth(self, limit=None):
  158. """
  159. Iterate through a QuerySet of Prefixes and annotate the hierarchical level of each. While it would be preferable
  160. to do this using .extra() on the QuerySet to count the unique parents of each prefix, that approach introduces
  161. performance issues at scale.
  162. Because we're adding a non-field attribute to the model, annotation must be made *after* any QuerySet
  163. modifications.
  164. """
  165. queryset = self
  166. stack = []
  167. for p in queryset:
  168. try:
  169. prev_p = stack[-1]
  170. except IndexError:
  171. prev_p = None
  172. if prev_p is not None:
  173. while (p.prefix not in prev_p.prefix) or p.prefix == prev_p.prefix:
  174. stack.pop()
  175. try:
  176. prev_p = stack[-1]
  177. except IndexError:
  178. prev_p = None
  179. break
  180. if prev_p is not None:
  181. prev_p.has_children = True
  182. stack.append(p)
  183. p.depth = len(stack) - 1
  184. if limit is None:
  185. return queryset
  186. return list(filter(lambda p: p.depth <= limit, queryset))
  187. @python_2_unicode_compatible
  188. class Prefix(CreatedUpdatedModel, CustomFieldModel):
  189. """
  190. A Prefix represents an IPv4 or IPv6 network, including mask length. Prefixes can optionally be assigned to Sites and
  191. VRFs. A Prefix must be assigned a status and may optionally be assigned a used-define Role. A Prefix can also be
  192. assigned to a VLAN where appropriate.
  193. """
  194. family = models.PositiveSmallIntegerField(choices=AF_CHOICES, editable=False)
  195. prefix = IPNetworkField(help_text="IPv4 or IPv6 network with mask")
  196. site = models.ForeignKey('dcim.Site', related_name='prefixes', on_delete=models.PROTECT, blank=True, null=True)
  197. vrf = models.ForeignKey('VRF', related_name='prefixes', on_delete=models.PROTECT, blank=True, null=True,
  198. verbose_name='VRF')
  199. tenant = models.ForeignKey(Tenant, related_name='prefixes', blank=True, null=True, on_delete=models.PROTECT)
  200. vlan = models.ForeignKey('VLAN', related_name='prefixes', on_delete=models.PROTECT, blank=True, null=True,
  201. verbose_name='VLAN')
  202. status = models.PositiveSmallIntegerField('Status', choices=PREFIX_STATUS_CHOICES, default=PREFIX_STATUS_ACTIVE,
  203. help_text="Operational status of this prefix")
  204. role = models.ForeignKey('Role', related_name='prefixes', on_delete=models.SET_NULL, blank=True, null=True,
  205. help_text="The primary function of this prefix")
  206. is_pool = models.BooleanField(verbose_name='Is a pool', default=False,
  207. help_text="All IP addresses within this prefix are considered usable")
  208. description = models.CharField(max_length=100, blank=True)
  209. custom_field_values = GenericRelation(CustomFieldValue, content_type_field='obj_type', object_id_field='obj_id')
  210. objects = PrefixQuerySet.as_manager()
  211. csv_headers = [
  212. 'prefix', 'vrf', 'tenant', 'site', 'vlan_group', 'vlan_vid', 'status', 'role', 'is_pool', 'description',
  213. ]
  214. class Meta:
  215. ordering = ['vrf', 'family', 'prefix']
  216. verbose_name_plural = 'prefixes'
  217. def __str__(self):
  218. return str(self.prefix)
  219. def get_absolute_url(self):
  220. return reverse('ipam:prefix', args=[self.pk])
  221. def clean(self):
  222. if self.prefix:
  223. # Disallow host masks
  224. if self.prefix.version == 4 and self.prefix.prefixlen == 32:
  225. raise ValidationError({
  226. 'prefix': "Cannot create host addresses (/32) as prefixes. Create an IPv4 address instead."
  227. })
  228. elif self.prefix.version == 6 and self.prefix.prefixlen == 128:
  229. raise ValidationError({
  230. 'prefix': "Cannot create host addresses (/128) as prefixes. Create an IPv6 address instead."
  231. })
  232. # Enforce unique IP space (if applicable)
  233. if (self.vrf is None and settings.ENFORCE_GLOBAL_UNIQUE) or (self.vrf and self.vrf.enforce_unique):
  234. duplicate_prefixes = self.get_duplicates()
  235. if duplicate_prefixes:
  236. raise ValidationError({
  237. 'prefix': "Duplicate prefix found in {}: {}".format(
  238. "VRF {}".format(self.vrf) if self.vrf else "global table",
  239. duplicate_prefixes.first(),
  240. )
  241. })
  242. def save(self, *args, **kwargs):
  243. if self.prefix:
  244. # Clear host bits from prefix
  245. self.prefix = self.prefix.cidr
  246. # Infer address family from IPNetwork object
  247. self.family = self.prefix.version
  248. super(Prefix, self).save(*args, **kwargs)
  249. def to_csv(self):
  250. return csv_format([
  251. self.prefix,
  252. self.vrf.rd if self.vrf else None,
  253. self.tenant.name if self.tenant else None,
  254. self.site.name if self.site else None,
  255. self.vlan.group.name if self.vlan and self.vlan.group else None,
  256. self.vlan.vid if self.vlan else None,
  257. self.get_status_display(),
  258. self.role.name if self.role else None,
  259. self.is_pool,
  260. self.description,
  261. ])
  262. def get_status_class(self):
  263. return STATUS_CHOICE_CLASSES[self.status]
  264. def get_duplicates(self):
  265. return Prefix.objects.filter(vrf=self.vrf, prefix=str(self.prefix)).exclude(pk=self.pk)
  266. def get_child_ips(self):
  267. """
  268. Return all IPAddresses within this Prefix.
  269. """
  270. return IPAddress.objects.filter(address__net_contained_or_equal=str(self.prefix), vrf=self.vrf)
  271. def get_available_ips(self):
  272. """
  273. Return all available IPs within this prefix as an IPSet.
  274. """
  275. prefix = netaddr.IPSet(self.prefix)
  276. child_ips = netaddr.IPSet([ip.address.ip for ip in self.get_child_ips()])
  277. available_ips = prefix - child_ips
  278. # Remove unusable IPs from non-pool prefixes
  279. if not self.is_pool:
  280. available_ips -= netaddr.IPSet([
  281. netaddr.IPAddress(self.prefix.first),
  282. netaddr.IPAddress(self.prefix.last),
  283. ])
  284. return available_ips
  285. def get_utilization(self):
  286. """
  287. Determine the utilization of the prefix and return it as a percentage. For Prefixes with a status of
  288. "container", calculate utilization based on child prefixes. For all others, count child IP addresses.
  289. """
  290. if self.status == PREFIX_STATUS_CONTAINER:
  291. queryset = Prefix.objects.filter(prefix__net_contained=str(self.prefix), vrf=self.vrf)
  292. child_prefixes = netaddr.IPSet([p.prefix for p in queryset])
  293. return int(float(child_prefixes.size) / self.prefix.size * 100)
  294. else:
  295. child_count = IPAddress.objects.filter(
  296. address__net_contained_or_equal=str(self.prefix), vrf=self.vrf
  297. ).count()
  298. prefix_size = self.prefix.size
  299. if self.family == 4 and self.prefix.prefixlen < 31 and not self.is_pool:
  300. prefix_size -= 2
  301. return int(float(child_count) / prefix_size * 100)
  302. @property
  303. def new_subnet(self):
  304. if self.family == 4:
  305. if self.prefix.prefixlen <= 30:
  306. return netaddr.IPNetwork('{}/{}'.format(self.prefix.network, self.prefix.prefixlen + 1))
  307. return None
  308. if self.family == 6:
  309. if self.prefix.prefixlen <= 126:
  310. return netaddr.IPNetwork('{}/{}'.format(self.prefix.network, self.prefix.prefixlen + 1))
  311. return None
  312. class IPAddressManager(models.Manager):
  313. def get_queryset(self):
  314. """
  315. By default, PostgreSQL will order INETs with shorter (larger) prefix lengths ahead of those with longer
  316. (smaller) masks. This makes no sense when ordering IPs, which should be ordered solely by family and host
  317. address. We can use HOST() to extract just the host portion of the address (ignoring its mask), but we must
  318. then re-cast this value to INET() so that records will be ordered properly. We are essentially re-casting each
  319. IP address as a /32 or /128.
  320. """
  321. qs = super(IPAddressManager, self).get_queryset()
  322. return qs.annotate(host=RawSQL('INET(HOST(ipam_ipaddress.address))', [])).order_by('family', 'host')
  323. @python_2_unicode_compatible
  324. class IPAddress(CreatedUpdatedModel, CustomFieldModel):
  325. """
  326. An IPAddress represents an individual IPv4 or IPv6 address and its mask. The mask length should match what is
  327. configured in the real world. (Typically, only loopback interfaces are configured with /32 or /128 masks.) Like
  328. Prefixes, IPAddresses can optionally be assigned to a VRF. An IPAddress can optionally be assigned to an Interface.
  329. Interfaces can have zero or more IPAddresses assigned to them.
  330. An IPAddress can also optionally point to a NAT inside IP, designating itself as a NAT outside IP. This is useful,
  331. for example, when mapping public addresses to private addresses. When an Interface has been assigned an IPAddress
  332. which has a NAT outside IP, that Interface's Device can use either the inside or outside IP as its primary IP.
  333. """
  334. family = models.PositiveSmallIntegerField(choices=AF_CHOICES, editable=False)
  335. address = IPAddressField(help_text="IPv4 or IPv6 address (with mask)")
  336. vrf = models.ForeignKey('VRF', related_name='ip_addresses', on_delete=models.PROTECT, blank=True, null=True,
  337. verbose_name='VRF')
  338. tenant = models.ForeignKey(Tenant, related_name='ip_addresses', blank=True, null=True, on_delete=models.PROTECT)
  339. status = models.PositiveSmallIntegerField(
  340. 'Status', choices=IPADDRESS_STATUS_CHOICES, default=IPADDRESS_STATUS_ACTIVE,
  341. help_text='The operational status of this IP'
  342. )
  343. role = models.PositiveSmallIntegerField(
  344. 'Role', choices=IPADDRESS_ROLE_CHOICES, blank=True, null=True, help_text='The functional role of this IP'
  345. )
  346. interface = models.ForeignKey(Interface, related_name='ip_addresses', on_delete=models.CASCADE, blank=True,
  347. null=True)
  348. nat_inside = models.OneToOneField('self', related_name='nat_outside', on_delete=models.SET_NULL, blank=True,
  349. null=True, verbose_name='NAT (Inside)',
  350. help_text="The IP for which this address is the \"outside\" IP")
  351. description = models.CharField(max_length=100, blank=True)
  352. custom_field_values = GenericRelation(CustomFieldValue, content_type_field='obj_type', object_id_field='obj_id')
  353. objects = IPAddressManager()
  354. csv_headers = [
  355. 'address', 'vrf', 'tenant', 'status', 'role', 'device', 'virtual_machine', 'interface_name', 'is_primary',
  356. 'description',
  357. ]
  358. class Meta:
  359. ordering = ['family', 'address']
  360. verbose_name = 'IP address'
  361. verbose_name_plural = 'IP addresses'
  362. def __str__(self):
  363. return str(self.address)
  364. def get_absolute_url(self):
  365. return reverse('ipam:ipaddress', args=[self.pk])
  366. def get_duplicates(self):
  367. return IPAddress.objects.filter(vrf=self.vrf, address__net_host=str(self.address.ip)).exclude(pk=self.pk)
  368. def clean(self):
  369. if self.address:
  370. # Enforce unique IP space (if applicable)
  371. if (self.vrf is None and settings.ENFORCE_GLOBAL_UNIQUE) or (self.vrf and self.vrf.enforce_unique):
  372. duplicate_ips = self.get_duplicates()
  373. if duplicate_ips:
  374. raise ValidationError({
  375. 'address': "Duplicate IP address found in {}: {}".format(
  376. "VRF {}".format(self.vrf) if self.vrf else "global table",
  377. duplicate_ips.first(),
  378. )
  379. })
  380. def save(self, *args, **kwargs):
  381. if self.address:
  382. # Infer address family from IPAddress object
  383. self.family = self.address.version
  384. super(IPAddress, self).save(*args, **kwargs)
  385. def to_csv(self):
  386. # Determine if this IP is primary for a Device
  387. if self.family == 4 and getattr(self, 'primary_ip4_for', False):
  388. is_primary = True
  389. elif self.family == 6 and getattr(self, 'primary_ip6_for', False):
  390. is_primary = True
  391. else:
  392. is_primary = False
  393. return csv_format([
  394. self.address,
  395. self.vrf.rd if self.vrf else None,
  396. self.tenant.name if self.tenant else None,
  397. self.get_status_display(),
  398. self.get_role_display(),
  399. self.device.identifier if self.device else None,
  400. self.virtual_machine.name if self.device else None,
  401. self.interface.name if self.interface else None,
  402. is_primary,
  403. self.description,
  404. ])
  405. @property
  406. def device(self):
  407. if self.interface:
  408. return self.interface.device
  409. return None
  410. def get_status_class(self):
  411. return STATUS_CHOICE_CLASSES[self.status]
  412. @python_2_unicode_compatible
  413. class VLANGroup(models.Model):
  414. """
  415. A VLAN group is an arbitrary collection of VLANs within which VLAN IDs and names must be unique.
  416. """
  417. name = models.CharField(max_length=50)
  418. slug = models.SlugField()
  419. site = models.ForeignKey('dcim.Site', related_name='vlan_groups', on_delete=models.PROTECT, blank=True, null=True)
  420. class Meta:
  421. ordering = ['site', 'name']
  422. unique_together = [
  423. ['site', 'name'],
  424. ['site', 'slug'],
  425. ]
  426. verbose_name = 'VLAN group'
  427. verbose_name_plural = 'VLAN groups'
  428. def __str__(self):
  429. return self.name
  430. def get_absolute_url(self):
  431. return "{}?group_id={}".format(reverse('ipam:vlan_list'), self.pk)
  432. def get_next_available_vid(self):
  433. """
  434. Return the first available VLAN ID (1-4094) in the group.
  435. """
  436. vids = [vlan['vid'] for vlan in self.vlans.order_by('vid').values('vid')]
  437. for i in range(1, 4095):
  438. if i not in vids:
  439. return i
  440. return None
  441. @python_2_unicode_compatible
  442. class VLAN(CreatedUpdatedModel, CustomFieldModel):
  443. """
  444. A VLAN is a distinct layer two forwarding domain identified by a 12-bit integer (1-4094). Each VLAN must be assigned
  445. to a Site, however VLAN IDs need not be unique within a Site. A VLAN may optionally be assigned to a VLANGroup,
  446. within which all VLAN IDs and names but be unique.
  447. Like Prefixes, each VLAN is assigned an operational status and optionally a user-defined Role. A VLAN can have zero
  448. or more Prefixes assigned to it.
  449. """
  450. site = models.ForeignKey('dcim.Site', related_name='vlans', on_delete=models.PROTECT, blank=True, null=True)
  451. group = models.ForeignKey('VLANGroup', related_name='vlans', blank=True, null=True, on_delete=models.PROTECT)
  452. vid = models.PositiveSmallIntegerField(verbose_name='ID', validators=[
  453. MinValueValidator(1),
  454. MaxValueValidator(4094)
  455. ])
  456. name = models.CharField(max_length=64)
  457. tenant = models.ForeignKey(Tenant, related_name='vlans', blank=True, null=True, on_delete=models.PROTECT)
  458. status = models.PositiveSmallIntegerField('Status', choices=VLAN_STATUS_CHOICES, default=1)
  459. role = models.ForeignKey('Role', related_name='vlans', on_delete=models.SET_NULL, blank=True, null=True)
  460. description = models.CharField(max_length=100, blank=True)
  461. custom_field_values = GenericRelation(CustomFieldValue, content_type_field='obj_type', object_id_field='obj_id')
  462. csv_headers = ['site', 'group_name', 'vid', 'name', 'tenant', 'status', 'role', 'description']
  463. class Meta:
  464. ordering = ['site', 'group', 'vid']
  465. unique_together = [
  466. ['group', 'vid'],
  467. ['group', 'name'],
  468. ]
  469. verbose_name = 'VLAN'
  470. verbose_name_plural = 'VLANs'
  471. def __str__(self):
  472. return self.display_name or super(VLAN, self).__str__()
  473. def get_absolute_url(self):
  474. return reverse('ipam:vlan', args=[self.pk])
  475. def clean(self):
  476. # Validate VLAN group
  477. if self.group and self.group.site != self.site:
  478. raise ValidationError({
  479. 'group': "VLAN group must belong to the assigned site ({}).".format(self.site)
  480. })
  481. def to_csv(self):
  482. return csv_format([
  483. self.site.name if self.site else None,
  484. self.group.name if self.group else None,
  485. self.vid,
  486. self.name,
  487. self.tenant.name if self.tenant else None,
  488. self.get_status_display(),
  489. self.role.name if self.role else None,
  490. self.description,
  491. ])
  492. @property
  493. def display_name(self):
  494. if self.vid and self.name:
  495. return "{} ({})".format(self.vid, self.name)
  496. return None
  497. def get_status_class(self):
  498. return STATUS_CHOICE_CLASSES[self.status]
  499. @python_2_unicode_compatible
  500. class Service(CreatedUpdatedModel):
  501. """
  502. A Service represents a layer-four service (e.g. HTTP or SSH) running on a Device or VirtualMachine. A Service may
  503. optionally be tied to one or more specific IPAddresses belonging to its parent.
  504. """
  505. device = models.ForeignKey(
  506. to='dcim.Device',
  507. on_delete=models.CASCADE,
  508. related_name='services',
  509. verbose_name='device',
  510. null=True,
  511. blank=True
  512. )
  513. virtual_machine = models.ForeignKey(
  514. to='virtualization.VirtualMachine',
  515. on_delete=models.CASCADE,
  516. related_name='services',
  517. null=True,
  518. blank=True
  519. )
  520. name = models.CharField(
  521. max_length=30
  522. )
  523. protocol = models.PositiveSmallIntegerField(
  524. choices=IP_PROTOCOL_CHOICES
  525. )
  526. port = models.PositiveIntegerField(
  527. validators=[MinValueValidator(1), MaxValueValidator(65535)],
  528. verbose_name='Port number'
  529. )
  530. ipaddresses = models.ManyToManyField(
  531. to='ipam.IPAddress',
  532. related_name='services',
  533. blank=True,
  534. verbose_name='IP addresses'
  535. )
  536. description = models.CharField(
  537. max_length=100,
  538. blank=True
  539. )
  540. class Meta:
  541. ordering = ['protocol', 'port']
  542. def __str__(self):
  543. return '{} ({}/{})'.format(self.name, self.port, self.get_protocol_display())
  544. @property
  545. def parent(self):
  546. return self.device or self.virtual_machine
  547. def clean(self):
  548. # A Service must belong to a Device *or* to a VirtualMachine
  549. if self.device and self.virtual_machine:
  550. raise ValidationError("A service cannot be associated with both a device and a virtual machine.")
  551. if not self.device and not self.virtual_machine:
  552. raise ValidationError("A service must be associated with either a device or a virtual machine.")