models.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  1. from __future__ import unicode_literals
  2. import netaddr
  3. from django.conf import settings
  4. from django.contrib.contenttypes.fields import GenericRelation
  5. from django.core.exceptions import ValidationError
  6. from django.core.validators import MaxValueValidator, MinValueValidator
  7. from django.db import models
  8. from django.db.models import Q
  9. from django.db.models.expressions import RawSQL
  10. from django.urls import reverse
  11. from django.utils.encoding import python_2_unicode_compatible
  12. from taggit.managers import TaggableManager
  13. from dcim.models import Interface
  14. from extras.models import CustomFieldModel
  15. from utilities.models import ChangeLoggedModel
  16. from .constants import *
  17. from .fields import IPNetworkField, IPAddressField
  18. from .querysets import PrefixQuerySet
  19. @python_2_unicode_compatible
  20. class VRF(ChangeLoggedModel, CustomFieldModel):
  21. """
  22. A virtual routing and forwarding (VRF) table represents a discrete layer three forwarding domain (e.g. a routing
  23. table). Prefixes and IPAddresses can optionally be assigned to VRFs. (Prefixes and IPAddresses not assigned to a VRF
  24. are said to exist in the "global" table.)
  25. """
  26. name = models.CharField(
  27. max_length=50
  28. )
  29. rd = models.CharField(
  30. max_length=21,
  31. unique=True,
  32. verbose_name='Route distinguisher'
  33. )
  34. tenant = models.ForeignKey(
  35. to='tenancy.Tenant',
  36. on_delete=models.PROTECT,
  37. related_name='vrfs',
  38. blank=True,
  39. null=True
  40. )
  41. enforce_unique = models.BooleanField(
  42. default=True,
  43. verbose_name='Enforce unique space',
  44. help_text='Prevent duplicate prefixes/IP addresses within this VRF'
  45. )
  46. description = models.CharField(
  47. max_length=100,
  48. blank=True
  49. )
  50. custom_field_values = GenericRelation(
  51. to='extras.CustomFieldValue',
  52. content_type_field='obj_type',
  53. object_id_field='obj_id'
  54. )
  55. tags = TaggableManager()
  56. serializer = 'ipam.api.serializers.VRFSerializer'
  57. csv_headers = ['name', 'rd', 'tenant', 'enforce_unique', 'description']
  58. class Meta:
  59. ordering = ['name', 'rd']
  60. verbose_name = 'VRF'
  61. verbose_name_plural = 'VRFs'
  62. def __str__(self):
  63. return self.display_name or super(VRF, self).__str__()
  64. def get_absolute_url(self):
  65. return reverse('ipam:vrf', args=[self.pk])
  66. def to_csv(self):
  67. return (
  68. self.name,
  69. self.rd,
  70. self.tenant.name if self.tenant else None,
  71. self.enforce_unique,
  72. self.description,
  73. )
  74. @property
  75. def display_name(self):
  76. if self.name and self.rd:
  77. return "{} ({})".format(self.name, self.rd)
  78. return None
  79. @python_2_unicode_compatible
  80. class RIR(ChangeLoggedModel):
  81. """
  82. A Regional Internet Registry (RIR) is responsible for the allocation of a large portion of the global IP address
  83. space. This can be an organization like ARIN or RIPE, or a governing standard such as RFC 1918.
  84. """
  85. name = models.CharField(
  86. max_length=50,
  87. unique=True
  88. )
  89. slug = models.SlugField(
  90. unique=True
  91. )
  92. is_private = models.BooleanField(
  93. default=False,
  94. verbose_name='Private',
  95. help_text='IP space managed by this RIR is considered private'
  96. )
  97. serializer = 'ipam.api.serializers.RIRSerializer'
  98. csv_headers = ['name', 'slug', 'is_private']
  99. class Meta:
  100. ordering = ['name']
  101. verbose_name = 'RIR'
  102. verbose_name_plural = 'RIRs'
  103. def __str__(self):
  104. return self.name
  105. def get_absolute_url(self):
  106. return "{}?rir={}".format(reverse('ipam:aggregate_list'), self.slug)
  107. def to_csv(self):
  108. return (
  109. self.name,
  110. self.slug,
  111. self.is_private,
  112. )
  113. @python_2_unicode_compatible
  114. class Aggregate(ChangeLoggedModel, CustomFieldModel):
  115. """
  116. An aggregate exists at the root level of the IP address space hierarchy in NetBox. Aggregates are used to organize
  117. the hierarchy and track the overall utilization of available address space. Each Aggregate is assigned to a RIR.
  118. """
  119. family = models.PositiveSmallIntegerField(
  120. choices=AF_CHOICES
  121. )
  122. prefix = IPNetworkField()
  123. rir = models.ForeignKey(
  124. to='ipam.RIR',
  125. on_delete=models.PROTECT,
  126. related_name='aggregates',
  127. verbose_name='RIR'
  128. )
  129. date_added = models.DateField(
  130. blank=True,
  131. null=True
  132. )
  133. description = models.CharField(
  134. max_length=100,
  135. blank=True
  136. )
  137. custom_field_values = GenericRelation(
  138. to='extras.CustomFieldValue',
  139. content_type_field='obj_type',
  140. object_id_field='obj_id'
  141. )
  142. tags = TaggableManager()
  143. serializer = 'ipam.api.serializers.AggregateSerializer'
  144. csv_headers = ['prefix', 'rir', 'date_added', 'description']
  145. class Meta:
  146. ordering = ['family', 'prefix']
  147. def __str__(self):
  148. return str(self.prefix)
  149. def get_absolute_url(self):
  150. return reverse('ipam:aggregate', args=[self.pk])
  151. def clean(self):
  152. if self.prefix:
  153. # Clear host bits from prefix
  154. self.prefix = self.prefix.cidr
  155. # Ensure that the aggregate being added is not covered by an existing aggregate
  156. covering_aggregates = Aggregate.objects.filter(prefix__net_contains_or_equals=str(self.prefix))
  157. if self.pk:
  158. covering_aggregates = covering_aggregates.exclude(pk=self.pk)
  159. if covering_aggregates:
  160. raise ValidationError({
  161. 'prefix': "Aggregates cannot overlap. {} is already covered by an existing aggregate ({}).".format(
  162. self.prefix, covering_aggregates[0]
  163. )
  164. })
  165. # Ensure that the aggregate being added does not cover an existing aggregate
  166. covered_aggregates = Aggregate.objects.filter(prefix__net_contained=str(self.prefix))
  167. if self.pk:
  168. covered_aggregates = covered_aggregates.exclude(pk=self.pk)
  169. if covered_aggregates:
  170. raise ValidationError({
  171. 'prefix': "Aggregates cannot overlap. {} covers an existing aggregate ({}).".format(
  172. self.prefix, covered_aggregates[0]
  173. )
  174. })
  175. def save(self, *args, **kwargs):
  176. if self.prefix:
  177. # Infer address family from IPNetwork object
  178. self.family = self.prefix.version
  179. super(Aggregate, self).save(*args, **kwargs)
  180. def to_csv(self):
  181. return (
  182. self.prefix,
  183. self.rir.name,
  184. self.date_added,
  185. self.description,
  186. )
  187. def get_utilization(self):
  188. """
  189. Determine the prefix utilization of the aggregate and return it as a percentage.
  190. """
  191. queryset = Prefix.objects.filter(prefix__net_contained_or_equal=str(self.prefix))
  192. child_prefixes = netaddr.IPSet([p.prefix for p in queryset])
  193. return int(float(child_prefixes.size) / self.prefix.size * 100)
  194. @python_2_unicode_compatible
  195. class Role(ChangeLoggedModel):
  196. """
  197. A Role represents the functional role of a Prefix or VLAN; for example, "Customer," "Infrastructure," or
  198. "Management."
  199. """
  200. name = models.CharField(
  201. max_length=50,
  202. unique=True
  203. )
  204. slug = models.SlugField(
  205. unique=True
  206. )
  207. weight = models.PositiveSmallIntegerField(
  208. default=1000
  209. )
  210. serializer = 'ipam.api.serializers.RoleSerializer'
  211. csv_headers = ['name', 'slug', 'weight']
  212. class Meta:
  213. ordering = ['weight', 'name']
  214. def __str__(self):
  215. return self.name
  216. def to_csv(self):
  217. return (
  218. self.name,
  219. self.slug,
  220. self.weight,
  221. )
  222. @python_2_unicode_compatible
  223. class Prefix(ChangeLoggedModel, CustomFieldModel):
  224. """
  225. A Prefix represents an IPv4 or IPv6 network, including mask length. Prefixes can optionally be assigned to Sites and
  226. VRFs. A Prefix must be assigned a status and may optionally be assigned a used-define Role. A Prefix can also be
  227. assigned to a VLAN where appropriate.
  228. """
  229. family = models.PositiveSmallIntegerField(
  230. choices=AF_CHOICES,
  231. editable=False
  232. )
  233. prefix = IPNetworkField(
  234. help_text='IPv4 or IPv6 network with mask'
  235. )
  236. site = models.ForeignKey(
  237. to='dcim.Site',
  238. on_delete=models.PROTECT,
  239. related_name='prefixes',
  240. blank=True,
  241. null=True
  242. )
  243. vrf = models.ForeignKey(
  244. to='ipam.VRF',
  245. on_delete=models.PROTECT,
  246. related_name='prefixes',
  247. blank=True,
  248. null=True,
  249. verbose_name='VRF'
  250. )
  251. tenant = models.ForeignKey(
  252. to='tenancy.Tenant',
  253. on_delete=models.PROTECT,
  254. related_name='prefixes',
  255. blank=True,
  256. null=True
  257. )
  258. vlan = models.ForeignKey(
  259. to='ipam.VLAN',
  260. on_delete=models.PROTECT,
  261. related_name='prefixes',
  262. blank=True,
  263. null=True,
  264. verbose_name='VLAN'
  265. )
  266. status = models.PositiveSmallIntegerField(
  267. choices=PREFIX_STATUS_CHOICES,
  268. default=PREFIX_STATUS_ACTIVE,
  269. verbose_name='Status',
  270. help_text='Operational status of this prefix'
  271. )
  272. role = models.ForeignKey(
  273. to='ipam.Role',
  274. on_delete=models.SET_NULL,
  275. related_name='prefixes',
  276. blank=True,
  277. null=True,
  278. help_text='The primary function of this prefix'
  279. )
  280. is_pool = models.BooleanField(
  281. verbose_name='Is a pool',
  282. default=False,
  283. help_text='All IP addresses within this prefix are considered usable'
  284. )
  285. description = models.CharField(
  286. max_length=100,
  287. blank=True
  288. )
  289. custom_field_values = GenericRelation(
  290. to='extras.CustomFieldValue',
  291. content_type_field='obj_type',
  292. object_id_field='obj_id'
  293. )
  294. objects = PrefixQuerySet.as_manager()
  295. tags = TaggableManager()
  296. serializer = 'ipam.api.serializers.PrefixSerializer'
  297. csv_headers = [
  298. 'prefix', 'vrf', 'tenant', 'site', 'vlan_group', 'vlan_vid', 'status', 'role', 'is_pool', 'description',
  299. ]
  300. class Meta:
  301. ordering = ['vrf', 'family', 'prefix']
  302. verbose_name_plural = 'prefixes'
  303. def __str__(self):
  304. return str(self.prefix)
  305. def get_absolute_url(self):
  306. return reverse('ipam:prefix', args=[self.pk])
  307. def clean(self):
  308. if self.prefix:
  309. # Disallow host masks
  310. if self.prefix.version == 4 and self.prefix.prefixlen == 32:
  311. raise ValidationError({
  312. 'prefix': "Cannot create host addresses (/32) as prefixes. Create an IPv4 address instead."
  313. })
  314. elif self.prefix.version == 6 and self.prefix.prefixlen == 128:
  315. raise ValidationError({
  316. 'prefix': "Cannot create host addresses (/128) as prefixes. Create an IPv6 address instead."
  317. })
  318. # Enforce unique IP space (if applicable)
  319. if (self.vrf is None and settings.ENFORCE_GLOBAL_UNIQUE) or (self.vrf and self.vrf.enforce_unique):
  320. duplicate_prefixes = self.get_duplicates()
  321. if duplicate_prefixes:
  322. raise ValidationError({
  323. 'prefix': "Duplicate prefix found in {}: {}".format(
  324. "VRF {}".format(self.vrf) if self.vrf else "global table",
  325. duplicate_prefixes.first(),
  326. )
  327. })
  328. def save(self, *args, **kwargs):
  329. if self.prefix:
  330. # Clear host bits from prefix
  331. self.prefix = self.prefix.cidr
  332. # Infer address family from IPNetwork object
  333. self.family = self.prefix.version
  334. super(Prefix, self).save(*args, **kwargs)
  335. def to_csv(self):
  336. return (
  337. self.prefix,
  338. self.vrf.rd if self.vrf else None,
  339. self.tenant.name if self.tenant else None,
  340. self.site.name if self.site else None,
  341. self.vlan.group.name if self.vlan and self.vlan.group else None,
  342. self.vlan.vid if self.vlan else None,
  343. self.get_status_display(),
  344. self.role.name if self.role else None,
  345. self.is_pool,
  346. self.description,
  347. )
  348. def get_status_class(self):
  349. return STATUS_CHOICE_CLASSES[self.status]
  350. def get_duplicates(self):
  351. return Prefix.objects.filter(vrf=self.vrf, prefix=str(self.prefix)).exclude(pk=self.pk)
  352. def get_child_prefixes(self):
  353. """
  354. Return all Prefixes within this Prefix and VRF. If this Prefix is a container in the global table, return child
  355. Prefixes belonging to any VRF.
  356. """
  357. if self.vrf is None and self.status == PREFIX_STATUS_CONTAINER:
  358. return Prefix.objects.filter(prefix__net_contained=str(self.prefix))
  359. else:
  360. return Prefix.objects.filter(prefix__net_contained=str(self.prefix), vrf=self.vrf)
  361. def get_child_ips(self):
  362. """
  363. Return all IPAddresses within this Prefix and VRF. If this Prefix is a container in the global table, return
  364. child IPAddresses belonging to any VRF.
  365. """
  366. if self.vrf is None and self.status == PREFIX_STATUS_CONTAINER:
  367. return IPAddress.objects.filter(address__net_host_contained=str(self.prefix))
  368. else:
  369. return IPAddress.objects.filter(address__net_host_contained=str(self.prefix), vrf=self.vrf)
  370. def get_available_prefixes(self):
  371. """
  372. Return all available Prefixes within this prefix as an IPSet.
  373. """
  374. prefix = netaddr.IPSet(self.prefix)
  375. child_prefixes = netaddr.IPSet([child.prefix for child in self.get_child_prefixes()])
  376. available_prefixes = prefix - child_prefixes
  377. return available_prefixes
  378. def get_available_ips(self):
  379. """
  380. Return all available IPs within this prefix as an IPSet.
  381. """
  382. prefix = netaddr.IPSet(self.prefix)
  383. child_ips = netaddr.IPSet([ip.address.ip for ip in self.get_child_ips()])
  384. available_ips = prefix - child_ips
  385. # Remove unusable IPs from non-pool prefixes
  386. if not self.is_pool:
  387. available_ips -= netaddr.IPSet([
  388. netaddr.IPAddress(self.prefix.first),
  389. netaddr.IPAddress(self.prefix.last),
  390. ])
  391. return available_ips
  392. def get_first_available_prefix(self):
  393. """
  394. Return the first available child prefix within the prefix (or None).
  395. """
  396. available_prefixes = self.get_available_prefixes()
  397. if not available_prefixes:
  398. return None
  399. return available_prefixes.iter_cidrs()[0]
  400. def get_first_available_ip(self):
  401. """
  402. Return the first available IP within the prefix (or None).
  403. """
  404. available_ips = self.get_available_ips()
  405. if not available_ips:
  406. return None
  407. return '{}/{}'.format(next(available_ips.__iter__()), self.prefix.prefixlen)
  408. def get_utilization(self):
  409. """
  410. Determine the utilization of the prefix and return it as a percentage. For Prefixes with a status of
  411. "container", calculate utilization based on child prefixes. For all others, count child IP addresses.
  412. """
  413. if self.status == PREFIX_STATUS_CONTAINER:
  414. queryset = Prefix.objects.filter(prefix__net_contained=str(self.prefix), vrf=self.vrf)
  415. child_prefixes = netaddr.IPSet([p.prefix for p in queryset])
  416. return int(float(child_prefixes.size) / self.prefix.size * 100)
  417. else:
  418. # Compile an IPSet to avoid counting duplicate IPs
  419. child_count = netaddr.IPSet([ip.address.ip for ip in self.get_child_ips()]).size
  420. prefix_size = self.prefix.size
  421. if self.family == 4 and self.prefix.prefixlen < 31 and not self.is_pool:
  422. prefix_size -= 2
  423. return int(float(child_count) / prefix_size * 100)
  424. class IPAddressManager(models.Manager):
  425. def get_queryset(self):
  426. """
  427. By default, PostgreSQL will order INETs with shorter (larger) prefix lengths ahead of those with longer
  428. (smaller) masks. This makes no sense when ordering IPs, which should be ordered solely by family and host
  429. address. We can use HOST() to extract just the host portion of the address (ignoring its mask), but we must
  430. then re-cast this value to INET() so that records will be ordered properly. We are essentially re-casting each
  431. IP address as a /32 or /128.
  432. """
  433. qs = super(IPAddressManager, self).get_queryset()
  434. return qs.annotate(host=RawSQL('INET(HOST(ipam_ipaddress.address))', [])).order_by('family', 'host')
  435. @python_2_unicode_compatible
  436. class IPAddress(ChangeLoggedModel, CustomFieldModel):
  437. """
  438. An IPAddress represents an individual IPv4 or IPv6 address and its mask. The mask length should match what is
  439. configured in the real world. (Typically, only loopback interfaces are configured with /32 or /128 masks.) Like
  440. Prefixes, IPAddresses can optionally be assigned to a VRF. An IPAddress can optionally be assigned to an Interface.
  441. Interfaces can have zero or more IPAddresses assigned to them.
  442. An IPAddress can also optionally point to a NAT inside IP, designating itself as a NAT outside IP. This is useful,
  443. for example, when mapping public addresses to private addresses. When an Interface has been assigned an IPAddress
  444. which has a NAT outside IP, that Interface's Device can use either the inside or outside IP as its primary IP.
  445. """
  446. family = models.PositiveSmallIntegerField(
  447. choices=AF_CHOICES,
  448. editable=False
  449. )
  450. address = IPAddressField(
  451. help_text='IPv4 or IPv6 address (with mask)'
  452. )
  453. vrf = models.ForeignKey(
  454. to='ipam.VRF',
  455. on_delete=models.PROTECT,
  456. related_name='ip_addresses',
  457. blank=True,
  458. null=True,
  459. verbose_name='VRF'
  460. )
  461. tenant = models.ForeignKey(
  462. to='tenancy.Tenant',
  463. on_delete=models.PROTECT,
  464. related_name='ip_addresses',
  465. blank=True,
  466. null=True
  467. )
  468. status = models.PositiveSmallIntegerField(
  469. choices=IPADDRESS_STATUS_CHOICES,
  470. default=IPADDRESS_STATUS_ACTIVE,
  471. verbose_name='Status',
  472. help_text='The operational status of this IP'
  473. )
  474. role = models.PositiveSmallIntegerField(
  475. verbose_name='Role',
  476. choices=IPADDRESS_ROLE_CHOICES,
  477. blank=True,
  478. null=True,
  479. help_text='The functional role of this IP'
  480. )
  481. interface = models.ForeignKey(
  482. to='dcim.Interface',
  483. on_delete=models.CASCADE,
  484. related_name='ip_addresses',
  485. blank=True,
  486. null=True
  487. )
  488. nat_inside = models.OneToOneField(
  489. to='self',
  490. on_delete=models.SET_NULL,
  491. related_name='nat_outside',
  492. blank=True,
  493. null=True,
  494. verbose_name='NAT (Inside)',
  495. help_text='The IP for which this address is the "outside" IP'
  496. )
  497. description = models.CharField(
  498. max_length=100,
  499. blank=True
  500. )
  501. custom_field_values = GenericRelation(
  502. to='extras.CustomFieldValue',
  503. content_type_field='obj_type',
  504. object_id_field='obj_id'
  505. )
  506. objects = IPAddressManager()
  507. tags = TaggableManager()
  508. serializer = 'ipam.api.serializers.IPAddressSerializer'
  509. csv_headers = [
  510. 'address', 'vrf', 'tenant', 'status', 'role', 'device', 'virtual_machine', 'interface_name', 'is_primary',
  511. 'description',
  512. ]
  513. class Meta:
  514. ordering = ['family', 'address']
  515. verbose_name = 'IP address'
  516. verbose_name_plural = 'IP addresses'
  517. def __str__(self):
  518. return str(self.address)
  519. def get_absolute_url(self):
  520. return reverse('ipam:ipaddress', args=[self.pk])
  521. def get_duplicates(self):
  522. return IPAddress.objects.filter(vrf=self.vrf, address__net_host=str(self.address.ip)).exclude(pk=self.pk)
  523. def clean(self):
  524. if self.address:
  525. # Enforce unique IP space (if applicable)
  526. if (self.vrf is None and settings.ENFORCE_GLOBAL_UNIQUE) or (self.vrf and self.vrf.enforce_unique):
  527. duplicate_ips = self.get_duplicates()
  528. if duplicate_ips:
  529. raise ValidationError({
  530. 'address': "Duplicate IP address found in {}: {}".format(
  531. "VRF {}".format(self.vrf) if self.vrf else "global table",
  532. duplicate_ips.first(),
  533. )
  534. })
  535. def save(self, *args, **kwargs):
  536. if self.address:
  537. # Infer address family from IPAddress object
  538. self.family = self.address.version
  539. super(IPAddress, self).save(*args, **kwargs)
  540. def to_csv(self):
  541. # Determine if this IP is primary for a Device
  542. if self.family == 4 and getattr(self, 'primary_ip4_for', False):
  543. is_primary = True
  544. elif self.family == 6 and getattr(self, 'primary_ip6_for', False):
  545. is_primary = True
  546. else:
  547. is_primary = False
  548. return (
  549. self.address,
  550. self.vrf.rd if self.vrf else None,
  551. self.tenant.name if self.tenant else None,
  552. self.get_status_display(),
  553. self.get_role_display(),
  554. self.device.identifier if self.device else None,
  555. self.virtual_machine.name if self.virtual_machine else None,
  556. self.interface.name if self.interface else None,
  557. is_primary,
  558. self.description,
  559. )
  560. @property
  561. def device(self):
  562. if self.interface:
  563. return self.interface.device
  564. return None
  565. @property
  566. def virtual_machine(self):
  567. if self.interface:
  568. return self.interface.virtual_machine
  569. return None
  570. def get_status_class(self):
  571. return STATUS_CHOICE_CLASSES[self.status]
  572. def get_role_class(self):
  573. return ROLE_CHOICE_CLASSES[self.role]
  574. @python_2_unicode_compatible
  575. class VLANGroup(ChangeLoggedModel):
  576. """
  577. A VLAN group is an arbitrary collection of VLANs within which VLAN IDs and names must be unique.
  578. """
  579. name = models.CharField(
  580. max_length=50
  581. )
  582. slug = models.SlugField()
  583. site = models.ForeignKey(
  584. to='dcim.Site',
  585. on_delete=models.PROTECT,
  586. related_name='vlan_groups',
  587. blank=True,
  588. null=True
  589. )
  590. serializer = 'ipam.api.serializers.VLANGroupSerializer'
  591. csv_headers = ['name', 'slug', 'site']
  592. class Meta:
  593. ordering = ['site', 'name']
  594. unique_together = [
  595. ['site', 'name'],
  596. ['site', 'slug'],
  597. ]
  598. verbose_name = 'VLAN group'
  599. verbose_name_plural = 'VLAN groups'
  600. def __str__(self):
  601. return self.name
  602. def get_absolute_url(self):
  603. return "{}?group_id={}".format(reverse('ipam:vlan_list'), self.pk)
  604. def to_csv(self):
  605. return (
  606. self.name,
  607. self.slug,
  608. self.site.name if self.site else None,
  609. )
  610. def get_next_available_vid(self):
  611. """
  612. Return the first available VLAN ID (1-4094) in the group.
  613. """
  614. vids = [vlan['vid'] for vlan in self.vlans.order_by('vid').values('vid')]
  615. for i in range(1, 4095):
  616. if i not in vids:
  617. return i
  618. return None
  619. @python_2_unicode_compatible
  620. class VLAN(ChangeLoggedModel, CustomFieldModel):
  621. """
  622. A VLAN is a distinct layer two forwarding domain identified by a 12-bit integer (1-4094). Each VLAN must be assigned
  623. to a Site, however VLAN IDs need not be unique within a Site. A VLAN may optionally be assigned to a VLANGroup,
  624. within which all VLAN IDs and names but be unique.
  625. Like Prefixes, each VLAN is assigned an operational status and optionally a user-defined Role. A VLAN can have zero
  626. or more Prefixes assigned to it.
  627. """
  628. site = models.ForeignKey(
  629. to='dcim.Site',
  630. on_delete=models.PROTECT,
  631. related_name='vlans',
  632. blank=True,
  633. null=True
  634. )
  635. group = models.ForeignKey(
  636. to='ipam.VLANGroup',
  637. on_delete=models.PROTECT,
  638. related_name='vlans',
  639. blank=True,
  640. null=True
  641. )
  642. vid = models.PositiveSmallIntegerField(
  643. verbose_name='ID',
  644. validators=[MinValueValidator(1), MaxValueValidator(4094)]
  645. )
  646. name = models.CharField(
  647. max_length=64
  648. )
  649. tenant = models.ForeignKey(
  650. to='tenancy.Tenant',
  651. on_delete=models.PROTECT,
  652. related_name='vlans',
  653. blank=True,
  654. null=True
  655. )
  656. status = models.PositiveSmallIntegerField(
  657. choices=VLAN_STATUS_CHOICES,
  658. default=1,
  659. verbose_name='Status'
  660. )
  661. role = models.ForeignKey(
  662. to='ipam.Role',
  663. on_delete=models.SET_NULL,
  664. related_name='vlans',
  665. blank=True,
  666. null=True
  667. )
  668. description = models.CharField(
  669. max_length=100,
  670. blank=True
  671. )
  672. custom_field_values = GenericRelation(
  673. to='extras.CustomFieldValue',
  674. content_type_field='obj_type',
  675. object_id_field='obj_id'
  676. )
  677. tags = TaggableManager()
  678. serializer = 'ipam.api.serializers.VLANSerializer'
  679. csv_headers = ['site', 'group_name', 'vid', 'name', 'tenant', 'status', 'role', 'description']
  680. class Meta:
  681. ordering = ['site', 'group', 'vid']
  682. unique_together = [
  683. ['group', 'vid'],
  684. ['group', 'name'],
  685. ]
  686. verbose_name = 'VLAN'
  687. verbose_name_plural = 'VLANs'
  688. def __str__(self):
  689. return self.display_name or super(VLAN, self).__str__()
  690. def get_absolute_url(self):
  691. return reverse('ipam:vlan', args=[self.pk])
  692. def clean(self):
  693. # Validate VLAN group
  694. if self.group and self.group.site != self.site:
  695. raise ValidationError({
  696. 'group': "VLAN group must belong to the assigned site ({}).".format(self.site)
  697. })
  698. def to_csv(self):
  699. return (
  700. self.site.name if self.site else None,
  701. self.group.name if self.group else None,
  702. self.vid,
  703. self.name,
  704. self.tenant.name if self.tenant else None,
  705. self.get_status_display(),
  706. self.role.name if self.role else None,
  707. self.description,
  708. )
  709. @property
  710. def display_name(self):
  711. if self.vid and self.name:
  712. return "{} ({})".format(self.vid, self.name)
  713. return None
  714. def get_status_class(self):
  715. return STATUS_CHOICE_CLASSES[self.status]
  716. def get_members(self):
  717. # Return all interfaces assigned to this VLAN
  718. return Interface.objects.filter(
  719. Q(untagged_vlan_id=self.pk) |
  720. Q(tagged_vlans=self.pk)
  721. )
  722. @python_2_unicode_compatible
  723. class Service(ChangeLoggedModel, CustomFieldModel):
  724. """
  725. A Service represents a layer-four service (e.g. HTTP or SSH) running on a Device or VirtualMachine. A Service may
  726. optionally be tied to one or more specific IPAddresses belonging to its parent.
  727. """
  728. device = models.ForeignKey(
  729. to='dcim.Device',
  730. on_delete=models.CASCADE,
  731. related_name='services',
  732. verbose_name='device',
  733. null=True,
  734. blank=True
  735. )
  736. virtual_machine = models.ForeignKey(
  737. to='virtualization.VirtualMachine',
  738. on_delete=models.CASCADE,
  739. related_name='services',
  740. null=True,
  741. blank=True
  742. )
  743. name = models.CharField(
  744. max_length=30
  745. )
  746. protocol = models.PositiveSmallIntegerField(
  747. choices=IP_PROTOCOL_CHOICES
  748. )
  749. port = models.PositiveIntegerField(
  750. validators=[MinValueValidator(1), MaxValueValidator(65535)],
  751. verbose_name='Port number'
  752. )
  753. ipaddresses = models.ManyToManyField(
  754. to='ipam.IPAddress',
  755. related_name='services',
  756. blank=True,
  757. verbose_name='IP addresses'
  758. )
  759. description = models.CharField(
  760. max_length=100,
  761. blank=True
  762. )
  763. custom_field_values = GenericRelation(
  764. to='extras.CustomFieldValue',
  765. content_type_field='obj_type',
  766. object_id_field='obj_id'
  767. )
  768. serializer = 'ipam.api.serializers.ServiceSerializer'
  769. class Meta:
  770. ordering = ['protocol', 'port']
  771. def __str__(self):
  772. return '{} ({}/{})'.format(self.name, self.port, self.get_protocol_display())
  773. def get_absolute_url(self):
  774. return reverse('ipam:service', args=[self.pk])
  775. @property
  776. def parent(self):
  777. return self.device or self.virtual_machine
  778. def clean(self):
  779. # A Service must belong to a Device *or* to a VirtualMachine
  780. if self.device and self.virtual_machine:
  781. raise ValidationError("A service cannot be associated with both a device and a virtual machine.")
  782. if not self.device and not self.virtual_machine:
  783. raise ValidationError("A service must be associated with either a device or a virtual machine.")