virtualmachines.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. import decimal
  2. from django.contrib.contenttypes.fields import GenericRelation
  3. from django.core.exceptions import ValidationError
  4. from django.core.validators import MinValueValidator
  5. from django.db import models
  6. from django.db.models import Q, Sum
  7. from django.db.models.functions import Lower
  8. from django.utils.translation import gettext_lazy as _
  9. from dcim.models import BaseInterface
  10. from dcim.models.mixins import RenderConfigMixin
  11. from extras.models import ConfigContextModel
  12. from extras.querysets import ConfigContextModelQuerySet
  13. from netbox.config import get_config
  14. from netbox.models import NetBoxModel, PrimaryModel
  15. from netbox.models.features import ContactsMixin, ImageAttachmentsMixin
  16. from netbox.models.mixins import OwnerMixin
  17. from utilities.fields import CounterCacheField, NaturalOrderingField
  18. from utilities.ordering import naturalize_interface
  19. from utilities.query_functions import CollateAsChar
  20. from utilities.tracking import TrackingModelMixin
  21. from ..choices import *
  22. __all__ = (
  23. 'VMInterface',
  24. 'VirtualDisk',
  25. 'VirtualMachine',
  26. 'VirtualMachineType',
  27. )
  28. class VirtualMachineType(ImageAttachmentsMixin, PrimaryModel):
  29. """
  30. A type defining default attributes (platform, vCPUs, memory, etc.) for virtual machines.
  31. """
  32. name = models.CharField(
  33. verbose_name=_('name'),
  34. max_length=100,
  35. )
  36. slug = models.SlugField(
  37. verbose_name=_('slug'),
  38. max_length=100,
  39. unique=True,
  40. )
  41. default_platform = models.ForeignKey(
  42. to='dcim.Platform',
  43. on_delete=models.SET_NULL,
  44. related_name='+',
  45. blank=True,
  46. null=True,
  47. verbose_name=_('default platform'),
  48. )
  49. default_vcpus = models.DecimalField(
  50. verbose_name=_('default vCPUs'),
  51. max_digits=6,
  52. decimal_places=2,
  53. blank=True,
  54. null=True,
  55. validators=(MinValueValidator(decimal.Decimal('0.01')),),
  56. )
  57. default_memory = models.PositiveIntegerField(
  58. verbose_name=_('default memory'),
  59. blank=True,
  60. null=True,
  61. )
  62. # Counter fields
  63. virtual_machine_count = CounterCacheField(
  64. to_model='virtualization.VirtualMachine',
  65. to_field='virtual_machine_type',
  66. )
  67. clone_fields = (
  68. 'default_platform',
  69. 'default_vcpus',
  70. 'default_memory',
  71. )
  72. class Meta:
  73. ordering = ('name',)
  74. constraints = (
  75. models.UniqueConstraint(
  76. Lower('name'),
  77. name='%(app_label)s_%(class)s_unique_name',
  78. violation_error_message=_('Virtual machine type name must be unique.'),
  79. ),
  80. )
  81. indexes = (
  82. models.Index(fields=('name',)), # Default ordering
  83. )
  84. verbose_name = _('virtual machine type')
  85. verbose_name_plural = _('virtual machine types')
  86. def __str__(self):
  87. return self.name
  88. class VirtualMachine(
  89. ContactsMixin, ImageAttachmentsMixin, RenderConfigMixin, ConfigContextModel, TrackingModelMixin, PrimaryModel
  90. ):
  91. """
  92. A virtual machine which runs on a Cluster or a standalone Device.
  93. Each VM must be placed in at least one of three ways:
  94. 1. Assigned to a Site alone (e.g. for logical grouping without a specific host).
  95. 2. Assigned to a Cluster and optionally pinned to a host Device within that cluster.
  96. 3. Assigned directly to a standalone Device (one that does not belong to any cluster).
  97. When a Cluster or Device is set, the Site is automatically inherited if not explicitly provided.
  98. If a Device belongs to a Cluster, the Cluster must also be specified on the VM.
  99. """
  100. virtual_machine_type = models.ForeignKey(
  101. to='virtualization.VirtualMachineType',
  102. on_delete=models.PROTECT,
  103. related_name='instances',
  104. verbose_name=_('type'),
  105. blank=True,
  106. null=True,
  107. )
  108. site = models.ForeignKey(
  109. to='dcim.Site',
  110. on_delete=models.PROTECT,
  111. related_name='virtual_machines',
  112. blank=True,
  113. null=True
  114. )
  115. cluster = models.ForeignKey(
  116. to='virtualization.Cluster',
  117. on_delete=models.PROTECT,
  118. related_name='virtual_machines',
  119. blank=True,
  120. null=True
  121. )
  122. device = models.ForeignKey(
  123. to='dcim.Device',
  124. on_delete=models.PROTECT,
  125. related_name='virtual_machines',
  126. blank=True,
  127. null=True
  128. )
  129. tenant = models.ForeignKey(
  130. to='tenancy.Tenant',
  131. on_delete=models.PROTECT,
  132. related_name='virtual_machines',
  133. blank=True,
  134. null=True
  135. )
  136. platform = models.ForeignKey(
  137. to='dcim.Platform',
  138. on_delete=models.SET_NULL,
  139. related_name='virtual_machines',
  140. blank=True,
  141. null=True
  142. )
  143. name = models.CharField(
  144. verbose_name=_('name'),
  145. max_length=64,
  146. db_collation="natural_sort"
  147. )
  148. status = models.CharField(
  149. max_length=50,
  150. choices=VirtualMachineStatusChoices,
  151. default=VirtualMachineStatusChoices.STATUS_ACTIVE,
  152. verbose_name=_('status')
  153. )
  154. start_on_boot = models.CharField(
  155. max_length=32,
  156. choices=VirtualMachineStartOnBootChoices,
  157. default=VirtualMachineStartOnBootChoices.STATUS_OFF,
  158. verbose_name=_('start on boot'),
  159. )
  160. role = models.ForeignKey(
  161. to='dcim.DeviceRole',
  162. on_delete=models.PROTECT,
  163. related_name='virtual_machines',
  164. blank=True,
  165. null=True
  166. )
  167. primary_ip4 = models.OneToOneField(
  168. to='ipam.IPAddress',
  169. on_delete=models.SET_NULL,
  170. related_name='+',
  171. blank=True,
  172. null=True,
  173. verbose_name=_('primary IPv4')
  174. )
  175. primary_ip6 = models.OneToOneField(
  176. to='ipam.IPAddress',
  177. on_delete=models.SET_NULL,
  178. related_name='+',
  179. blank=True,
  180. null=True,
  181. verbose_name=_('primary IPv6')
  182. )
  183. vcpus = models.DecimalField(
  184. max_digits=6,
  185. decimal_places=2,
  186. blank=True,
  187. null=True,
  188. verbose_name=_('vCPUs'),
  189. validators=(
  190. MinValueValidator(decimal.Decimal(0.01)),
  191. )
  192. )
  193. memory = models.PositiveIntegerField(
  194. blank=True,
  195. null=True,
  196. verbose_name=_('memory')
  197. )
  198. disk = models.PositiveIntegerField(
  199. blank=True,
  200. null=True,
  201. verbose_name=_('disk')
  202. )
  203. serial = models.CharField(
  204. verbose_name=_('serial number'),
  205. blank=True,
  206. max_length=50
  207. )
  208. services = GenericRelation(
  209. to='ipam.Service',
  210. content_type_field='parent_object_type',
  211. object_id_field='parent_object_id',
  212. related_query_name='virtual_machine',
  213. )
  214. # Counter fields
  215. interface_count = CounterCacheField(
  216. to_model='virtualization.VMInterface',
  217. to_field='virtual_machine'
  218. )
  219. virtual_disk_count = CounterCacheField(
  220. to_model='virtualization.VirtualDisk',
  221. to_field='virtual_machine'
  222. )
  223. objects = ConfigContextModelQuerySet.as_manager()
  224. clone_fields = (
  225. 'virtual_machine_type', 'site', 'cluster', 'device', 'tenant', 'platform', 'status', 'role', 'vcpus', 'memory',
  226. 'disk',
  227. )
  228. class Meta:
  229. ordering = ('name', 'pk') # Name may be non-unique
  230. indexes = (
  231. models.Index(fields=('name', 'id')), # Default ordering
  232. # Partial index supporting the background renderer's scan for objects whose config
  233. # context cache has been invalidated (see extras.jobs.RenderConfigContextJob and
  234. # extras.cache). Indexing only the NULL-cache rows keeps that lookup cheap on large
  235. # tables where the steady state is for nearly every row to be populated.
  236. models.Index(
  237. fields=('id',),
  238. condition=Q(_config_context_data__isnull=True),
  239. name='virtualization_vm_cc_null',
  240. ),
  241. )
  242. constraints = (
  243. models.UniqueConstraint(
  244. Lower('name'), 'cluster', 'tenant',
  245. name='%(app_label)s_%(class)s_unique_name_cluster_tenant',
  246. condition=Q(cluster__isnull=False),
  247. nulls_distinct=False,
  248. violation_error_message=_('Virtual machine name must be unique per cluster and tenant.')
  249. ),
  250. models.UniqueConstraint(
  251. Lower('name'), 'device', 'tenant',
  252. name='%(app_label)s_%(class)s_unique_name_device_tenant',
  253. condition=Q(cluster__isnull=True, device__isnull=False),
  254. nulls_distinct=False,
  255. violation_error_message=_('Virtual machine name must be unique per device and tenant.')
  256. ),
  257. )
  258. verbose_name = _('virtual machine')
  259. verbose_name_plural = _('virtual machines')
  260. permissions = [
  261. ('render_config', 'Render configuration'),
  262. ]
  263. def __str__(self):
  264. return self.name
  265. def clean(self):
  266. super().clean()
  267. # Must be assigned to a site, cluster, and/or device
  268. if not self.site and not self.cluster and not self.device:
  269. raise ValidationError(
  270. _('A virtual machine must be assigned to a site, cluster, or device.')
  271. )
  272. # Validate site for cluster & VM
  273. if self.cluster and self.site and self.cluster._site and self.cluster._site != self.site:
  274. raise ValidationError({
  275. 'cluster': _(
  276. 'The selected cluster ({cluster}) is not assigned to this site ({site}).'
  277. ).format(cluster=self.cluster, site=self.site)
  278. })
  279. # Validate site for the device & VM (when the device is standalone)
  280. if self.device and self.site and self.device.site and self.device.site != self.site:
  281. raise ValidationError({
  282. 'site': _(
  283. 'The selected device ({device}) is not assigned to this site ({site}).'
  284. ).format(device=self.device, site=self.site)
  285. })
  286. # Direct device assignment is only for standalone hosts. If the selected
  287. # device already belongs to a cluster, require that cluster explicitly.
  288. if self.device and not self.cluster and self.device.cluster:
  289. raise ValidationError({
  290. 'cluster': _(
  291. "Must specify the assigned device's cluster ({cluster}) when assigning host device {device}."
  292. ).format(cluster=self.device.cluster, device=self.device)
  293. })
  294. # Validate assigned cluster device
  295. if self.device and self.cluster and self.device.cluster_id != self.cluster_id:
  296. raise ValidationError({
  297. 'device': _(
  298. "The selected device ({device}) is not assigned to this cluster ({cluster})."
  299. ).format(device=self.device, cluster=self.cluster)
  300. })
  301. # Validate aggregate disk size
  302. if not self._state.adding:
  303. total_disk = self.virtualdisks.aggregate(Sum('size', default=0))['size__sum']
  304. if total_disk and self.disk is None:
  305. self.disk = total_disk
  306. elif total_disk and self.disk != total_disk:
  307. raise ValidationError({
  308. 'disk': _(
  309. "The specified disk size ({size}) must match the aggregate size of assigned virtual disks "
  310. "({total_size})."
  311. ).format(size=self.disk, total_size=total_disk)
  312. })
  313. # Validate primary IP addresses
  314. interfaces = self.interfaces.all() if self.pk else VMInterface.objects.none()
  315. for family in (4, 6):
  316. field = f'primary_ip{family}'
  317. ip = getattr(self, field)
  318. if ip is not None:
  319. if ip.address.version != family:
  320. raise ValidationError({
  321. field: _(
  322. "Must be an IPv{family} address. ({ip} is an IPv{version} address.)"
  323. ).format(family=family, ip=ip, version=ip.address.version)
  324. })
  325. if ip.assigned_object in interfaces:
  326. pass
  327. elif ip.nat_inside is not None and ip.nat_inside.assigned_object in interfaces:
  328. pass
  329. else:
  330. raise ValidationError({
  331. field: _("The specified IP address ({ip}) is not assigned to this VM.").format(ip=ip),
  332. })
  333. def save(self, *args, **kwargs):
  334. # Assign a site from a cluster or device if not set
  335. if not self.site:
  336. if self.cluster and self.cluster._site:
  337. self.site = self.cluster._site
  338. elif self.device and self.device.site:
  339. self.site = self.device.site
  340. if self._state.adding:
  341. self.apply_type_defaults()
  342. super().save(*args, **kwargs)
  343. def apply_type_defaults(self):
  344. """
  345. Populate any empty fields with defaults from the assigned VirtualMachineType.
  346. """
  347. if not self.virtual_machine_type_id:
  348. return
  349. defaults = {
  350. 'platform_id': 'default_platform_id',
  351. 'vcpus': 'default_vcpus',
  352. 'memory': 'default_memory',
  353. }
  354. for field, default_field in defaults.items():
  355. if getattr(self, field) is None:
  356. default_value = getattr(self.virtual_machine_type, default_field)
  357. if default_value is not None:
  358. setattr(self, field, default_value)
  359. def get_status_color(self):
  360. return VirtualMachineStatusChoices.colors.get(self.status)
  361. def get_start_on_boot_color(self):
  362. return VirtualMachineStartOnBootChoices.colors.get(self.start_on_boot)
  363. @property
  364. def primary_ip(self):
  365. if get_config().PREFER_IPV4 and self.primary_ip4:
  366. return self.primary_ip4
  367. if self.primary_ip6:
  368. return self.primary_ip6
  369. if self.primary_ip4:
  370. return self.primary_ip4
  371. return None
  372. #
  373. # VM components
  374. #
  375. class ComponentModel(OwnerMixin, NetBoxModel):
  376. """
  377. An abstract model inherited by any model which has a parent VirtualMachine.
  378. """
  379. virtual_machine = models.ForeignKey(
  380. to='virtualization.VirtualMachine',
  381. on_delete=models.CASCADE,
  382. related_name='%(class)ss'
  383. )
  384. name = models.CharField(
  385. verbose_name=_('name'),
  386. max_length=64,
  387. db_collation="natural_sort"
  388. )
  389. description = models.CharField(
  390. verbose_name=_('description'),
  391. max_length=200,
  392. blank=True
  393. )
  394. class Meta:
  395. abstract = True
  396. constraints = (
  397. models.UniqueConstraint(
  398. fields=('virtual_machine', 'name'),
  399. name='%(app_label)s_%(class)s_unique_virtual_machine_name'
  400. ),
  401. )
  402. def __str__(self):
  403. return self.name
  404. def to_objectchange(self, action):
  405. objectchange = super().to_objectchange(action)
  406. objectchange.related_object = self.virtual_machine
  407. return objectchange
  408. @property
  409. def parent_object(self):
  410. return self.virtual_machine
  411. class VMInterface(ComponentModel, BaseInterface, TrackingModelMixin):
  412. name = models.CharField(
  413. verbose_name=_('name'),
  414. max_length=64,
  415. )
  416. _name = NaturalOrderingField(
  417. target_field='name',
  418. naturalize_function=naturalize_interface,
  419. max_length=100,
  420. blank=True
  421. )
  422. virtual_machine = models.ForeignKey(
  423. to='virtualization.VirtualMachine',
  424. on_delete=models.CASCADE,
  425. related_name='interfaces' # Override ComponentModel
  426. )
  427. ip_addresses = GenericRelation(
  428. to='ipam.IPAddress',
  429. content_type_field='assigned_object_type',
  430. object_id_field='assigned_object_id',
  431. related_query_name='vminterface'
  432. )
  433. vrf = models.ForeignKey(
  434. to='ipam.VRF',
  435. on_delete=models.SET_NULL,
  436. related_name='vminterfaces',
  437. null=True,
  438. blank=True,
  439. verbose_name=_('VRF')
  440. )
  441. fhrp_group_assignments = GenericRelation(
  442. to='ipam.FHRPGroupAssignment',
  443. content_type_field='interface_type',
  444. object_id_field='interface_id',
  445. related_query_name='+'
  446. )
  447. tunnel_terminations = GenericRelation(
  448. to='vpn.TunnelTermination',
  449. content_type_field='termination_type',
  450. object_id_field='termination_id',
  451. related_query_name='vminterface',
  452. )
  453. l2vpn_terminations = GenericRelation(
  454. to='vpn.L2VPNTermination',
  455. content_type_field='assigned_object_type',
  456. object_id_field='assigned_object_id',
  457. related_query_name='vminterface',
  458. )
  459. mac_addresses = GenericRelation(
  460. to='dcim.MACAddress',
  461. content_type_field='assigned_object_type',
  462. object_id_field='assigned_object_id',
  463. related_query_name='vminterface'
  464. )
  465. class Meta(ComponentModel.Meta):
  466. verbose_name = _('interface')
  467. verbose_name_plural = _('interfaces')
  468. ordering = ('virtual_machine', CollateAsChar('_name'))
  469. def clean(self):
  470. super().clean()
  471. # Parent validation
  472. # An interface cannot be its own parent
  473. if self.pk and self.parent_id == self.pk:
  474. raise ValidationError({'parent': _("An interface cannot be its own parent.")})
  475. # An interface's parent must belong to the same virtual machine
  476. if self.parent and self.parent.virtual_machine != self.virtual_machine:
  477. raise ValidationError({
  478. 'parent': _(
  479. "The selected parent interface ({parent}) belongs to a different virtual machine "
  480. "({virtual_machine})."
  481. ).format(parent=self.parent, virtual_machine=self.parent.virtual_machine)
  482. })
  483. # Bridge validation
  484. # An interface cannot be bridged to itself
  485. if self.pk and self.bridge_id == self.pk:
  486. raise ValidationError({'bridge': _("An interface cannot be bridged to itself.")})
  487. # A bridged interface belong to the same virtual machine
  488. if self.bridge and self.bridge.virtual_machine != self.virtual_machine:
  489. raise ValidationError({
  490. 'bridge': _(
  491. "The selected bridge interface ({bridge}) belongs to a different virtual machine "
  492. "({virtual_machine})."
  493. ).format(bridge=self.bridge, virtual_machine=self.bridge.virtual_machine)
  494. })
  495. # VLAN validation
  496. # Validate untagged VLAN
  497. if self.untagged_vlan and self.untagged_vlan.site not in [self.virtual_machine.site, None]:
  498. raise ValidationError({
  499. 'untagged_vlan': _(
  500. "The untagged VLAN ({untagged_vlan}) must belong to the same site as the interface's parent "
  501. "virtual machine, or it must be global."
  502. ).format(untagged_vlan=self.untagged_vlan)
  503. })
  504. @property
  505. def l2vpn_termination(self):
  506. return self.l2vpn_terminations.first()
  507. class VirtualDisk(ComponentModel, TrackingModelMixin):
  508. size = models.PositiveIntegerField(
  509. verbose_name=_('size'),
  510. )
  511. class Meta(ComponentModel.Meta):
  512. verbose_name = _('virtual disk')
  513. verbose_name_plural = _('virtual disks')
  514. ordering = ('virtual_machine', 'name')