models.py 32 KB

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