models.py 30 KB

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