Compare commits

..
Author SHA1 Message Date
renovate[bot] d8bbcb1e40 deps: update dependency serialize-javascript to v7.1.3 [security] 2026-11-10 21:10:31 +00:00
Marcelo Fukumoto 08e483e3c8 chore(deps): align resolutions and yarn.lock with @rancher/shell 3.0.14 (#1239)
* chore(deps): align resolutions and yarn.lock with @rancher/shell 3.0.14

yarn only applies resolutions from the root package.json, so the ones
@rancher/shell 3.0.14 declares never reached the extension. Copy them
over, use the **/ form for diff2html/diff since diff2html sits under
@rancher/shell here, and drop the cronstrue pin so the extension and the
shell both use the 3.9.0 the shell depends on.

Re-resolve yarn.lock against the shell's own lockfile so every shared
package lands on the version the shell ships, and semver and
@types/node follow the shell's versions too.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* chore(deps): keep the cronstrue pin

cronstrue 3 describes @reboot, so the backup schedule form enabled Create
for it while Harvester's webhook rejects it. The dashboard itself runs
cronstrue 2.53.0 and the shell went back to that after 3.0.14, so keep
our 2.59.0 pin.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

---------

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>
2026-11-10 22:07:49 +01:00
Marcelo Fukumoto ee915249ce fix: keep the ignore rule name valid when the check has spaces (#1234)
Backup schedule checks are named after the schedule's condition reason,
such as "Proactive Schedule Suspend". The rule name used it lowercased,
spaces included, so Kubernetes refused it and the check could not be
ignored. Turn whatever a name can't have into hyphens. The rule keeps
the check as it is in its spec, which is what the controller matches.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>
2026-11-10 12:21:30 +01:00
Volker TheileandMarcelo Fukumoto 784c22e27e fix: show resource counts for all side navigation items (#1196)
* fix: show resource counts for all side navigation items

The side navigation looks up the count of a nav item by its name, but the
counts are keyed by the K8s resource type. Many Harvester nav items are
named differently than the resource they list (e.g. harvesterhci.io.volume
lists persistentvolumeclaim), so no count was shown for them. Some list
views also show only a subset of their resource type, so the plain count
would not match the list.

Override the count getter of the harvester store:
- Resolve the nav item to the resource type it lists, using the same
  fallback to the configureType resource as schemaFor. This fixes Hosts,
  Alertmanager Configs, Cluster Flows, Cluster Outputs, Flows, Outputs
  and Secrets.
- Count only the subset shown by the list for Volumes, VM Networks,
  VM Backups, VM Snapshots, Volume Snapshots, Cloud Configuration
  Templates and Storage. The matches are counted per namespace once per
  store list using sharedComputed.
- Like the list views, do not count resources in system namespaces when
  "All Namespaces" is selected.

Steve's counts endpoint only returns the total per resource type, so the
filtered counts are computed from the store list and are only available
once that list is loaded. Until then these nav items show no count, unless
there are no resources of that type at all (then 0). The dashboard loads
PVCs and networks, the VM list PVCs and backups, the other resources are
loaded when their list is opened.

Related to: https://github.com/harvester/harvester/issues/11984

Signed-off-by: Volker Theile <vtheile@suse.com>

* refactor: get the side navigation counts from the server

Stop loading full resource lists and filtering them in the browser to
get the side navigation counts.

- Nav items listing all resources of a type use the counts endpoint,
  through the resource type of the nav item.
- VM backups, VM snapshots, volume snapshots, storage classes, cloud
  config templates and VM networks request their subset from
  /v1/harvester with a page size of 1. These requests run again when the
  counts endpoint reports other numbers for the type, and when the
  namespace filter changes.
- Namespaces count the already loaded namespaces that are neither system
  nor Fleet managed.
- Volumes have no count: the list hides volumes that are only marked by
  annotations, which the API cannot filter on.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* refactor: keep the side navigation count helpers in the store getters

Move them out of their own file, next to the count getter that uses them.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* fix: make the side navigation count requests more robust

- Ignore a late response of the previous cluster. Resetting the request
  ids when loading a cluster let it overwrite the count of the new one.
- Keep the watchers when a cluster left while it was loading finishes
  loading after the new one.
- Show no count instead of 0 on Harvester v1.3, which ignores the query
  and sends all resources without a count.
- Hide the storage network by its generated name. Networks created
  before Harvester v1.4 do not have the hash label, and an upgrade does
  not add it.
- Stop refreshing after leaving the product, cancel pending refreshes
  when the watchers stop, and cope with the store module being
  unregistered when logging out.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* fix: count only the settings the Settings page shows

The nav item showed the total of all Setting resources, but the page only
shows the allowed ones that exist in the cluster and are supported by its
version.

Move these rules into a visibleSettings getter that both the page and the
count use, so that they always agree. SettingList no longer needs its
feature flag check.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* test: remove a Settings page test that was committed twice

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* fix: show the number of volumes in the side navigation

The Volumes list hides golden image volumes and the temporary volumes CDI
uses to populate a volume, so the total of the counts endpoint would be
wrong.

Golden image volumes are only marked by an annotation, which Harvester's
API cannot filter on, but each one belongs to a DataVolume owned by its VM
image. So request the volumes that are not owned by another volume, and
the DataVolumes owned by a VM image, and show the difference.

Every nav item with a list now has a number, so remove NO_COUNT.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

---------

Signed-off-by: Volker Theile <vtheile@suse.com>
Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>
Co-authored-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>
2026-11-10 12:20:34 +01:00
aa6d11a840 fix: block VM creation/save with invalid CloudInit YAML (#1040)
* fix(vm): block VM creation with invalid CloudInit YAML content

* fix(vm): add isWindows guard to validateCloudInit in template version

* fix: validate Windows CloudInit YAML on save

Co-authored-by: a110605 <5744158+a110605@users.noreply.github.com>

* fix: validate cloud-init by format in the VM mixin

Cloud-init picks the user data format from the first line, so scripts,
MIME messages and Jinja templates are valid without being YAML. Parsing
all user data blocked them, and it stopped any existing VM holding one
from being saved, even with nothing changed.

Only parse user data that starts with #cloud-config, and require a
mapping for it and for network data, because plain words are valid YAML
and were still saved.

Both forms already use the VM mixin, so the check moves there and shares
the header pattern with hasCloudConfigComment.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* fix: save other user data formats as typed and check text without a header

The form added #cloud-config to any user data that parses as YAML, so a
script was saved with the header and its lines folded together, and Edit
Config then failed the check on it. User data that starts with a script,
MIME or another cloud-init or Cloudbase-Init format is now saved as typed,
and any other text is checked as cloud-config, with or without the header,
because the form adds the header when saving it.

Editing only checks cloud-init that changed, so a VM saved before this
change can still be edited with the cloud-init it already has.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

---------

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: a110605 <5744158+a110605@users.noreply.github.com>
Co-authored-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>
2026-11-09 15:59:37 +00:00
67ff2777d6 feat: add resource health dashboard in a Components tab (#1225)
* feat: add component health dashboard sections

Add health summary and component health tables with severity filters and expandable check details.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Signed-off-by: Jack Yu <jack.yu@suse.com>

* feat: use health API group for component health resources

Update dashboard resource types to use the health.harvesterhci.io API group.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Signed-off-by: Jack Yu <jack.yu@suse.com>

* feat: add component health ignore controls

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Signed-off-by: Jack Yu <jack.yu@suse.com>

* feat: gate component health behind the componentHealth feature flag

Only show the component health dashboard sections on Harvester v1.10.0 and later.

Signed-off-by: Jack Yu <jack.yu@suse.com>

* fix: address component health review comments

- sort the health summary table by a severity rank
- use buttons instead of anchors for restore and show more actions
- let the affected resources list expand so every resource can be restored
- widen the ignore popup and cap its height

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Signed-off-by: Jack Yu <jack.yu@suse.com>

* refactor: split component health into dedicated components

Move the health summary, component health tabs and ignore popup out of
the dashboard page into components/health, and share the constants and
helpers through utils/component-health.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Signed-off-by: Jack Yu <jack.yu@suse.com>

* fix: sort component health by severity rank

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Signed-off-by: Jack Yu <jack.yu@suse.com>

* fix: toggle health rows in place and tell empty filters from no checks

- toggle the expanded message and resource ids by mutating the unwrapped
  arrays, the template does not pass refs
- show "No checks match the selected filters" when the severity filters
  hide existing checks, keep "No issues detected" for a report without
  checks

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Signed-off-by: Jack Yu <jack.yu@suse.com>

* refactor: fetch component health resources in their own components

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Signed-off-by: Jack Yu <jack.yu@suse.com>

* feat: move health into a Components tab with the checks as sub-rows

The dashboard showed the summary table, then side tabs with a second
table for each component. It is now one table in a new Components tab
next to the Events tabs: one row per component, which opens to its
checks. Rows start closed, and the component name is a button so the
keyboard can open them. The tab only shows when the addon's resources
exist.

The table's own filter box replaces the severity dropdown. It only looks
at the table's own rows and the checks are in the sub-rows, so the rows
give it the text of their checks, a row only shows the checks it found,
and the rows it found open.

Ignoring a check moves from a popover, which cut off its Reason field
and Ignore button, to an RcModal that starts over each time it opens.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* refactor: use RcButton for the component health buttons

The Ignore modal's button already was one. This moves the rest of them,
the row's Ignore, Restore, the "show more" links and the component name,
off the global btn classes.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* refactor: manage one ignore rule per check from the row's actions

A check now has one rule, reached through the table's action menu: create
it when the check has none, view, edit or delete it when it has one. View
and edit use the same modal as create. This replaces the Ignore button and
the Restore links, which could only delete a whole rule and said the check
was restored when it wasn't.

The modal's section titles were the radio group's h3, as big as the modal's
own title. They follow what rancher/dashboard does in its forms now.

The actions follow what the user may do. The rules are only loaded with
their schema, and a list that fails no longer empties the table.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* refactor: let the tables filter by themselves and show resources as chips

The filter had logic of its own on top of the table's. The nested table now
filters its rows the way the outer one does, with what is typed in the box.
Rows no longer open by themselves, which is how the other tables with
sub-rows behave. Expand All and Collapse All are there instead, copied from
what the table has from shell 3.0.15.

Affected resources are chips under the name the UI has for their type, with
the usual counter badge and the API version beside it. Ignored resources are
outlined instead of filled, and the text of an ignored check is muted. The
links use the shell's wording.

The component rows lose Last Updated. The summary only has one time, for its
counts as a whole, so it said nothing about the component in the row. They say
Error instead of Critical, as the checks inside them do. The Node column goes,
as nothing sets its label.

The Components tab shows the number of errors as a badge, as nothing else on
the page tells there are any.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* fix: name the ignore rule after its check and make its expiry clear

- Name the rule the UI makes after its check, so Kubernetes refuses a
  second one for the same check. The row's menu only manages that rule.
- Show the rule's current expiry above the durations, and the new one
  under them once a duration is chosen. Edit starts with none chosen,
  Save stays off until something changes, and a warning says when an
  expired rule would stay expired.
- Delete the rule through the shell's delete prompt, like every other
  delete.
- Say which list could not be loaded, instead of showing it as empty.
- Keep the full count of affected resources, say how many ignored ones
  are left out of the list, and count them on Show ignored.
- Drop the checks' Last Updated, which is the time of their whole report.
- Leave out the row menu when no check has an action.
- Mark the Components tab with the shell's alert icon when there are
  errors, with their number in its tooltip, instead of a badge.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

---------

Signed-off-by: Jack Yu <jack.yu@suse.com>
Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>
Co-authored-by: Jack Yu <jack.yu@suse.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 16:56:15 +01:00
marcelofukumoto 73eaccc2ad fix: show VNC console dialogs in full screen and restore deleting custom shortcut keys (#1222)
* fix: show the VNC console's dialogs in full screen

Only the console went full screen and dialogs render outside of it, so the
Ctrl+Alt+Del and Soft Reboot confirmations, among others, stayed hidden behind
it until full screen was left. Put the whole page in full screen instead.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* fix: bring back deleting saved VNC console shortcut keys

The Vue 3 migration dropped the close button from the list of saved shortcuts,
which left no way to delete one. Restore it, and remove by position in the list:
the old code parsed the displayed HTML to find the shortcut, which cannot match
one with the Space key in it, such as Ctrl+Space.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* fix: tidy the VNC console's custom shortcut keys

Give the saved shortcuts in the menu the same space as the separator above
them, and name the dialog's buttons Cancel and Save, which say what they do.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

---------

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>
2026-11-06 09:58:41 +01:00
marcelofukumoto 12c28c08fa feat: align the storage performance options with the Rancher machine pool form (#1212)
* feat: align the storage performance options with the Rancher machine pool form

Show the storage performance profile on every volume instead of behind a
collapsible toggle, and move the VM-wide options to a plain Storage
Performance section in the Advanced Options tab. Put the Native I/O tip in
a live region so screen readers announce the cache mode change, use an
integer input for the I/O thread count, and use the same copy as the
Rancher form.

Skip the view-only backup row in the image and container volumes when it
has nothing to show, so it no longer adds an empty gap above the profile.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* fix: announce the storage performance warnings and name the virtio requirement

- Put the bus tip and the Filesystem warning in an always-rendered status
  region. They appear above the field being changed, so screen readers need
  them announced.
- Say in the bus tip that a dedicated I/O thread needs the virtio bus, because
  KubeVirt rejects it on any other bus.
- Mark I/O Thread Count as required while editing, like the Rancher form.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* fix: state only the dedicated I/O thread requirement in the bus tip

Neither the Harvester docs nor KubeVirt tie cache mode or I/O mode to the bus,
so stop saying that those options work best on virtio.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

---------

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>
2026-11-05 18:51:46 +01:00
Alejandro Bonilla 840f9de73e fix: show quotes in high-performance storage hints and keep Custom profile (#1204)
* fix: show quotes in high-performance storage hints and keep Custom profile

The Native I/O and I/O threads policy hints were passed to Banner as
:label="t(...)". t() escapes HTML and Banner escapes the label again,
so the quotes showed up as &quot;. Use label-key instead, which renders
the string once.

Picking the Custom performance profile and then choosing options that
match the Default or High Performance preset flipped the selector back
to that preset. Keep an explicit Custom choice and only infer the
profile from the disk values otherwise.

Related: harvester/harvester#11550

Signed-off-by: Alejandro Bonilla <abonilla@suse.com>

* fix: only keep Custom profile when the user picked it

syncProfile() skipped re-detection whenever the profile was Custom,
including a Custom that was inferred from the disk values. In an
existing-volume row, switching from a volume with a WriteBack override
to one with High Performance values left the selector on Custom.

Track the user's explicit Custom choice in its own flag and use that
in the guard, so an inferred Custom still follows the disk values.

Related: harvester/harvester#11550

Signed-off-by: Alejandro Bonilla <abonilla@suse.com>

* test: cover the label-key hints of VMPerformanceOptions

Check that the I/O threads policy and no virtio disk hints are passed to Banner as label keys, so their quotes are not escaped twice, and that the I/O threads policy hint is hidden once a policy is set.

Signed-off-by: Alejandro Bonilla <abonilla@suse.com>

---------

Signed-off-by: Alejandro Bonilla <abonilla@suse.com>
2026-11-04 12:23:30 +08:00
Victor ChangandMarcelo Fukumoto 3fb2d3da56 fix: bind bulk VM disk deletion checkbox to checkAll (#1146)
* fix: bind bulk VM disk deletion checkbox to checkAll

Signed-off-by: Victor Chang <t7902195204@gmail.com>

* test: cover the VM delete prompt checkboxes

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

---------

Signed-off-by: Victor Chang <t7902195204@gmail.com>
Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>
Co-authored-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>
2026-11-03 22:05:47 +01:00
marcelofukumoto 77b643540e fix: label the VPC group of subnets without a VPC as None (#1210)
Kube-OVN sets a subnet's VPC (ovn-cluster when none is given), but a
subnet it hasn't processed, such as one with an invalid provider, has
none. The VPC page grouped those under "Virtual Private Cloud:" with an
empty name, and its Create Subnet, Topology and actions buttons pointed
at no VPC.

Show None as the VPC name for that group and leave out its VPC buttons.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>
2026-10-29 17:00:00 +01:00
marcelofukumoto 78d0a591a8 feat: move the device pages into a Hardware Devices side nav group (#1211)
The PCI, SR-IOV Network, SR-IOV GPU, vGPU, vGPU MIG and USB device pages
were listed under Advanced. Give them their own top-level group, placed
after Backup and Snapshots. Add-ons stay under Advanced.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>
2026-10-28 19:51:40 +01:00
marcelofukumoto 6e0e0237ef feat: use the SUSE Virtualization product name on Prime (#1202)
* feat: switch the product name with Rancher Prime

Use a [[Harvester]] token for the product name in the translations, so
Rancher 2.16 fills it from the l10n global that harvester-manager
registers: SUSE Virtualization on Rancher Prime, Harvester otherwise.

Rancher before 2.16 shows the tokens as written, so on those hosts (and
standalone) the extension resolves them to Harvester itself.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat: switch the standalone product name with the server flavor

Standalone has no Rancher Prime, so register the [[Harvester]] l10n
global from the server-flavor setting instead: SUSE Virtualization on
prime, Harvester otherwise.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* fix: point the network policy banner to the documentation

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat: use the SUSE theme in standalone Prime

Standalone Prime kept the harvester brand and only overrode the primary
colour, so the rest of the palette and the fonts didn't match Rancher
Prime. Switch the ui-brand setting to suse in the store when the server
flavor is prime, which makes the shell load the SUSE theme.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* fix: keep the SUSE theme after a brand setting change event

The watcher also reads the setting's value, so a change from the server
loaded into the same object switches the brand back to suse.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

---------

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>
2026-10-26 17:28:50 +01:00
marcelofukumoto d6f6f7c54c chore(deps): bump @rancher/shell to 3.0.14 (#1208)
* chore(deps): bump @rancher/shell to 3.0.14

3.0.14 resolves [[name]] tokens in translations from values registered
as l10n globals, which the standalone UI needs to pick the product name.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* fix: save cloud-config template edits with @rancher/shell 3.0.14

The YamlEditor of shell 3.0.14 no longer emits onChanges, so editing a
template saved its old cloud config. Copy the text from update:value,
which both shell versions emit.

Jest transforms @replit/codemirror-vim-core, an ESM-only dependency of
the new YamlEditor, like the dashboard does.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* fix: keep the YAML editor heights with CodeMirror 6

The min-height rules targeted the CodeMirror 5 element, so the editors
shrank to their text.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* fix: reject IP ranges the network settings don't support

The CIDR check of @rancher/shell 3.0.14 also accepts short forms such as
10.1/16, extra parts and IPv6, so the VM migration, RWX and storage
network settings saved them. Use a strict IPv4 CIDR check of our own.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* fix: keep the look of the file selector buttons

The FileSelector of @rancher/shell 3.0.14 no longer takes button classes
and renders a medium secondary button. Pass the variant and size that
match the previous primary and secondary buttons.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* fix: keep Enter in a migration wizard field on the same step

The Wizard of @rancher/shell 3.0.14 renders its step headers as submit
buttons, so Enter in a text field clicked the first one and jumped back
to step 1.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* fix: show the created message after a restore, upgrade or upload

Since @rancher/shell 3.0.14, save() no longer shows the message for
resources with a generated name; callers show it with
notifyGeneratedName().

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* refactor: fold the logging output buffer with the CodeMirror 6 helpers

The YAML editor of @rancher/shell 3.0.14 is CodeMirror 6, and its
CodeMirror 5 methods are deprecated.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* fix: keep the shell's table views off in standalone

@rancher/shell 3.0.14 turns its table views on for every list in the
standalone UI, as the server has no ui-configurable-tables feature and
the default is on. The table views drop the filters the lists put in the
table header, which also left the Images list empty. Add the feature,
disabled, to the management store in standalone only.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* fix: reject zero-padded octets in IP ranges

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

---------

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>
2026-10-23 19:58:19 +02:00
Alejandro BonillaandClaude Opus 5.5 39ed41e527 feat: move OS type, CPU model and system options to the VM Basics tab (#1179)
* feat: move OS type, CPU model and system options to the VM Basics tab

OS Type, CPU Model and the CPU/system checkboxes (CPU pinning, USB
tablet, TPM, EFI, Secure Boot and their persistent-state options) are
core machine settings, but they were buried at the bottom of Advanced
Options. Show them on the Basics tab, next to CPU and memory.

Install Guest Agent stays in Advanced Options because it changes the
cloud config. It now sits right below the User Data editor (the data it
modifies) through a new optional slot in the Cloud Config component.

Only the placement changes; behaviour and validation are untouched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Alejandro Bonilla <abonilla@suse.com>

* feat: follow the review on the VM Basics layout

- Basics now reads OS Type and CPU Model, then CPU and memory, then the
  system checkboxes, the CPU Manager banner and the SSH key, in the order
  proposed in review. The checkboxes sit in one wrapper; USB Tablet drops
  its extra mt-20 and uses the plain `check` class like the others.
- Advanced Options puts Maintenance Strategy on the same row as Run
  Strategy; Reserved Memory moves to its own row.
- The moved labels leave harvester.virtualMachine.advancedOptions: TPM,
  EFI, Secure Boot and the persistent-state labels are now under
  harvester.virtualMachine.systemOptions (also used by the template
  version editor), and the CPU Manager banner text is under
  harvester.virtualMachine.cpuPinning.cpuManager.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Alejandro Bonilla <abonilla@suse.com>

* feat: match the VM template form and address review on the VM Basics layout

The VM template form still had OS Type, CPU Model and the CPU/system
checkboxes under Advanced Options, so creating a VM and creating a
template put them in different places. Use the same layout as the VM
form:

- Basics: OS Type and CPU Model, then CPU and memory, then the CPU
  Pinning, USB Tablet, TPM, EFI and Secure Boot checkboxes (plus the
  persistent-state options when they apply), then the SSH key.
- Advanced Options: Run Strategy and Maintenance Strategy on one row,
  Reserved Memory on its own row, then Show more and Cloud Config.
  Install Guest Agent sits right below the User Data editor through the
  after-user-data slot.

Review follow-ups on both forms:

- OS Type shows an info icon in create mode warning that selecting an
  image with an OS label on the Volumes tab may change the OS Type
  selection, now that OS Type comes before the volumes.
- The CPU Manager banner under CPU Pinning is info in create mode, where
  it only explains why the checkbox is disabled, and stays a warning in
  edit mode, where it is about the restart.

Only placement and presentation change; behaviour and validation are
untouched.

Signed-off-by: Alejandro Bonilla <abonilla@suse.com>

---------

Signed-off-by: Alejandro Bonilla <abonilla@suse.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 22:38:16 +08:00
2f72f25b6e feat: improve VNC console with a version gate, in-use screen and confirmations (#1195)
* feat: improve vnc console

Signed-off-by: Andy Lee <andy.lee@suse.com>

* fix: keep VNC console retries from kicking the active session

Builds on "feat: improve vnc console" (#1147) by Andy Lee.

- Keep retrying with preserveSession after a failed reconnect attempt, so a
  displaced console waits for the other session to be released instead of
  failing immediately or taking the console back.
- Close the RFB socket when noVNC asks for credentials, so a failed console
  does not hold the VNC session.
- Restore Custom Shortcut Keys, which were removed in #1147.
- Add unit tests for the console reconnect behavior.

Related: harvester/harvester#10420
Signed-off-by: Alejandro Bonilla <abonilla@suse.com>

* fix: expose VNC quality and compression settings

- Add 0-9 sliders for the JPEG quality and compression level, which were
  already passed to noVNC but could not be changed.
- Mark the connection status as a polite live region so screen readers
  announce connection changes.

Related: harvester/harvester#10420
Signed-off-by: Alejandro Bonilla <abonilla@suse.com>

* fix: gate VNC session protection by version and rework the in-use screen

- Add the vncPreserveSession feature flag for Harvester v1.7.0, the first
  release whose KubeVirt (1.6.3) honours preserveSession. Without it the
  console connects as before, offers no Take Over and does not reconnect on
  its own after the session drops, so two open consoles no longer keep
  kicking each other out.
- Replace the error page with a short card that says when the console is in
  use, and confirm Take Over in a modal instead of window.confirm.
- Keep the overlay text readable on its dark background.
- Show "Connected (view only)", translate the Ctrl+Alt+Del label and remove
  unused translation keys.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat: show whether the VNC console has keyboard focus

noVNC hides the canvas focus outline, so nothing showed where typing would go.
Draw a ring around the console while it has focus, show a toolbar hint
("Typing goes to the virtual machine" / "Click the console to type"), focus
the console when it connects and return focus to it after sending keys from
the toolbar.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat: confirm Ctrl+Alt+Del and Soft Reboot in the VNC console

Both buttons can restart the virtual machine with one click: Soft Reboot
always, and Ctrl+Alt+Del on most Linux guests. Ask in a modal first, as the
VM list already does for Soft Reboot, and return focus to the console after.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* fix: return focus to the VNC console after its confirm modal closes

The modal gave focus back to the toolbar button that opened it, so typing
did not reach the console until it was clicked again.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* refactor: drop the VNC keyboard focus hint from the toolbar

The ring around the console already shows when it has keyboard focus.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
Signed-off-by: Alejandro Bonilla <abonilla@suse.com>
Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Alejandro Bonilla <abonilla@suse.com>
2026-10-21 18:30:27 +02:00
Volker Theile 5406c08f76 perf: speed up the VM list with many VMs (#1189)
* perf: speed up the VM list with many VMs

The VM list scanned whole store lists for every row and re-evaluated the same values per row on every render and sort. With several hundred VMs this blocked the browser on sorting and on every VM update.

Performance:
- look up launcher pods and migrations through shared indexes (namespace/name -> resource) instead of scanning per row; the indexes are computed per store list, so they stay in sync with in-place store updates
- use the same migration lookup (getLatestMigration) in the VM model and on the VM detail page
- look up PVCs, PVs, VMIs and restore backups by id
- merge VMs and VMIs with a Set
- evaluate the VM state once when sorting by state
- check the unschedulable condition before the pod based state checks
- cache feature flag results and per-schema/per-setting values that are the same for every row

Bug fixes:
- the launcher pod map was never rebuilt, because the store keeps the same array
- pods, volumes and migrations of a VM with the same name in another namespace could be picked up

The order of the volumes of a VM (vm.volumes) now follows the VM spec instead of the store order. Nothing depends on it.

Measured in a synthetic setup, 100 rows per page, sorting by state (Chrome, dev build):
- ~490 VMs, ~500 PVCs/PVs: 1.9 s -> 1.0 s
- ~490 VMs, 600 PVs, 200 migrations: 6.0 s -> 0.7 s, main thread blocked during VM updates 78% -> 32%
With few volumes the gain is much smaller (8-20%).

Related to: https://github.com/harvester/harvester/issues/9513

Signed-off-by: Volker Theile <vtheile@suse.com>

* fix: read VM data from the store of the resource instead of a fixed one

The migrations of a VMI and the migration badge of the state column were read from the hardcoded `harvester` store. In the Rancher explorer (embedded and standalone) the data is loaded into the `cluster` store, so a running migration was shown neither in the VM state nor as badge.

The VM model remembered the store of the current product in a module variable on first use and never updated it. The same model is used in the Harvester product (`harvester` store) and in the Rancher explorer (`cluster` store), and Rancher keeps the page loaded when going from the explorer of a Harvester cluster to Virtualization Management and into the Harvester product. The VM list then read the VMIs, launcher pods, volumes and restores from the wrong store, and running VMs were shown as Starting until the page was reloaded.

Read the data from the store the resource lives in (`this.$getters`, in the formatter the store of the current product). In the Harvester product this is still the `harvester` store, so nothing changes there.

Not covered: volume details like the lock icon of encrypted volumes. The explorer uses the generic Rancher PVC model, which does not know them, and settings based checks (feature flags, backup target) are not loaded there either.

Related to: https://github.com/harvester/harvester/issues/11882

Signed-off-by: Volker Theile <vtheile@suse.com>

---------

Signed-off-by: Volker Theile <vtheile@suse.com>
2026-10-14 13:31:09 +02:00
Volker Theile 71141b257a feat: Add a unit test target (jest) to the UI extension and run it in CI (#1192)
- Introduce test targets.
- Adding additional tests.

Related to: https://github.com/harvester/harvester/issues/11892

Signed-off-by: Volker Theile <vtheile@suse.com>
2026-10-13 18:00:38 +02:00
Volker Theile 02862bbeea fix: "Failed to resolve component: LabelValue" in the container volume form (#1193)
Related to: https://github.com/harvester/harvester/issues/11893

Signed-off-by: Volker Theile <vtheile@suse.com>
2026-10-13 08:13:51 +02:00
Volker Theile 5f13aadeed feat: Make use of status conditions when activating maintenance mode (#1145)
Related to: https://github.com/harvester/harvester/issues/9022

Signed-off-by: Volker Theile <vtheile@suse.com>
2026-10-07 13:17:01 +02:00
Alejandro Bonilla da36db143f fix: gate high-performance storage on v1.9.1 (#1181)
The storage performance options ship in Harvester v1.9.1, not v1.9.0.
Move highPerformanceStorage to the v1.9.1 feature flags so the UI does
not offer them on v1.9.0 clusters.

Signed-off-by: Alejandro Bonilla <abonilla@suse.com>
2026-10-07 13:20:47 +08:00
Alejandro BonillaandClaude Opus 5.5 5af181f5b6 feat: support network boot (PXE) for VM interfaces (#1176)
Add an "Enable network boot (PXE)" option to bridge network interfaces and
a VM-level choice to place network boot devices before or after volumes.
The form now owns interface boot order: enabled NICs get sequential boot
orders ahead of or behind the volumes, and a stale bootOrder is no longer
inherited from the old spec.

This also fixes editing a VM whose interface bootOrder was set in YAML
(the documented workaround): the form used to renumber disks from 1 while
keeping the NIC's bootOrder, producing a duplicate that KubeVirt rejects.

The boot order shown on the VM, snapshot and backup detail pages now
includes network interfaces.

Related: harvester/harvester#3325

Signed-off-by: Alejandro Bonilla <abonilla@suse.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 11:21:27 +08:00
Alejandro BonillaandClaude 528255dea4 feat: expose KubeVirt high-performance storage features in VM and Volume UI (#1133)
* feat: expose KubeVirt high-performance storage features in VM and Volume UI

Adds UI to configure KubeVirt high-performance disk/storage settings that
were previously only reachable via VMBuilder/Terraform:

- Per-volume "Storage Performance Options": a performance profile
  (Default / High Performance / Custom) exposing per-disk cache, io and
  dedicatedIOThread on all disk types (VM image/root, new, existing,
  container) and on the standalone Volume form.
- VM-wide "High Performance (I/O Threads and Multi-Queue)": blockMultiQueue
  and ioThreadsPolicy (+ supplemental-pool thread count), shown only in the
  VM section since these are domain-level and cannot be set per-PVC.
- Compatibility guardrails: io=native forces cache=none; cache=none on
  Filesystem volumeMode warns; blockMultiQueue requires a virtio disk.

Ref: harvester/harvester#11550

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Signed-off-by: Alejandro Bonilla <abonilla@suse.com>

* fix: address review feedback on high-performance storage UI

Resolves the Copilot review comments on #1133:

- Gate the whole feature behind a new `highPerformanceStorage` release
  feature flag (v1.9.0) so older supported clusters never render the
  controls or receive unsupported KubeVirt fields.
- Force Cache Mode to "none" whenever Native I/O is selected, including
  from the "Default" ('') cache value, and disable every non-"none" cache
  option (Default included) while Native is active. Previously the empty
  cache value slipped past the guardrail and produced an invalid combo.
- Clear an already-enabled blockMultiQueue when the last virtio disk is
  removed, so a disabled checkbox can no longer persist an invalid setting.
- Strip stale cache/io/dedicatedIOThread fields from the merged disk spec
  when a regenerated disk no longer requests them, so switching a disk back
  to "Default" (or unchecking Dedicated I/O Thread) while editing no longer
  silently preserves the previous values.
- Expose the disclosure toggle's state to assistive tech via aria-expanded
  and an expand/collapse aria-label.
- Add unit tests for the profile transitions and the Native/cache guardrails.

Ref: harvester/harvester#11550

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Signed-off-by: Alejandro Bonilla <abonilla@suse.com>

* fix: address second-round review on high-performance storage UI

Resolves the two Copilot findings on #1133 and votdev's UX feedback on
harvester/harvester#11550:

- Restore the disk's original bus when the performance profile goes back
  to "Default". The "High Performance" preset switches the bus to virtio,
  but leaving the preset only cleared cache/io/dedicatedIOThread, so a
  SATA/SCSI disk was silently left on virtio — a bus change that can make
  an existing guest unbootable. The pre-preset bus is now remembered and
  put back, unless the user picked a different bus themselves in the
  meantime.
- Pass the VM-wide performance values from the VM detail page to the
  shared Volume component. The mixin already parsed them via
  getInitConfig(), but the detail caller never forwarded them, so
  VMPerformanceOptions fell back to its prop defaults and hid itself in
  view mode — configured blockMultiQueue / ioThreadsPolicy settings were
  invisible. They are also refreshed in the value watcher so the panel
  does not go stale.
- Make the VM-wide "High Performance" panel expandable/collapsible,
  matching the per-volume "Storage Performance Options" disclosure. It
  stays collapsed unless the VM already has something configured, so the
  average user is not faced with specialist tuning controls by default.
- Fix the unit tests to use Vue Test Utils v2 mount options. They used
  the v1 top-level `mocks` key, which VTU 2.x ignores, so every case
  failed on mount. The repo has no jest config or test script, so this
  was not caught. Add coverage for the bus save/restore behaviour.

Ref: harvester/harvester#11550

Co-Authored-By: Claude <noreply@anthropic.com>
Signed-off-by: Alejandro Bonilla <abonilla@suse.com>

---------

Signed-off-by: Alejandro Bonilla <abonilla@suse.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-02 17:48:18 +08:00
freeze 3c92a06268 feat: drop striped LVM volume group type from v1.9.1 (#1167)
The LVM add-on reaches GA in v1.9.1 and only supports dm-thin.
    Gate the striped option behind a v1.9.1 feature flag, default new
    LVM storage classes to dm-thin, and reset a cloned striped type so
    older clusters keep the current behaviour.

    Related issue: harvester/harvester#11731

Signed-off-by: Vicente Cheng <vicente.cheng@suse.com>
2026-09-23 12:14:48 +08:00
freeze 6256cdc97a ci: pin package version to the git tag for tag builds (#1165)
Sprint tags (vX.Y.Z-dev-YYYYMMDD) only share a prefix with the
    x.y.z-dev version in package.json, so every sprint plugin reported
    the same version and the catalog image push hit "Cannot overwrite
    production image". Bump the tree to the tag before building.

    Related issue: harvester/harvester#11047

Signed-off-by: Vicente Cheng <vicente.cheng@suse.com>
2026-09-22 19:33:24 +08:00
renovate[bot] 4323132565 deps: update patch dependencies (#1159)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-09-21 11:00:14 +08:00
Andy Lee d05ec68e16 chore: add v1.10.0 and v1.9.1 feature flags (#1156)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-09-18 16:34:06 +08:00
Andy Lee cb2cef5e73 fix: avoid userpreferences PUT flood from SideNav refresh trigger (#1119)
kickSideNav toggled a dummy favorite via addFavorite/removeFavorite, which persist through prefs/set and issue a PUT /v1/userpreferences on every toggle, flooding the backend and surfacing 500 errors. Switch to the in-memory prefs/load mutation so the SideNav still re-renders without any network request.

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-09-16 09:31:28 +08:00
Andy Lee 45116b568a feat: change logo based on server-flavor setting (#1151)
* feat: use prime logo when server-flavor is prime

Signed-off-by: Andy Lee <andy.lee@suse.com>

* feat: expose server-flavor setting

Signed-off-by: Andy Lee <andy.lee@suse.com>

* refactor: copilot review

Signed-off-by: Andy Lee <andy.lee@suse.com>

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-09-16 09:30:37 +08:00
Victor Chang f42d798d10 fix: require names for cloud configuration templates (#1138)
Signed-off-by: Victor Chang <t7902195204@gmail.com>
2026-09-16 09:17:29 +08:00
Andy Lee 50b4cf5248 feat: add rancher k3k addon UI page (#1137)
* feat: add k3k addon UI

Signed-off-by: Andy Lee <andy.lee@suse.com>

* feat: add rancher-k3k addon UI

Signed-off-by: Andy Lee <andy.lee@suse.com>

* refactor: copilot review

Signed-off-by: Andy Lee <andy.lee@suse.com>

* refactor: copilot review

Signed-off-by: Andy Lee <andy.lee@suse.com>

* refactor: remove k3k edit page

Signed-off-by: Andy Lee <andy.lee@suse.com>

* refactor: k3k addon description

Signed-off-by: Andy Lee <andy.lee@suse.com>

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-09-14 15:46:14 +08:00
Siva Kanakala cba37194b6 fix: preserve per-volume storage class when editing image-sourced volumes and fallback to the image StorageClass for new volumes (#1144)
Signed-off-by: Siva Kanakala <siva.kanakala@suse.com>
2026-09-10 13:08:53 +08:00
renovate[bot] bbe0c4643f deps: update dependency qs to v6.16.0 [security] (#1134)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-09-07 13:56:15 +08:00
marcelofukumoto 00584f1d19 chore(deps): bump @rancher/shell to 3.0.13 (#1130)
Clears 26 of the 54 open Dependabot alerts (axios, dompurify, serve-static, and
drops vulnerable send / @tootallnate/once copies).

3.0.13 ships the flat-config ESLint 10 toolchain, so lint now routes through the
@rancher/shell launcher (keeping the legacy .eslintrc on ESLint 7); a prelint step
installs an ESLint-7-compatible eslint-plugin-jest into the isolated toolchain.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>
2026-09-04 10:36:52 +02:00
Tim SerongandVolker Theile 4fa6470343 feat: LHv2: graduate from "Experimental" to "Preview" (#1129)
In Harvester v1.9.0, we're moving LHv2 from "Experimental" to "Preview",
so I've added a new preview label to the settings interface.  I figure
given Experimental had the "error" color, I should make "Preview" use
the warning color, to make it a bit less alarming :-)

Related-to: https://github.com/harvester/harvester/issues/9960

Signed-off-by: Tim Serong <tserong@suse.com>
Co-authored-by: Volker Theile <vtheile@suse.com>
2026-09-01 11:30:38 +10:00
Andy Lee d550046189 fix: vGPU doesn't display when creating harvester downstream cluster (#1123)
* fix: vGPU doesn't display in edit VM page

Signed-off-by: Andy Lee <andy.lee@suse.com>

* fix: align PCI passthrough action buttons height

Match the enable/disable passthrough and Actions dropdown buttons to 40px and move the selected-count label below them.

Signed-off-by: Andy Lee <andy.lee@suse.com>

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-08-25 16:24:37 +08:00
Po Han Huang 5f32a9ade5 feat: improve readability for vm migration UI (#1112)
Signed-off-by: pohanhuang <pohan.huang@suse.com>
2026-08-18 12:32:02 +08:00
marcelofukumoto 3f39d561be security: fix 15 transitive Dependabot alerts via yarn.lock re-resolution (#1115)
Re-resolve 15 vulnerable transitive dependencies to their latest in-range
patched versions in yarn.lock only (no package.json changes): @babel/core,
@babel/plugin-transform-modules-systemjs, brace-expansion, fast-uri, form-data,
http-proxy-middleware, immutable, joi, js-cookie, launch-editor, nanoid,
shell-quote, svgo, websocket-driver, ws.

The remaining alerts are pinned by parent packages (chiefly @rancher/shell) or
need a cross-major bump, so they can't be resolved by the lockfile alone; they
are tracked separately.

Signed-off-by: Marcelo Fukumoto <marceloyfukumoto@gmail.com>
2026-08-17 10:30:05 +02:00
Andy Lee 7c84269ed6 fix: exclude forklift namespace from system classification (#1114)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-08-17 15:23:23 +10:00
Andy Lee f63be73b11 fix: ACCESS_MODE undefined error in forklift mapping page (#1111) 2026-08-14 10:01:27 +08:00
Andy Lee fabc1cec21 fix: prevent duplicated cloud-config for empty user data (#1109)
* fix: prevent duplicated cloud-config for empty user data

Signed-off-by: Andy Lee <andy.lee@suse.com>

* refactor: AI review

Signed-off-by: Andy Lee <andy.lee@suse.com>

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-08-12 14:20:25 +08:00
Andy Lee ed2b6f2551 fix: remove map ownerref writeback and delete maps via plan refs (#1105)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-08-10 18:14:48 +08:00
renovate[bot] 72282ae50e deps: update dependency @types/lodash to v4.17.25 (#1099)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-08-10 10:10:31 +08:00
Volker Theile 8fba4e7050 fix: Rename to Windows Unattended & Sysprep (#1096)
Rename title and other mentions of Sysprep to prevent misunderstandings regarding functionality. For the average Windows administrator who simply wants to automate the installation of a Windows ISO, it isn't immediately intuitive when the term “Sysprep” is used on its own.

Related to: https://github.com/harvester/harvester/issues/1836
Related to: https://github.com/harvester/harvester-ui-extension/pull/954

Signed-off-by: Volker Theile <vtheile@suse.com>
2026-08-07 11:22:23 +08:00
Andy Lee fbd4a1108f ci: add test steps in PR template (#1093)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-08-05 15:53:40 +08:00
Andy Lee 823a88c85b ci: not use actions/github-script@v7 (#1092)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-08-05 14:37:24 +08:00
Andy Lee 3a2c6e3a3d ci: support manual standalone build trigger and PR comment (#1091)
* ci: add manually trigger build

Signed-off-by: Andy Lee <andy.lee@suse.com>

* refactor: PR comment

Signed-off-by: Andy Lee <andy.lee@suse.com>

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-08-05 14:21:41 +08:00
Andy Lee be6e9b5f06 fix(subnet): support None option for VLAN dropdown (#1085)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-08-05 12:23:57 +08:00
Andy Lee a88bed9eb4 fix: clear keyword should clear highlight (#1088)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-08-05 00:24:34 +08:00
Andy Lee f97f14c811 deps: bump @rancher/shell to 3.0.12-rc.7 (#1084)
* deps: update rancher/shell to 3.0.12-rc.7

Signed-off-by: Andy Lee <andy.lee@suse.com>

* fix: move filter labels/schedule buttons position

Signed-off-by: Andy Lee <andy.lee@suse.com>

* feat: improve serial console

Signed-off-by: Andy Lee <andy.lee@suse.com>

* feat(serial-console): add terminal search toolbar and highlight tuning

Signed-off-by: Andy Lee <andy.lee@suse.com>

* refactor: clear searach result after close

Signed-off-by: Andy Lee <andy.lee@suse.com>

* refactor: fine tune serial console

Signed-off-by: Andy Lee <andy.lee@suse.com>

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-08-04 19:53:24 +08:00
Andy Lee f8a29a1c54 fix: project resource quota not set in POST API payload (#1082)
* fix: project resource quota not set in POST API payload

Signed-off-by: Andy Lee <andy.lee@suse.com>

* fix: guard onQuotasInput against undefined payload

Signed-off-by: Andy Lee <andy.lee@suse.com>

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-08-04 13:27:30 +08:00
freeze 9a935434c2 feat: support attaching volumes as shareable disks (#1026)
Show a Shareable checkbox when attaching an existing volume whose
    PVC is RWX Block and not provisioned by Longhorn. Checking it sets
    disk.shareable and shows a data-corruption warning banner.

    Related issue: harvester/harvester#9650

Signed-off-by: Vicente Cheng <vicente.cheng@suse.com>
2026-08-03 16:24:33 +08:00
Andy Lee afe632b723 feat: add access/volume mode support and improvements for VM migration (#1074)
* fix: VM migration tab not appear when first login

Signed-off-by: Andy Lee <andy.lee@suse.com>

* feat: add access/ volume mode model

Signed-off-by: Andy Lee <andy.lee@suse.com>

* feat: add selected all | clear all actions for selected VM

Signed-off-by: Andy Lee <andy.lee@suse.com>

* fix: bugs in VM selection table

Signed-off-by: Andy Lee <andy.lee@suse.com>

* refactor: copilot review

Signed-off-by: Andy Lee <andy.lee@suse.com>

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-08-03 12:58:37 +08:00
renovate[bot] d050f21f9a deps: update patch dependencies (#1075)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-08-03 12:58:04 +08:00
Andy Lee b87f367583 fix: prevent VM detail page hang when static IP assigned (#1072)
Make syncStaticIpAnnotations idempotent so it no longer mutates VM
annotations when already in sync, breaking a reactive update loop that
froze the browser on the VM detail page. Also stack multiple IP
addresses vertically in the IP Address column.

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-07-31 16:55:25 +08:00
Andy Lee 92aa8ec603 ci: disable footer-max-line-length rule (#1069)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-07-29 14:46:07 +08:00
Alejandro BonillaandVolker Theile e013534373 feat: allow Cloud Config for Windows guests (Cloudbase-Init) (#984)
* feat(vm): allow Cloud Config for Windows guests

Currently the Cloud Config editor is completely hidden when a VM's
OS Type is set to Windows, and no `cloudinitdisk` volume or secret
is written to the VM spec even if the user has entered content.

This blocks a common Windows-on-Harvester workflow: using
Cloudbase-Init to run first-boot configuration (install VMDP,
enable OpenSSH server, add authorized_keys, join a domain, run
`runcmd` steps, etc.). Users on Windows today have to hand-edit the
VM YAML after creation to attach a cloudinitdisk, which is fragile
and undiscoverable.

Changes:
- Remove the `v-if="!isWindows"` on the CloudConfig component so
  the editor is available for every OS type. The Sysprep editor
  continues to render only for Windows, so Windows now gets both
  panels; Linux is unchanged.
- Drop the `if (!this.isWindows)` guard around the cloudinitdisk
  volume serialization so the disk is attached whenever the user
  provided user-data or network-data, regardless of OS.
- Drop the `|| this.isWindows` early-return in `saveSecret` so the
  cloud-init secret is persisted for Windows VMs too.
- `getInitUserData` now returns a bare `#cloud-config\n` header for
  Windows instead of the Linux qemu-guest-agent runcmd template
  (which would fail on Cloudbase-Init). VMDP installs the QGA on
  Windows as a native service, so the runcmd path is not needed.

The "Install guest agent" checkbox stays disabled for Windows
because it specifically drives the Linux QGA-via-runcmd recipe.

Fixes point 2 of harvester/harvester#11124.

Signed-off-by: Alejandro Bonilla <abonilla@suse.com>

* fix(vm): do not clear cloud-config on isWindows watcher fire

The isWindows watcher runs on every change of the isWindows computed
property, including on mount when editing an existing Windows VM. Setting
this['userScript'] and this['networkScript'] to undefined at that point
wipes the cloud-config data that was just loaded from the existing VM's
cloudinit secret, so the Advanced -> Cloud Config editor shows empty
even though the VM has data on the wire.

Remove the two clears - Cloud Config is now supported for Windows guests
by this PR, so there is no reason to unset the user/network scripts when
the OS type is Windows. sshKey and installAgent remain gated (SSH keys
are injected via cloud-init on Linux only, and the qemu-guest-agent
package install checkbox does not apply to Windows).

Signed-off-by: Alejandro Bonilla <abonilla@suse.com>
Co-authored-by: Volker Theile <vtheile@suse.com>

* refactor(vm): Get CloudInit working for VM templates

- Remove unnecessary osType watcher in cloud config. The watcher (see `pkg/harvester/edit/kubevirt.io.virtualmachine/VirtualMachineCloudConfig/DataTemplate.vue`) that cleared the cloud config template for Windows VMs is no longer necessary.
- Automatically strip the CloudInit `User Data` properties `package_update` and `packages` for OS type `Windows`.

Signed-off-by: Volker Theile <vtheile@suse.com>

---------

Signed-off-by: Alejandro Bonilla <abonilla@suse.com>
Signed-off-by: Volker Theile <vtheile@suse.com>
Co-authored-by: Volker Theile <vtheile@suse.com>
2026-07-28 11:32:30 +02:00
Andy Lee d23c3d3b72 revert: PR build artifact (#1066)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-07-28 15:39:20 +08:00
Andy Lee 719c33fa12 ci: fix CI_BRANCH ternary so PR builds skip upload gate (#1062)
* ci: fix CI_BRANCH ternary so PR builds skip upload gate

Signed-off-by: Andy Lee <andy.lee@suse.com>

* ci: simplify CI_BRANCH expression comment

Signed-off-by: Andy Lee <andy.lee@suse.com>

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-07-28 14:34:21 +08:00
Andy Lee a6bd7ec00e feat: add VMware VDDK image input field to VM migration provider (#1057)
* feat: add VMware VDDK image option to VM migration provider

Add an optional VMware VDDK Image field to the Configure Provider step of the VM migration wizard, bound to spec.settings.vddkInitImage when set and left unset when empty. Supports create and edit flows and populates from the existing provider when editing.

Signed-off-by: Andy Lee <andy.lee@suse.com>

* refactor: copilot review

Signed-off-by: Andy Lee <andy.lee@suse.com>

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-07-28 14:10:44 +08:00
Andy Lee ac26fe2f0e ci: trigger standalone build when PR labeled with build-artifact (#1058)
* ci: trigger standalone build when PR labeled with build-artifact

Signed-off-by: Andy Lee <andy.lee@suse.com>

* ci: skip upload gate for PR-triggered standalone builds

Signed-off-by: Andy Lee <andy.lee@suse.com>

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-07-28 13:56:11 +08:00
Andy Lee 790cade04d feat: validate migration plan name against existing providers and plans (#1053)
Show an error banner and disable the Create and Start action when the migration plan name matches an existing provider or migration plan name.

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-07-24 16:43:57 +08:00
Andy Lee 2903e86c02 refactor: new design for review page (#1051)
* refactor: new design for review page

Signed-off-by: Andy Lee <andy.lee@suse.com>

* refactor: customize empty table rows message

Signed-off-by: Andy Lee <andy.lee@suse.com>

* refactor: fixed the table column

Signed-off-by: Andy Lee <andy.lee@suse.com>

* style: update header tag and align fixed header actions in review migration step

Signed-off-by: Andy Lee <andy.lee@suse.com>

* style: remove unneeded overflow css

Signed-off-by: Andy Lee <andy.lee@suse.com>

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-07-24 10:24:22 +08:00
Andy Lee 2d747e435a fix: forklift mapping UX and migration progress fixes (#1049)
* refactor: modify relatedResources using ownerReferences uid

Signed-off-by: Andy Lee <andy.lee@suse.com>

* refactor: wordings

Signed-off-by: Andy Lee <andy.lee@suse.com>

* fix(vm-migration): keep completed VMs green and linkable in failed plans

When a plan fails overall, VMs that already reached 100% were marked with an error: their progress bar turned red while the label still read "Finished Successfully", and the migrated-VM detail link was hidden.

Skip the plan-level failure fallback for VMs at 100% and drop the !planFailed guard from the detail-link condition so successfully migrated VMs stay green and stay navigable.

Signed-off-by: Andy Lee <andy.lee@suse.com>

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-07-23 14:38:49 +08:00
CopilotandAndy Lee eadda2a18b refactor: extract access mode strings to static ACCESS_MODE constant (#1039)
* refactor: extract access mode strings to static ACCESS_MODE constant

Signed-off-by: Andy Lee <andy.lee@suse.com>

* refactor: destructure ACCESS_MODE variables in CDISettings.vue accessModeOptions

* refactor: destructure ACCESS_MODE at top level in all consumer files

* fix(lint): reorder imports to top of module in CDISettings, harvesterhci.io.volume, and VirtualMachineVolume

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
2026-07-21 11:07:48 +08:00
Volker Theile a178302f73 fix: Creating a VM with no cloud init user data but network data only fails (#1044)
Related to: https://github.com/harvester/harvester/issues/11213

Signed-off-by: Volker Theile <vtheile@suse.com>
2026-07-21 11:06:24 +08:00
Andy Lee d376bfb3a5 docs: require scope-less conventional commit format in guides (#1042)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-07-20 20:05:36 +08:00
Andy Lee 7a84e08f99 fix(vm-migration): show elapsed duration for in-progress plans (#1037)
formatDuration returned an empty value when a migration was in progress (started set but completed missing), causing the duration column to show an em-dash for all running plans. It now computes elapsed time up to Date.now() when completed is absent, only returning the placeholder when started is unset or timestamps are invalid.

Related issue: harvester/harvester#10417

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-07-20 17:05:27 +08:00
Andy Lee 3d39626b93 docs(agents): clarify agent guide and share it across AI assistants (#1035)
* ci: disable header-max-length commit rule

Signed-off-by: Andy Lee <andy.lee@suse.com>

* docs(agents): clarify agent guide and share it across AI assistants

- Symlink CLAUDE.md and GEMINI.md to AGENTS.md so Claude Code, Copilot
  and Gemini read the same guidance
- Use the full conventional-commit format with scope in the guide
- Clarify Vue SFC block order and the feature-flag development steps
- Bump the documented Node.js requirement to v24

Signed-off-by: Andy Lee <andy.lee@suse.com>

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-07-20 15:51:12 +08:00
Andy Lee 1c3b40b631 refactor(host): update resource usage gauges and table column headers to fit small screen (#1031)
* refactor(host): update resource usage gauges and table column headers

- Replace ConsumptionGauge with PercentageBar in CPU/Memory/Storage
  formatters to show the percentage next to the progress bar
- Rename the Disk State column header to Disk (via i18n)
- Display the CPU Manager column header on two lines

Signed-off-by: Andy Lee <andy.lee@suse.com>

* refactor: add noopener noreferrer rel

Signed-off-by: Andy Lee <andy.lee@suse.com>

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-07-20 15:29:12 +08:00
Andy Lee 87baf75301 fix(ci): support scoped commit prefixes in PR label extraction (#1032)
Strip the scope in parentheses so titles like 'refactor(host): ...'
resolve to the 'refactor' type instead of falling back to 'other'.

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-07-20 15:23:26 +08:00
Andy Lee a10d651827 feat: improve VM migration dashboard mapping labels and VM detail link (#1029)
* feat: improve VM migration dashboard mapping labels and VM detail link

- Display Management Network / Ignored labels via i18n in mappings column and review card
- Add clickable external-link icon to migrated VM detail page after successful migration
- Add tooltip to the VM detail external-link icon

Signed-off-by: Andy Lee <andy.lee@suse.com>

* refactor: modify duration column width

Signed-off-by: Andy Lee <andy.lee@suse.com>

* refactor: copilot review comment

Signed-off-by: Andy Lee <andy.lee@suse.com>

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-07-20 14:30:26 +08:00
renovate[bot] 11ff7c8a7c deps: update dependency @types/node to v25.9.5 (#1021)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-07-20 12:20:34 +08:00
Jack Yu f6dffe9816 feat: support skip MIG mode configuration in srivogpu (#1009)
Signed-off-by: Jack Yu <jack.yu@suse.com>
2026-07-20 11:22:40 +08:00
Andy Lee b813bc578e docs: add XSS safety comment for VM display name annotation (#1019)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-07-17 17:30:59 +08:00
Andy Lee 7c3b2730ab fix: remove bootable volume validation in VM disk validator (#1016)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-07-17 16:59:02 +08:00
Andy LeeandCopilot App 429d9e18ad fix: stale cloud-init secret name reused after VM name change (#1012)
* fix: regenerate stale cloud-init secret name after VM name change

When creating a VM, the cloud-init/sysprep secret name was generated
once and cached for the component's lifetime (needNewSecret is always
false during create). If a first create attempt was rejected by the
API (e.g. duplicate name) and the user corrected the name and retried,
the VM was created successfully but reused the secret name derived
from the rejected attempt, and any subsequent secret-creation failure
surfaced as a stale error after the VM already existed.

Now the secret name (and Windows sysprep secret name) is regenerated
whenever the VM name prefix used to generate it no longer matches the
current name, and is proactively reset on a failed create attempt so
retries always start fresh.

Fixes harvester/harvester#11174

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Signed-off-by: Andy Lee <andy.lee@suse.com>

* refactor: copilot review

Signed-off-by: Andy Lee <andy.lee@suse.com>

* refactor: remove console

Signed-off-by: Andy Lee <andy.lee@suse.com>

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-07-17 14:29:01 +08:00
Andy Lee dc166d8fc9 ci: modify PR template (#1013)
* ci: modify PR template

Signed-off-by: Andy Lee <andy.lee@suse.com>

* refactor: review comment

Signed-off-by: Andy Lee <andy.lee@suse.com>

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-07-17 14:22:32 +08:00
Andy Lee 3ff4534294 feat: allow user specify namespace for migrated VM (#1007)
* feat: allow user specify namespace for migrated VM

Signed-off-by: Andy Lee <andy.lee@suse.com>

* refactor: not pre-select target namespace

Signed-off-by: Andy Lee <andy.lee@suse.com>

* refactor: ignore option

Signed-off-by: Andy Lee <andy.lee@suse.com>

* refactor: copilot review

Signed-off-by: Andy Lee <andy.lee@suse.com>

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-07-16 15:29:39 +08:00
Andy Lee d4223ad2ae feat: keep upgrade button appear (#1003)
* feat: keep upgrade button appear

Signed-off-by: Andy Lee <andy.lee@suse.com>

* refactor: copilot review

Signed-off-by: Andy Lee <andy.lee@suse.com>

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-07-16 11:24:51 +08:00
Andy Lee 44297ada16 feat: add migration plan duration time column (#1005)
* feat: add migration plan duration time column

Signed-off-by: Andy Lee <andy.lee@suse.com>

* feat: allow duration column to be sorted

Signed-off-by: Andy Lee <andy.lee@suse.com>

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-07-15 18:42:01 +08:00
Andy Lee aea53fdd65 chore: update main branch to 1.10.0-dev (#1004)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-07-15 18:23:32 +08:00
Andy Lee 9640c87947 fix: allow input vlan 1 in host network (#999)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-07-15 15:24:49 +08:00
Volker Theile 2cefd7cb78 fix: A disk entry must be either disk or cdrom, never both (#998)
Related to: https://github.com/harvester/harvester/issues/11154

Signed-off-by: Volker Theile <vtheile@suse.com>
2026-07-15 09:11:58 +02:00
Andy Lee fb6ffa3c0f refactor: add customized migration plan delete model (#996)
* refactor: add customized migration plan delete model

Signed-off-by: Andy Lee <andy.lee@suse.com>

* refactor: copilot review

Signed-off-by: Andy Lee <andy.lee@suse.com>

* refactor: copilot review

Signed-off-by: Andy Lee <andy.lee@suse.com>

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-07-14 17:36:25 +08:00
Andy Lee e0436bff28 feat: add migration steps tooltip when mouse hover on progress bar (#994)
* feat: add progress bar tooltip

Signed-off-by: Andy Lee <andy.lee@suse.com>

* refactor: copilot review

Signed-off-by: Andy Lee <andy.lee@suse.com>

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-07-14 14:37:13 +08:00
Andy Lee 219f39ae52 refactor: rename pod network to management network (#992) 2026-07-14 13:56:59 +08:00
Andy Lee 41cf44d231 refactor: forklift UI bug and enhancement (#989)
* fix: hide Virtul machine migration tabs if forklift addon is not enabled

Signed-off-by: Andy Lee <andy.lee@suse.com>

* fix: rename advanced to configurations

Signed-off-by: Andy Lee <andy.lee@suse.com>

* fix: fixed column width

Signed-off-by: Andy Lee <andy.lee@suse.com>

* refactor: review comment

Signed-off-by: Andy Lee <andy.lee@suse.com>

* revert: power on background color

Signed-off-by: Andy Lee <andy.lee@suse.com>

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-07-14 12:04:00 +08:00
Jack Yu 7d09cb7142 feat: prevent users from selecting mounted devices (#987)
Signed-off-by: Jack Yu <jack.yu@suse.com>
2026-07-14 11:29:41 +08:00
marcelofukumoto 560643d299 feat: forklift UI (#891)
* feat: forklift poc first commit

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat: add migration and plan detail pages with progress tracking

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat(forklift): UI based on the FIGMA

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat(forklift): Fixed config based on new figma changes

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat(forklift): New changes added based on new figma

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat(forklift): Add the succeded state

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* Merge the new APIs

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat(forklift): Applied fix to select the proper data on network. Added condition to show critical

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat(forklift): Added icons, critical state, fix grids, action button

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat(forklift): Change to use the proper provider instead of a hardcoded

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat(forklift): Added pagination UI

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat(forklift): FIxed the routing for the extension

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat(forklift): route and router doesnt work properly on extensions

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat(forklift): fixed to fix the icon on extension

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat(forklift): Added overflow hidden to mapping target list

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat(forklift): Added better handling on the saving and testing

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat(forklift): Remove test flags

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat(forklift): Changed based on review

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat(forklift): fixed title and button

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat(forklift): Design changes

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat(forklift): Changed to Wizard

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat(forklift): added the provider wizard

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat(forklift): Fixed some UI changes

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat(forklift): Removed wrong configs used for testing

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat(forklift): update size

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat(forklift): small fixes

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat(forklift): small fixes after Copilot

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat(forklift): small fixes after Copilot

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat(forklift): reverted settings.json changes

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat(forklift): small fixes after Copilot

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat(forklift): Fix the way it is registered

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat(forklift): Fixed the type for VMware

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat(forklift): small changes before rebase

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat: Added new API for the vms

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat: Fix some labels

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat: Added some final fixes to structure

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat: added loading to provider steps

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat: added comments from copilot review

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

---------

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>
2026-07-13 16:58:35 +08:00
Renuka Devi Rajendran c3bb0ea4be feat: Display mgmt interface details under mgmt cluster network (#974)
Signed-off-by: Renuka Devi Rajendran <renuka.rajendran@suse.com>
2026-07-10 11:40:57 +08:00
Andy Lee 3c37f04ef6 chore: limit the rancher to 2.15.0+ for harvester v1.9.0 (#982)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-07-10 10:52:33 +08:00
Volker Theile d98db6ba49 feat: Allow user to customize snapshot/backup deadline (#866)
* feat: Allow user to customize snapshot/backup deadline

Related to: https://github.com/harvester/harvester/issues/4098
Related to: https://github.com/harvester/harvester/pull/10545

Signed-off-by: Volker Theile <vtheile@suse.com>

* feat: Allow user to customize snapshot/backup deadline

Related to: https://github.com/harvester/harvester/issues/4098
Related to: https://github.com/harvester/harvester/pull/10545

Signed-off-by: Volker Theile <vtheile@suse.com>

---------

Signed-off-by: Volker Theile <vtheile@suse.com>
2026-07-09 08:44:47 +02:00
Andy Lee 531ed03796 feat: allow user specify static IP when VM creation (#973)
* feat: allow suer give static IP for VM

Signed-off-by: Andy Lee <andy.lee@suse.com>

* feat: add feature flag

Signed-off-by: Andy Lee <andy.lee@suse.com>

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-07-09 13:17:19 +08:00
Andy Lee 59f260eab8 fix: vpc topology should consume NAD labels (#975)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-07-08 13:47:25 +08:00
126 changed files with 11362 additions and 3291 deletions
+12
View File
@@ -0,0 +1,12 @@
name: Run Unit Tests
description: Run Unit Tests
runs:
using: 'composite'
steps:
- name: Setup env
uses: ./.github/actions/setup
- name: Run unit tests
shell: bash
run: yarn test:ci
+7 -3
View File
@@ -8,12 +8,16 @@
- [ ] Yes, the backend owner is @
- [ ] No, frontend-only.
### Related Issue #
### Related Issue
<!-- Link the issue as harvester/harvester#<issue_number> -->
harvester/harvester#<issue_number>
### Test screenshot or video (Required)
<!-- Attach screenshot or video of the changes and eventual comparison if you find it necessary -->
### Test Steps
<!-- Provide the test steps for reviewer to verify the issue -->
1. Go to ... page
### Test screenshot or video
<!-- Attach screenshot or video of the changes and eventual comparison -->
@@ -1,6 +1,7 @@
name: Build Standalone on PR Merge
on:
workflow_dispatch: # manually trigger on Github Actions only support PR branch pushed to harvester/harvester-ui-extension
push:
branches:
- main
@@ -29,3 +30,35 @@ jobs:
id-token: write
with:
CI_BRANCH: ${{github.ref_name}}
comment-on-pr:
name: Comment build result on PR
# Only for manual runs so the existing push / pull_request flows are untouched.
if: github.event_name == 'workflow_dispatch'
needs:
- build
runs-on: ubuntu-latest
permissions:
pull-requests: write
steps:
- name: Add build artifact comment to the PR opened from this branch
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
BRANCH: ${{ github.ref_name }}
run: |
set -euo pipefail
# Match scripts/version: sanitize the branch and map main -> latest.
if [ "$BRANCH" = "main" ]; then
DIR="latest"
else
DIR=$(printf '%s' "$BRANCH" | sed -E 's/[^a-zA-Z0-9.-]+/-/g')
fi
URL="https://releases.rancher.com/harvester-ui/dashboard/${DIR}/index.html"
PR=$(gh pr list --repo "$GITHUB_REPOSITORY" --state open --base main --head "$BRANCH" --json number --jq '.[0].number // empty')
if [ -z "$PR" ]; then
echo "No open PR found for branch $BRANCH, skipping comment."
exit 0
fi
BODY=$(printf '🚀 **UI Artifact Build Status:** `SUCCESS` ✅\n> ui-index: %s\n> ui-source: external' "$URL")
gh pr comment "$PR" --repo "$GITHUB_REPOSITORY" --body "$BODY"
+8
View File
@@ -71,3 +71,11 @@ jobs:
GITHUB_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
GITHUB_BEFORE: ${{ github.event.before }}
GITHUB_AFTER: ${{ github.event.after }}
unit-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- name: Run unit tests
uses: ./.github/actions/test
+25
View File
@@ -59,6 +59,8 @@ You are an expert Senior Software Engineer specializing in Vue.js and TypeScript
| `yarn serve-pkgs` | Serve the locally built extension for testing |
| `yarn lint` | Run ESLint (zero warnings allowed) |
| `yarn lint:fix` | Run ESLint with auto-fix |
| `yarn test` | Run the unit tests (Jest) in watch mode |
| `yarn test:ci` | Run the unit tests once, as CI does (silent) |
| `yarn clean` | Clean build artifacts |
| `yarn agents:generate` | Regenerate `AGENTS.md` from `docs/agents.md/` sources |
@@ -95,6 +97,16 @@ You are an expert Senior Software Engineer specializing in Vue.js and TypeScript
- ESLint covers `.js`, `.ts`, and `.vue` files.
- Always run `yarn lint:fix` before committing.
### Unit Tests
- **Run**:
```bash
yarn test
```
- `yarn test` starts Jest in watch mode (like in the Rancher dashboard) and only runs the tests related to changed files. It does not exit, so use `yarn test:ci` for a single run of all tests, e.g. in scripts.
- CI runs `yarn test:ci` on every pull request.
- See the Unit Tests section of the Contributors Guide for how the tests are set up.
### Commit Conventions
- Commits are validated by [commitlint](https://commitlint.js.org/) via a Husky `commit-msg` hook.
@@ -187,6 +199,19 @@ To add a feature in a new release, follow these steps:
See https://github.com/harvester/harvester-ui-tests
## Unit Tests (Jest)
Unit and component tests run with [Jest](https://jestjs.io/). The setup follows the Rancher dashboard and the Rancher extension template ([rancher/ui-plugin-examples](https://github.com/rancher/ui-plugin-examples)), so both stay aligned.
- Run the tests in watch mode with `yarn test`, all tests once with `yarn test:ci`, a single file with `yarn test <path>`. CI runs `yarn test:ci` on every pull request.
- Test files live next to the code in `__tests__` folders and are named `<name>.test.js` or `<name>.test.ts`.
- Configuration:
- `jest.config.js`: environment, module aliases (`@shell`, `@components`, `@pkg`) and transforms.
- `jest.setup.js`: global mocks (`t`, `$store`, common directives) and browser APIs that jsdom does not provide.
- `vue3JestRegisterTs.js`: makes TypeScript available to the Vue compiler, otherwise `.vue` files with typed props fail to compile.
- Components are tested with the Vue Test Utils 2 API: use `props` and `global.mocks`, not the Vue 2 options `propsData` and `mocks`.
- Models and utils can be tested without mounting anything, see `pkg/harvester/models/__tests__` for examples.
## Node Dependencies
Dependencies are managed via `package.json` and `yarn`
+12
View File
@@ -15,6 +15,8 @@
| `yarn serve-pkgs` | Serve the locally built extension for testing |
| `yarn lint` | Run ESLint (zero warnings allowed) |
| `yarn lint:fix` | Run ESLint with auto-fix |
| `yarn test` | Run the unit tests (Jest) in watch mode |
| `yarn test:ci` | Run the unit tests once, as CI does (silent) |
| `yarn clean` | Clean build artifacts |
| `yarn agents:generate` | Regenerate `AGENTS.md` from `docs/agents.md/` sources |
@@ -51,6 +53,16 @@
- ESLint covers `.js`, `.ts`, and `.vue` files.
- Always run `yarn lint:fix` before committing.
### Unit Tests
- **Run**:
```bash
yarn test
```
- `yarn test` starts Jest in watch mode (like in the Rancher dashboard) and only runs the tests related to changed files. It does not exit, so use `yarn test:ci` for a single run of all tests, e.g. in scripts.
- CI runs `yarn test:ci` on every pull request.
- See the Unit Tests section of the Contributors Guide for how the tests are set up.
### Commit Conventions
- Commits are validated by [commitlint](https://commitlint.js.org/) via a Husky `commit-msg` hook.
@@ -0,0 +1,12 @@
## Unit Tests (Jest)
Unit and component tests run with [Jest](https://jestjs.io/). The setup follows the Rancher dashboard and the Rancher extension template ([rancher/ui-plugin-examples](https://github.com/rancher/ui-plugin-examples)), so both stay aligned.
- Run the tests in watch mode with `yarn test`, all tests once with `yarn test:ci`, a single file with `yarn test <path>`. CI runs `yarn test:ci` on every pull request.
- Test files live next to the code in `__tests__` folders and are named `<name>.test.js` or `<name>.test.ts`.
- Configuration:
- `jest.config.js`: environment, module aliases (`@shell`, `@components`, `@pkg`) and transforms.
- `jest.setup.js`: global mocks (`t`, `$store`, common directives) and browser APIs that jsdom does not provide.
- `vue3JestRegisterTs.js`: makes TypeScript available to the Vue compiler, otherwise `.vue` files with typed props fail to compile.
- Components are tested with the Vue Test Utils 2 API: use `props` and `global.mocks`, not the Vue 2 options `propsData` and `mocks`.
- Models and utils can be tested without mounting anything, see `pkg/harvester/models/__tests__` for examples.
+46
View File
@@ -0,0 +1,46 @@
// Same settings in every environment, otherwise tests that format dates depend on the machine
process.env.TZ = 'UTC';
// The setup follows the one of the Rancher dashboard and of the Rancher extension template (rancher/ui-plugin-examples)
module.exports = {
roots: ['<rootDir>/pkg'],
testEnvironment: 'jsdom',
// Jest 28+ (jest-environment-jsdom) defaults package resolution to the "browser" export condition, which makes
// packages like @vue/test-utils resolve their browser (global-Vue) build and throw "Vue is not defined".
testEnvironmentOptions: { customExportConditions: ['node', 'node-addons'] },
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
watchman: false,
moduleFileExtensions: ['js', 'mjs', 'json', 'vue', 'ts'],
modulePaths: ['<rootDir>'],
moduleNameMapper: {
'^~/(.*)$': '<rootDir>/$1',
'^@/(.*)$': '<rootDir>/$1',
'^@shell/(.*)$': '<rootDir>/node_modules/@rancher/shell/$1',
'^@components/(.*)$': '<rootDir>/node_modules/@rancher/shell/rancher-components/$1',
// At build time @pkg/<path> is resolved to the package that imports it (see vue.config.js of @rancher/shell)
'^@pkg/harvester/(.*)$': '<rootDir>/pkg/harvester/$1',
'^@pkg/(.*)$': '<rootDir>/pkg/harvester/$1',
// clipboard-polyfill's package `exports` only declares an `import` condition, so map it to its ESM build
// (transpiled via transformIgnorePatterns below)
'^clipboard-polyfill$': '<rootDir>/node_modules/clipboard-polyfill/dist/es6/clipboard-polyfill.es6.js',
'\\.(jpe?g|png|gif|webp|svg|mp4|webm|ogg|mp3|wav|flac|aac|woff2?|eot|ttf|otf)$': '<rootDir>/svgTransform.js',
},
modulePathIgnorePatterns: ['<rootDir>/pkg/harvester/node_modules'],
testPathIgnorePatterns: ['<rootDir>/node_modules/', '<rootDir>(/.*)*/__tests__/utils/'],
transform: {
// vue3-jest, but with TypeScript registered for the Vue compiler first, see vue3JestRegisterTs.js
'^.+\\.vue$': '<rootDir>/vue3JestRegisterTs.js',
// isolatedModules: transpile only, the types are not checked while testing
'^.+\\.tsx?$': ['ts-jest', { tsconfig: { sourceMap: true, isolatedModules: true } }],
// Use the project babel config (babel.config.js, which extends the one of @rancher/shell)
'^.+\\.js$': '<rootDir>/node_modules/babel-jest',
// process mjs (e.g. vee-validate ESM) with babel-jest
'^.+\\.mjs$': '<rootDir>/node_modules/babel-jest',
'^.+\\.svg$': '<rootDir>/svgTransform.js',
},
transformIgnorePatterns: [
// @rancher/shell is shipped untranspiled, the other packages are ESM-only. @replit/codemirror-vim-core is
// required by the CommonJS build of @replit/codemirror-vim, which the shell's YamlEditor imports
'/node_modules/(?!(@rancher/shell|color|color-string|color-convert|color-name|vee-validate|@vee-validate|clipboard-polyfill|intl-messageformat|@formatjs|@replit/codemirror-vim-core)/)',
],
};
+106
View File
@@ -0,0 +1,106 @@
/* eslint-env jest */
import { createApp } from 'vue';
import { config } from '@vue/test-utils';
import i18n from '@shell/plugins/i18n';
import FloatingVue from 'floating-vue';
import { floatingVueOptions } from '@shell/plugins/floating-vue';
import vSelect from 'vue-select';
import cleanTooltipDirective from '@shell/directives/clean-tooltip';
import cleanHtmlDirective from '@shell/directives/clean-html';
import htmlStrippedAriaLabelDirective from '@shell/directives/strip-html-aria-label';
import '@shell/plugins/replaceall';
import { TextEncoder, TextDecoder } from 'util';
const vueApp = createApp({});
global.TextEncoder = TextEncoder;
global.TextDecoder = TextDecoder;
// vueApp.config.productionTip = false;
vueApp.use(i18n, { store: { dispatch() {} } });
vueApp.use(FloatingVue, floatingVueOptions);
vueApp.directive('clean-html', cleanHtmlDirective);
vueApp.directive('clean-tooltip', cleanTooltipDirective);
vueApp.component('v-select', vSelect);
config.global.components['v-select'] = vSelect;
config.global.plugins = [FloatingVue];
config.global.mocks['t'] = (key) => `%${ key }%`;
config.global.mocks['$store'] = {
getters: {},
dispatch: jest.fn(),
commit: jest.fn(),
};
config.global.directives = {
...config.global.directives,
t: {
mounted(el, binding) {
el.textContent = `%${ binding.value }%`;
},
updated(el, binding) {
el.textContent = `%${ binding.value }%`;
}
},
'clean-tooltip': cleanTooltipDirective,
'clean-html': cleanHtmlDirective,
'stripped-aria-label': htmlStrippedAriaLabelDirective,
};
config.global.stubs['t'] = { template: '<span><slot /></span>' };
/**
* Global configuration for Jest tests
*/
beforeAll(() => {
// matchMedia and getContext methods aren't included in jest's version of jsdom for us to mock
// implemented as per jest documentation: https://jestjs.io/docs/manual-mocks#mocking-methods-which-are-not-implemented-in-jsdom
Object.defineProperty(window, 'matchMedia', {
value: jest.fn().mockImplementation(() => ({
addListener: jest.fn(),
removeListener: jest.fn(),
addEventListener: jest.fn(),
removeEventListener: jest.fn()
}))
});
Object.defineProperty(HTMLCanvasElement.prototype, 'getContext', {
value: jest.fn().mockImplementation(() => ({
createLinearGradient: jest.fn(),
fillRect: jest.fn(),
getImageData: jest.fn(() => ({ data: [] }))
}))
});
Object.defineProperty(window, 'IntersectionObserver', {
writable: true,
value: jest.fn().mockImplementation(() => ({
observe: jest.fn(),
unobserve: jest.fn(),
disconnect: jest.fn(),
})),
});
});
jest.mock('@shell/composables/useI18n', () => {
return {
useI18n() {
return { t: (key, options) => `${ key }${ options ? `-${ JSON.stringify(options) }` : '' }` };
}
};
});
// eslint-disable-next-line no-console
jest.spyOn(console, 'warn').mockImplementation((warning) => warning.includes('[Vue warn]') ? null : console.log(warning));
/**
* Common initialization for each test, required for resetting states
*/
beforeEach(() => {
// jest.resetModules(); // Use this function inside your test if you need to remove any cache stored
// jest.clearAllMocks(); // Use this function inside your test if you need to reset mocks
jest.restoreAllMocks(); // Use this function inside your test if you need to reset mocks and restore existing functionality
// Mock the $extension object
// config.mocks['$extension'] = { getDynamic: () => undefined };
config.global.mocks['$store'] = { getters: { 'i18n/t': jest.fn() } };
// Overrides some components
// config.stubs['my-component'] = { template: "<div></div> "};
});
+33 -9
View File
@@ -1,13 +1,14 @@
{
"name": "harvester-ui-extension",
"version": "1.9.1-rc5",
"version": "1.10.0-dev",
"private": false,
"engines": {
"node": ">=24.0.0"
},
"dependencies": {
"@babel/plugin-transform-class-static-block": "7.29.7",
"@rancher/shell": "3.0.12-rc.7",
"@novnc/novnc": "1.7.0",
"@rancher/shell": "3.0.14",
"@vue-flow/background": "^1.3.0",
"@vue-flow/controls": "^1.1.1",
"@vue-flow/core": "^1.33.5",
@@ -27,36 +28,51 @@
"yaml": "^2.5.1"
},
"resolutions": {
"@types/node": "25.9.5",
"@novnc/novnc": "1.7.0",
"@tootallnate/once": "^2.0.1",
"@types/lodash": "4.17.25",
"@types/node": "25.3.3",
"cookie": "0.7.2",
"cronstrue": "2.59.0",
"d3-color": "3.1.0",
"**/diff2html/diff": "5.2.2",
"ejs": "3.1.10",
"follow-redirects": "1.16.0",
"glob": "7.2.3",
"glob-parent": "6.0.2",
"json5": "2.2.3",
"@types/lodash": "4.17.25",
"markdown-it": "14.3.1",
"merge": "2.1.1",
"node-forge": "1.4.0",
"nth-check": "2.1.1",
"postcss": "8.5.26",
"postcss-selector-parser": "7.1.6",
"qs": "6.16.0",
"roarr": "7.21.7",
"semver": "7.8.5",
"semver": "7.5.4",
"serialize-javascript": "7.1.3",
"uuid": "11.1.1",
"webpack-dev-server": "5.2.6",
"ws": "8.21.0",
"@vue/cli-service/html-webpack-plugin": "^5.0.0"
},
"scripts": {
"dev": "NODE_ENV=dev ./node_modules/.bin/vue-cli-service serve",
"build": "./node_modules/.bin/vue-cli-service build",
"clean": "./node_modules/@rancher/shell/scripts/clean",
"lint": "./node_modules/.bin/eslint --max-warnings 0 --ext .js,.ts,.vue .",
"lint:fix": "./node_modules/.bin/eslint --fix --max-warnings 0 --ext .js,.ts,.vue .",
"lint": "./node_modules/@rancher/shell/scripts/lint --max-warnings 0 --ext .js,.ts,.vue .",
"lint:fix": "./node_modules/@rancher/shell/scripts/lint --fix --max-warnings 0 --ext .js,.ts,.vue .",
"test": "jest --watch",
"test:ci": "NODE_OPTIONS=--max_old_space_size=8192 jest --silent",
"build-pkg": "./node_modules/@rancher/shell/scripts/build-pkg.sh",
"serve-pkgs": "./node_modules/@rancher/shell/scripts/serve-pkgs",
"publish-pkgs": "./node_modules/@rancher/shell/scripts/extension/publish",
"parse-tag-name": "./node_modules/@rancher/shell/scripts/extension/parse-tag-name",
"commitlint": "commitlint --edit",
"prepare": "husky",
"agents:generate": "./scripts/generate-agent-and-persona-mds.sh"
"agents:generate": "./scripts/generate-agent-and-persona-mds.sh",
"prelint": "npm --prefix node_modules/@rancher/shell/eslint-legacy install eslint-plugin-jest@^24 --no-save --no-audit --no-fund --legacy-peer-deps --loglevel=error",
"prelint:fix": "npm --prefix node_modules/@rancher/shell/eslint-legacy install eslint-plugin-jest@^24 --no-save --no-audit --no-fund --legacy-peer-deps --loglevel=error"
},
"devDependencies": {
"@commitlint/load": "^19.8.1",
@@ -64,6 +80,14 @@
"@commitlint/config-conventional": "^19.8.1",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^7.1.0",
"husky": "^9.1.7"
"husky": "^9.1.7",
"@types/jest": "29.5.12",
"@vue/test-utils": "2.4.6",
"@vue/vue3-jest": "29.2.6",
"babel-jest": "29.7.0",
"babel-plugin-transform-require-context": "0.1.1",
"jest": "29.7.0",
"jest-environment-jsdom": "29.7.0",
"ts-jest": "29.4.12"
}
}
@@ -128,6 +128,7 @@ export default {
try {
await proxyResource.save();
proxyResource.notifyGeneratedName?.();
this.cancel();
} catch (err) {
-8
View File
@@ -141,10 +141,6 @@ export default {
filterCategorySettings() {
return this.settings.filter((s) => {
if (!this.getFeatureEnabled(s.featureFlag)) {
return false;
}
if (this.category !== 'advanced') {
return (CATEGORY[this.category] || []).find((item) => item === s.id);
} else if (this.category === 'advanced') {
@@ -155,10 +151,6 @@ export default {
}) || [];
},
getFeatureEnabled(id) {
return id ? this.$store.getters['harvester-common/getFeatureEnabled'](id) : true;
},
getSettingOption(id) {
return HCI_ALLOWED_SETTINGS.find((setting) => setting.id === id);
},
@@ -0,0 +1,336 @@
<script setup>
import { computed, ref, watch } from 'vue';
import { useStore } from 'vuex';
import SortableTable from '@shell/components/SortableTable';
import { BadgeState } from '@components/BadgeState';
import { RcCounterBadge, RcTag } from '@components/Pill';
import { RcButton } from '@components/RcButton';
import { useI18n } from '@shell/composables/useI18n';
import { _CREATE, _EDIT, _VIEW } from '@shell/config/query-params';
import { HCI } from '../../types';
import {
AFFECTED_RESOURCES_TRUNCATE_COUNT, MESSAGE_TRUNCATE_LENGTH, activeAffectedResourceNames, affectedResourceLabel,
allAffectedResourceNames, ignoreRuleName, ignoredResourceCount, resourceIgnoredBy, severityColor
} from '../../utils/component-health';
const props = defineProps({
rows: {
type: Array,
required: true,
},
ignoreRules: {
type: Array,
default: () => [],
},
showIgnored: {
type: Boolean,
default: false,
},
// what is typed in the filter box of the table this one sits in
filterText: {
type: String,
default: '',
},
// the checks could not be loaded, so having none does not mean there are no issues
loadFailed: {
type: Boolean,
default: false,
},
});
const emit = defineEmits(['open-rule']);
const store = useStore();
const { t } = useI18n(store);
const headers = [
{
name: 'severity',
labelKey: 'harvester.dashboard.sections.componentHealth.severity',
value: 'severityRank',
sort: 'severityRank',
search: false,
width: 110,
},
{
name: 'checkName',
labelKey: 'harvester.dashboard.sections.componentHealth.check',
value: 'checkName',
sort: 'checkName',
// all that a row shows, so the filter also finds a resource hidden behind "more"
search: 'filterText',
},
{
name: 'message',
labelKey: 'harvester.dashboard.sections.componentHealth.message',
value: 'message',
search: false,
canBeVariable: true,
},
{
name: 'affectedCount',
labelKey: 'harvester.dashboard.sections.componentHealth.affectedCount',
value: 'affectedCount',
sort: 'affectedCount',
search: false,
width: 340,
canBeVariable: true,
},
];
const table = ref(null);
// this table has no filter box of its own, but it filters its rows the same way
watch([table, () => props.filterText], ([checksTable, text]) => {
if (checksTable) {
checksTable.searchQuery = text;
}
});
const canCreateRule = computed(() => {
const schema = store.getters['harvester/schemaFor'](HCI.HEALTH_IGNORE_RULE);
return !!schema?.collectionMethods?.find((method) => method.toLowerCase() === 'post');
});
// only the rule the UI made for the check, others on it are left as they are
function actionsOf(row) {
const name = ignoreRuleName(row.componentHealthName, row.checkName);
const rule = props.ignoreRules.find(({ metadata }) => metadata?.name === name);
const action = (key, icon, invoke) => ({
action: key,
label: t(`harvester.dashboard.sections.componentHealth.ignore.${ key }`),
icon: `icon ${ icon }`,
enabled: true,
invoke,
});
const open = (mode) => () => emit('open-rule', {
row, rule, mode
});
if (!rule) {
return canCreateRule.value ? [action(_CREATE, 'icon-plus', open(_CREATE))] : [];
}
const actions = [action(_VIEW, 'icon-document', open(_VIEW))];
if (rule.canUpdate) {
actions.push(action(_EDIT, 'icon-edit', open(_EDIT)));
}
if (rule.canDelete) {
actions.push({ divider: true }, action('delete', 'icon-trash', () => rule.promptRemove()));
}
return actions;
}
// the table's action menu reads them from the row, as it does on a resource
const rowsWithActions = computed(() => props.rows.map((row) => ({ ...row, availableActions: actionsOf(row) })));
// a menu that could only say there is nothing to do is left out
const hasActions = computed(() => rowsWithActions.value.some((row) => row.availableActions.length));
const expandedMessageIds = ref([]);
const expandedResourceIds = ref([]);
function affectedResourceNames(row) {
return props.showIgnored ? allAffectedResourceNames(row) : activeAffectedResourceNames(row);
}
// called from the template, where the refs are unwrapped, so the array is changed in place
function toggleId(list, id) {
const index = list.indexOf(id);
if (index === -1) {
list.push(id);
} else {
list.splice(index, 1);
}
}
function isMessageTruncated(message) {
return !!message && message.length > MESSAGE_TRUNCATE_LENGTH;
}
function displayedMessage(row, message) {
return expandedMessageIds.value.includes(row.id) || !isMessageTruncated(message) ? message : message.slice(0, MESSAGE_TRUNCATE_LENGTH);
}
function visibleAffectedResourceNames(row) {
const names = affectedResourceNames(row);
return expandedResourceIds.value.includes(row.id) ? names : names.slice(0, AFFECTED_RESOURCES_TRUNCATE_COUNT);
}
function remainingAffectedResourcesCount(row) {
return Math.max(affectedResourceNames(row).length - AFFECTED_RESOURCES_TRUNCATE_COUNT, 0);
}
function isResourceIgnored(row, name) {
return row.ignored || !!resourceIgnoredBy(row, name);
}
// the ignored resources that are left out of the list
function hiddenIgnoredCount(row) {
return props.showIgnored ? 0 : ignoredResourceCount(row);
}
</script>
<template>
<div
v-if="!rows.length"
class="text-muted"
>
{{ t(`harvester.dashboard.sections.componentHealth.${ loadFailed ? 'checksNotLoaded' : 'noIssues' }`) }}
</div>
<SortableTable
v-else
ref="table"
:rows="rowsWithActions"
:headers="headers"
key-field="id"
:search="false"
:table-actions="false"
:row-actions="hasActions"
:paging="true"
:rows-per-page="10"
default-sort-by="severity"
>
<template #cell:severity="{row}">
<BadgeState
:color="severityColor(row.severity)"
:label="row.severity"
/>
</template>
<template #cell:checkName="{row, value}">
<span :class="{ 'text-muted': row.ignored }">
{{ value }}
<template v-if="row.ignored">
({{ t('harvester.dashboard.sections.componentHealth.ignore.ignored') }})
</template>
</span>
</template>
<template #cell:message="{row, value}">
<span :class="{ 'text-muted': row.ignored }">
{{ displayedMessage(row, value) }}
<RcButton
v-if="isMessageTruncated(value)"
variant="link"
size="small"
class="compact-link"
:aria-expanded="expandedMessageIds.includes(row.id)"
@click="toggleId(expandedMessageIds, row.id)"
>
{{ expandedMessageIds.includes(row.id) ? t('generic.showLess') : t('generic.showMore') }}
</RcButton>
</span>
</template>
<template #cell:affectedCount="{row, value}">
<div
v-if="affectedResourceNames(row).length"
class="affected-resources"
>
<div class="affected-title">
<span class="text-label">{{ affectedResourceLabel(row, store) }}</span>
<RcCounterBadge
:count="value || allAffectedResourceNames(row).length"
type="inactive"
/>
<span class="api-version text-muted">{{ row.affectedResources.apiVersion }}</span>
</div>
<div class="affected-names">
<RcTag
v-for="name in visibleAffectedResourceNames(row)"
:key="name"
class="affected-name"
:class="{ ignored: isResourceIgnored(row, name) }"
type="inactive"
:disabled="isResourceIgnored(row, name)"
>
<span class="name">{{ name }}</span>
<!-- when all of the check is ignored its name says so -->
<span v-if="!row.ignored && isResourceIgnored(row, name)">
({{ t('harvester.dashboard.sections.componentHealth.ignore.ignored') }})
</span>
</RcTag>
</div>
<RcButton
v-if="remainingAffectedResourcesCount(row)"
variant="link"
size="small"
class="compact-link"
:aria-expanded="expandedResourceIds.includes(row.id)"
@click="toggleId(expandedResourceIds, row.id)"
>
{{ expandedResourceIds.includes(row.id) ? t('generic.showLess') : t('generic.plusMore', { n: remainingAffectedResourcesCount(row) }) }}
</RcButton>
<span
v-if="hiddenIgnoredCount(row)"
class="hidden-ignored text-muted"
>
{{ t('harvester.dashboard.sections.componentHealth.ignore.plusIgnored', { n: hiddenIgnoredCount(row) }) }}
</span>
</div>
<span v-else>
{{ t('harvester.dashboard.sections.componentHealth.noAffectedResources') }}
</span>
</template>
</SortableTable>
</template>
<style lang="scss" scoped>
// these sit next to text, so they line up with it
.compact-link {
--rc-button-padding: 0;
}
.affected-resources {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 4px;
padding: 4px 0;
}
.affected-title {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px 8px;
margin-bottom: 4px;
}
.api-version {
font-size: 12px;
}
// the same size as the "+ N more" link above it
.hidden-ignored {
font-size: 12px;
}
.affected-names {
display: flex;
flex-wrap: wrap;
gap: 4px;
}
.affected-name {
max-width: 100%;
font-size: 12px;
// a long name wraps, so none is ever cut off
.name {
min-width: 0;
overflow-wrap: anywhere;
}
// the ones that count are filled, the ignored ones are only outlined
&.rc-tag.ignored {
background: transparent;
border-style: dashed;
border-color: var(--rc-disabled-text-color);
}
}
</style>
@@ -0,0 +1,342 @@
<script setup>
import { computed, onMounted, ref } from 'vue';
import { HCI } from '../../types';
import { useStore } from 'vuex';
import { useI18n } from '@shell/composables/useI18n';
import SortableTable from '@shell/components/SortableTable';
import { exceptionToErrorsArray } from '@shell/utils/error';
import Banner from '@components/Banner/Banner.vue';
import { BadgeState } from '@components/BadgeState';
import { Checkbox } from '@components/Form/Checkbox';
import { RcButton } from '@components/RcButton';
import { useModal } from '@components/RcModal';
import ComponentChecksTable from './ComponentChecksTable.vue';
import IgnoreRuleModal from './IgnoreRuleModal.vue';
import {
COMPONENT_HEALTH_SEVERITIES, HEALTH_SUMMARY_SEVERITY_RANK, activeAffectedResourceNames, affectedResourceKind,
affectedResourceLabel, allAffectedResourceNames, componentOf, healthSummarySeverity, ignoredCounts, severityColor
} from '../../utils/component-health';
const store = useStore();
const { t } = useI18n(store);
const table = ref(null);
const loading = ref(true);
const lists = {
healthSummaries: ref([]),
componentHealths: ref([]),
ignoreRules: ref([]),
};
const { healthSummaries, componentHealths, ignoreRules } = lists;
// the lists that could not be loaded, with why
const loadErrors = ref({});
const headers = [
{
name: 'severity',
labelKey: 'harvester.dashboard.sections.healthSummary.severity',
value: 'severityRank',
sort: 'severityRank',
search: 'severity',
width: 110,
},
{
name: 'component',
labelKey: 'harvester.dashboard.sections.healthSummary.component',
value: 'component',
sort: 'component',
// the table's filter only looks at its own rows, the checks are in the sub-rows
search: ['component', 'checksFilterText'],
},
{
align: 'right',
name: 'errorCount',
labelKey: 'harvester.dashboard.sections.healthSummary.errorCount',
value: 'errorCount',
sort: 'errorCount',
search: false,
width: 120,
},
{
align: 'right',
name: 'warningCount',
labelKey: 'harvester.dashboard.sections.healthSummary.warningCount',
value: 'warningCount',
sort: 'warningCount',
search: false,
width: 120,
},
];
const {
open: openRuleModal, isOpen: ruleModalOpen, payload: ruleToOpen, modal: ruleModal
} = useModal();
const showIgnored = ref(false);
const filterText = computed(() => table.value?.searchQuery || '');
const checks = computed(() => {
const result = [];
(componentHealths.value || []).forEach((componentHealth) => {
const component = componentOf(componentHealth);
const statusChecks = componentHealth?.status?.checks || {};
Object.entries(statusChecks).forEach(([checkName, check]) => {
result.push({
id: `${ componentHealth.id }/${ checkName }`,
component,
componentHealthName: componentHealth.metadata?.name,
checkName,
ignored: !!check.ignored,
severity: check.severity,
// the table sorts on a row property, the severities are not in alphabetical order
severityRank: COMPONENT_HEALTH_SEVERITIES.indexOf(check.severity),
message: check.message,
affectedCount: check.affectedCount,
affectedResources: check.affectedResources,
});
});
});
return result;
});
const shownChecks = computed(() => checks.value.filter((check) => showIgnored.value || !check.ignored).map((check) => ({
...check,
filterText: [
check.component,
check.severity,
check.checkName,
check.message,
check.affectedResources?.apiVersion,
affectedResourceKind(check),
affectedResourceLabel(check, store),
...(showIgnored.value ? allAffectedResourceNames(check) : activeAffectedResourceNames(check)),
].join(' ').toLowerCase(),
})));
const ignored = computed(() => ignoredCounts(checks.value));
const hasIgnored = computed(() => ignored.value.checks + ignored.value.resources > 0);
// says what turning it on brings back, the same whether it is on or off
const showIgnoredLabel = computed(() => {
const counts = [
ignored.value.checks && t('harvester.dashboard.sections.componentHealth.ignoredChecks', { count: ignored.value.checks }),
ignored.value.resources && t('harvester.dashboard.sections.componentHealth.ignoredResources', { count: ignored.value.resources }),
].filter(Boolean).join(', ');
return t('harvester.dashboard.sections.componentHealth.showIgnored', { counts });
});
const rows = computed(() => {
const result = [];
(healthSummaries.value || []).forEach((healthSummary) => {
const components = healthSummary?.status?.components || {};
Object.entries(components).forEach(([component, counts]) => {
const componentChecks = shownChecks.value.filter((check) => check.component === component);
const row = {
id: `${ healthSummary.id }/${ component }`,
component,
errorCount: counts?.errorCount || 0,
warningCount: counts?.warningCount || 0,
checksFilterText: componentChecks.map((check) => check.filterText).join(' '),
checks: componentChecks,
};
row.severity = healthSummarySeverity(row);
// the table sorts on a row property, so the severity has to be on the row
row.severityRank = HEALTH_SUMMARY_SEVERITY_RANK[row.severity];
result.push(row);
});
});
return result;
});
onMounted(async() => {
const types = {
healthSummaries: HCI.HEALTH_SUMMARY,
componentHealths: HCI.COMPONENT_HEALTH,
};
if (store.getters['harvester/schemaFor'](HCI.HEALTH_IGNORE_RULE)) {
types.ignoreRules = HCI.HEALTH_IGNORE_RULE;
}
// a list that fails does not stop the others from showing
await Promise.all(Object.entries(types).map(async([key, type]) => {
try {
lists[key].value = await store.dispatch('harvester/findAll', { type });
} catch (err) {
loadErrors.value[key] = exceptionToErrorsArray(err).join(', ');
}
}));
loading.value = false;
});
// the table has these from shell 3.0.15, in the props of its #header-right slot, so they can go with that bump
function expandAll() {
table.value.expanded = Object.fromEntries(rows.value.map((row) => [row.id, true]));
}
function collapseAll() {
table.value.expanded = {};
}
</script>
<template>
<Banner
v-for="(error, key) in loadErrors"
:key="key"
color="error"
:label="t(`harvester.dashboard.sections.componentHealth.loadFailed.${ key }`, { error })"
/>
<SortableTable
ref="table"
:rows="rows"
:headers="headers"
:loading="loading"
key-field="id"
:table-actions="false"
:row-actions="false"
:paging="true"
:rows-per-page="10"
:sub-rows="true"
:sub-expandable="true"
:sub-expand-column="true"
default-sort-by="severity"
>
<template #header-left>
<div
v-if="hasIgnored"
class="show-ignored"
>
<Checkbox
v-model:value="showIgnored"
type="checkbox"
:label="showIgnoredLabel"
/>
</div>
</template>
<template #header-right>
<div
v-if="rows.length"
class="expand-actions"
>
<RcButton
variant="link"
size="small"
@click="expandAll"
>
{{ t('harvester.dashboard.sections.healthSummary.expandAll') }}
</RcButton>
<RcButton
variant="link"
size="small"
@click="collapseAll"
>
{{ t('harvester.dashboard.sections.healthSummary.collapseAll') }}
</RcButton>
</div>
</template>
<template #cell:severity="{row}">
<BadgeState
:color="severityColor(row.severity)"
:label="row.severity"
/>
</template>
<!-- the table's chevron can't take the keyboard focus, this opens the row from the keyboard -->
<template #cell:component="{row}">
<RcButton
variant="link"
class="component-name"
:aria-expanded="!!table?.isExpanded(row)"
@click="table.toggleExpand(row)"
>
{{ row.component }}
</RcButton>
</template>
<template #sub-row="{row, fullColspan}">
<tr class="sub-row">
<td :colspan="fullColspan">
<ComponentChecksTable
class="sub-table"
:rows="row.checks"
:ignore-rules="ignoreRules"
:show-ignored="showIgnored"
:filter-text="filterText"
:load-failed="!!loadErrors.componentHealths"
@open-rule="openRuleModal"
/>
</td>
</tr>
</template>
</SortableTable>
<!-- mounted each time it opens, so the form always starts over -->
<IgnoreRuleModal
v-if="ruleModalOpen"
v-bind="ruleToOpen"
:modal="ruleModal"
/>
</template>
<style lang="scss" scoped>
// the filter box in the same row is taller, this lines up with it
.show-ignored {
display: flex;
align-items: center;
height: 100%;
}
.expand-actions {
display: flex;
align-items: center;
gap: 8px;
}
// a button is taller than the table's rows
.component-name {
--rc-button-padding: 0;
&.rc-button.btn-medium:not(.btn-sm) {
min-height: 0;
line-height: inherit;
}
}
// the shell has this look for a table in a sub-row from 3.0.15, this can go with that bump
.sub-row {
background-color: var(--body-bg) !important;
> td:first-child {
padding-left: 0;
padding-right: 0;
}
.sub-table {
padding: 16px 32px;
}
:deep(.sortable-table) {
border: 0;
border-radius: 0;
outline: 0;
}
:deep(thead tr:hover) {
background-color: var(--body-bg);
}
:deep(thead th) {
font-weight: 600;
}
:deep(tbody tr) {
border-bottom: 0;
}
}
</style>
@@ -0,0 +1,320 @@
<script setup>
import { computed, ref } from 'vue';
import { useStore } from 'vuex';
import dayjs from 'dayjs';
import isEqual from 'lodash/isEqual';
import Banner from '@components/Banner/Banner.vue';
import { LabeledInput } from '@components/Form/LabeledInput';
import { RadioGroup } from '@components/Form/Radio';
import { RcButton } from '@components/RcButton';
import { RcHeading } from '@components/RcHeading';
import { RcModal } from '@components/RcModal';
import LabelValue from '@shell/components/LabelValue';
import LabeledSelect from '@shell/components/form/LabeledSelect';
import { useI18n } from '@shell/composables/useI18n';
import { _CREATE, _VIEW } from '@shell/config/query-params';
import { exceptionToErrorsArray } from '@shell/utils/error';
import { dateTimeFormat } from '@shell/utils/time';
import { HCI } from '../../types';
import { IGNORE_DURATION_DAYS, IGNORE_RULE_SOURCE_LABEL, allAffectedResourceNames, ignoreRuleName } from '../../utils/component-health';
const props = defineProps({
row: {
type: Object,
required: true,
},
// empty when the rule is created
rule: {
type: Object,
default: null,
},
mode: {
type: String,
default: _CREATE,
},
// `show` and the `close` handler, from whoever owns this modal's visibility
modal: {
type: Object,
required: true,
},
});
const store = useStore();
const { t } = useI18n(store);
const isView = computed(() => props.mode === _VIEW);
const ruleResources = props.rule?.spec?.resources || [];
const expiresAt = props.rule?.spec?.expiresAt;
const hasExpired = !!expiresAt && !dayjs(expiresAt).isAfter(dayjs());
// a rule can still list resources that are no longer affected
const resourceOptions = computed(() => [...new Set([...allAffectedResourceNames(props.row), ...ruleResources])]);
// a rule that lists no resource ignores the entire check
const chosenScope = ref(props.rule && !ruleResources.length ? 'check' : null);
const scope = computed({
get: () => chosenScope.value || (resourceOptions.value.length ? 'resources' : 'check'),
set: (value) => {
chosenScope.value = value;
},
});
// null selects every resource, the ones that are not selected are kept visible
const selected = ref(ruleResources.length ? ruleResources : null);
// a rule keeps the expiry it has until another duration is chosen
const duration = ref(props.rule ? null : 'days7');
const reason = ref(props.rule?.spec?.reason || '');
const errors = ref([]);
const saving = ref(false);
const selectedResources = computed(() => {
return selected.value === null ? resourceOptions.value : resourceOptions.value.filter((name) => selected.value.includes(name));
});
const scopeOptions = computed(() => [
{ label: t('harvester.dashboard.sections.componentHealth.ignore.scopeCheck'), value: 'check' },
{ label: t('harvester.dashboard.sections.componentHealth.ignore.scopeResources'), value: 'resources' },
]);
const durationOptions = computed(() => Object.keys(IGNORE_DURATION_DAYS).map((key) => ({
label: t(`harvester.dashboard.sections.componentHealth.ignore.${ key }`),
value: key,
})));
// worked out once for each choice, so the date shown is the date saved
const newExpiresAt = computed(() => {
const days = IGNORE_DURATION_DAYS[duration.value];
return days ? dayjs().add(days, 'day').toISOString() : undefined;
});
const spec = computed(() => {
const out = {
componentHealth: props.row.componentHealthName,
checkKey: props.row.checkName,
};
// the rule only lists the selected resources, so it does not swallow the ones coming later
if (scope.value === 'resources') {
out.resources = selectedResources.value;
}
const expiry = duration.value ? newExpiresAt.value : expiresAt;
if (expiry) {
out.expiresAt = expiry;
}
if (reason.value) {
out.reason = reason.value;
}
return out;
});
// what the form changes, in an order that does not depend on the options
const editable = (ruleSpec) => ({
resources: [...(ruleSpec?.resources || [])].sort(),
expiresAt: ruleSpec?.expiresAt || '',
reason: ruleSpec?.reason || '',
});
const hasChanges = computed(() => !props.rule || !isEqual(editable(spec.value), editable(props.rule.spec)));
// a rule that lists no resource would ignore the entire check
const canSave = computed(() => (scope.value === 'check' || selectedResources.value.length > 0) && hasChanges.value);
// saving something else on an expired rule leaves it expired
const staysExpired = computed(() => hasExpired && !duration.value && hasChanges.value);
const currentExpiry = computed(() => {
if (!expiresAt) {
return t('harvester.dashboard.sections.componentHealth.ignore.neverExpires');
}
return t(`harvester.dashboard.sections.componentHealth.ignore.${ hasExpired ? 'expiredOn' : 'expiresOn' }`, { date: dateTimeFormat(expiresAt, store) });
});
const newExpiry = computed(() => {
if (!newExpiresAt.value) {
return t('harvester.dashboard.sections.componentHealth.ignore.willNeverExpire');
}
return t('harvester.dashboard.sections.componentHealth.ignore.willExpireOn', { date: dateTimeFormat(newExpiresAt.value, store) });
});
function close() {
// stays open while the rule is saved, so a failure can still be shown
if (!saving.value) {
props.modal.onClose();
}
}
async function save() {
errors.value = [];
saving.value = true;
try {
const rule = props.rule ? await store.dispatch('harvester/clone', { resource: props.rule }) : await store.dispatch('harvester/create', {
type: HCI.HEALTH_IGNORE_RULE,
metadata: {
name: ignoreRuleName(props.row.componentHealthName, props.row.checkName),
labels: { [IGNORE_RULE_SOURCE_LABEL]: 'user' },
},
});
rule.spec = spec.value;
await rule.save();
store.dispatch('growl/success', {
title: t('generic.notification.title.succeed'),
message: t(`harvester.dashboard.sections.componentHealth.ignore.${ props.rule ? 'updated' : 'created' }`, { name: props.row.checkName }),
}, { root: true });
saving.value = false;
close();
} catch (err) {
errors.value = exceptionToErrorsArray(err?.data || err);
saving.value = false;
}
}
</script>
<template>
<!-- Not v-bind="modal": closing goes through close(), which refuses while the rule is saved -->
<RcModal
:show="modal.show"
:title="t(`harvester.dashboard.sections.componentHealth.ignore.${ mode }`)"
data-testid="component-health-ignore-modal"
@close="close"
@primary-action="save"
>
<div class="row">
<div class="col span-6">
<LabelValue
:name="t('harvester.dashboard.sections.componentHealth.component')"
:value="row.component"
/>
</div>
<div class="col span-6">
<LabelValue
:name="t('harvester.dashboard.sections.componentHealth.check')"
:value="row.checkName"
/>
</div>
</div>
<div v-if="resourceOptions.length">
<RcHeading :size="4">
{{ t('harvester.dashboard.sections.componentHealth.ignore.scope') }}
</RcHeading>
<RadioGroup
v-model:value="scope"
name="ignore-scope"
:aria-label="t('harvester.dashboard.sections.componentHealth.ignore.scope')"
:mode="mode"
:options="scopeOptions"
/>
<div
v-if="scope === 'resources'"
class="ignore-resources"
>
<LabeledSelect
:value="selectedResources"
:label="t('harvester.dashboard.sections.componentHealth.ignore.resources')"
:mode="mode"
:options="resourceOptions"
:multiple="true"
:close-on-select="false"
:clearable="false"
:required="!isView"
@update:value="selected = $event"
/>
</div>
</div>
<div>
<RcHeading :size="4">
{{ t('harvester.dashboard.sections.componentHealth.ignore.duration') }}
</RcHeading>
<p
v-if="rule"
class="current-expiry mb-10"
data-testid="component-health-ignore-current-expiry"
>
{{ currentExpiry }}
</p>
<template v-if="!isView">
<RadioGroup
v-model:value="duration"
name="ignore-duration"
:aria-label="t('harvester.dashboard.sections.componentHealth.ignore.duration')"
:mode="mode"
:options="durationOptions"
:row="true"
/>
<p
v-if="duration"
class="new-expiry text-muted"
data-testid="component-health-ignore-new-expiry"
>
{{ newExpiry }}
</p>
</template>
</div>
<LabeledInput
v-model:value="reason"
:label="t('harvester.dashboard.sections.componentHealth.ignore.reason')"
:placeholder="isView ? '' : t('harvester.dashboard.sections.componentHealth.ignore.reasonPlaceholder')"
:mode="mode"
/>
<Banner
v-for="(err, i) in errors"
:key="i"
class="m-0"
color="error"
:label="err"
/>
<Banner
v-if="staysExpired"
class="m-0"
color="warning"
data-testid="component-health-ignore-stays-expired"
:label="t('harvester.dashboard.sections.componentHealth.ignore.staysExpired', { date: dateTimeFormat(expiresAt, store) })"
/>
<template
v-if="isView"
#actions="{ close: closeModal }"
>
<RcButton
variant="primary"
size="large"
data-testid="component-health-ignore-close"
@click="closeModal"
>
{{ t('generic.close') }}
</RcButton>
</template>
<template
v-else
#primary-action="{ primaryAction }"
>
<RcButton
variant="primary"
size="large"
:disabled="!canSave || saving"
:aria-busy="saving"
data-testid="component-health-ignore-confirm"
@click="primaryAction"
>
{{ t(rule ? 'generic.save' : 'generic.create') }}
</RcButton>
</template>
</RcModal>
</template>
<style lang="scss" scoped>
// lines the field up with the radio's label
.ignore-resources {
margin: 10px 0 0 19px;
}
</style>
@@ -0,0 +1,912 @@
import { mount as vtuMount, flushPromises } from '@vue/test-utils';
import { createStore } from 'vuex';
import Banner from '@components/Banner/Banner.vue';
import { BadgeState } from '@components/BadgeState';
import { Checkbox } from '@components/Form/Checkbox';
import { LabeledInput } from '@components/Form/LabeledInput';
import { RadioGroup } from '@components/Form/Radio';
import { RcCounterBadge, RcTag } from '@components/Pill';
import { RcModal } from '@components/RcModal';
import LabeledSelect from '@shell/components/form/LabeledSelect';
import { HCI } from '../../../types';
import { affectedResourceLabel, ignoreRuleName, ignoredCounts, totalErrorCount } from '../../../utils/component-health';
import HealthSummaryTable from '../HealthSummaryTable.vue';
import ComponentChecksTable from '../ComponentChecksTable.vue';
import IgnoreRuleModal from '../IgnoreRuleModal.vue';
jest.mock('focus-trap', () => ({
createFocusTrap: jest.fn(() => ({
activate: jest.fn(),
deactivate: jest.fn(),
})),
}));
const TYPES = {
healthSummaries: HCI.HEALTH_SUMMARY,
componentHealths: HCI.COMPONENT_HEALTH,
ignoreRules: HCI.HEALTH_IGNORE_RULE,
};
const saveRule = jest.fn();
const newRule = { save: saveRule };
const editedRule = { save: saveRule };
const createRule = jest.fn(() => newRule);
const cloneRule = jest.fn(() => editedRule);
let store;
// resources are fetched by the components themselves, so serve them from a mocked store
const opts = (props = {}) => {
store = createStore({
getters: {
'i18n/t': () => (k) => k,
'i18n/exists': () => () => true,
'prefs/get': () => () => false,
currentProduct: () => ({ inStore: 'harvester' }),
'harvester/schemaFor': () => (type) => (props.noSchemaFor === type ? null : { collectionMethods: props.collectionMethods || ['GET', 'POST'] }),
'type-map/labelFor': () => (schema, count) => `label of ${ count }`,
},
actions: {
'growl/success': jest.fn(),
'harvester/findAll': (_, { type }) => {
const key = Object.keys(TYPES).find((k) => TYPES[k] === type);
props.onFindAll?.(type);
return props.failing === key ? Promise.reject(new Error('failed')) : props[key] || [];
},
'harvester/create': createRule,
'harvester/clone': cloneRule,
}
});
return { global: { plugins: [store], stubs: { teleport: true } } };
};
const toggleExpand = jest.fn();
// renders the summary rows with every sub-row open, and the checks of each sub-row
const summaryTable = {
props: ['rows', 'headers'],
data() {
return { searchQuery: '', expanded: {} };
},
methods: { toggleExpand, isExpanded: () => false },
template: `<div>
<slot name="header-left" />
<slot name="header-right" />
<div class="summary">{{ rows.map(r => r.id + ":" + r.severityRank).join(",") }}</div>
<div v-for="row in rows" :key="row.id" class="name"><slot name="cell:component" :row="row" /></div>
<div v-for="row in rows" :key="row.id" :class="'sub-' + row.component"><slot name="sub-row" :row="row" :fullColspan="1" /></div>
</div>`,
};
const checksTable = {
props: ['rows', 'headers', 'rowActions'],
data() {
return { searchQuery: '' };
},
template: '<div class="checks">{{ rows.map(r => r.id + ":" + r.severityRank).join(",") }}</div>',
};
const mountSummary = async(props) => {
const base = opts(props);
const w = vtuMount(HealthSummaryTable, { ...base, global: { ...base.global, stubs: { ...base.global.stubs, SortableTable: summaryTable } } });
await flushPromises();
return w;
};
const mountChecks = (props, stubs = {}, storeProps = {}) => {
const base = opts(storeProps);
return vtuMount(ComponentChecksTable, {
...base,
props,
global: {
...base.global,
stubs: {
...base.global.stubs, SortableTable: checksTable, ...stubs
}
},
});
};
const summaryOf = (components) => ({ id: 's', status: { components } });
const healthOf = (id, component, checks) => ({
id, metadata: { name: id, labels: { 'health.harvesterhci.io/component': component } }, status: { checks }
});
const CHECK = {
id: 'h/a',
component: 'x',
componentHealthName: 'h',
checkName: 'a',
affectedResources: { kind: 'VirtualMachine', names: { one: {}, two: {} } },
};
const IN_A_WEEK = new Date(Date.now() + (7 * 24 * 3600 * 1000)).toISOString();
const LAST_WEEK = new Date(Date.now() - (7 * 24 * 3600 * 1000)).toISOString();
// named the way the UI names the rule of a check, unless `extra` says otherwise
const ruleOf = (spec = {}, extra = {}) => {
const fullSpec = {
componentHealth: 'h', checkKey: 'a', ...spec
};
return {
metadata: { name: ignoreRuleName(fullSpec.componentHealth, fullSpec.checkKey) },
spec: fullSpec,
canUpdate: true,
canDelete: true,
promptRemove: jest.fn(),
...extra,
};
};
const actionsOf = (props = {}, storeProps = {}) => {
const w = mountChecks({ rows: [CHECK], ...props }, {}, storeProps);
const actions = w.findComponent(checksTable).props('rows')[0].availableActions;
return {
w,
actions,
keys: actions.map((action) => (action.divider ? '-' : action.action)),
invoke: (key) => actions.find((action) => action.action === key).invoke(),
};
};
const mountRuleModal = ({
rule, mode, save = () => {}, row = CHECK
} = {}) => {
createRule.mockClear();
cloneRule.mockClear();
saveRule.mockReset().mockImplementation(save);
delete newRule.spec;
delete editedRule.spec;
const onClose = jest.fn();
const w = vtuMount(IgnoreRuleModal, {
...opts(),
props: {
row, rule, mode, modal: { show: true, onClose }
},
});
return {
w,
onClose,
confirm: () => w.find('[data-testid="component-health-ignore-confirm"]'),
duration: () => w.findAllComponents(RadioGroup).find((group) => group.props('name') === 'ignore-duration'),
currentExpiry: () => w.find('[data-testid="component-health-ignore-current-expiry"]'),
newExpiry: () => w.find('[data-testid="component-health-ignore-new-expiry"]'),
warning: () => w.findAllComponents(Banner).find((banner) => banner.props('color') === 'warning'),
};
};
describe('health components', () => {
it('ranks the health summary rows by severity', async() => {
const w = await mountSummary({
healthSummaries: [{
id: 'a',
status: {
components: {
x: { errorCount: 1 }, y: {}, z: { warningCount: 2 }
}
}
}]
});
expect(w.find('.summary').text()).toBe('a/x:0,a/y:2,a/z:1');
});
it('opens a row from the component name, which takes the keyboard focus', async() => {
toggleExpand.mockClear();
const w = await mountSummary({ healthSummaries: [summaryOf({ x: {} })] });
const name = w.find('.name button');
expect(name.text()).toBe('x');
expect(name.attributes('aria-expanded')).toBe('false');
await name.trigger('click');
expect(toggleExpand.mock.calls.map(([row]) => row.component)).toStrictEqual(['x']);
});
it('shows the checks of a component in its sub-row', async() => {
const w = await mountSummary({
healthSummaries: [summaryOf({ x: { errorCount: 1 }, y: { warningCount: 1 } })],
componentHealths: [
healthOf('h1', 'x', { a: { severity: 'Error' } }),
healthOf('h2', 'y', { b: { severity: 'Warning' } }),
healthOf('h3', 'x', { c: { severity: 'Error' } }),
],
});
const rowsOf = (component) => w.findAllComponents(ComponentChecksTable).find((c) => c.element.closest(`.sub-${ component }`)).props('rows').map((r) => r.id);
expect(rowsOf('x')).toStrictEqual(['h1/a', 'h3/c']);
expect(rowsOf('y')).toStrictEqual(['h2/b']);
});
it('ranks the checks Error, Warning, Info', async() => {
const w = await mountSummary({
healthSummaries: [summaryOf({ x: { errorCount: 1 } })],
componentHealths: [healthOf('h', 'x', {
a: { severity: 'Info' }, b: { severity: 'Error' }, c: { severity: 'Warning' }
})],
});
expect(w.findComponent(ComponentChecksTable).props('rows').map((r) => `${ r.id }:${ r.severityRank }`)).toStrictEqual(['h/a:2', 'h/b:0', 'h/c:1']);
});
it('gives what was typed in the outer table to the table of checks', async() => {
const w = await mountSummary({
healthSummaries: [summaryOf({ x: { errorCount: 1 } })],
componentHealths: [healthOf('h', 'x', { a: { severity: 'Error' } })],
});
await w.findComponent(summaryTable).setData({ searchQuery: 'warn' });
expect(w.findComponent(ComponentChecksTable).props('filterText')).toBe('warn');
});
it('lets the table of checks filter its own rows', async() => {
const w = mountChecks({ rows: [CHECK], filterText: 'warn' });
const table = w.findComponent(checksTable);
await flushPromises();
expect(table.vm.searchQuery).toBe('warn');
await w.setProps({ filterText: 'error' });
expect(table.vm.searchQuery).toBe('error');
expect(table.props('headers').filter((header) => header.search !== false).map((header) => header.search)).toStrictEqual(['filterText']);
});
it('calls a row with errors Error, and only its errors match that word', async() => {
const w = await mountSummary({
healthSummaries: [summaryOf({ x: { errorCount: 1 } })],
componentHealths: [healthOf('h', 'x', { a: { severity: 'Error' }, b: { severity: 'Warning' } })],
});
const checks = w.findComponent(ComponentChecksTable).props('rows');
expect(w.findComponent(summaryTable).props('rows')[0].severity).toBe('Error');
expect(checks.map((r) => r.filterText.includes('error'))).toStrictEqual([true, false]);
});
it('does not search the count columns', async() => {
const w = await mountSummary({ healthSummaries: [summaryOf({ x: {} })] });
const { headers } = w.findComponent(summaryTable).props();
expect(headers.filter((header) => header.search !== false).map((header) => header.name)).toStrictEqual(['severity', 'component']);
});
it('gives the table filter what a sub-row shows', async() => {
const w = await mountSummary({
healthSummaries: [summaryOf({ x: { warningCount: 1 } })],
componentHealths: [healthOf('h', 'x', {
a: {
severity: 'Warning',
message: 'Some Message',
affectedResources: {
apiVersion: 'kubevirt.io/v1', kind: 'VirtualMachine', names: { 'vm-shown': {}, 'vm-hidden': { ignored: true } }
},
}
})],
});
const filterText = () => w.findComponent(summaryTable).props('rows')[0].checksFilterText;
['x', 'warning', 'a', 'some message', 'kubevirt.io/v1', 'virtualmachine', 'label of', 'vm-shown'].forEach((text) => expect(filterText()).toContain(text));
expect(filterText()).not.toContain('vm-hidden');
await w.findComponent(Checkbox).vm.$emit('update:value', true);
expect(filterText()).toContain('vm-hidden');
});
it('leaves the rows as they are when filtering', async() => {
toggleExpand.mockClear();
const w = await mountSummary({
healthSummaries: [summaryOf({ x: { errorCount: 1 }, y: { warningCount: 1 } })],
componentHealths: [healthOf('h1', 'x', { a: { severity: 'Error' } }), healthOf('h2', 'y', { b: { severity: 'Warning' } })],
});
const table = w.findComponent(summaryTable);
await table.setData({ searchQuery: 'warning' });
await table.setData({ searchQuery: '' });
expect(toggleExpand).not.toHaveBeenCalled();
expect(table.vm.expanded).toStrictEqual({});
});
it('expands and collapses all the rows', async() => {
const w = await mountSummary({ healthSummaries: [summaryOf({ x: {}, y: {} })] });
const table = w.findComponent(summaryTable);
const [expand, collapse] = w.findAll('.expand-actions button');
await expand.trigger('click');
expect(table.vm.expanded).toStrictEqual({ 's/x': true, 's/y': true });
await collapse.trigger('click');
expect(table.vm.expanded).toStrictEqual({});
});
it('only offers to expand and collapse when there are rows', async() => {
const w = await mountSummary({});
expect(w.find('.expand-actions').exists()).toBe(false);
});
it('only offers the ignored checks when there are some', async() => {
const w = await mountSummary({
healthSummaries: [summaryOf({ x: { warningCount: 1 } })],
componentHealths: [healthOf('h', 'x', { a: { severity: 'Error', ignored: true }, b: { severity: 'Warning' } })],
});
const shownRows = () => w.findComponent(ComponentChecksTable).props('rows').map((r) => r.id);
expect(shownRows()).toStrictEqual(['h/b']);
expect(w.text()).toContain('showIgnored');
await w.findComponent(Checkbox).vm.$emit('update:value', true);
expect(shownRows()).toStrictEqual(['h/a', 'h/b']);
const clean = await mountSummary({
healthSummaries: [summaryOf({ x: { warningCount: 1 } })],
componentHealths: [healthOf('h', 'x', { b: { severity: 'Warning' } })],
});
expect(clean.text()).not.toContain('showIgnored');
});
it('expands a long message', async() => {
const message = 'x'.repeat(150);
const table = { props: ['rows'], template: '<div><slot name="cell:message" :row="rows[0]" :value="rows[0].message" /></div>' };
const w = mountChecks({ rows: [{ ...CHECK, message }] }, { SortableTable: table });
expect(w.text()).not.toContain(message);
expect(w.text()).toContain('generic.showMore');
await w.find('button.variant-link').trigger('click');
expect(w.text()).toContain(message);
expect(w.text()).toContain('generic.showLess');
});
it('shows the resources as chips, under what the UI calls them and their full count', () => {
const table = { props: ['rows'], template: '<div><slot name="cell:affectedCount" :row="rows[0]" :value="rows[0].affectedCount" /></div>' };
const row = {
...CHECK,
affectedCount: 7,
affectedResources: {
apiVersion: 'longhorn.io/v1beta2', kind: 'Volume', names: { one: { ignored: true, ignoredBy: 'r' }, two: {} }
}
};
const w = mountChecks({ rows: [row] }, { SortableTable: table });
expect(w.find('.affected-title .text-label').text()).toBe('label of 7');
expect(w.find('.affected-title .api-version').text()).toBe('longhorn.io/v1beta2');
expect(w.findComponent(RcCounterBadge).props('count')).toBe(7);
expect(w.findAllComponents(RcTag).map((tag) => tag.text())).toStrictEqual(['two']);
});
it('keeps the full count and says how many ignored resources it leaves out', () => {
const table = { props: ['rows'], template: '<div><slot name="cell:affectedCount" :row="rows[0]" :value="rows[0].affectedCount" /></div>' };
const row = {
...CHECK, affectedCount: 2, affectedResources: { kind: 'Volume', names: { one: { ignored: true, ignoredBy: 'r' }, two: {} } }
};
const hidden = mountChecks({ rows: [row] }, { SortableTable: table });
const shown = mountChecks({ rows: [row], showIgnored: true }, { SortableTable: table });
expect(hidden.findComponent(RcCounterBadge).props('count')).toBe(2);
expect(hidden.find('.hidden-ignored').text()).toContain('ignore.plusIgnored');
expect(shown.findComponent(RcCounterBadge).props('count')).toBe(2);
expect(shown.find('.hidden-ignored').exists()).toBe(false);
});
it('counts what "Show ignored" brings back, each thing once', () => {
const check = (ignored, names) => ({ ignored, affectedResources: { names } });
expect(ignoredCounts([
check(true, { a: { ignored: true }, b: { ignored: true } }),
check(false, { c: { ignored: true }, d: {} }),
check(false, {
e: { ignored: true }, f: { ignored: true }, g: {}
}),
check(false, { h: {} }),
])).toStrictEqual({ checks: 1, resources: 3 });
expect(ignoredCounts(undefined)).toStrictEqual({ checks: 0, resources: 0 });
});
it('names the rule of a check after it', () => {
expect(ignoreRuleName('harvester-controller-vmimage', 'ImageRetryLimitExceeded')).toBe('harvester-controller-vmimage.imageretrylimitexceeded');
});
it('turns what a name can not have in a check into hyphens', () => {
expect(ignoreRuleName('harvester-controller-schedulevmbackup', 'Proactive Schedule Suspend')).toBe('harvester-controller-schedulevmbackup.proactive-schedule-suspend');
expect(ignoreRuleName('h', ' Reach_Max Failure! ')).toBe('h.reach-max-failure');
});
it('tells the ignored resources apart, and all of them when the check is ignored', () => {
const table = { props: ['rows'], template: '<div><slot name="cell:severity" :row="rows[0]" /><slot name="cell:affectedCount" :row="rows[0]" :value="2" /></div>' };
const row = {
...CHECK, severity: 'Error', affectedResources: { kind: 'Volume', names: { one: { ignored: true, ignoredBy: 'r' }, two: {} } }
};
const wholeRow = {
...row, ignored: true, affectedResources: { kind: 'Volume', names: { one: {}, two: {} } }
};
const tags = (w) => w.findAllComponents(RcTag).map((tag) => ({
ignored: tag.classes().includes('ignored'), disabled: tag.props('disabled'), says: tag.text().includes('ignore.ignored')
}));
const partly = mountChecks({ rows: [row], showIgnored: true }, { SortableTable: table });
const whole = mountChecks({ rows: [wholeRow], showIgnored: true }, { SortableTable: table });
expect(tags(partly)).toStrictEqual([
{
ignored: true, disabled: true, says: true
},
{
ignored: false, disabled: false, says: false
},
]);
expect(partly.findComponent(BadgeState).props('color')).toBe('bg-error');
expect(tags(whole)).toStrictEqual([
{
ignored: true, disabled: true, says: false
},
{
ignored: true, disabled: true, says: false
},
]);
expect(whole.findComponent(BadgeState).props('color')).toBe('bg-error');
});
it('keeps the resources past the first ones behind a link', async() => {
const table = { props: ['rows'], template: '<div><slot name="cell:affectedCount" :row="rows[0]" :value="rows[0].affectedCount" /></div>' };
const names = Object.fromEntries(['a', 'b', 'c', 'd', 'e', 'f', 'g'].map((name) => [name, {}]));
const row = {
...CHECK, affectedCount: 7, affectedResources: { kind: 'VirtualMachine', names }
};
const w = mountChecks({ rows: [row] }, { SortableTable: table });
expect(w.findAllComponents(RcTag)).toHaveLength(3);
expect(w.find('button.variant-link').text()).toContain('generic.plusMore');
await w.find('button.variant-link').trigger('click');
expect(w.findAllComponents(RcTag)).toHaveLength(7);
expect(w.find('button.variant-link').text()).toContain('generic.showLess');
});
it('adds up the errors of all the components, for the alert on the tab', () => {
const components = {
x: { errorCount: 2, warningCount: 5 }, y: { errorCount: 1 }, z: {}
};
expect(totalErrorCount([summaryOf(components)])).toBe(3);
expect(totalErrorCount([summaryOf({ x: { warningCount: 5 } })])).toBe(0);
expect(totalErrorCount([{ id: 'empty' }])).toBe(0);
expect(totalErrorCount(undefined)).toBe(0);
});
it('names the resources by their schema, or by their kind without one', () => {
const store = {
getters: {
'harvester/schemaFor': (id) => (['longhorn.io.volume', 'node'].includes(id) ? { id } : null),
'type-map/labelFor': (schema, count) => `${ schema.id } ${ count }`,
}
};
const label = (apiVersion, kind) => affectedResourceLabel({ affectedCount: 6, affectedResources: { apiVersion, kind } }, store);
expect(label('longhorn.io/v1beta2', 'Volume')).toBe('longhorn.io.volume 6');
expect(label('v1', 'Node')).toBe('node 6');
expect(label('harvesterhci.io/v1beta1', 'Upgrade')).toBe('Upgrade');
});
it('tells when a component has no checks, unless they could not be loaded', () => {
expect(mountChecks({ rows: [] }).text()).toContain('noIssues');
expect(mountChecks({ rows: [], loadFailed: true }).text()).toContain('checksNotLoaded');
});
it('still shows the checks when the rules can not be loaded, and says so', async() => {
const w = await mountSummary({
healthSummaries: [summaryOf({ x: { errorCount: 1 } })],
componentHealths: [healthOf('h', 'x', { a: { severity: 'Error' } })],
failing: 'ignoreRules',
});
const checks = w.findComponent(ComponentChecksTable);
expect(checks.props('rows').map((r) => r.id)).toStrictEqual(['h/a']);
expect(checks.props('loadFailed')).toBe(false);
expect(w.findAllComponents(Banner).map((banner) => banner.props('label'))).toStrictEqual(['%harvester.dashboard.sections.componentHealth.loadFailed.ignoreRules%']);
});
it('does not call a component without issues when its checks can not be loaded', async() => {
const w = await mountSummary({
healthSummaries: [summaryOf({ x: { errorCount: 1 } })],
failing: 'componentHealths',
});
expect(w.findComponent(ComponentChecksTable).props('loadFailed')).toBe(true);
expect(w.findAllComponents(Banner).map((banner) => banner.props('label'))).toStrictEqual(['%harvester.dashboard.sections.componentHealth.loadFailed.componentHealths%']);
});
it('does not ask for the rules without their schema', async() => {
const onFindAll = jest.fn();
await mountSummary({ noSchemaFor: HCI.HEALTH_IGNORE_RULE, onFindAll });
expect(onFindAll.mock.calls.map(([type]) => type)).toStrictEqual([HCI.HEALTH_SUMMARY, HCI.COMPONENT_HEALTH]);
});
it('marks a check and the resources that are ignored', () => {
const table = {
props: ['rows'],
template: '<div><slot name="cell:checkName" :row="rows[0]" :value="rows[0].checkName" /><slot name="cell:affectedCount" :row="rows[0]" :value="2" /></div>',
};
const row = { ...CHECK, affectedResources: { kind: 'VirtualMachine', names: { one: { ignored: true, ignoredBy: 'r' }, two: {} } } };
const textOf = (props) => mountChecks({ showIgnored: true, ...props }, { SortableTable: table }).text().replace(/\s+/g, ' ');
expect(textOf({ rows: [row] })).toMatch(/one ?\(%harvester\.dashboard\.sections\.componentHealth\.ignore\.ignored%\) ?two/);
expect(textOf({ rows: [row] })).not.toContain('a (%harvester');
expect(textOf({ rows: [{ ...row, ignored: true }] })).toContain('a (%harvester.dashboard.sections.componentHealth.ignore.ignored%)');
});
describe('the actions of a check', () => {
it('offers to create a rule when the check has none from the UI', () => {
const elsewhere = ruleOf({}, { metadata: { name: 'ignore-x7k2p' } });
const { w, keys, invoke } = actionsOf({ ignoreRules: [ruleOf({ checkKey: 'b' }), ruleOf({ componentHealth: 'other' }), elsewhere] });
expect(keys).toStrictEqual(['create']);
invoke('create');
expect(w.emitted('open-rule')).toStrictEqual([[{
row: CHECK, rule: undefined, mode: 'create'
}]]);
});
it('offers to view, edit and delete the rule of the check, and only that one', () => {
const rule = ruleOf();
const elsewhere = ruleOf({}, { metadata: { name: 'ignore-x7k2p' } });
const { w, keys, invoke } = actionsOf({ ignoreRules: [elsewhere, ruleOf({ checkKey: 'b' }), rule] });
expect(keys).toStrictEqual(['view', 'edit', '-', 'delete']);
invoke('view');
invoke('edit');
invoke('delete');
expect(w.emitted('open-rule')).toStrictEqual([
[{
row: CHECK, rule, mode: 'view'
}],
[{
row: CHECK, rule, mode: 'edit'
}],
]);
expect(rule.promptRemove).toHaveBeenCalledTimes(1);
expect(elsewhere.promptRemove).not.toHaveBeenCalled();
});
it('only offers what the user is allowed to do', () => {
const keysFor = (extra) => actionsOf({ ignoreRules: [ruleOf({}, extra)] }).keys;
expect(keysFor({ canDelete: false })).toStrictEqual(['view', 'edit']);
expect(keysFor({ canUpdate: false })).toStrictEqual(['view', '-', 'delete']);
expect(keysFor({ canUpdate: false, canDelete: false })).toStrictEqual(['view']);
expect(actionsOf({}, { collectionMethods: ['GET'] }).keys).toStrictEqual([]);
expect(actionsOf({}, { noSchemaFor: HCI.HEALTH_IGNORE_RULE }).keys).toStrictEqual([]);
});
it('leaves out the menu when no check has anything in it', () => {
const rowActions = (props, storeProps) => actionsOf(props, storeProps).w.findComponent(checksTable).props('rowActions');
expect(rowActions({}, { collectionMethods: ['GET'] })).toBe(false);
expect(rowActions({ ignoreRules: [ruleOf()] }, { collectionMethods: ['GET'] })).toBe(true);
expect(rowActions({})).toBe(true);
});
});
describe('creating a rule', () => {
it('starts the modal over each time it opens', async() => {
const w = await mountSummary({
healthSummaries: [summaryOf({ x: { errorCount: 1 } })],
componentHealths: [healthOf('h', 'x', { a: { severity: 'Error' } })],
});
const open = async() => {
await w.findComponent(ComponentChecksTable).vm.$emit('open-rule', { row: CHECK, mode: 'create' });
await flushPromises();
};
expect(w.findComponent(RcModal).exists()).toBe(false);
await open();
await w.findComponent(LabeledInput).vm.$emit('update:value', 'known issue');
await flushPromises();
expect(w.findComponent(LabeledInput).props('value')).toBe('known issue');
await w.findComponent(RcModal).vm.$emit('close');
await flushPromises();
expect(w.findComponent(RcModal).exists()).toBe(false);
await open();
expect(w.findComponent(LabeledInput).props('value')).toBe('');
});
it('ignores the selected resources for the chosen time', async() => {
const { w, onClose, confirm } = mountRuleModal();
await w.findComponent(LabeledSelect).vm.$emit('update:value', ['two']);
await w.findComponent(LabeledInput).vm.$emit('update:value', 'known issue');
await flushPromises();
await confirm().trigger('click');
await flushPromises();
expect(cloneRule).not.toHaveBeenCalled();
expect(newRule.spec).toStrictEqual({
componentHealth: 'h',
checkKey: 'a',
resources: ['two'],
expiresAt: expect.any(String),
reason: 'known issue',
});
expect(saveRule).toHaveBeenCalledTimes(1);
expect(onClose).toHaveBeenCalledTimes(1);
});
it('names the rule after its check, so a second one for it is refused', async() => {
const { confirm } = mountRuleModal();
await confirm().trigger('click');
await flushPromises();
expect(createRule.mock.calls[0][1].metadata).toStrictEqual({ name: 'h.a', labels: { 'health.harvesterhci.io/source': 'user' } });
});
it('gives a check with spaces a valid name, and keeps the check as it is', async() => {
const { confirm } = mountRuleModal({ row: { ...CHECK, checkName: 'Proactive Schedule Suspend' } });
await confirm().trigger('click');
await flushPromises();
expect(createRule.mock.calls[0][1].metadata.name).toBe('h.proactive-schedule-suspend');
expect(newRule.spec.checkKey).toBe('Proactive Schedule Suspend');
});
it('says when the rule will expire, from 7 days on', async() => {
const {
confirm, duration, currentExpiry, newExpiry
} = mountRuleModal();
expect(currentExpiry().exists()).toBe(false);
expect(duration().props('value')).toBe('days7');
expect(newExpiry().text()).toContain('ignore.willExpireOn');
await duration().vm.$emit('update:value', 'forever');
await flushPromises();
expect(newExpiry().text()).toContain('ignore.willNeverExpire');
expect(confirm().attributes('disabled')).toBeUndefined();
});
it('ignores the entire check forever without listing its resources', async() => {
const { w, confirm } = mountRuleModal();
const [scope, duration] = w.findAllComponents(RadioGroup);
await scope.vm.$emit('update:value', 'check');
await duration.vm.$emit('update:value', 'forever');
await flushPromises();
await confirm().trigger('click');
await flushPromises();
expect(newRule.spec).toStrictEqual({ componentHealth: 'h', checkKey: 'a' });
});
it('only offers the entire check when the check lists no resources', () => {
const w = vtuMount(IgnoreRuleModal, {
...opts(),
props: { row: { ...CHECK, affectedResources: undefined }, modal: { show: true, onClose: jest.fn() } },
});
expect(w.findAllComponents(RadioGroup)).toHaveLength(1);
expect(w.findComponent(LabeledSelect).exists()).toBe(false);
});
it('can not ignore without a resource selected', async() => {
const { w, confirm } = mountRuleModal();
expect(confirm().attributes('disabled')).toBeUndefined();
await w.findComponent(LabeledSelect).vm.$emit('update:value', []);
await flushPromises();
expect(confirm().attributes('disabled')).toBeDefined();
});
it('stays open and shows the error when saving fails', async() => {
const { w, onClose, confirm } = mountRuleModal({ save: () => Promise.reject(new Error('forbidden')) });
await confirm().trigger('click');
await flushPromises();
expect(w.text()).toContain('forbidden');
expect(onClose).not.toHaveBeenCalled();
expect(confirm().attributes('disabled')).toBeUndefined();
});
it('does not close while the rule is saved', async() => {
let finishSaving;
const { w, onClose, confirm } = mountRuleModal({
save: () => new Promise((resolve) => {
finishSaving = resolve;
})
});
await confirm().trigger('click');
await flushPromises();
expect(confirm().attributes('disabled')).toBeDefined();
await w.findComponent(RcModal).vm.$emit('close');
expect(onClose).not.toHaveBeenCalled();
finishSaving();
await flushPromises();
expect(onClose).toHaveBeenCalledTimes(1);
});
});
describe('editing a rule', () => {
it('starts from what the rule has, with no new duration chosen', () => {
const rule = ruleOf({
resources: ['two'], expiresAt: IN_A_WEEK, reason: 'known issue'
});
const {
w, duration, currentExpiry, newExpiry
} = mountRuleModal({ rule, mode: 'edit' });
const [scope] = w.findAllComponents(RadioGroup);
expect(scope.props('value')).toBe('resources');
expect(w.findComponent(LabeledSelect).props('value')).toStrictEqual(['two']);
expect(currentExpiry().text()).toContain('ignore.expiresOn');
expect(duration().props('value')).toBeNull();
expect(duration().props('options').map((option) => option.value)).toStrictEqual(['days7', 'days30', 'forever']);
expect(newExpiry().exists()).toBe(false);
expect(w.findComponent(LabeledInput).props('value')).toBe('known issue');
});
it('can not save until something changes', async() => {
const { w, confirm, duration } = mountRuleModal({ rule: ruleOf(), mode: 'edit' });
const reason = (value) => w.findComponent(LabeledInput).vm.$emit('update:value', value);
expect(confirm().attributes('disabled')).toBeDefined();
await reason('known issue');
await flushPromises();
expect(confirm().attributes('disabled')).toBeUndefined();
await reason('');
await duration().vm.$emit('update:value', 'forever');
await flushPromises();
expect(confirm().attributes('disabled')).toBeDefined();
await duration().vm.$emit('update:value', 'days7');
await flushPromises();
expect(confirm().attributes('disabled')).toBeUndefined();
});
it('saves on a copy of the rule, with the expiry it has', async() => {
const rule = ruleOf({
resources: ['two'], expiresAt: IN_A_WEEK, reason: 'known issue'
});
const { w, onClose, confirm } = mountRuleModal({ rule, mode: 'edit' });
await w.findComponent(LabeledInput).vm.$emit('update:value', 'still known');
await flushPromises();
await confirm().trigger('click');
await flushPromises();
expect(createRule).not.toHaveBeenCalled();
expect(cloneRule.mock.calls[0][1]).toStrictEqual({ resource: rule });
expect(editedRule.spec).toStrictEqual({ ...rule.spec, reason: 'still known' });
expect(saveRule).toHaveBeenCalledTimes(1);
expect(onClose).toHaveBeenCalledTimes(1);
});
it('takes the resources, the expiry and the reason off the rule', async() => {
const { w, confirm, duration } = mountRuleModal({
rule: ruleOf({
resources: ['two'], expiresAt: IN_A_WEEK, reason: 'known issue'
}),
mode: 'edit'
});
const [scope] = w.findAllComponents(RadioGroup);
await scope.vm.$emit('update:value', 'check');
await duration().vm.$emit('update:value', 'forever');
await w.findComponent(LabeledInput).vm.$emit('update:value', '');
await flushPromises();
await confirm().trigger('click');
await flushPromises();
expect(editedRule.spec).toStrictEqual({ componentHealth: 'h', checkKey: 'a' });
});
it('renews an expired rule with the duration chosen', async() => {
const {
confirm, duration, currentExpiry, newExpiry
} = mountRuleModal({ rule: ruleOf({ expiresAt: LAST_WEEK }), mode: 'edit' });
expect(currentExpiry().text()).toContain('ignore.expiredOn');
await duration().vm.$emit('update:value', 'days30');
await flushPromises();
expect(newExpiry().text()).toContain('ignore.willExpireOn');
await confirm().trigger('click');
await flushPromises();
expect(new Date(editedRule.spec.expiresAt).getTime()).toBeGreaterThan(new Date(IN_A_WEEK).getTime());
});
it('warns that an expired rule stays expired when only something else changes', async() => {
const { w, duration, warning } = mountRuleModal({ rule: ruleOf({ expiresAt: LAST_WEEK }), mode: 'edit' });
expect(warning()).toBeUndefined();
await w.findComponent(LabeledInput).vm.$emit('update:value', 'known issue');
await flushPromises();
expect(warning().props('label')).toContain('ignore.staysExpired');
await duration().vm.$emit('update:value', 'days7');
await flushPromises();
expect(warning()).toBeUndefined();
});
it('does not warn about a rule that has not expired', async() => {
const { w, warning } = mountRuleModal({ rule: ruleOf({ expiresAt: IN_A_WEEK }), mode: 'edit' });
await w.findComponent(LabeledInput).vm.$emit('update:value', 'known issue');
await flushPromises();
expect(warning()).toBeUndefined();
});
it('opens a rule without resources on the entire check, and selects them all when asked', async() => {
const {
w, confirm, duration, currentExpiry
} = mountRuleModal({ rule: ruleOf(), mode: 'edit' });
const [scope] = w.findAllComponents(RadioGroup);
expect(scope.props('value')).toBe('check');
expect(currentExpiry().text()).toContain('ignore.neverExpires');
expect(duration().props('value')).toBeNull();
expect(w.findComponent(LabeledSelect).exists()).toBe(false);
await scope.vm.$emit('update:value', 'resources');
await flushPromises();
expect(w.findComponent(LabeledSelect).props('value')).toStrictEqual(['one', 'two']);
await confirm().trigger('click');
await flushPromises();
expect(editedRule.spec.resources).toStrictEqual(['one', 'two']);
});
it('keeps a resource of the rule that is no longer affected', async() => {
const { w, confirm } = mountRuleModal({ rule: ruleOf({ resources: ['gone', 'two'] }), mode: 'edit' });
const select = w.findComponent(LabeledSelect);
expect(select.props('options')).toStrictEqual(['one', 'two', 'gone']);
expect(select.props('value')).toStrictEqual(['two', 'gone']);
await w.findComponent(LabeledInput).vm.$emit('update:value', 'known issue');
await flushPromises();
await confirm().trigger('click');
await flushPromises();
expect(editedRule.spec.resources).toStrictEqual(['two', 'gone']);
});
});
describe('viewing a rule', () => {
it('shows what the rule has without letting it change', async() => {
const {
w, onClose, confirm, duration, currentExpiry
} = mountRuleModal({
rule: ruleOf({
resources: ['two'], expiresAt: IN_A_WEEK, reason: 'known issue'
}),
mode: 'view'
});
[...w.findAllComponents(RadioGroup), w.findComponent(LabeledSelect), w.findComponent(LabeledInput)].forEach((field) => {
expect(field.props('mode')).toBe('view');
});
expect(currentExpiry().text()).toContain('ignore.expiresOn');
expect(duration()).toBeUndefined();
expect(w.findComponent(LabeledInput).props('value')).toBe('known issue');
expect(confirm().exists()).toBe(false);
expect(w.find('[data-testid="rc-modal-cancel"]').exists()).toBe(false);
await w.find('[data-testid="component-health-ignore-close"]').trigger('click');
expect(onClose).toHaveBeenCalledTimes(1);
expect(cloneRule).not.toHaveBeenCalled();
expect(saveRule).not.toHaveBeenCalled();
});
});
});
+471 -84
View File
@@ -1,153 +1,540 @@
<template>
<div>
<div v-if="connected && disconnected">
<main class="main-layout error">
<div class="text-center">
<BrandImage
file-name="error-desert-landscape.svg"
width="900"
height="300"
/>
<h1>
{{ t('generic.notification.title.warning') }}
</h1>
<h2 class="text-secondary mt-20">
{{ t('vncConsole.error.message') }}
</h2>
</div>
</main>
</div>
<div v-if="reconnecting">
<main class="main-layout">
<div class="text-center">
<h2 class="text-secondary mt-20">
{{ t('vncConsole.reconnecting.message') }}:{{ retryTimes }} of {{ maximumRetryTimes }}
</h2>
</div>
</main>
</div>
<div
ref="view"
/>
</div>
</template>
<script>
import RFB from '@novnc/novnc/core/rfb';
import BrandImage from '@shell/components/BrandImage';
import ModalWithCard from '@shell/components/ModalWithCard';
import ZoomableRFB from './ZoomableRFB';
export const CONSOLE_STATUS = {
CONNECTING: 'connecting',
CONNECTED: 'connected',
RECONNECTING: 'reconnecting',
DISCONNECTED: 'disconnected',
FAILED: 'failed',
};
export const CONSOLE_FAILURE = {
IN_USE: 'inUse',
UNAVAILABLE: 'unavailable',
DROPPED: 'dropped',
ERROR: 'error',
};
const MAXIMUM_RETRY_TIMES = 10;
const BASE_RECONNECT_DELAY = 1000;
const MAXIMUM_RECONNECT_DELAY = 30000;
const clampLevel = (value, fallback) => {
const level = Number.parseInt(value, 10);
if (Number.isNaN(level)) {
return fallback;
}
return Math.min(Math.max(level, 0), 9);
};
export default {
name: 'NovncConsole',
components: { ModalWithCard },
props: {
url: {
type: String,
default: ''
}
},
settings: {
type: Object,
default: () => ({})
},
// KubeVirt honours preserveSession from v1.6.3. Older versions ignore it, so every
// connection takes the console over and automatic retries would kick the other user.
preserveSession: {
type: Boolean,
default: true
},
vmRunning: {
type: Boolean,
default: true
},
},
components: { BrandImage },
emits: ['status-changed', 'capabilities'],
data() {
return {
rfb: null,
connected: false,
disconnected: false,
reconnectDelay: 3000,
reconnecting: false,
maximumRetryTimes: 10,
status: CONSOLE_STATUS.CONNECTING,
statusDetail: '',
desktopName: '',
retryTimes: 0,
setTimeout: null,
maximumRetryTimes: MAXIMUM_RETRY_TIMES,
reconnectTimer: null,
isClosed: false,
failure: '',
showTakeOverModal: false,
focused: false,
};
},
computed: {
statusInfo() {
return {
status: this.status,
detail: this.statusDetail,
desktopName: this.desktopName,
retryTimes: this.retryTimes,
maximumRetryTimes: this.maximumRetryTimes,
};
},
showError() {
return this.status === CONSOLE_STATUS.FAILED || (this.status === CONSOLE_STATUS.DISCONNECTED && this.failure === CONSOLE_FAILURE.DROPPED);
},
canTakeOver() {
return this.preserveSession && !this.isClosed;
},
failureTitle() {
return this.t(`harvester.virtualMachine.detail.console.failure.${ this.failure || CONSOLE_FAILURE.ERROR }`);
},
showReconnecting() {
return this.status === CONSOLE_STATUS.RECONNECTING;
},
},
watch: {
url() {
this.reconnect();
},
settings: {
deep: true,
handler: 'applySettings'
},
statusInfo: {
immediate: true,
handler(neu) {
this.$emit('status-changed', neu);
}
},
},
mounted() {
// noVNC hides the canvas focus outline, so track focus to show where typing goes.
this.$refs.view.addEventListener('focusin', this.onFocusIn);
this.$refs.view.addEventListener('focusout', this.onFocusOut);
this.$nextTick(() => {
this.connect();
});
},
beforeUnmount() {
this.clearTimeout();
this.$refs.view?.removeEventListener('focusin', this.onFocusIn);
this.$refs.view?.removeEventListener('focusout', this.onFocusOut);
this.isClosed = true;
this.clearReconnectTimer();
this.teardown();
},
methods: {
connect() {
const rfb = new RFB(this.$refs.view, this.url);
connect(takeOver = false) {
if (!this.url || this.isClosed) {
return;
}
rfb.addEventListener('connect', () => {
this.clearTimeout();
this.teardown();
this.connected = true;
this.retryTimes = 0;
this.reconnecting = false;
});
this.failure = '';
this.status = this.retryTimes > 0 ? CONSOLE_STATUS.RECONNECTING : CONSOLE_STATUS.CONNECTING;
rfb.addEventListener('disconnect', (e) => {
this.clearTimeout();
let rfb;
this.disconnected = true;
this.rfb = null;
this.reconnect();
});
try {
const url = new URL(this.url);
if (this.preserveSession) {
url.searchParams.set('preserveSession', takeOver === true ? 'false' : 'true');
}
rfb = new ZoomableRFB(this.$refs.view, url.href, { shared: true });
} catch (err) {
this.statusDetail = err?.message || `${ err }`;
this.status = CONSOLE_STATUS.FAILED;
return;
}
rfb.addEventListener('connect', this.onConnect);
rfb.addEventListener('disconnect', this.onDisconnect);
rfb.addEventListener('securityfailure', this.onSecurityFailure);
rfb.addEventListener('credentialsrequired', this.onCredentialsRequired);
rfb.addEventListener('desktopname', this.onDesktopName);
rfb.addEventListener('capabilities', this.onCapabilities);
this.rfb = rfb;
this.applySettings();
},
reconnect() {
this.clearReconnectTimer();
this.isClosed = false;
this.retryTimes = 0;
this.statusDetail = '';
this.connect();
},
takeOver() {
this.showTakeOverModal = true;
},
cancelTakeOver() {
this.showTakeOverModal = false;
},
confirmTakeOver() {
this.showTakeOverModal = false;
this.clearReconnectTimer();
this.isClosed = false;
this.retryTimes = 0;
this.statusDetail = '';
this.connect(true);
},
disconnect() {
this.isClosed = true;
this.clearReconnectTimer();
this.teardown();
this.status = CONSOLE_STATUS.DISCONNECTED;
},
onConnect() {
this.clearReconnectTimer();
this.retryTimes = 0;
this.statusDetail = '';
this.status = CONSOLE_STATUS.CONNECTED;
this.applySettings();
this.focus();
},
focus() {
this.rfb?.focus();
},
onFocusIn() {
this.focused = true;
},
onFocusOut() {
this.focused = false;
},
onDisconnect() {
const wasConnected = this.status === CONSOLE_STATUS.CONNECTED;
const wasRetrying = this.status === CONSOLE_STATUS.RECONNECTING;
this.teardown(false);
if (this.isClosed) {
if (this.status !== CONSOLE_STATUS.FAILED) {
this.status = CONSOLE_STATUS.DISCONNECTED;
}
return;
}
if (wasConnected && !this.preserveSession) {
// Without preserveSession a retry would take the console back from whoever
// opened it, and the two sessions would keep kicking each other out.
this.clearReconnectTimer();
this.failure = CONSOLE_FAILURE.DROPPED;
this.statusDetail = this.t('harvester.virtualMachine.detail.console.failureDetail.dropped');
this.status = CONSOLE_STATUS.DISCONNECTED;
} else if (wasConnected) {
this.scheduleReconnect();
} else if (wasRetrying) {
// Retries use preserveSession, so they fail while another session owns the
// console. Keep retrying so the console is picked up once it is released,
// instead of kicking the other session back out.
this.statusDetail = this.t('harvester.virtualMachine.detail.console.status.inUse');
this.scheduleReconnect();
} else {
this.clearReconnectTimer();
this.fail(this.preserveSession && this.vmRunning ? CONSOLE_FAILURE.IN_USE : CONSOLE_FAILURE.UNAVAILABLE);
}
},
// The browser cannot see why a WebSocket handshake failed. With preserveSession and a
// running VM, a refused connection almost always means another session holds the console.
fail(failure, detail) {
this.failure = failure;
this.statusDetail = detail ?? this.t(`harvester.virtualMachine.detail.console.failureDetail.${ failure }`);
this.status = CONSOLE_STATUS.FAILED;
},
// Authentication problems will not fix themselves, so stop retrying.
onSecurityFailure(e) {
this.isClosed = true;
this.clearReconnectTimer();
this.fail(CONSOLE_FAILURE.ERROR, e?.detail?.reason || '');
},
// noVNC pauses the handshake until credentials are sent, so close the socket
// to avoid holding the console while the failure is shown.
onCredentialsRequired() {
this.isClosed = true;
this.clearReconnectTimer();
this.teardown();
this.fail(CONSOLE_FAILURE.ERROR, this.t('harvester.virtualMachine.detail.console.status.credentialsRequired'));
},
onDesktopName(e) {
this.desktopName = e?.detail?.name || '';
},
onCapabilities(e) {
this.$emit('capabilities', e?.detail?.capabilities || {});
},
scheduleReconnect() {
this.clearReconnectTimer();
if (this.isClosed) {
return;
}
if (this.retryTimes >= this.maximumRetryTimes) {
this.reconnecting = false;
this.connected = true;
this.disconnected = true;
this.fail(this.vmRunning ? CONSOLE_FAILURE.IN_USE : CONSOLE_FAILURE.UNAVAILABLE);
return;
}
this.retryTimes += 1;
this.reconnecting = true;
this.connected = false;
this.disconnected = false;
this.status = CONSOLE_STATUS.RECONNECTING;
this.setTimeout = setTimeout(() => {
const delay = Math.min(BASE_RECONNECT_DELAY * (2 ** (this.retryTimes - 1)), MAXIMUM_RECONNECT_DELAY);
this.reconnectTimer = setTimeout(() => {
this.reconnectTimer = null;
this.connect();
}, this.reconnectDelay);
}, delay);
},
clearTimeout() {
if (this.setTimeout) {
clearTimeout(this.setTimeout);
clearReconnectTimer() {
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
},
disconnect() {
this.rfb.disconnect();
teardown(disconnect = true) {
const rfb = this.rfb;
if (!rfb) {
return;
}
this.rfb = null;
rfb.removeEventListener('connect', this.onConnect);
rfb.removeEventListener('disconnect', this.onDisconnect);
rfb.removeEventListener('securityfailure', this.onSecurityFailure);
rfb.removeEventListener('credentialsrequired', this.onCredentialsRequired);
rfb.removeEventListener('desktopname', this.onDesktopName);
rfb.removeEventListener('capabilities', this.onCapabilities);
if (!disconnect) {
return;
}
try {
rfb.disconnect();
} catch (err) {
// The socket may already be gone, nothing left to clean up.
}
},
applySettings() {
const rfb = this.rfb;
if (!rfb) {
return;
}
const settings = this.settings || {};
rfb.viewOnly = !!settings.viewOnly;
rfb.scaleViewport = !!settings.scaleViewport;
rfb.resizeSession = !!settings.resizeSession;
rfb.clipViewport = !!settings.clipViewport;
rfb.dragViewport = !!settings.dragViewport;
rfb.zoomPercent = settings.zoomPercent;
rfb.focusOnClick = settings.focusOnClick !== false;
rfb.qualityLevel = clampLevel(settings.qualityLevel, 6);
rfb.compressionLevel = clampLevel(settings.compressionLevel, 2);
},
ctrlAltDelete() {
this.rfb.sendCtrlAltDel();
this.rfb?.sendCtrlAltDel();
},
sendKey(keysym, code, down) {
this.rfb.sendKey(keysym, code, down);
}
this.rfb?.sendKey(keysym, code, down);
},
}
};
</script>
<template>
<div class="novnc-console">
<div
ref="view"
class="novnc-screen"
:class="{ 'is-focused': focused }"
/>
<div
v-if="showError || showReconnecting"
class="novnc-overlay"
>
<div
v-if="showError"
class="novnc-overlay__card text-center"
>
<h3>
{{ failureTitle }}
</h3>
<p
v-if="statusDetail"
class="mt-10"
>
{{ statusDetail }}
</p>
<button
class="btn role-primary mt-20"
@click="reconnect"
>
{{ t('harvester.action.reconnect') }}
</button>
<button
v-if="canTakeOver"
class="btn role-secondary mt-20 ml-10"
@click="takeOver"
>
{{ t('harvester.virtualMachine.detail.console.takeOver.label') }}
</button>
</div>
<div
v-else
class="text-center"
>
<h2>
{{ t('vncConsole.reconnecting.message') }}:{{ retryTimes }} of {{ maximumRetryTimes }}
</h2>
<p
v-if="statusDetail"
class="mt-10"
>
{{ statusDetail }}
</p>
</div>
</div>
<ModalWithCard
v-if="showTakeOverModal"
name="takeOverConsole"
:width="480"
@finish="cancelTakeOver"
>
<template #title>
{{ t('harvester.virtualMachine.detail.console.takeOver.title') }}
</template>
<template #content>
<p>{{ t('harvester.virtualMachine.detail.console.takeOver.confirm') }}</p>
</template>
<template #footer>
<div class="take-over-actions">
<button
class="btn role-secondary mr-10"
@click="cancelTakeOver"
>
{{ t('generic.cancel') }}
</button>
<button
class="btn role-primary"
@click="confirmTakeOver"
>
{{ t('harvester.virtualMachine.detail.console.takeOver.label') }}
</button>
</div>
</template>
</ModalWithCard>
</div>
</template>
<style lang="scss" scoped>
.error {
.novnc-console {
position: relative;
box-sizing: border-box;
height: 100%;
padding: 8px;
overflow: hidden;
}
.row {
align-items: center;
.novnc-screen {
height: 100%;
}
.novnc-overlay {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 1;
display: flex;
align-items: center;
justify-content: center;
overflow: auto;
background: rgba(0, 0, 0, 0.75);
// The overlay is always dark, so its text cannot follow the theme's text colours.
color: #fff;
h2,
h3 {
color: #fff;
}
h1 {
font-size: 5rem;
p {
color: rgba(255, 255, 255, 0.8);
}
.desert-landscape {
img {
max-width: 100%;
}
&__card {
max-width: 480px;
padding: 0 20px;
}
}
.take-over-actions {
display: flex;
justify-content: flex-end;
width: 100%;
}
</style>
<style lang="scss">
// noVNC sets an inline `outline: none` on its canvas, so mark keyboard focus with a ring instead.
.novnc-screen.is-focused canvas {
box-shadow: 0 0 0 2px var(--primary);
}
</style>
@@ -136,20 +136,15 @@ export default {
this.addedShortcutKeys.push([].concat(this.keysRecord));
},
removeKey(keys) {
const key = keys.replace(/(\s*)<code>|<\/code>/g, '').replace(/\s*,\s*/g, ',');
// The index is the one in displayedKeys, which lists the added shortcuts first.
removeKey(index) {
const added = this.addedShortcutKeys.length;
this.addedShortcutKeys = this.addedShortcutKeys.filter((item) => {
const formatkey = item.map((K) => K.key.charAt(0).toUpperCase() + K.key.slice(1)).join(',');
return formatkey !== key;
});
this.preferredShortcutKeys = this.preferredShortcutKeys.filter((item) => {
const formatkey = item.map((K) => K.key.charAt(0).toUpperCase() + K.key.slice(1)).join(',');
return formatkey !== key;
});
if (index < added) {
this.addedShortcutKeys.splice(index, 1);
} else {
this.preferredShortcutKeys.splice(index - added, 1);
}
},
async saveKeys(buttonCb) {
@@ -220,6 +215,8 @@ export default {
<Banner
v-for="(keys,index) in displayedKeys"
:key="index"
:closable="true"
@close="removeKey(index)"
>
<span v-clean-html="keys"></span>
</Banner>
@@ -233,10 +230,10 @@ export default {
class="btn role-secondary mr-20"
@click.prevent="closeRecordingModal"
>
<t k="generic.close" />
<t k="generic.cancel" />
</button>
<AsyncButton
mode="done"
mode="edit"
@click="saveKeys"
/>
</div>
@@ -1,5 +1,6 @@
<script>
import { STEVE } from '@shell/config/types';
import ModalWithCard from '@shell/components/ModalWithCard';
import { escapeHtml } from '@shell/utils/string';
import { allHash } from '@shell/utils/promise';
import KeyTable from '@novnc/novnc/core/input/keysym';
@@ -8,9 +9,29 @@ import { HCI } from '../../types';
import NovncConsole from './NovncConsole';
import NovncConsoleItem from './NovncConsoleItem';
import NovncConsoleCustomKeys from './NovncConsoleCustomKeys';
import { normalizeZoom } from './ZoomableRFB';
const CONSOLE_SETTINGS_KEY = 'harvester-vnc-console-settings';
const PREFERED_SHORTCUT_KEYS = 'prefered-shortcut-keys';
export const CONFIRM_ACTION = {
CTRL_ALT_DEL: 'ctrlAltDel',
SOFT_REBOOT: 'softReboot',
};
const VIEW_MODE = {
SCALE: 'scale',
NONE: 'none',
};
const DEFAULT_SETTINGS = {
viewMode: VIEW_MODE.NONE,
zoomPercent: 100,
viewOnly: false,
qualityLevel: 6,
compressionLevel: 2,
};
const SHORT_KEYS = {
ControlLeft: {
label: 'Ctrl',
@@ -106,7 +127,7 @@ const F_KEYS = {
export default {
name: 'NovncConsoleWrapper',
components: {
NovncConsole, NovncConsoleItem, NovncConsoleCustomKeys
ModalWithCard, NovncConsole, NovncConsoleItem, NovncConsoleCustomKeys
},
async fetch() {
@@ -132,44 +153,68 @@ export default {
keysRecord: [],
vmResource: {},
renderKeysModal: false,
currentUser: null,
hideCustomKeysBar: false,
settings: { ...DEFAULT_SETTINGS },
capabilities: {},
isFullscreen: false,
confirmAction: null,
consoleStatus: {
status: 'connecting',
retryTimes: 0,
maximumRetryTimes: 0,
desktopName: '',
},
};
},
computed: {
preference() {
return this.$store.getters['management/all'](STEVE.PREFERENCE)?.[0];
},
// Custom keys are stored in the user preference, which is not available everywhere.
hideCustomKeysBar() {
return !this.preference?.data;
},
savedShortcutKeys() {
const preference = this.$store.getters['management/all'](STEVE.PREFERENCE);
const preferedShortcutKeys = preference?.[0]?.data?.[PREFERED_SHORTCUT_KEYS];
let out = [];
if (!preference?.[0]?.data) {
// eslint-disable-next-line vue/no-side-effects-in-computed-properties
this.hideCustomKeysBar = true;
return out;
}
const preferedShortcutKeys = this.preference?.data?.[PREFERED_SHORTCUT_KEYS];
if (!preferedShortcutKeys) {
return out;
return [];
}
try {
out = JSON.parse(preferedShortcutKeys);
return JSON.parse(preferedShortcutKeys);
} catch (err) {
this.$store.dispatch('growl/fromError', {
title: this.t('generic.notification.title.error', { name: escapeHtml(this.value.metadata.name) }),
err,
}, { root: true });
return [];
}
},
return out;
preferredShortcutKeys() {
return (this.savedShortcutKeys || []).map((item) => {
return {
label: item.map((K) => K.key.charAt(0).toUpperCase() + K.key.slice(1)).join('+'),
value: item
};
});
},
canSendKeys() {
return this.consoleStatus.status === 'connected' && !this.settings.viewOnly;
},
isDown() {
return this.isEmpty(this.value);
},
preserveSession() {
return !!this.$store.getters['harvester-common/getFeatureEnabled']('vncPreserveSession');
},
vmRunning() {
return this.value?.status?.phase === 'Running';
},
url() {
const ip = `${ window.location.hostname }:${ window.location.port }`;
@@ -192,13 +237,16 @@ export default {
...F_KEYS,
};
out.AltLeft.keys = { PrintScreen: FUNCTION_KEYS.PrintScreen, ...F_KEYS };
out.ControlLeft.keys = {
AltLeft: {
...Object.assign(SHORT_KEYS.AltLeft, {}),
keys: { Delete: FUNCTION_KEYS.Delete }
out.AltLeft = { ...SHORT_KEYS.AltLeft, keys: { PrintScreen: FUNCTION_KEYS.PrintScreen, ...F_KEYS } };
out.ControlLeft = {
...SHORT_KEYS.ControlLeft,
keys: {
AltLeft: {
...SHORT_KEYS.AltLeft,
keys: { Delete: FUNCTION_KEYS.Delete }
},
...NORMAL_KEYS,
},
...NORMAL_KEYS,
};
return out;
@@ -208,14 +256,57 @@ export default {
return !!this.vmResource?.actions?.softreboot;
},
preferredShortcutKeys() {
return (this.savedShortcutKeys || []).map((item) => {
return {
label: item.map((K) => K.key.charAt(0).toUpperCase() + K.key.slice(1)).join('+'),
value: item
};
});
rfbSettings() {
return {
viewOnly: this.settings.viewOnly,
scaleViewport: this.settings.viewMode === VIEW_MODE.SCALE,
zoomPercent: normalizeZoom(this.settings.zoomPercent),
resizeSession: false,
clipViewport: false,
dragViewport: false,
qualityLevel: this.settings.qualityLevel,
compressionLevel: this.settings.compressionLevel,
};
},
viewModeOptions() {
return Object.values(VIEW_MODE).map((value) => ({
value,
label: this.t(`harvester.virtualMachine.detail.console.settings.viewMode.${ value }`)
}));
},
statusLabel() {
const { status, retryTimes, maximumRetryTimes } = this.consoleStatus;
if (status === 'reconnecting') {
return this.t('harvester.virtualMachine.detail.console.status.reconnecting', { retryTimes, maximumRetryTimes });
}
if (status === 'connected' && this.settings.viewOnly) {
return this.t('harvester.virtualMachine.detail.console.status.connectedViewOnly');
}
return this.t(`harvester.virtualMachine.detail.console.status.${ status }`);
},
},
watch: {
settings: {
deep: true,
handler(neu) {
window.localStorage.setItem(CONSOLE_SETTINGS_KEY, JSON.stringify(neu));
}
},
},
mounted() {
this.loadSettings();
document.addEventListener('fullscreenchange', this.onFullscreenChange);
},
beforeUnmount() {
document.removeEventListener('fullscreenchange', this.onFullscreenChange);
},
methods: {
@@ -233,36 +324,39 @@ export default {
// Send function key, e.g. ALT + F
sendKeys() {
if (!this.canSendKeys || !this.$refs.novncConsole) {
return;
}
this.keysRecord.forEach((key) => {
this.$refs.novncConsole.sendKey(this.allKeys[key].value, key, true);
});
this.keysRecord.reverse().forEach((key) => {
[...this.keysRecord].reverse().forEach((key) => {
this.$refs.novncConsole.sendKey(this.allKeys[key].value, key, false);
});
this.$refs.popover.isOpen = false;
this.$refs.popover.hide();
this.keysRecord = [];
this.$refs.novncConsole.focus();
},
sendCustomKeys(keys) {
if (!this.canSendKeys || !this.$refs.novncConsole) {
return;
}
const keyList = [].concat(keys);
keyList.forEach((K) => {
this.$refs.novncConsole.sendKey(KeyboardUtil.getKeysym(K), KeyboardUtil.getKeycode(K), true);
});
keyList.reverse().forEach((K) => {
[...keyList].reverse().forEach((K) => {
this.$refs.novncConsole.sendKey(KeyboardUtil.getKeysym(K), KeyboardUtil.getKeycode(K), false);
});
},
reconnect() {
this.$refs.novncConsole.reconnect();
},
softReboot() {
this.vmResource.doSoftReboot();
this.$refs.novncConsole.focus();
},
showKeysModal() {
@@ -272,6 +366,89 @@ export default {
hideKeysModal() {
this.renderKeysModal = false;
},
reconnect() {
this.$refs.novncConsole.reconnect();
},
loadSettings() {
try {
const saved = JSON.parse(window.localStorage.getItem(CONSOLE_SETTINGS_KEY) || '{}');
this.settings = {
viewMode: Object.values(VIEW_MODE).includes(saved?.viewMode) ? saved.viewMode : DEFAULT_SETTINGS.viewMode,
zoomPercent: normalizeZoom(saved?.zoomPercent ?? DEFAULT_SETTINGS.zoomPercent),
viewOnly: saved?.viewOnly === true,
qualityLevel: saved?.qualityLevel ?? DEFAULT_SETTINGS.qualityLevel,
compressionLevel: saved?.compressionLevel ?? DEFAULT_SETTINGS.compressionLevel,
};
} catch (err) {
this.settings = { ...DEFAULT_SETTINGS };
}
},
onStatusChanged(info) {
this.consoleStatus = info;
},
onCapabilities(capabilities) {
this.capabilities = capabilities;
},
// Both can restart the VM with one click (Ctrl+Alt+Del reboots most Linux guests), so ask first.
ctrlAltDelete() {
if (this.canSendKeys) {
this.confirmAction = CONFIRM_ACTION.CTRL_ALT_DEL;
}
},
softReboot() {
this.confirmAction = CONFIRM_ACTION.SOFT_REBOOT;
},
// The modal returns focus to the console canvas (return-focus-selector) once it closes.
cancelConfirm() {
this.confirmAction = null;
},
runConfirmedAction() {
const action = this.confirmAction;
this.confirmAction = null;
if (action === CONFIRM_ACTION.CTRL_ALT_DEL && this.canSendKeys) {
this.$refs.novncConsole?.ctrlAltDelete();
} else if (action === CONFIRM_ACTION.SOFT_REBOOT) {
this.vmResource.doSoftReboot();
}
},
async toggleFullscreen() {
try {
if (document.fullscreenElement) {
await document.exitFullscreen();
} else {
// The whole page and not only the console, because dialogs render outside of it.
await document.documentElement.requestFullscreen();
// Keyboard lock lets shortcuts such as Ctrl+W and F11 reach the guest.
await navigator.keyboard?.lock?.(['KeyW', 'F11']);
}
} catch (err) {
this.$store.dispatch('growl/fromError', {
title: this.t('generic.notification.title.error', { name: escapeHtml(this.value.metadata.name) }),
err,
}, { root: true });
}
},
onFullscreenChange() {
this.isFullscreen = !!document.fullscreenElement;
if (!this.isFullscreen) {
navigator.keyboard?.unlock?.();
}
},
}
};
</script>
@@ -280,108 +457,319 @@ export default {
<div id="app">
<div class="vm-console">
<div class="combination-keys">
<v-dropdown
ref="popover"
placement="top"
trigger="click"
:container="false"
@auto-hide="keysRecord = []"
>
<button class="btn btn-sm bg-primary">
{{ t("harvester.virtualMachine.detail.console.shortcutKeys") }}
</button>
<template #popper>
<novnc-console-item
:items="keymap"
:path="keysRecord"
:pos="0"
@update="update"
@send-keys="sendKeys"
/>
</template>
</v-dropdown>
<button
v-if="hasSoftRebootAction"
class="btn btn-sm bg-primary"
@click="softReboot"
>
{{ t("harvester.action.softreboot") }}
</button>
<button
class="btn btn-sm bg-primary"
@click="reconnect"
>
{{ t("harvester.action.reconnect") }}
</button>
<v-dropdown
v-if="!hideCustomKeysBar"
ref="customKeyPopover"
placement="top"
trigger="click"
:container="false"
>
<button class="btn btn-sm bg-primary">
{{ t("harvester.virtualMachine.detail.console.customShortcutKeys") }}
</button>
<template #popper>
<div>
<button
class="btn btn-sm bg-primary"
@click="showKeysModal"
>
{{ t("harvester.virtualMachine.detail.console.management") }}
</button>
</div>
<hr>
<div
v-for="(keys, index) in preferredShortcutKeys"
:key="index"
<div class="toolbar-group">
<v-dropdown
ref="popover"
placement="top"
trigger="click"
:container="false"
@auto-hide="keysRecord = []"
>
<button
class="btn btn-sm bg-primary"
:disabled="!canSendKeys"
>
<button
class="btn btn-sm bg-primary"
@click="sendCustomKeys(keys.value)"
>
{{ keys.label }}
</button>
</div>
</template>
</v-dropdown>
{{ t("harvester.virtualMachine.detail.console.shortcutKeys") }}
</button>
<NovncConsoleCustomKeys
v-if="renderKeysModal"
:current-user="currentUser"
@close="hideKeysModal"
/>
<template #popper>
<novnc-console-item
:items="keymap"
:path="keysRecord"
:pos="0"
@update="update"
@send-keys="sendKeys"
/>
</template>
</v-dropdown>
<button
class="btn btn-sm bg-primary"
:disabled="!canSendKeys"
@click="ctrlAltDelete"
>
{{ t("harvester.virtualMachine.detail.console.ctrlAltDel") }}
</button>
<v-dropdown
v-if="!hideCustomKeysBar"
placement="top"
trigger="click"
:container="false"
>
<button class="btn btn-sm bg-primary">
{{ t("harvester.virtualMachine.detail.console.customShortcutKeys") }}
</button>
<template #popper>
<div>
<button
class="btn btn-sm bg-primary"
@click="showKeysModal"
>
{{ t("harvester.virtualMachine.detail.console.management") }}
</button>
</div>
<hr>
<div
v-for="(keys, index) in preferredShortcutKeys"
:key="index"
class="custom-shortcut"
>
<button
class="btn btn-sm bg-primary"
:disabled="!canSendKeys"
@click="sendCustomKeys(keys.value)"
>
{{ keys.label }}
</button>
</div>
</template>
</v-dropdown>
<v-dropdown
placement="top"
trigger="click"
:container="false"
>
<button class="btn btn-sm bg-primary">
{{ t("harvester.virtualMachine.detail.console.settings.label") }}
</button>
<template #popper>
<div class="console-panel">
<label>{{ t('harvester.virtualMachine.detail.console.settings.viewMode.label') }}</label>
<div
v-for="option in viewModeOptions"
:key="option.value"
>
<label class="console-panel__option">
<input
v-model="settings.viewMode"
type="radio"
:value="option.value"
>
{{ option.label }}
</label>
</div>
<label
for="vnc-zoom"
class="console-panel__zoom-label"
>
<span>{{ t('harvester.virtualMachine.detail.console.settings.zoom') }}</span>
<span>{{ settings.zoomPercent }}%</span>
</label>
<input
id="vnc-zoom"
v-model.number="settings.zoomPercent"
class="console-panel__zoom"
type="range"
min="50"
max="200"
step="10"
:disabled="settings.viewMode === 'scale'"
:aria-valuetext="`${ settings.zoomPercent }%`"
>
<label class="console-panel__option">
<input
v-model="settings.viewOnly"
type="checkbox"
>
{{ t('harvester.virtualMachine.detail.console.settings.viewOnly') }}
</label>
<label
for="vnc-quality"
class="console-panel__zoom-label"
>
<span>{{ t('harvester.virtualMachine.detail.console.settings.quality') }}</span>
<span>{{ settings.qualityLevel }}</span>
</label>
<input
id="vnc-quality"
v-model.number="settings.qualityLevel"
class="console-panel__zoom"
type="range"
min="0"
max="9"
step="1"
>
<label
for="vnc-compression"
class="console-panel__zoom-label"
>
<span>{{ t('harvester.virtualMachine.detail.console.settings.compression') }}</span>
<span>{{ settings.compressionLevel }}</span>
</label>
<input
id="vnc-compression"
v-model.number="settings.compressionLevel"
class="console-panel__zoom"
type="range"
min="0"
max="9"
step="1"
>
</div>
</template>
</v-dropdown>
</div>
<div class="toolbar-group">
<span
class="console-status"
role="status"
aria-live="polite"
>{{ statusLabel }}</span>
<button
v-if="hasSoftRebootAction"
class="btn btn-sm bg-primary"
@click="softReboot"
>
{{ t("harvester.action.softreboot") }}
</button>
<button
class="btn btn-sm bg-primary"
@click="reconnect"
>
{{ t("harvester.action.reconnect") }}
</button>
<button
class="btn btn-sm bg-primary"
@click="toggleFullscreen"
>
{{ isFullscreen ? t('harvester.virtualMachine.detail.console.fullscreen.exit') : t('harvester.virtualMachine.detail.console.fullscreen.enter') }}
</button>
</div>
</div>
<NovncConsole
v-if="url && !isDown"
ref="novncConsole"
:url="url"
:settings="rfbSettings"
:preserve-session="preserveSession"
:vm-running="vmRunning"
@status-changed="onStatusChanged"
@capabilities="onCapabilities"
/>
<p v-if="isDown">
{{ t("harvester.virtualMachine.detail.console.down") }}
</p>
<ModalWithCard
v-if="confirmAction"
name="confirmConsoleAction"
:width="480"
return-focus-selector=".novnc-screen canvas"
@finish="cancelConfirm"
>
<template #title>
{{ t(`harvester.virtualMachine.detail.console.confirm.${ confirmAction }.title`) }}
</template>
<template #content>
<p>{{ t(`harvester.virtualMachine.detail.console.confirm.${ confirmAction }.message`) }}</p>
</template>
<template #footer>
<div class="confirm-actions">
<button
class="btn role-secondary mr-10"
@click="cancelConfirm"
>
{{ t('generic.cancel') }}
</button>
<button
class="btn role-primary"
data-testid="vnc-confirm-action"
@click="runConfirmedAction"
>
{{ t(`harvester.virtualMachine.detail.console.confirm.${ confirmAction }.button`) }}
</button>
</div>
</template>
</ModalWithCard>
<NovncConsoleCustomKeys
v-if="renderKeysModal"
@close="hideKeysModal"
/>
</div>
</div>
</template>
<style lang="scss" scoped>
.vm-console {
height: 100%;
height: 100vh;
height: 100dvh;
display: grid;
grid-template-rows: 30px auto;
grid-template-rows: 32px minmax(0, 1fr);
}
.combination-keys {
display: flex;
align-items: center;
justify-content: space-between;
background: rgb(40, 40, 40);
}
.toolbar-group {
display: flex;
align-items: center;
gap: 4px;
}
.confirm-actions {
display: flex;
justify-content: flex-end;
width: 100%;
}
// The space around the separator above the list.
.custom-shortcut + .custom-shortcut {
margin-top: 7px;
}
.console-status {
color: #fff;
font-size: 12px;
margin-right: 8px;
}
.console-panel {
display: flex;
flex-direction: column;
width: 260px;
padding: 4px;
&__zoom-label {
display: flex;
justify-content: space-between;
margin-top: 8px;
font-variant-numeric: tabular-nums;
}
&__zoom {
width: 100%;
margin: 4px 0 8px;
}
&__option {
display: flex;
align-items: center;
gap: 6px;
margin: 2px 0;
}
}
</style>
<style lang="scss">
@@ -0,0 +1,31 @@
import RFB from '@novnc/novnc/core/rfb';
export function normalizeZoom(value) {
const percent = Number(value);
if (!Number.isFinite(percent)) {
return 100;
}
return Math.min(200, Math.max(50, Math.round(percent / 10) * 10));
}
export default class ZoomableRFB extends RFB {
get zoomPercent() {
return this._zoomPercent ?? 100;
}
set zoomPercent(value) {
this._zoomPercent = normalizeZoom(value);
this._updateScale();
}
_updateScale() {
if (this.scaleViewport) {
super._updateScale();
} else {
this._display.scale = this.zoomPercent / 100;
this._fixScrollbars();
}
}
}
@@ -0,0 +1,197 @@
import { shallowMount } from '@vue/test-utils';
import NovncConsole, { CONSOLE_STATUS, CONSOLE_FAILURE } from '../NovncConsole.vue';
const mockInstances = [];
jest.mock('../ZoomableRFB', () => {
return jest.fn().mockImplementation((el, url) => {
const listeners = {};
const rfb = {
url,
addEventListener: jest.fn((name, cb) => {
listeners[name] = cb;
}),
removeEventListener: jest.fn(),
disconnect: jest.fn(),
focus: jest.fn(),
emit: (name, detail) => listeners[name]?.({ detail }),
};
mockInstances.push(rfb);
return rfb;
});
});
const URL = 'wss://example.com/apis/subresources.kubevirt.io/v1/namespaces/default/virtualmachineinstances/vm/vnc';
const mountConsole = (props = {}) => {
mockInstances.length = 0;
jest.useFakeTimers();
return shallowMount(NovncConsole, { props: { url: URL, ...props } });
};
const lastRFB = () => mockInstances[mockInstances.length - 1];
describe('component: NovncConsole', () => {
it('should connect with preserveSession so an existing session is not kicked', async() => {
mountConsole();
await jest.runOnlyPendingTimersAsync();
expect(new window.URL(lastRFB().url).searchParams.get('preserveSession')).toBe('true');
});
it('should keep retrying while the console is held by another session', async() => {
const wrapper = mountConsole();
await jest.runOnlyPendingTimersAsync();
lastRFB().emit('connect');
// Dropped by another session taking over.
lastRFB().emit('disconnect');
expect(wrapper.vm.status).toBe(CONSOLE_STATUS.RECONNECTING);
// The first retry is rejected because the other session is still active.
jest.advanceTimersByTime(1000);
lastRFB().emit('disconnect');
expect(wrapper.vm.status).toBe(CONSOLE_STATUS.RECONNECTING);
expect(wrapper.vm.retryTimes).toBe(2);
expect(wrapper.vm.statusDetail).toBe('%harvester.virtualMachine.detail.console.status.inUse%');
expect(new window.URL(lastRFB().url).searchParams.get('preserveSession')).toBe('true');
});
it('should fail with a take over option after the retries are exhausted', async() => {
const wrapper = mountConsole();
await jest.runOnlyPendingTimersAsync();
lastRFB().emit('connect');
lastRFB().emit('disconnect');
for (let i = 0; i < wrapper.vm.maximumRetryTimes; i++) {
jest.runOnlyPendingTimers();
lastRFB().emit('disconnect');
}
expect(wrapper.vm.status).toBe(CONSOLE_STATUS.FAILED);
expect(wrapper.vm.failure).toBe(CONSOLE_FAILURE.IN_USE);
expect(wrapper.vm.isClosed).toBe(false);
});
it('should show the console as in use when a running VM refuses the first connection', async() => {
const wrapper = mountConsole();
await jest.runOnlyPendingTimersAsync();
lastRFB().emit('disconnect');
expect(wrapper.vm.status).toBe(CONSOLE_STATUS.FAILED);
expect(wrapper.vm.failure).toBe(CONSOLE_FAILURE.IN_USE);
expect(wrapper.vm.canTakeOver).toBe(true);
});
it('should not claim the console is in use when the VM is not running', async() => {
const wrapper = mountConsole({ vmRunning: false });
await jest.runOnlyPendingTimersAsync();
lastRFB().emit('disconnect');
expect(wrapper.vm.failure).toBe(CONSOLE_FAILURE.UNAVAILABLE);
});
it('should only take over after the modal is confirmed', async() => {
const wrapper = mountConsole();
await jest.runOnlyPendingTimersAsync();
const connections = mockInstances.length;
wrapper.vm.takeOver();
expect(wrapper.vm.showTakeOverModal).toBe(true);
expect(mockInstances).toHaveLength(connections);
wrapper.vm.confirmTakeOver();
expect(wrapper.vm.showTakeOverModal).toBe(false);
expect(new window.URL(lastRFB().url).searchParams.get('preserveSession')).toBe('false');
});
it('should not take over when the modal is cancelled', async() => {
const wrapper = mountConsole();
await jest.runOnlyPendingTimersAsync();
const connections = mockInstances.length;
wrapper.vm.takeOver();
wrapper.vm.cancelTakeOver();
expect(wrapper.vm.showTakeOverModal).toBe(false);
expect(mockInstances).toHaveLength(connections);
});
it('should focus the console once it connects, so typing reaches the VM', async() => {
mountConsole();
await jest.runOnlyPendingTimersAsync();
lastRFB().emit('connect');
expect(lastRFB().focus).toHaveBeenCalledWith();
});
it('should mark the console while it has keyboard focus', async() => {
const wrapper = mountConsole();
const view = wrapper.find('.novnc-screen');
await jest.runOnlyPendingTimersAsync();
view.element.dispatchEvent(new FocusEvent('focusin'));
await wrapper.vm.$nextTick();
expect(view.classes()).toContain('is-focused');
view.element.dispatchEvent(new FocusEvent('focusout'));
await wrapper.vm.$nextTick();
expect(view.classes()).not.toContain('is-focused');
});
describe('when the cluster does not support preserveSession', () => {
it('should connect without the parameter and offer no take over', async() => {
const wrapper = mountConsole({ preserveSession: false });
await jest.runOnlyPendingTimersAsync();
expect(new window.URL(lastRFB().url).searchParams.has('preserveSession')).toBe(false);
lastRFB().emit('disconnect');
expect(wrapper.vm.failure).toBe(CONSOLE_FAILURE.UNAVAILABLE);
expect(wrapper.vm.canTakeOver).toBe(false);
});
it('should not reconnect on its own after the session drops', async() => {
const wrapper = mountConsole({ preserveSession: false });
await jest.runOnlyPendingTimersAsync();
lastRFB().emit('connect');
const connections = mockInstances.length;
lastRFB().emit('disconnect');
jest.runOnlyPendingTimers();
expect(wrapper.vm.status).toBe(CONSOLE_STATUS.DISCONNECTED);
expect(wrapper.vm.failure).toBe(CONSOLE_FAILURE.DROPPED);
expect(wrapper.vm.showError).toBe(true);
expect(mockInstances).toHaveLength(connections);
});
});
it('should close the socket when credentials are required', async() => {
const wrapper = mountConsole();
await jest.runOnlyPendingTimersAsync();
const rfb = lastRFB();
rfb.emit('credentialsrequired');
expect(rfb.disconnect).toHaveBeenCalledWith();
expect(wrapper.vm.rfb).toBeNull();
expect(wrapper.vm.status).toBe(CONSOLE_STATUS.FAILED);
});
});
@@ -0,0 +1,92 @@
import { shallowMount } from '@vue/test-utils';
import Banner from '@components/Banner/Banner.vue';
import NovncConsoleCustomKeys from '../NovncConsoleCustomKeys.vue';
const PREFERED_SHORTCUT_KEYS = 'prefered-shortcut-keys';
const key = (value) => ({ key: value, code: value });
const CTRL_F2 = [key('Control'), key('F2')];
const CTRL_SPACE = [key('Control'), key(' ')];
const ALT_T = [key('Alt'), key('t')];
const mountKeys = (saved = []) => {
const preference = {
data: { [PREFERED_SHORTCUT_KEYS]: JSON.stringify(saved) },
save: jest.fn().mockResolvedValue(),
};
const wrapper = shallowMount(NovncConsoleCustomKeys, {
global: {
mocks: { $store: { getters: { 'management/all': () => [preference] } } },
stubs: { ModalWithCard: { template: '<div><slot name="content" /></div>' } },
},
});
return { wrapper, preference };
};
const listed = (wrapper) => wrapper.find('.displayed-banners').findAllComponents(Banner);
const closeBanner = async(wrapper, index) => {
listed(wrapper)[index].vm.$emit('close');
await wrapper.vm.$nextTick();
};
const savedAfterDone = async(wrapper, preference) => {
await wrapper.vm.saveKeys(jest.fn());
return JSON.parse(preference.data[PREFERED_SHORTCUT_KEYS]);
};
describe('component: NovncConsoleCustomKeys', () => {
it('should offer to remove every listed shortcut', () => {
const { wrapper } = mountKeys([CTRL_F2, ALT_T]);
expect(listed(wrapper).map((banner) => banner.props('closable'))).toStrictEqual([true, true]);
});
it('should save without the shortcut that was removed', async() => {
const { wrapper, preference } = mountKeys([CTRL_F2, ALT_T]);
await closeBanner(wrapper, 0);
expect(listed(wrapper)).toHaveLength(1);
expect(preference.save).not.toHaveBeenCalled();
await expect(savedAfterDone(wrapper, preference)).resolves.toStrictEqual([ALT_T]);
expect(preference.save).toHaveBeenCalledTimes(1);
});
it('should remove a shortcut with the Space key in it', async() => {
const { wrapper, preference } = mountKeys([CTRL_SPACE, ALT_T]);
await closeBanner(wrapper, 0);
await expect(savedAfterDone(wrapper, preference)).resolves.toStrictEqual([ALT_T]);
});
it('should tell a shortcut that was just added from the saved ones', async() => {
const { wrapper, preference } = mountKeys([CTRL_F2]);
wrapper.vm.keysRecord = ALT_T;
wrapper.vm.addShortcutKey();
await wrapper.vm.$nextTick();
// Just added shortcuts are listed first.
await closeBanner(wrapper, 1);
await expect(savedAfterDone(wrapper, preference)).resolves.toStrictEqual([ALT_T]);
});
it('should keep the saved shortcuts when it is closed without saving', async() => {
const { wrapper, preference } = mountKeys([CTRL_F2, ALT_T]);
await closeBanner(wrapper, 0);
wrapper.vm.closeRecordingModal();
expect(wrapper.emitted('close')).toHaveLength(1);
expect(preference.save).not.toHaveBeenCalled();
expect(JSON.parse(preference.data[PREFERED_SHORTCUT_KEYS])).toStrictEqual([CTRL_F2, ALT_T]);
});
});
@@ -0,0 +1,108 @@
import { shallowMount } from '@vue/test-utils';
import NovncConsoleWrapper, { CONFIRM_ACTION } from '../NovncConsoleWrapper.vue';
jest.mock('../ZoomableRFB', () => ({ normalizeZoom: (value) => value }));
jest.mock('@novnc/novnc/core/input/keysym', () => ({}), { virtual: true });
jest.mock('@novnc/novnc/core/input/util', () => ({}), { virtual: true });
const consoleRef = {
ctrlAltDelete: jest.fn(),
focus: jest.fn(),
};
const mountWrapper = () => {
consoleRef.ctrlAltDelete.mockClear();
consoleRef.focus.mockClear();
const wrapper = shallowMount(NovncConsoleWrapper, {
props: {
value: {
id: 'default/vm', metadata: { name: 'vm' }, status: { phase: 'Running' }
}
},
global: {
mocks: {
$store: {
getters: {
'management/all': () => [],
'harvester-common/getFeatureEnabled': () => true,
},
},
$fetchState: { pending: false },
},
stubs: {
NovncConsole: {
template: '<div />',
methods: {
ctrlAltDelete: consoleRef.ctrlAltDelete,
focus: consoleRef.focus,
},
},
},
},
});
wrapper.vm.onStatusChanged({ status: 'connected' });
return wrapper;
};
describe('component: NovncConsoleWrapper', () => {
it('should only send Ctrl+Alt+Del after it is confirmed', async() => {
const wrapper = mountWrapper();
wrapper.vm.ctrlAltDelete();
expect(wrapper.vm.confirmAction).toBe(CONFIRM_ACTION.CTRL_ALT_DEL);
expect(consoleRef.ctrlAltDelete).not.toHaveBeenCalled();
wrapper.vm.runConfirmedAction();
expect(consoleRef.ctrlAltDelete).toHaveBeenCalledTimes(1);
expect(wrapper.vm.confirmAction).toBeNull();
});
it('should not send Ctrl+Alt+Del when the confirmation is cancelled', () => {
const wrapper = mountWrapper();
wrapper.vm.ctrlAltDelete();
wrapper.vm.cancelConfirm();
expect(consoleRef.ctrlAltDelete).not.toHaveBeenCalled();
expect(wrapper.vm.confirmAction).toBeNull();
});
it('should only soft reboot after it is confirmed', () => {
const wrapper = mountWrapper();
const doSoftReboot = jest.fn();
wrapper.vm.vmResource = { doSoftReboot };
wrapper.vm.softReboot();
expect(doSoftReboot).not.toHaveBeenCalled();
wrapper.vm.runConfirmedAction();
expect(doSoftReboot).toHaveBeenCalledTimes(1);
});
it('should not ask to send Ctrl+Alt+Del while keys cannot be sent', () => {
const wrapper = mountWrapper();
wrapper.vm.onStatusChanged({ status: 'reconnecting' });
wrapper.vm.ctrlAltDelete();
expect(wrapper.vm.confirmAction).toBeNull();
});
it('should put the whole page in full screen, so that dialogs rendered outside the console show', async() => {
const wrapper = mountWrapper();
const requestFullscreen = jest.fn().mockResolvedValue();
document.documentElement.requestFullscreen = requestFullscreen;
await wrapper.vm.toggleFullscreen();
expect(requestFullscreen).toHaveBeenCalledTimes(1);
delete document.documentElement.requestFullscreen;
});
});
@@ -19,7 +19,8 @@ export default {
<div class="row mb-20">
<div class="col span-12">
<FileSelector
class="btn btn-sm bg-primary mb-10"
variant="primary"
class="mb-10"
:label="t('generic.readFromFile')"
@selected="onKeySelected"
/>
@@ -191,7 +191,8 @@ export default {
>
<div class="col span-12">
<FileSelector
class="btn btn-sm bg-primary mb-10"
variant="primary"
class="mb-10"
:label="t('generic.readFromFile')"
@selected="onKeySelected"
/>
@@ -213,9 +214,7 @@ $yaml-height: 540px;
:deep() .yaml-editor{
flex: 1;
min-height: $yaml-height;
& .code-mirror .CodeMirror {
position: initial;
height: auto;
& .code-mirror .cm-editor {
min-height: $yaml-height;
}
}
@@ -3,7 +3,7 @@ import { LabeledInput } from '@components/Form/LabeledInput';
import LabeledSelect from '@shell/components/form/LabeledSelect.vue';
import { RadioGroup } from '@components/Form/Radio';
import ArrayList from '@shell/components/form/ArrayList';
import { isValidCIDR } from '@shell/utils/validators/cidr';
import { isValidCIDR } from '@pkg/harvester/utils/regular';
import { _EDIT } from '@shell/config/query-params';
import { Banner } from '@components/Banner';
import { allHash } from '@shell/utils/promise';
@@ -62,7 +62,8 @@ export default {
<div class="chooseFile">
<FileSelector
:include-file-name="true"
class="btn btn-sm bg-primary mr-20"
variant="primary"
class="mr-20"
label="Choose File"
@selected="onKeySelectedCa('publicCertificate', $event)"
/>
@@ -80,7 +81,8 @@ export default {
<div class="chooseFile">
<FileSelector
:include-file-name="true"
class="btn btn-sm bg-primary mr-20"
variant="primary"
class="mr-20"
label="Choose File"
@selected="onKeySelectedCa('privateKey', $event)"
/>
@@ -98,7 +100,8 @@ export default {
<div class="chooseFile">
<FileSelector
:include-file-name="true"
class="btn btn-sm bg-primary mr-20"
variant="primary"
class="mr-20"
label="Choose File"
@selected="onKeySelectedCa('ca', $event)"
/>
@@ -3,7 +3,7 @@ import { LabeledInput } from '@components/Form/LabeledInput';
import LabeledSelect from '@shell/components/form/LabeledSelect.vue';
import { RadioGroup } from '@components/Form/Radio';
import ArrayList from '@shell/components/form/ArrayList';
import { isValidCIDR } from '@shell/utils/validators/cidr';
import { isValidCIDR } from '@pkg/harvester/utils/regular';
import { _EDIT } from '@shell/config/query-params';
import { Banner } from '@components/Banner';
import Tip from '@shell/components/Tip';
@@ -5,7 +5,7 @@ import { RadioGroup } from '@components/Form/Radio';
import { Banner } from '@components/Banner';
import ArrayList from '@shell/components/form/ArrayList';
import { allHash } from '@shell/utils/promise';
import { isValidCIDR } from '@shell/utils/validators/cidr';
import { isValidCIDR } from '@pkg/harvester/utils/regular';
import { NODE } from '@shell/config/types';
import { _EDIT } from '@shell/config/query-params';
import { HCI } from '../../types';
+6 -1
View File
@@ -56,6 +56,7 @@ const FEATURE_FLAGS = {
'kubevirtMigration',
'hotplugNic',
'resumeUpgradePausedNode',
'vncPreserveSession',
],
'v1.7.1': [],
'v1.8.0': [
@@ -81,7 +82,11 @@ const FEATURE_FLAGS = {
'lvmDmThinOnly',
'highPerformanceStorage',
],
'v1.10.0': [],
'v1.10.0': [
'maintenanceModeConditions',
'maintenanceModeDrainTimeoutSetting',
'componentHealth',
],
};
const generateFeatureFlags = () => {
+48 -30
View File
@@ -57,8 +57,12 @@ import {
} from './table-headers';
import { ADD_ONS } from './harvester-map';
import { registerAddonSideNav } from '../utils/dynamic-nav';
import { setStandalonePrime } from '../utils/l10n-globals';
import { setVendor } from '@shell/config/private-label';
import { createCssVars } from '@shell/utils/color';
import { CONFIGURABLE_TABLES } from '@shell/store/features';
import { tableViewsOffFeature } from '../utils/table-views';
import { SETTING } from '@shell/config/settings';
import { primeBrandUpdater } from '../utils/prime-brand';
const TEMPLATE = HCI.VM_VERSION;
const MONITORING_GROUP = 'Monitoring & Logging::Monitoring';
@@ -121,27 +125,9 @@ export function init($plugin, store) {
const [isHarvesterPrime, isDark, privateLabel] = JSON.parse(value);
const primeLogo = isDark ? require('../assets/images/dark/suse-virtualization.svg') : require('../assets/images/suse-virtualization.svg');
setStandalonePrime(isHarvesterPrime);
setVendor(privateLabel || '');
let primaryColorStyle = document.getElementById('harvester-prime-primary-color');
// set harvester prime primary color style to #4dd192 (Cyan Green)
if (isHarvesterPrime) {
if (!primaryColorStyle) {
primaryColorStyle = document.createElement('style');
primaryColorStyle.id = 'harvester-prime-primary-color';
document.head.appendChild(primaryColorStyle);
primaryColorStyle.sheet.insertRule('body.theme-light, body.theme-dark {}', 0);
}
const colors = createCssVars('#4dd192', isDark ? 'dark' : 'light');
const rule = primaryColorStyle.sheet.cssRules[0];
Object.entries(colors).forEach(([property, color]) => rule.style.setProperty(property.trim(), color));
} else {
primaryColorStyle?.remove();
}
const primeLabelKey = privateLabel ? 'harvester.branding.primeLabel' : 'harvester.branding.primeEmptyLabel';
store.dispatch('setIsSingleProduct', {
@@ -156,6 +142,30 @@ export function init($plugin, store) {
},
{ immediate: true }
);
// Keep the shell's table views off: they drop the filters the lists put in the table header
store.watch(
(_state, getters) => getters['management/byId'](MANAGEMENT.FEATURE, CONFIGURABLE_TABLES),
(feature) => {
if (!feature) {
store.dispatch('management/load', { data: tableViewsOffFeature() });
}
},
{ immediate: true }
);
const updateBrand = primeBrandUpdater();
// The value is read too: a change event from the server is loaded into the same setting object
store.watch(
(_state, getters) => {
const brandSetting = getters['management/byId'](MANAGEMENT.SETTING, SETTING.BRAND);
return [!!getters['harvester-common/isHarvesterPrime'], brandSetting, brandSetting?.value];
},
([isHarvesterPrime, brandSetting]) => updateBrand(brandSetting, isHarvesterPrime),
{ immediate: true }
);
}
product({
@@ -700,16 +710,24 @@ export function init($plugin, store) {
basicType(
[
TEMPLATE,
HCI.SSH,
HCI.CLOUD_TEMPLATE,
HCI.STORAGE,
HCI.SR_IOV,
HCI.PCI_DEVICE,
HCI.SR_IOVGPU_DEVICE,
HCI.VGPU_DEVICE,
HCI.MIG_CONFIGURATION,
HCI.USB_DEVICE,
],
'hardwareDevices'
);
weightGroup('hardwareDevices', 488, true);
basicType(
[
TEMPLATE,
HCI.SSH,
HCI.CLOUD_TEMPLATE,
HCI.STORAGE,
HCI.ADD_ONS,
HCI.SECRET,
HCI.SETTING
@@ -1107,7 +1125,7 @@ export function init($plugin, store) {
virtualType({
label: 'PCI Devices',
group: 'advanced',
group: 'hardwareDevices',
weight: 14,
name: HCI.PCI_DEVICE,
namespaced: false,
@@ -1143,7 +1161,7 @@ export function init($plugin, store) {
virtualType({
ifHaveType: HCI.SR_IOV,
labelKey: 'harvester.sriov.label',
group: 'advanced',
group: 'hardwareDevices',
weight: 15,
name: HCI.SR_IOV,
namespaced: false,
@@ -1163,7 +1181,7 @@ export function init($plugin, store) {
virtualType({
ifHaveType: HCI.SR_IOVGPU_DEVICE,
labelKey: 'harvester.sriovgpu.label',
group: 'advanced',
group: 'hardwareDevices',
weight: 13,
name: HCI.SR_IOVGPU_DEVICE,
namespaced: false,
@@ -1182,7 +1200,7 @@ export function init($plugin, store) {
virtualType({
labelKey: 'harvester.vgpu.label',
group: 'advanced',
group: 'hardwareDevices',
weight: 12,
name: HCI.VGPU_DEVICE,
namespaced: false,
@@ -1210,7 +1228,7 @@ export function init($plugin, store) {
virtualType({
labelKey: 'harvester.migconfiguration.label',
group: 'advanced',
group: 'hardwareDevices',
weight: 12,
name: HCI.MIG_CONFIGURATION,
namespaced: false,
@@ -1230,7 +1248,7 @@ export function init($plugin, store) {
virtualType({
labelKey: 'harvester.usb.label',
group: 'advanced',
group: 'hardwareDevices',
weight: 11,
name: HCI.USB_DEVICE,
namespaced: false,
+1 -1
View File
@@ -22,7 +22,7 @@ export const HCI = {
VM_NAME_PREFIX: 'harvesterhci.io/vmNamePrefix',
VM_DISPLAY_NAME: 'harvesterhci.io/vmDisplayName',
VM_RESERVED_MEMORY: 'harvesterhci.io/reservedMemory',
MAINTENANCE_STATUS: 'harvesterhci.io/maintain-status',
MAINTENANCE_STATUS: 'harvesterhci.io/maintain-status', // Deprecated >= v1.10.0
HOST_CUSTOM_NAME: 'harvesterhci.io/host-custom-name',
HOST_CONSOLE_URL: 'harvesterhci.io/host-console-url',
RESTORE_NAME: 'restore.harvesterhci.io/name',
+5 -1
View File
@@ -45,7 +45,8 @@ export const HCI_SETTING = {
MAX_HOTPLUG_RATIO: 'max-hotplug-ratio',
KUBEVIRT_MIGRATION: 'kubevirt-migration',
INSTANCE_MANAGER_RESOURCES: 'instance-manager-resources',
CLUSTER_POD_SECURITY_STANDARD: 'cluster-pod-security-standard'
CLUSTER_POD_SECURITY_STANDARD: 'cluster-pod-security-standard',
MAINTENANCE_MODE_DRAIN_TIMEOUT: 'maintenance-mode-drain-timeout'
};
export const HCI_ALLOWED_SETTINGS = {
@@ -148,6 +149,9 @@ export const HCI_ALLOWED_SETTINGS = {
},
[HCI_SETTING.CLUSTER_POD_SECURITY_STANDARD]: {
kind: 'json', from: 'import', canReset: true, featureFlag: 'clusterPodSecurityStandardSetting'
},
[HCI_SETTING.MAINTENANCE_MODE_DRAIN_TIMEOUT]: {
kind: 'number', canReset: true, featureFlag: 'maintenanceModeDrainTimeoutSetting'
}
};
+7
View File
@@ -15,6 +15,13 @@ export const VOLUME_MODE = {
FILE_SYSTEM: 'Filesystem'
};
export const ACCESS_MODE = {
READ_WRITE_MANY: 'ReadWriteMany',
READ_WRITE_ONCE: 'ReadWriteOnce',
READ_ONLY_MANY: 'ReadOnlyMany',
READ_WRITE_ONCE_POD: 'ReadWriteOncePod',
};
export const NETWORK_PROTOCOL = {
IPv4: 'IPv4',
IPv6: 'IPv6',
@@ -15,6 +15,7 @@ import OverviewKeypairs from '../kubevirt.io.virtualmachine/VirtualMachineTabs/V
import Volume from '../../edit/kubevirt.io.virtualmachine/VirtualMachineVolume';
import Network from '../../edit/kubevirt.io.virtualmachine/VirtualMachineNetwork';
import CloudConfig from '../../edit/kubevirt.io.virtualmachine/VirtualMachineCloudConfig';
import { getBootDevices } from '../../utils/vm';
const UNDEFINED = 'n/a';
export default {
@@ -74,18 +75,8 @@ export default {
return image?.spec?.displayName || '-';
},
disks() {
const disks = this?.spec?.template?.spec?.domain?.devices?.disks || [];
return disks.filter((disk) => {
return !!disk.bootOrder;
}).sort((a, b) => {
if (a.bootOrder < b.bootOrder) {
return -1;
}
return 1;
});
bootDevices() {
return getBootDevices(this?.spec?.template?.spec?.domain?.devices);
},
cdroms() {
@@ -101,8 +92,10 @@ export default {
getDeviceType(o) {
if (o.disk) {
return 'Disk';
} else {
} else if (o.cdrom) {
return 'CD-ROM';
} else {
return 'Network';
}
},
isEmpty(o) {
@@ -184,10 +177,10 @@ export default {
<div>
<ul>
<li
v-for="(disk, i) in disks"
v-for="(device, i) in bootDevices"
:key="i"
>
{{ disk.bootOrder }}. {{ disk.name }} ({{ getDeviceType(disk) }})
{{ device.bootOrder }}. {{ device.name }} ({{ getDeviceType(device) }})
</li>
</ul>
</div>
@@ -233,6 +226,7 @@ export default {
>
<Network
v-model:value="networkRows"
:network-boot-first="networkBootFirst"
:mode="mode"
/>
</Tab>
@@ -15,6 +15,7 @@ import OverviewKeypairs from '../kubevirt.io.virtualmachine/VirtualMachineTabs/V
import Volume from '../../edit/kubevirt.io.virtualmachine/VirtualMachineVolume';
import Network from '../../edit/kubevirt.io.virtualmachine/VirtualMachineNetwork';
import CloudConfig from '../../edit/kubevirt.io.virtualmachine/VirtualMachineCloudConfig';
import { getBootDevices } from '../../utils/vm';
const UNDEFINED = 'n/a';
export default {
@@ -74,18 +75,8 @@ export default {
return image?.spec?.displayName || '-';
},
disks() {
const disks = this?.spec?.template?.spec?.domain?.devices?.disks || [];
return disks.filter((disk) => {
return !!disk.bootOrder;
}).sort((a, b) => {
if (a.bootOrder < b.bootOrder) {
return -1;
}
return 1;
});
bootDevices() {
return getBootDevices(this?.spec?.template?.spec?.domain?.devices);
},
cdroms() {
@@ -101,8 +92,10 @@ export default {
getDeviceType(o) {
if (o.disk) {
return 'Disk';
} else {
} else if (o.cdrom) {
return 'CD-ROM';
} else {
return 'Network';
}
},
isEmpty(o) {
@@ -184,10 +177,10 @@ export default {
<div>
<ul>
<li
v-for="(disk, i) in disks"
v-for="(device, i) in bootDevices"
:key="i"
>
{{ disk.bootOrder }}. {{ disk.name }} ({{ getDeviceType(disk) }})
{{ device.bootOrder }}. {{ device.name }} ({{ getDeviceType(device) }})
</li>
</ul>
</div>
@@ -234,6 +227,7 @@ export default {
>
<Network
v-model:value="networkRows"
:network-boot-first="networkBootFirst"
:mode="mode"
/>
</Tab>
@@ -6,6 +6,7 @@ import HarvesterIpAddress from '../../../formatters/HarvesterIpAddress';
import VMConsoleBar from '../../../components/VMConsoleBar';
import { HCI } from '../../../types';
import { getVmCPUMemoryValues } from '../../../utils/cpuMemory';
import { getBootDevices } from '../../../utils/vm';
const UNDEFINED = 'n/a';
@@ -69,18 +70,8 @@ export default {
return image?.spec?.displayName || 'N/A';
},
disks() {
const disks = this.value?.spec?.template?.spec?.domain?.devices?.disks || [];
return disks.filter((disk) => {
return !!disk.bootOrder;
}).sort((a, b) => {
if (a.bootOrder < b.bootOrder) {
return -1;
}
return 1;
});
bootDevices() {
return getBootDevices(this.value?.spec?.template?.spec?.domain?.devices);
},
cdroms() {
@@ -122,8 +113,10 @@ export default {
getDeviceType(o) {
if (o.disk) {
return 'Disk';
} else {
} else if (o.cdrom) {
return 'CD-ROM';
} else {
return 'Network';
}
},
isEmpty(o) {
@@ -219,16 +212,16 @@ export default {
<div class="col span-6">
<InputOrDisplay
:name="t('harvester.virtualMachine.detail.details.bootOrder')"
:value="disks"
:value="bootDevices"
:mode="mode"
>
<template #value>
<ul>
<li
v-for="(disk, i) in disks"
v-for="(device, i) in bootDevices"
:key="i"
>
{{ disk.bootOrder }}. {{ disk.name }} ({{ getDeviceType(disk) }})
{{ device.bootOrder }}. {{ device.name }} ({{ getDeviceType(device) }})
</li>
</ul>
</template>
@@ -14,9 +14,11 @@ import Labels from '@shell/components/form/Labels';
import LabelValue from '@shell/components/LabelValue';
import { HCI } from '../../types';
import VM_MIXIN from '../../mixins/harvester-vm';
import { getLatestMigration } from '../../utils/vm';
import CloudConfig from '../../edit/kubevirt.io.virtualmachine/VirtualMachineCloudConfig';
import Volume from '../../edit/kubevirt.io.virtualmachine/VirtualMachineVolume';
import VMPerformanceOptions from '../../edit/kubevirt.io.virtualmachine/VirtualMachineVolume/VMPerformanceOptions';
import Network from '../../edit/kubevirt.io.virtualmachine/VirtualMachineNetwork';
import AccessCredentials from '../../edit/kubevirt.io.virtualmachine/VirtualMachineAccessCredentials';
import Events from './VirtualMachineTabs/VirtualMachineEvents';
@@ -39,6 +41,7 @@ export default {
OverviewBasics,
LabelValue,
Volume,
VMPerformanceOptions,
Network,
OverviewKeypairs,
CloudConfig,
@@ -139,18 +142,7 @@ export default {
const inStore = this.$store.getters['currentProduct'].inStore;
const vmimList = this.$store.getters[`${ inStore }/all`](HCI.VMIM) || [];
const vmiName = this.vmi?.name || '';
// filter the corresponding vmims by vmim.spec.vmiName and find the latest one by creationTimestamp
const vmim = vmimList.filter((VMIM) => VMIM?.spec?.vmiName === vmiName).sort((a, b) => {
if (a?.metadata?.creationTimestamp > b?.metadata?.creationTimestamp) {
return -1;
}
return 1;
});
return vmim.length > 0 && vmim[0] ? vmim[0] : null;
return getLatestMigration(vmimList, this.vmi?.metadata?.namespace, this.vmi?.name) || null;
},
migrationEvents() {
@@ -214,6 +206,7 @@ export default {
this['diskRows'] = diskRows;
this['networkRows'] = this.getNetworkRows(neu, { fromTemplate: false, init: false });
this['networkBootFirst'] = this.isNetworkBootFirst(neu.spec);
// getInitConfig() seeds these on created(); refresh them here too so the
// VM-wide performance panel does not go stale when the spec changes.
@@ -262,9 +255,15 @@ export default {
:namespace="value.metadata.namespace"
:vm="value"
:resource-type="value.type"
/>
<VMPerformanceOptions
:block-multi-queue="blockMultiQueue"
:io-threads-policy="ioThreadsPolicy"
:io-thread-count="ioThreadCount"
:has-virtio-disk="hasVirtioDisk"
:has-dedicated-iothread="hasDedicatedIOThread"
mode="view"
class="mt-20"
/>
</Tab>
@@ -276,6 +275,7 @@ export default {
>
<Network
v-model:value="networkRows"
:network-boot-first="networkBootFirst"
mode="view"
:vm="value"
/>
@@ -0,0 +1,141 @@
import { mount } from '@vue/test-utils';
import { _CREATE, _EDIT, _VIEW } from '@shell/config/query-params';
import YamlEditor from '@shell/components/YamlEditor';
import { HCI } from '@pkg/harvester/config/labels-annotations';
import HarvesterEditCloudTemplate from '../harvesterhci.io.cloudtemplate.vue';
const OLD_CONFIG = '#cloud-config\npassword: old\n';
const NEW_CONFIG = '#cloud-config\npassword: new\n';
// A cloud-config template as the store gives it, `save` records what would be sent to the API
function cloudTemplate({ isNew = false } = {}) {
const value = {
type: 'configmap',
metadata: {
name: 'tpl',
namespace: 'default',
...(isNew ? {} : { labels: { [HCI.CLOUD_INIT]: 'user' } }),
},
data: isNew ? undefined : { cloudInit: OLD_CONFIG },
$dispatch: jest.fn(),
save: () => Promise.resolve(),
saved: [],
};
jest.spyOn(value, 'save').mockImplementation(() => {
value.saved.push(JSON.parse(JSON.stringify({ metadata: value.metadata, data: value.data })));
return Promise.resolve();
});
return value;
}
// The real shell YamlEditor, with only its CodeMirror editor stubbed, so the events the form listens to are the
// ones the shell emits
function mountForm(mode, value) {
return mount(HarvesterEditCloudTemplate, {
props: { value, mode },
global: {
stubs: {
CruResource: { template: '<div><slot /></div>' },
Tabbed: { template: '<div><slot /></div>' },
Tab: { template: '<div><slot /></div>' },
NameNsDescription: true,
LabeledSelect: true,
CodeMirror: {
name: 'CodeMirror', template: '<div />', emits: ['onInput', 'onReady', 'validationChanged']
},
FileDiff: true,
},
mocks: {
$store: {
getters: {
'prefs/get': jest.fn(),
'type-map/isSpoofed': () => false,
currentStore: () => 'harvester',
'harvester/schemaFor': () => ({ linkFor: () => '/v1/harvester/configmaps' }),
'i18n/t': (key) => key,
},
},
$router: { replace: jest.fn() },
$route: {
name: 'c-cluster-product-resource-id', params: {}, query: {}
},
},
},
});
}
// What a user typing in the editor does: CodeMirror reports the new text to the YamlEditor
async function typeInEditor(wrapper, text) {
wrapper.findComponent(YamlEditor).findComponent({ name: 'CodeMirror' }).vm.$emit('onInput', text);
await wrapper.vm.$nextTick();
}
describe('component: HarvesterEditCloudTemplate', () => {
it('should save the edited cloud config when editing a template', async() => {
const value = cloudTemplate();
const wrapper = mountForm(_EDIT, value);
await typeInEditor(wrapper, NEW_CONFIG);
await wrapper.vm.save(jest.fn());
expect(value.save).toHaveBeenCalledTimes(1);
expect(value.saved[0].data).toStrictEqual({ cloudInit: NEW_CONFIG });
});
it('should keep the template type label when editing a template', async() => {
const value = cloudTemplate();
const wrapper = mountForm(_EDIT, value);
await typeInEditor(wrapper, NEW_CONFIG);
await wrapper.vm.save(jest.fn());
expect(value.saved[0].metadata.labels).toStrictEqual({ [HCI.CLOUD_INIT]: 'user' });
});
it('should save the last text when the cloud config is edited several times', async() => {
const value = cloudTemplate();
const wrapper = mountForm(_EDIT, value);
await typeInEditor(wrapper, '#cloud-config\n');
await typeInEditor(wrapper, NEW_CONFIG);
await wrapper.vm.save(jest.fn());
expect(value.saved[0].data).toStrictEqual({ cloudInit: NEW_CONFIG });
});
it('should save the cloud config unchanged when only saving a template', async() => {
const value = cloudTemplate();
const wrapper = mountForm(_EDIT, value);
await wrapper.vm.save(jest.fn());
expect(value.saved[0].data).toStrictEqual({ cloudInit: OLD_CONFIG });
});
it('should save the cloud config and the template type when creating a template', async() => {
const value = cloudTemplate({ isNew: true });
const wrapper = mountForm(_CREATE, value);
await typeInEditor(wrapper, NEW_CONFIG);
await wrapper.vm.save(jest.fn());
expect(value.save).toHaveBeenCalledWith({ url: '/v1/harvester/configmaps' });
expect(value.saved[0]).toStrictEqual({
metadata: {
name: 'tpl', namespace: 'default', labels: { [HCI.CLOUD_INIT]: 'user' }
},
data: { cloudInit: NEW_CONFIG },
});
});
it('should show the template cloud config in the editor when viewing a template', () => {
const value = cloudTemplate();
const wrapper = mountForm(_VIEW, value);
expect(wrapper.findComponent(YamlEditor).props('value')).toBe(OLD_CONFIG);
expect(value.data).toStrictEqual({ cloudInit: OLD_CONFIG });
});
});
@@ -0,0 +1,36 @@
import { HCI } from '@pkg/harvester/types';
import VM_MIXIN from '@pkg/harvester/mixins/harvester-vm';
import HarvesterEditTemplateVersion from '../harvesterhci.io.virtualmachinetemplateversion.vue';
async function saveWith(userScript) {
const buttonCb = jest.fn();
const form = {
userScript,
errors: [],
t: (key) => key,
parseVM: jest.fn(),
validateCloudInit: VM_MIXIN.methods.validateCloudInit,
templateValue: { metadata: {} },
$store: { dispatch: jest.fn().mockResolvedValue([]) },
};
await HarvesterEditTemplateVersion.methods.saveVMT.call(form, buttonCb);
return { form, buttonCb };
}
describe('page: harvesterhci.io.virtualmachinetemplateversion edit', () => {
it('should stop the save when the cloud config is invalid', async() => {
const { form, buttonCb } = await saveWith('#cloud-config\nsome words\n');
expect(form.errors).toStrictEqual(['harvester.virtualMachine.cloudConfig.user.invalidYaml']);
expect(buttonCb).toHaveBeenCalledWith(false);
expect(form.$store.dispatch).not.toHaveBeenCalled();
});
it('should go on with the save when the user data is a script', async() => {
const { form } = await saveWith('#!/bin/bash\napt-get update\n# start it\nsystemctl enable --now nginx\n');
expect(form.$store.dispatch).toHaveBeenCalledWith('harvester/findAll', { type: HCI.VM_TEMPLATE });
});
});
@@ -59,8 +59,8 @@ export default {
},
methods: {
update() {
this.value.data = { cloudInit: this.config };
update(config) {
this.value.data = { cloudInit: config };
},
updateBeforeSave() {
@@ -119,7 +119,7 @@ export default {
:mode="mode"
class="yaml-editor"
:editor-mode="mode === 'view' ? 'VIEW_CODE' : 'EDIT_CODE'"
@onChanges="update"
@update:value="update"
/>
</div>
</Tab>
@@ -133,9 +133,7 @@ export default {
:deep() .yaml-editor{
flex: 1;
min-height: $yaml-height;
& .code-mirror .CodeMirror {
position: initial;
height: auto;
& .code-mirror .cm-editor {
min-height: $yaml-height;
}
}
@@ -88,7 +88,8 @@ export default {
<div class="header mb-20">
<FileSelector
v-if="isCreate"
class="btn btn-sm bg-primary mt-10"
variant="primary"
class="mt-10"
:label="t('generic.readFromFile')"
accept=".pub"
@selected="onKeySelected"
@@ -16,6 +16,8 @@ import isEmpty from 'lodash/isEmpty';
import jsyaml from 'js-yaml';
import { createYaml } from '@shell/utils/create-yaml';
import YamlEditor, { EDITOR_MODES } from '@shell/components/YamlEditor';
import { foldAllComments } from '@components/RcCodeMirror';
import { unfoldCode } from '@codemirror/language';
import { FLOW_TYPE } from '../config/harvester-map';
const LOGGING_EVENT = 'Logging/Event';
@@ -172,10 +174,9 @@ export default {
});
}
},
onYamlEditorReady(cm) {
cm.getMode().fold = 'yamlcomments';
cm.execCommand('foldAll');
cm.execCommand('unfold');
onYamlEditorReady(view) {
foldAllComments(view);
unfoldCode(view);
},
}
};
@@ -1,5 +1,5 @@
<script>
import { VOLUME_MODE } from '@pkg/harvester/config/types';
import { VOLUME_MODE, ACCESS_MODE } from '@pkg/harvester/config/types';
import { HCI as HCI_ANNOTATIONS } from '@pkg/harvester/config/labels-annotations';
import ArrayList from '@shell/components/form/ArrayList';
import { Checkbox } from '@components/Form/Checkbox';
@@ -10,6 +10,10 @@ import { HCI_SETTING } from '../../config/settings';
import { allHash } from '@shell/utils/promise';
import { _EDIT, _CREATE } from '@shell/config/query-params';
const {
READ_WRITE_ONCE, READ_ONLY_MANY, READ_WRITE_MANY, READ_WRITE_ONCE_POD
} = ACCESS_MODE;
export default {
name: 'CDISettings',
@@ -90,10 +94,10 @@ export default {
accessModeOptions() {
return [
{ label: 'ReadWriteOnce', value: 'ReadWriteOnce' },
{ label: 'ReadOnlyMany', value: 'ReadOnlyMany' },
{ label: 'ReadWriteMany', value: 'ReadWriteMany' },
{ label: 'ReadWriteOncePod', value: 'ReadWriteOncePod' },
{ label: READ_WRITE_ONCE, value: READ_WRITE_ONCE },
{ label: READ_ONLY_MANY, value: READ_ONLY_MANY },
{ label: READ_WRITE_MANY, value: READ_WRITE_MANY },
{ label: READ_WRITE_ONCE_POD, value: READ_WRITE_ONCE_POD },
];
},
@@ -173,6 +173,7 @@ export default {
try {
await proxyResource.save();
proxyResource.notifyGeneratedName?.();
buttonCb(true);
this.$router.push({
@@ -299,6 +299,7 @@ export default {
const res = await this.value.save();
res.notifyGeneratedName?.();
res.uploadImage(file);
buttonCb(true);
@@ -21,6 +21,7 @@ import { HCI } from '../types';
import VM_MIXIN from '../mixins/harvester-vm';
import Reserved from './kubevirt.io.virtualmachine/VirtualMachineReserved';
import Volume from './kubevirt.io.virtualmachine/VirtualMachineVolume';
import VMPerformanceOptions from './kubevirt.io.virtualmachine/VirtualMachineVolume/VMPerformanceOptions';
import Network from './kubevirt.io.virtualmachine/VirtualMachineNetwork';
import CpuMemory from './kubevirt.io.virtualmachine/VirtualMachineCpuMemory';
import CpuModel from './kubevirt.io.virtualmachine/VirtualMachineCpuModel';
@@ -37,6 +38,7 @@ export default {
Tab,
SSHKey,
Volume,
VMPerformanceOptions,
Tabbed,
Network,
Checkbox,
@@ -177,8 +179,17 @@ export default {
},
async saveVMT(buttonCb) {
this.errors = [];
this.parseVM();
this.validateCloudInit();
if (this.errors.length) {
buttonCb(false);
return;
}
const templates = await this.$store.dispatch('harvester/findAll', { type: HCI.VM_TEMPLATE });
const template = templates.find( (O) => O.metadata.name === this.templateValue.metadata.name);
@@ -278,6 +289,25 @@ export default {
name="Basics"
:label="t('harvester.vmTemplate.tabs.basics')"
>
<div class="row mb-20">
<div class="col span-6">
<LabeledSelect
v-model:value="osType"
label-key="harvester.virtualMachine.osType"
:mode="mode"
:options="OS"
:tooltip="isCreate ? t('harvester.virtualMachine.osTypeTooltip') : null"
/>
</div>
<div class="col span-6">
<CpuModel
:value="spec.template.spec.domain.cpu?.model || ''"
:mode="mode"
@update:value="updateCpuModel"
/>
</div>
</div>
<CpuMemory
class="mb-20"
:cpu="cpu"
@@ -289,6 +319,69 @@ export default {
@updateCpuMemory="updateCpuMemory"
/>
<div class="mb-20">
<Checkbox
v-if="value.cpuPinningFeatureEnabled"
v-model:value="cpuPinning"
class="check"
type="checkbox"
tooltip-key="harvester.virtualMachine.cpuPinning.tooltip"
label-key="harvester.virtualMachine.cpuPinning.label"
:mode="mode"
/>
<Checkbox
v-model:value="installUSBTablet"
class="check"
type="checkbox"
:label="t('harvester.virtualMachine.enableUsb')"
:mode="mode"
/>
<Checkbox
v-model:value="tpmEnabled"
class="check"
type="checkbox"
label-key="harvester.virtualMachine.systemOptions.tpm"
:mode="mode"
/>
<Checkbox
v-if="value.tpmPersistentStateFeatureEnabled && tpmEnabled"
v-model:value="tpmPersistentStateEnabled"
class="check"
type="checkbox"
:label="t('harvester.virtualMachine.systemOptions.tpmPersistentState')"
:mode="mode"
/>
<Checkbox
v-model:value="efiEnabled"
class="check"
type="checkbox"
:label="t('harvester.virtualMachine.systemOptions.efiEnabled')"
:mode="mode"
/>
<Checkbox
v-if="value.efiPersistentStateFeatureEnabled && efiEnabled"
v-model:value="efiPersistentStateEnabled"
class="check"
type="checkbox"
:label="t('harvester.virtualMachine.systemOptions.efiPersistentState')"
:mode="mode"
/>
<Checkbox
v-if="efiEnabled"
v-model:value="secureBoot"
class="check"
type="checkbox"
:label="t('harvester.virtualMachine.systemOptions.secureBoot')"
:mode="mode"
/>
</div>
<div class="mb-20">
<SSHKey
v-model:value="sshKey"
@@ -308,9 +401,6 @@ export default {
>
<Volume
v-model:value="diskRows"
v-model:block-multi-queue="blockMultiQueue"
v-model:io-threads-policy="ioThreadsPolicy"
v-model:io-thread-count="ioThreadCount"
:mode="mode"
:namespace="value.metadata.namespace"
:existing-volume-disabled="true"
@@ -324,6 +414,7 @@ export default {
>
<Network
v-model:value="networkRows"
v-model:network-boot-first="networkBootFirst"
:mode="mode"
/>
</Tab>
@@ -445,18 +536,6 @@ export default {
:mode="mode"
/>
</div>
<div class="col span-6">
<LabeledSelect
v-model:value="osType"
label-key="harvester.virtualMachine.osType"
:mode="mode"
:options="OS"
/>
</div>
</div>
<div class="row mb-20">
<div class="col span-6">
<LabeledSelect
v-model:value="maintenanceStrategy"
@@ -466,6 +545,9 @@ export default {
:mode="mode"
/>
</div>
</div>
<div class="row mb-20">
<div class="col span-6">
<Reserved
:reserved-memory="reservedMemory"
@@ -475,16 +557,6 @@ export default {
</div>
</div>
<div class="row mb-20">
<div class="col span-6">
<CpuModel
:value="spec.template.spec.domain.cpu?.model || ''"
:mode="mode"
@update:value="updateCpuModel"
/>
</div>
</div>
<div class="row mb-20">
<a
v-if="showAdvanced"
@@ -514,6 +586,16 @@ export default {
</div>
</div>
<VMPerformanceOptions
v-model:block-multi-queue="blockMultiQueue"
v-model:io-threads-policy="ioThreadsPolicy"
v-model:io-thread-count="ioThreadCount"
:has-virtio-disk="hasVirtioDisk"
:has-dedicated-iothread="hasDedicatedIOThread"
:mode="mode"
class="mb-20"
/>
<CloudConfig
ref="yamlEditor"
:mode="mode"
@@ -522,76 +604,17 @@ export default {
:network-script="networkScript"
@updateUserData="updateUserData"
@updateNetworkData="updateNetworkData"
/>
<div class="spacer"></div>
<Checkbox
v-if="value.cpuPinningFeatureEnabled"
v-model:value="cpuPinning"
class="check"
type="checkbox"
tooltip-key="harvester.virtualMachine.cpuPinning.tooltip"
label-key="harvester.virtualMachine.cpuPinning.label"
:mode="mode"
/>
<Checkbox
v-model:value="installUSBTablet"
class="check"
type="checkbox"
:label="t('harvester.virtualMachine.enableUsb')"
:mode="mode"
/>
<Checkbox
v-model:value="installAgent"
class="check"
type="checkbox"
label-key="harvester.virtualMachine.installAgent"
:mode="mode"
/>
<Checkbox
v-model:value="tpmEnabled"
class="check"
type="checkbox"
label-key="harvester.virtualMachine.advancedOptions.tpm"
:mode="mode"
/>
<Checkbox
v-if="value.tpmPersistentStateFeatureEnabled && tpmEnabled"
v-model:value="tpmPersistentStateEnabled"
class="check"
type="checkbox"
:label="t('harvester.virtualMachine.advancedOptions.tpmPersistentState')"
:mode="mode"
/>
<Checkbox
v-model:value="efiEnabled"
class="check"
type="checkbox"
:label="t('harvester.virtualMachine.advancedOptions.efiEnabled')"
:mode="mode"
/>
<Checkbox
v-if="value.efiPersistentStateFeatureEnabled && efiEnabled"
v-model:value="efiPersistentStateEnabled"
class="check"
type="checkbox"
:label="t('harvester.virtualMachine.advancedOptions.efiPersistentState')"
:mode="mode"
/>
<Checkbox
v-if="efiEnabled"
v-model:value="secureBoot"
class="check"
type="checkbox"
:label="t('harvester.virtualMachine.advancedOptions.secureBoot')"
:mode="mode"
/>
>
<template #after-user-data>
<Checkbox
v-model:value="installAgent"
class="check mb-20"
type="checkbox"
label-key="harvester.virtualMachine.installAgent"
:mode="mode"
/>
</template>
</CloudConfig>
</Tab>
</Tabbed>
</CruResource>
@@ -172,6 +172,7 @@ export default {
try {
await proxyResource.save();
proxyResource.notifyGeneratedName?.();
buttonCb(true);
this.$router.push({
@@ -27,9 +27,11 @@ import { HCI, VOLUME_SNAPSHOT } from '../types';
import { LVM_DRIVER } from '../models/harvester/storage.k8s.io.storageclass';
import { DATA_ENGINE_V2 } from '../models/harvester/persistentvolumeclaim';
import { GIBIBYTE } from '../utils/unit';
import { VOLUME_MODE } from '@pkg/harvester/config/types';
import { VOLUME_MODE, ACCESS_MODE } from '@pkg/harvester/config/types';
import { isInternalStorageClass } from '../utils/storage-class';
const { READ_WRITE_MANY, READ_WRITE_ONCE, READ_ONLY_MANY } = ACCESS_MODE;
export default {
name: 'HarvesterVolume',
@@ -85,7 +87,7 @@ export default {
if (this.mode === _CREATE) {
// default volumeMode to Block
this.value.spec.volumeMode = VOLUME_MODE.BLOCK;
this.value.spec.accessModes = ['ReadWriteMany'];
this.value.spec.accessModes = [READ_WRITE_MANY];
}
const storage = this.value?.spec?.resources?.requests?.storage || null;
@@ -170,7 +172,7 @@ export default {
},
accessModeOptions() {
return ['ReadWriteOnce', 'ReadWriteMany', 'ReadOnlyMany'];
return [READ_WRITE_ONCE, READ_WRITE_MANY, READ_ONLY_MANY];
},
imageOption() {
@@ -366,7 +368,7 @@ export default {
getAccessMode() {
if (!this.longhornV2LVMSupport) {
return ['ReadWriteMany'];
return [READ_WRITE_MANY];
}
if (this.value?.spec?.accessModes && this.value?.spec?.accessModes?.length > 0) {
@@ -382,7 +384,7 @@ export default {
readWriteOnce = storageClass.provisioner === LVM_DRIVER || (!this.value.thirdPartyStorageFeatureEnabled && storageClass.parameters?.dataEngine === DATA_ENGINE_V2);
}
return readWriteOnce ? ['ReadWriteOnce'] : ['ReadWriteMany'];
return readWriteOnce ? [READ_WRITE_ONCE] : [READ_WRITE_MANY];
},
buildDataVolumeObj() {
const storage = {
@@ -157,7 +157,7 @@ $yaml-height: 200px;
flex: 1;
min-height: $yaml-height;
& .code-mirror .CodeMirror {
& .code-mirror .cm-editor {
min-height: $yaml-height;
}
}
@@ -219,6 +219,8 @@ export default {
/>
</div>
<slot name="after-user-data" />
<div class="mb-20">
<DataTemplate
ref="networkTemplate"
@@ -287,7 +289,7 @@ $yaml-height: 350px;
flex: 1;
min-height: $yaml-height;
& .code-mirror .CodeMirror {
& .code-mirror .cm-editor {
min-height: $yaml-height;
}
}
@@ -2,6 +2,7 @@
import InputOrDisplay from '@shell/components/InputOrDisplay';
import { LabeledInput } from '@components/Form/LabeledInput';
import LabeledSelect from '@shell/components/form/LabeledSelect';
import { Checkbox } from '@components/Form/Checkbox';
import { clone } from '@shell/utils/object';
import { _CREATE, _VIEW } from '@shell/config/query-params';
@@ -33,7 +34,7 @@ export default {
emits: ['update'],
components: {
LabeledInput, LabeledSelect, InputOrDisplay
LabeledInput, LabeledSelect, InputOrDisplay, Checkbox
},
props: {
@@ -169,6 +170,7 @@ export default {
this.value.isPod = true;
this.value.macAddress = '';
this.value.staticIp = '';
this.value.networkBoot = false;
} else {
this.value.isPod = false;
}
@@ -285,6 +287,22 @@ export default {
</div>
</div>
<div
v-if="!isMasquerade"
data-testid="input-hen-networkBoot"
class="row mb-20"
>
<div class="col span-12">
<Checkbox
v-model:value="value.networkBoot"
:label="t('harvester.virtualMachine.network.networkBoot.label')"
:tooltip="t('harvester.virtualMachine.network.networkBoot.tip')"
:mode="mode"
@update:value="update"
/>
</div>
</div>
<div v-if="!isMasquerade && isSingle">
<div class="row mb-20">
<a
@@ -1,5 +1,6 @@
<script>
import InfoBox from '@shell/components/InfoBox';
import { RadioGroup } from '@components/Form/Radio';
import { NETWORK_ATTACHMENT } from '@shell/config/types';
import { sortBy } from '@shell/utils/sort';
import { clone } from '@shell/utils/object';
@@ -10,7 +11,11 @@ import { HCI as HCI_ANNOTATIONS } from '../../../config/labels-annotations';
import Base from './base';
export default {
components: { InfoBox, Base },
components: {
InfoBox, Base, RadioGroup
},
emits: ['update:value', 'update:networkBootFirst'],
props: {
vm: {
@@ -35,6 +40,11 @@ export default {
isSingle: {
type: Boolean,
default: true
},
networkBootFirst: {
type: Boolean,
default: true
}
},
@@ -82,6 +92,20 @@ export default {
vmState() {
return this.vm?.stateDisplay;
},
hasNetworkBoot() {
return this.rows.some((R) => R.networkBoot);
},
networkBootOrderOptions() {
return [{
label: this.t('harvester.virtualMachine.network.networkBoot.first'),
value: true
}, {
label: this.t('harvester.virtualMachine.network.networkBoot.last'),
value: false
}];
}
},
@@ -218,6 +242,22 @@ export default {
/>
</InfoBox>
<div
v-if="hasNetworkBoot"
data-testid="input-hen-networkBootFirst"
class="mb-20"
>
<RadioGroup
:value="networkBootFirst"
name="networkBootFirst"
:label="t('harvester.virtualMachine.network.networkBoot.order')"
:options="networkBootOrderOptions"
:mode="mode"
:row="true"
@update:value="$emit('update:networkBootFirst', $event)"
/>
</div>
<button
v-if="!isView"
type="button"
@@ -2,7 +2,6 @@
import LabeledSelect from '@shell/components/form/LabeledSelect';
import { Checkbox } from '@components/Form/Checkbox';
import { Banner } from '@components/Banner';
import { _VIEW } from '@shell/config/query-params';
import { DISK_CACHE_MODE, DISK_IO_MODE, DISK_PERFORMANCE_PROFILE } from '../../../config/harvester-map';
const { DEFAULT, HIGH, CUSTOM } = DISK_PERFORMANCE_PROFILE;
@@ -31,23 +30,18 @@ export default {
},
data() {
const hasPerf = !!(this.value.cache || this.value.io || this.value.dedicatedIOThread);
return {
DISK_PERFORMANCE_PROFILE,
expanded: hasPerf,
profile: this.detectProfile(),
// Bus the disk used before the "High Performance" preset switched it to
// virtio, so returning to "Default" can put it back.
busBeforeHighProfile: null,
// True only while the user has explicitly picked "Custom" in the selector.
userSelectedCustom: false,
};
},
computed: {
isView() {
return this.mode === _VIEW;
},
storagePerformanceEnabled() {
return this.$store.getters['harvester-common/getFeatureEnabled']('highPerformanceStorage');
},
@@ -103,13 +97,13 @@ export default {
watch: {
// Keep the profile selector in sync if the row is repopulated (e.g. editing an existing VM).
'value.cache'() {
this.profile = this.detectProfile();
this.syncProfile();
},
'value.io'() {
this.profile = this.detectProfile();
this.syncProfile();
},
'value.dedicatedIOThread'() {
this.profile = this.detectProfile();
this.syncProfile();
},
},
@@ -128,6 +122,16 @@ export default {
return CUSTOM;
},
syncProfile() {
// An explicit "Custom" choice sticks, even if the options happen to
// match the Default or High Performance preset. An inferred "Custom"
// still follows the disk values.
if (this.userSelectedCustom) {
return;
}
this.profile = this.detectProfile();
},
cacheLabel(value) {
if (value === '') {
return this.t('harvester.virtualMachine.volume.performance.cacheMode.default');
@@ -140,6 +144,7 @@ export default {
const previous = this.profile;
this.profile = profile;
this.userSelectedCustom = profile === CUSTOM;
if (profile === DEFAULT) {
this.value.cache = '';
@@ -193,51 +198,49 @@ export default {
v-if="!isCdRom && storagePerformanceEnabled"
class="disk-performance"
>
<button
v-if="!isView"
type="button"
class="btn btn-sm role-link expand-toggle"
:aria-expanded="expanded"
:aria-label="expanded ? t('harvester.virtualMachine.volume.performance.collapse') : t('harvester.virtualMachine.volume.performance.expand')"
@click.prevent="expanded = !expanded"
>
<i
class="icon"
:class="expanded ? 'icon-chevron-down' : 'icon-chevron-right'"
/>
{{ t('harvester.virtualMachine.volume.performance.title') }}
</button>
<div
v-if="expanded || isView"
class="perf-body mt-10"
>
<div class="row mb-20">
<div
class="col span-6"
data-testid="input-disk-perf-profile"
>
<LabeledSelect
:value="profile"
:label="t('harvester.virtualMachine.volume.performance.profile.label')"
:tooltip="t('harvester.virtualMachine.volume.performance.profile.tip')"
:options="profileOptions"
:mode="mode"
@update:value="onProfileChange"
/>
</div>
</div>
<Banner
v-if="profile === DISK_PERFORMANCE_PROFILE.HIGH"
color="info"
:label="t('harvester.virtualMachine.volume.performance.highProfileTip')"
/>
<div class="row mb-20">
<div
v-if="isCustom || isView"
class="row mb-20"
class="col span-6"
data-testid="input-disk-perf-profile"
>
<LabeledSelect
:value="profile"
:label="t('harvester.virtualMachine.volume.performance.profile.label')"
:tooltip="t('harvester.virtualMachine.volume.performance.profile.tip')"
:options="profileOptions"
:mode="mode"
@update:value="onProfileChange"
/>
</div>
</div>
<Banner
v-if="profile === DISK_PERFORMANCE_PROFILE.HIGH"
color="info"
label-key="harvester.virtualMachine.volume.performance.highProfileTip"
/>
<!-- Always rendered, so screen readers announce these warnings when changing the fields below makes them appear
above the focused field -->
<div
role="status"
data-testid="disk-perf-warning-status"
>
<Banner
v-if="showBusTip"
color="warning"
data-testid="disk-perf-bus-tip"
:label="t('harvester.virtualMachine.volume.performance.busTip', { bus: value.bus }, true)"
/>
<Banner
v-if="showFilesystemCacheWarning"
color="warning"
label-key="harvester.virtualMachine.volume.performance.cacheMode.filesystemWarning"
/>
</div>
<template v-if="isCustom">
<div class="row mb-20">
<div
class="col span-6"
data-testid="input-disk-cache"
@@ -266,10 +269,7 @@ export default {
</div>
</div>
<div
v-if="isCustom || isView"
class="row mb-10"
>
<div class="row mb-20">
<div
class="col span-12"
data-testid="input-disk-dedicated-iothread"
@@ -283,39 +283,19 @@ export default {
/>
</div>
</div>
</template>
<!-- Always rendered, also outside Custom, so screen readers announce the tip when picking Native I/O changes
the cache mode, even if the new values switch the profile to High Performance -->
<div
role="status"
data-testid="disk-perf-native-status"
>
<Banner
v-if="isNativeIo"
color="info"
:label="t('harvester.virtualMachine.volume.performance.ioMode.nativeRequiresNoCacheTip')"
/>
<Banner
v-if="showFilesystemCacheWarning"
color="warning"
:label="t('harvester.virtualMachine.volume.performance.cacheMode.filesystemWarning')"
/>
<Banner
v-if="showBusTip"
color="warning"
:label="t('harvester.virtualMachine.volume.performance.busTip')"
label-key="harvester.virtualMachine.volume.performance.ioMode.nativeRequiresNoCacheTip"
/>
</div>
</div>
</template>
<style lang="scss" scoped>
.disk-performance {
border-top: 1px solid var(--border);
margin-top: 10px;
padding-top: 10px;
.expand-toggle {
padding: 0;
font-weight: 600;
.icon {
margin-right: 4px;
}
}
}
</style>
@@ -1,5 +1,4 @@
<script>
import InfoBox from '@shell/components/InfoBox';
import LabeledSelect from '@shell/components/form/LabeledSelect';
import { LabeledInput } from '@components/Form/LabeledInput';
import { Checkbox } from '@components/Form/Checkbox';
@@ -11,7 +10,7 @@ export default {
name: 'VMPerformanceOptions',
components: {
InfoBox, LabeledSelect, LabeledInput, Checkbox, Banner
LabeledSelect, LabeledInput, Checkbox, Banner
},
emits: ['update:blockMultiQueue', 'update:ioThreadsPolicy', 'update:ioThreadCount'],
@@ -50,12 +49,6 @@ export default {
},
},
data() {
// These are specialist tuning options, so keep the panel collapsed unless the
// VM already has something configured.
return { expanded: !!(this.blockMultiQueue || this.ioThreadsPolicy) };
},
computed: {
isView() {
return this.mode === _VIEW;
@@ -87,105 +80,71 @@ export default {
</script>
<template>
<InfoBox
<div
v-if="storagePerformanceEnabled && (!isView || blockMultiQueue || !!ioThreadsPolicy)"
class="vm-perf mt-10"
class="vm-perf"
>
<button
v-if="!isView"
type="button"
class="btn btn-sm role-link expand-toggle"
:aria-expanded="expanded"
:aria-label="expanded ? t('harvester.virtualMachine.volume.diskPerformance.collapse') : t('harvester.virtualMachine.volume.diskPerformance.expand')"
@click.prevent="expanded = !expanded"
>
<i
class="icon"
:class="expanded ? 'icon-chevron-down' : 'icon-chevron-right'"
/>
{{ t('harvester.virtualMachine.volume.diskPerformance.title') }}
</button>
<h3
v-else
class="mb-5"
>
<h3>
{{ t('harvester.virtualMachine.volume.diskPerformance.title') }}
</h3>
<p class="text-muted mb-10">
{{ t('harvester.virtualMachine.volume.diskPerformance.description') }}
</p>
<template v-if="expanded || isView">
<p class="text-muted mb-15 mt-10">
{{ t('harvester.virtualMachine.volume.diskPerformance.description') }}
</p>
<div class="row mb-10">
<div
class="col span-12"
data-testid="input-vm-block-multi-queue"
>
<Checkbox
:value="blockMultiQueue"
:label="t('harvester.virtualMachine.volume.diskPerformance.blockMultiQueue.label')"
:tooltip="t('harvester.virtualMachine.volume.diskPerformance.blockMultiQueue.tip')"
:mode="mode"
:disabled="!hasVirtioDisk"
@update:value="$emit('update:blockMultiQueue', $event)"
/>
</div>
</div>
<Banner
v-if="!hasVirtioDisk && !isView"
color="info"
:label="t('harvester.virtualMachine.volume.diskPerformance.blockMultiQueue.noVirtioTip')"
<div
class="mb-10"
data-testid="input-vm-block-multi-queue"
>
<Checkbox
:value="blockMultiQueue"
:label="t('harvester.virtualMachine.volume.diskPerformance.blockMultiQueue.label')"
:tooltip="t('harvester.virtualMachine.volume.diskPerformance.blockMultiQueue.tip')"
:mode="mode"
:disabled="!hasVirtioDisk"
@update:value="$emit('update:blockMultiQueue', $event)"
/>
</div>
<Banner
v-if="!hasVirtioDisk && !isView"
color="info"
label-key="harvester.virtualMachine.volume.diskPerformance.blockMultiQueue.noVirtioTip"
/>
<div class="row mb-10">
<div
class="col span-6"
data-testid="input-vm-iothreads-policy"
>
<LabeledSelect
:value="ioThreadsPolicy"
:label="t('harvester.virtualMachine.volume.diskPerformance.ioThreadsPolicy.label')"
:tooltip="t('harvester.virtualMachine.volume.diskPerformance.ioThreadsPolicy.tip')"
:options="ioThreadsPolicyOptions"
:mode="mode"
@update:value="$emit('update:ioThreadsPolicy', $event)"
/>
</div>
<div
v-if="ioThreadsPolicy === 'supplementalPool'"
class="col span-6"
data-testid="input-vm-iothread-count"
>
<LabeledInput
type="number"
min="1"
:value="ioThreadCount"
:label="t('harvester.virtualMachine.volume.diskPerformance.ioThreadCount.label')"
:tooltip="t('harvester.virtualMachine.volume.diskPerformance.ioThreadCount.tip')"
:mode="mode"
@update:value="$emit('update:ioThreadCount', Number($event))"
/>
</div>
<div class="row mb-20">
<div
class="col span-6"
data-testid="input-vm-iothreads-policy"
>
<LabeledSelect
:value="ioThreadsPolicy"
:label="t('harvester.virtualMachine.volume.diskPerformance.ioThreadsPolicy.label')"
:tooltip="t('harvester.virtualMachine.volume.diskPerformance.ioThreadsPolicy.tip')"
:options="ioThreadsPolicyOptions"
:mode="mode"
@update:value="$emit('update:ioThreadsPolicy', $event)"
/>
</div>
<Banner
v-if="hasDedicatedIothread && !ioThreadsPolicy"
color="info"
:label="t('harvester.virtualMachine.volume.diskPerformance.ioThreadsPolicy.autoEnabledTip')"
/>
</template>
</InfoBox>
<div
v-if="ioThreadsPolicy === 'supplementalPool'"
class="col span-6"
data-testid="input-vm-iothread-count"
>
<LabeledInput
type="integer"
min="1"
:required="!isView"
:value="ioThreadCount"
:label="t('harvester.virtualMachine.volume.diskPerformance.ioThreadCount.label')"
:tooltip="t('harvester.virtualMachine.volume.diskPerformance.ioThreadCount.tip')"
:mode="mode"
@update:value="$emit('update:ioThreadCount', Number($event))"
/>
</div>
</div>
<Banner
v-if="hasDedicatedIothread && !ioThreadsPolicy"
color="info"
label-key="harvester.virtualMachine.volume.diskPerformance.ioThreadsPolicy.autoEnabledTip"
/>
</div>
</template>
<style lang="scss" scoped>
.vm-perf {
.expand-toggle {
padding: 0;
font-weight: 600;
.icon {
margin-right: 4px;
}
}
}
</style>
@@ -1,5 +1,10 @@
import fs from 'fs';
import path from 'path';
import { load } from 'js-yaml';
import { mount } from '@vue/test-utils';
import { nextTick } from 'vue';
import { _EDIT } from '@shell/config/query-params';
import { Banner } from '@components/Banner';
import DiskPerformanceOptions from '../DiskPerformanceOptions.vue';
const mountOptions = (value, { featureEnabled = true } = {}) => ({
@@ -22,6 +27,12 @@ const hardDisk = (overrides = {}) => ({
type: 'disk', bus: 'virtio', cache: '', io: '', dedicatedIOThread: false, ...overrides
});
const nativeTip = (wrapper) => wrapper.findAllComponents(Banner)
.find((b) => b.props('labelKey') === 'harvester.virtualMachine.volume.performance.ioMode.nativeRequiresNoCacheTip');
const filesystemWarning = (wrapper) => wrapper.findAllComponents(Banner)
.find((b) => b.props('labelKey') === 'harvester.virtualMachine.volume.performance.cacheMode.filesystemWarning');
describe('component: DiskPerformanceOptions', () => {
it('is hidden when the highPerformanceStorage feature is disabled', () => {
const wrapper = mount(DiskPerformanceOptions, mountOptions(hardDisk(), { featureEnabled: false }));
@@ -35,6 +46,102 @@ describe('component: DiskPerformanceOptions', () => {
expect(wrapper.find('.disk-performance').exists()).toBe(true);
});
it('shows the profile without a toggle, and the individual fields only for Custom', () => {
const wrapper = mount(DiskPerformanceOptions, mountOptions(hardDisk()));
expect(wrapper.find('.expand-toggle').exists()).toBe(false);
expect(wrapper.find('[data-testid="input-disk-perf-profile"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="input-disk-cache"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="input-disk-dedicated-iothread"]').exists()).toBe(false);
});
it('shows the individual fields for a disk with custom options', () => {
const wrapper = mount(DiskPerformanceOptions, mountOptions(hardDisk({ cache: 'writeback', io: 'threads' })));
expect(wrapper.find('[data-testid="input-disk-cache"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="input-disk-io"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="input-disk-dedicated-iothread"]').exists()).toBe(true);
});
it('is hidden for a CD-ROM', () => {
const wrapper = mount(DiskPerformanceOptions, mountOptions(hardDisk({ type: 'cd-rom' })));
expect(wrapper.find('.disk-performance').exists()).toBe(false);
});
it('names the bus in the bus tip once the disk uses an option', () => {
const plain = mount(DiskPerformanceOptions, mountOptions(hardDisk({ bus: 'sata' })));
const tuned = mount(DiskPerformanceOptions, mountOptions(hardDisk({ bus: 'sata', cache: 'writeback' })));
expect(plain.find('[data-testid="disk-perf-bus-tip"]').exists()).toBe(false);
expect(tuned.find('[data-testid="disk-perf-bus-tip"]').exists()).toBe(true);
});
it('says in the bus tip that a dedicated I/O thread needs the virtio bus', () => {
const translations = load(fs.readFileSync(path.join(__dirname, '../../../../l10n/en-us.yaml'), 'utf8'));
const { busTip } = translations.harvester.virtualMachine.volume.performance;
expect(busTip).toContain('{bus}');
expect(busTip).toContain('A dedicated I/O thread needs the virtio bus');
});
it('shows the bus tip and the Filesystem warning inside a live region that is there before they appear', async() => {
const disk = { bus: 'sata', volumeMode: 'Filesystem' };
const wrapper = mount(DiskPerformanceOptions, mountOptions(hardDisk(disk)));
const status = wrapper.find('[data-testid="disk-perf-warning-status"]');
expect(status.attributes('role')).toBe('status');
expect(status.find('[data-testid="disk-perf-bus-tip"]').exists()).toBe(false);
expect(filesystemWarning(wrapper)).toBeUndefined();
await wrapper.setProps({ value: hardDisk({ ...disk, cache: 'none' }) });
expect(wrapper.find('[data-testid="disk-perf-warning-status"]').element).toBe(status.element);
expect(status.find('[data-testid="disk-perf-bus-tip"]').exists()).toBe(true);
expect(status.element.contains(filesystemWarning(wrapper)?.element)).toBe(true);
});
it('shows the Native I/O tip inside a live region that is there before Native I/O is picked', async() => {
const value = hardDisk({ cache: 'writeback', io: 'threads' });
const wrapper = mount(DiskPerformanceOptions, mountOptions(value));
const status = wrapper.find('[data-testid="disk-perf-native-status"]');
expect(status.attributes('role')).toBe('status');
expect(nativeTip(wrapper)).toBeUndefined();
wrapper.vm.onIoChange('native');
await wrapper.vm.$nextTick();
expect(wrapper.find('[data-testid="disk-perf-native-status"]').element).toBe(status.element);
expect(status.element.contains(nativeTip(wrapper)?.element)).toBe(true);
});
it('keeps the live region and the Native I/O tip when picking Native I/O switches Custom to High Performance', async() => {
const value = hardDisk({
cache: 'writeback', io: 'threads', dedicatedIOThread: true
});
const wrapper = mount(DiskPerformanceOptions, mountOptions(value));
const status = wrapper.find('[data-testid="disk-perf-native-status"]');
expect(wrapper.vm.profile).toBe('custom');
wrapper.vm.onIoChange('native');
await wrapper.vm.$nextTick();
expect(wrapper.vm.profile).toBe('highPerformance');
expect(wrapper.find('[data-testid="input-disk-cache"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="disk-perf-native-status"]').element).toBe(status.element);
expect(status.element.contains(nativeTip(wrapper)?.element)).toBe(true);
});
it('passes the Filesystem warning as a label key so its quotes are not double-escaped', () => {
const wrapper = mount(DiskPerformanceOptions, mountOptions(hardDisk({ cache: 'none', volumeMode: 'Filesystem' })));
const banner = filesystemWarning(wrapper);
expect(banner).toBeDefined();
expect(banner?.props('label')).toBeFalsy();
});
it('applies the High Performance preset and emits update', () => {
const value = hardDisk();
const wrapper = mount(DiskPerformanceOptions, mountOptions(value));
@@ -122,4 +229,58 @@ describe('component: DiskPerformanceOptions', () => {
expect(disabledByValue['writeback']).toBe(true);
expect(disabledByValue['writethrough']).toBe(true);
});
it.each([
['Default', {
cache: '', io: '', dedicatedIOThread: false
}],
['High Performance', {
cache: 'none', io: 'native', dedicatedIOThread: true
}],
])('stays on Custom when the options match the %s preset', async(_label, opts) => {
const value = hardDisk({ cache: 'writeback' });
const wrapper = mount(DiskPerformanceOptions, mountOptions(value));
wrapper.vm.onProfileChange('custom');
await wrapper.setProps({ value: { ...value, ...opts } });
await nextTick();
expect(wrapper.vm.profile).toBe('custom');
});
it('detects the profile from an existing disk', async() => {
const wrapper = mount(DiskPerformanceOptions, mountOptions(hardDisk()));
expect(wrapper.vm.profile).toBe('default');
await wrapper.setProps({
value: hardDisk({
cache: 'none', io: 'native', dedicatedIOThread: true
})
});
expect(wrapper.vm.profile).toBe('highPerformance');
});
it('updates an automatically detected Custom profile when preset values are loaded', async() => {
const wrapper = mount(DiskPerformanceOptions, mountOptions(hardDisk({ cache: 'writeback' })));
expect(wrapper.vm.profile).toBe('custom');
await wrapper.setProps({
value: hardDisk({
cache: 'none', io: 'native', dedicatedIOThread: true
})
});
expect(wrapper.vm.profile).toBe('highPerformance');
});
it('passes the Native I/O hint as a label key so its quotes are not double-escaped', () => {
const wrapper = mount(DiskPerformanceOptions, mountOptions(hardDisk({ io: 'native' })));
const banner = nativeTip(wrapper);
expect(banner).toBeDefined();
expect(banner?.props('label')).toBeFalsy();
});
});
@@ -0,0 +1,105 @@
import { mount } from '@vue/test-utils';
import { _CREATE, _VIEW } from '@shell/config/query-params';
import { Banner } from '@components/Banner';
import VMPerformanceOptions from '../VMPerformanceOptions.vue';
const AUTO_ENABLED_TIP = 'harvester.virtualMachine.volume.diskPerformance.ioThreadsPolicy.autoEnabledTip';
const NO_VIRTIO_TIP = 'harvester.virtualMachine.volume.diskPerformance.blockMultiQueue.noVirtioTip';
function mountOptions(props = {}, { featureEnabled = true } = {}) {
return mount(VMPerformanceOptions, {
props: { mode: _CREATE, ...props },
global: {
mocks: {
$store: {
getters: {
'harvester-common/getFeatureEnabled': () => featureEnabled,
'i18n/t': (key) => key,
'i18n/exists': () => true,
}
},
t: (key) => key,
},
},
});
}
function bannerFor(wrapper, labelKey) {
return wrapper.findAllComponents(Banner).find((b) => b.props('labelKey') === labelKey);
}
describe('component: VMPerformanceOptions', () => {
it('should be hidden when the highPerformanceStorage feature is disabled', () => {
const wrapper = mountOptions({}, { featureEnabled: false });
expect(wrapper.find('.vm-perf').exists()).toBe(false);
});
it('should show the section with its title and fields, without a toggle', () => {
const wrapper = mountOptions();
expect(wrapper.find('h3').text()).toBe('harvester.virtualMachine.volume.diskPerformance.title');
expect(wrapper.find('.expand-toggle').exists()).toBe(false);
expect(wrapper.find('[data-testid="input-vm-block-multi-queue"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="input-vm-iothreads-policy"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="input-vm-iothread-count"]').exists()).toBe(false);
});
it('should only accept whole numbers as the supplemental pool thread count', () => {
const wrapper = mountOptions({ ioThreadsPolicy: 'supplementalPool', ioThreadCount: 4 });
const input = wrapper.find('[data-testid="input-vm-iothread-count"] input');
expect(input.attributes('inputmode')).toBe('numeric');
});
it.each([
[_CREATE, true],
[_VIEW, false],
])('in %s mode, should mark the supplemental pool thread count as required: %p', (mode, required) => {
const wrapper = mountOptions({
mode, ioThreadsPolicy: 'supplementalPool', ioThreadCount: 4
});
expect(wrapper.find('[data-testid="input-vm-iothread-count"] .required').exists()).toBe(required);
});
it.each([
[{}, false],
[{ blockMultiQueue: true }, true],
[{ ioThreadsPolicy: 'auto' }, true],
])('in view mode with %p, should show the section: %p', (props, shown) => {
const wrapper = mountOptions({ ...props, mode: _VIEW });
expect(wrapper.find('.vm-perf').exists()).toBe(shown);
});
it('should clear Block Multi-Queue when the last virtio disk goes away', async() => {
const wrapper = mountOptions({ blockMultiQueue: true, hasVirtioDisk: true });
await wrapper.setProps({ hasVirtioDisk: false });
expect(wrapper.emitted('update:blockMultiQueue')).toStrictEqual([[false]]);
});
it('should pass the I/O threads policy hint as a label key so its quotes are not double-escaped', () => {
const wrapper = mountOptions({ hasDedicatedIothread: true });
const banner = bannerFor(wrapper, AUTO_ENABLED_TIP);
expect(banner).toBeDefined();
expect(banner.props('label')).toBeFalsy();
});
it('should not show the I/O threads policy hint when a policy is set', () => {
const wrapper = mountOptions({ hasDedicatedIothread: true, ioThreadsPolicy: 'shared' });
expect(bannerFor(wrapper, AUTO_ENABLED_TIP)).toBeUndefined();
});
it('should pass the no virtio disk hint as a label key', () => {
const wrapper = mountOptions({ hasVirtioDisk: false });
const banner = bannerFor(wrapper, NO_VIRTIO_TIP);
expect(banner).toBeDefined();
expect(banner.props('label')).toBeFalsy();
});
});
@@ -7,7 +7,6 @@ import UnitInput from '@shell/components/form/UnitInput';
import { LabeledInput } from '@components/Form/LabeledInput';
import LabeledSelect from '@shell/components/form/LabeledSelect';
import ModalWithCard from '@shell/components/ModalWithCard';
import VMPerformanceOptions from './VMPerformanceOptions';
import { VOLUME_HOTPLUG_ACTION, SOURCE_TYPE } from '../../../config/harvester-map';
import { PVC, STORAGE_CLASS } from '@shell/config/types';
import { clone } from '@shell/utils/object';
@@ -17,15 +16,17 @@ import { _VIEW, _EDIT, _CREATE } from '@shell/config/query-params';
import { PLUGIN_DEVELOPER, DEV } from '@shell/store/prefs';
import { PRODUCT_NAME as HARVESTER_PRODUCT } from '../../../config/harvester';
import { HCI } from '../../../types';
import { VOLUME_MODE } from '@pkg/harvester/config/types';
import { VOLUME_MODE, ACCESS_MODE } from '@pkg/harvester/config/types';
import { OFF } from '../../../models/kubevirt.io.virtualmachine';
import { EMPTY_IMAGE } from '../../../utils/vm';
const { READ_WRITE_MANY } = ACCESS_MODE;
export default {
emits: ['update:value', 'update:blockMultiQueue', 'update:ioThreadsPolicy', 'update:ioThreadCount'],
emits: ['update:value'],
components: {
Banner, BadgeStateFormatter, VueDraggableNext, InfoBox, LabeledInput, UnitInput, LabeledSelect, ModalWithCard, VMPerformanceOptions
Banner, BadgeStateFormatter, VueDraggableNext, InfoBox, LabeledInput, UnitInput, LabeledSelect, ModalWithCard
},
props: {
@@ -70,28 +71,12 @@ export default {
customAccessMode: {
type: String,
default: 'ReadWriteMany'
default: READ_WRITE_MANY
},
resourceType: {
type: String,
default: ''
},
// KubeVirt high-performance VM-level features
blockMultiQueue: {
type: Boolean,
default: false
},
ioThreadsPolicy: {
type: String,
default: ''
},
ioThreadCount: {
type: Number,
default: 2
}
},
@@ -162,14 +147,6 @@ export default {
isLHV2VolExpansionFeatureEnabled() {
return this.$store.getters['harvester-common/getFeatureEnabled']('lhV2VolExpansion');
},
hasVirtioDisk() {
return this.rows.some((R) => R.type === 'disk' && R.bus === 'virtio');
},
hasDedicatedIOThread() {
return this.rows.some((R) => R.dedicatedIOThread);
},
},
watch: {
@@ -531,18 +508,6 @@ export default {
</button>
</div>
<VMPerformanceOptions
:block-multi-queue="blockMultiQueue"
:io-threads-policy="ioThreadsPolicy"
:io-thread-count="ioThreadCount"
:has-virtio-disk="hasVirtioDisk"
:has-dedicated-iothread="hasDedicatedIOThread"
:mode="mode"
@update:block-multi-queue="$emit('update:blockMultiQueue', $event)"
@update:io-threads-policy="$emit('update:ioThreadsPolicy', $event)"
@update:io-thread-count="$emit('update:ioThreadCount', $event)"
/>
<ModalWithCard
v-if="isOpen"
name="deleteTip"
@@ -2,9 +2,23 @@ import { mount } from '@vue/test-utils';
import { _EDIT } from '@shell/config/query-params';
import HarvesterEditContainer from '../container.vue';
const mountOptions = () => ({
props: { mode: _EDIT, value: {} },
global: {
mocks: {
$store: {
getters: {
'harvester-common/getFeatureEnabled': () => true,
'i18n/t': jest.fn(),
}
}
}
}
});
describe('component: HarvesterEditContainer', () => {
it('should display all the inputs', () => {
const wrapper = mount(HarvesterEditContainer, { propsData: { mode: _EDIT, value: {} } });
const wrapper = mount(HarvesterEditContainer, mountOptions());
const inputWraps = wrapper.findAll('[data-testid^=input-hec-]');
@@ -15,7 +29,7 @@ describe('component: HarvesterEditContainer', () => {
'name',
'container',
])('should emit an update on %p input', (field) => {
const wrapper = mount(HarvesterEditContainer, { propsData: { mode: _EDIT, value: {} } });
const wrapper = mount(HarvesterEditContainer, mountOptions());
const input = wrapper.find(`[data-testid="input-hec-${ field }"]`).find('input');
const newValue = 123;
@@ -28,7 +42,7 @@ describe('component: HarvesterEditContainer', () => {
'type',
'bus',
])('should emit an update on %p selection change', async(field) => {
const wrapper = mount(HarvesterEditContainer, { propsData: { mode: _EDIT, value: {} } });
const wrapper = mount(HarvesterEditContainer, mountOptions());
const select = wrapper.find(`[data-testid="input-hec-${ field }"]`);
select.find('button').trigger('click');
@@ -37,4 +51,11 @@ describe('component: HarvesterEditContainer', () => {
expect(wrapper.emitted('update')).toHaveLength(1);
});
it('should not render an empty row when there is no backup to show', () => {
const wrapper = mount(HarvesterEditContainer, mountOptions());
const emptyRows = wrapper.findAll('.row').filter((row) => row.element.children.length === 0);
expect(emptyRows).toHaveLength(0);
});
});
@@ -5,14 +5,17 @@ import HarvesterEditExisting from '../existing.vue';
describe('component: HarvesterEditExisting', () => {
it('should display all the inputs', () => {
const wrapper = mount(HarvesterEditExisting, {
propsData: {
props: {
mode: _EDIT, value: {}, rows: []
},
mocks: {
$store: {
getters: {
'harvester/all': () => [],
'i18n/t': jest.fn()
global: {
mocks: {
$store: {
getters: {
'harvester-common/getFeatureEnabled': () => true,
'harvester/all': () => [],
'i18n/t': jest.fn()
}
}
}
}
@@ -27,14 +30,17 @@ describe('component: HarvesterEditExisting', () => {
'name',
])('should emit an update on %p input', (field) => {
const wrapper = mount(HarvesterEditExisting, {
propsData: {
props: {
mode: _EDIT, value: {}, rows: []
},
mocks: {
$store: {
getters: {
'harvester/all': () => [],
'i18n/t': jest.fn()
global: {
mocks: {
$store: {
getters: {
'harvester-common/getFeatureEnabled': () => true,
'harvester/all': () => [],
'i18n/t': jest.fn()
}
}
}
}
@@ -53,14 +59,17 @@ describe('component: HarvesterEditExisting', () => {
'size',
])('should emit an update on %p input and blur', (field) => {
const wrapper = mount(HarvesterEditExisting, {
propsData: {
props: {
mode: _EDIT, value: {}, rows: []
},
mocks: {
$store: {
getters: {
'harvester/all': () => [],
'i18n/t': jest.fn()
global: {
mocks: {
$store: {
getters: {
'harvester-common/getFeatureEnabled': () => true,
'harvester/all': () => [],
'i18n/t': jest.fn()
}
}
}
}
@@ -80,14 +89,17 @@ describe('component: HarvesterEditExisting', () => {
// 'bus', // disabled
])('should emit an update on %p selection change', async(field) => {
const wrapper = mount(HarvesterEditExisting, {
propsData: {
props: {
mode: _EDIT, value: {}, rows: []
},
mocks: {
$store: {
getters: {
'harvester/all': () => [],
'i18n/t': jest.fn()
global: {
mocks: {
$store: {
getters: {
'harvester-common/getFeatureEnabled': () => true,
'harvester/all': () => [],
'i18n/t': jest.fn()
}
}
}
}
@@ -2,23 +2,29 @@ import { mount } from '@vue/test-utils';
import { _CREATE } from '@shell/config/query-params';
import HarvesterEditVMImage from '../vmImage.vue';
// The form emits an update when it is created, so count only the updates that an interaction adds
const updates = (wrapper) => wrapper.emitted('update')?.length ?? 0;
describe('component: HarvesterEditVMImage', () => {
it('should display all the inputs', () => {
const wrapper = mount(HarvesterEditVMImage, {
propsData: {
props: {
mode: _CREATE,
isVirtualType: false,
newCreateId: '123',
validateRequired: true,
idx: 1
},
mocks: {
$store: {
getters: {
'harvester/all': jest.fn(),
'i18n/t': jest.fn(),
}
},
global: {
mocks: {
$store: {
getters: {
'harvester-common/getFeatureEnabled': () => true,
'harvester/all': jest.fn(),
'i18n/t': jest.fn(),
}
},
}
}
});
@@ -31,20 +37,23 @@ describe('component: HarvesterEditVMImage', () => {
'name',
])('should emit an update on %p input', (field) => {
const wrapper = mount(HarvesterEditVMImage, {
propsData: {
props: {
mode: _CREATE,
isVirtualType: false,
newCreateId: '123',
validateRequired: true,
idx: 1
},
mocks: {
$store: {
getters: {
'harvester/all': jest.fn(),
'i18n/t': jest.fn(),
}
},
global: {
mocks: {
$store: {
getters: {
'harvester-common/getFeatureEnabled': () => true,
'harvester/all': jest.fn(),
'i18n/t': jest.fn(),
}
},
}
}
});
const input = wrapper.find(`[data-testid="input-hevi-${ field }"]`).find('input');
@@ -57,31 +66,38 @@ describe('component: HarvesterEditVMImage', () => {
it.each([
'size',
])('should emit an update on %p input blur', (field) => {
])('should emit an update on %p input blur', async(field) => {
const wrapper = mount(HarvesterEditVMImage, {
propsData: {
props: {
mode: _CREATE,
isVirtualType: false,
newCreateId: '123',
validateRequired: true,
idx: 1
},
mocks: {
$store: {
getters: {
'harvester/all': jest.fn(),
'i18n/t': jest.fn(),
}
},
global: {
mocks: {
$store: {
getters: {
'harvester-common/getFeatureEnabled': () => true,
'harvester/all': jest.fn(),
'i18n/t': jest.fn(),
}
},
}
}
});
const input = wrapper.find(`[data-testid="input-hevi-${ field }"]`).find('input');
const newValue = 123;
input.setValue(newValue);
input.trigger('blur');
// setting the value already emits an update, so the blur has to add one on top of that
await input.setValue(newValue);
expect(wrapper.emitted('update')).toHaveLength(1);
const afterSetValue = updates(wrapper);
await input.trigger('blur');
expect(updates(wrapper)).toBeGreaterThan(afterSetValue);
});
it.each([
@@ -90,20 +106,23 @@ describe('component: HarvesterEditVMImage', () => {
'bus',
])('should emit an update on %p selection change', async(field) => {
const wrapper = mount(HarvesterEditVMImage, {
propsData: {
props: {
mode: _CREATE,
isVirtualType: false,
newCreateId: '123',
validateRequired: true,
idx: 1
},
mocks: {
$store: {
getters: {
'harvester/all': jest.fn(),
'i18n/t': jest.fn(),
}
},
global: {
mocks: {
$store: {
getters: {
'harvester-common/getFeatureEnabled': () => true,
'harvester/all': jest.fn(),
'i18n/t': jest.fn(),
}
},
}
}
});
const select = wrapper.find(`[data-testid="input-hevi-${ field }"]`);
@@ -114,4 +133,30 @@ describe('component: HarvesterEditVMImage', () => {
expect(wrapper.emitted('update')).toHaveLength(1);
});
it('should not render an empty row when there is no backup to show', () => {
const wrapper = mount(HarvesterEditVMImage, {
props: {
mode: _CREATE,
isVirtualType: false,
newCreateId: '123',
validateRequired: true,
idx: 1
},
global: {
mocks: {
$store: {
getters: {
'harvester-common/getFeatureEnabled': () => true,
'harvester/all': jest.fn(),
'i18n/t': jest.fn(),
}
},
}
}
});
const emptyRows = wrapper.findAll('.row').filter((row) => row.element.children.length === 0);
expect(emptyRows).toHaveLength(0);
});
});
@@ -2,18 +2,24 @@ import { mount } from '@vue/test-utils';
import { _EDIT } from '@shell/config/query-params';
import HarvesterEditVolume from '../volume.vue';
// The form emits an update when it is created, so count only the updates that an interaction adds
const updates = (wrapper) => wrapper.emitted('update')?.length ?? 0;
describe('component: HarvesterEditVolume', () => {
it('should display all the inputs', () => {
const wrapper = mount(HarvesterEditVolume, {
propsData: { validateRequired: true },
mocks: {
$store: {
getters: {
'harvester/all': jest.fn(),
'i18n/t': jest.fn(),
'i18n/exists': jest.fn(),
}
},
props: { validateRequired: true },
global: {
mocks: {
$store: {
getters: {
'harvester-common/getFeatureEnabled': () => true,
'harvester/all': jest.fn(),
'i18n/t': jest.fn(),
'i18n/exists': jest.fn(),
}
},
}
}
});
@@ -22,29 +28,56 @@ describe('component: HarvesterEditVolume', () => {
expect(inputWraps).toHaveLength(4);
});
it.each([
'name',
'size',
])('should emit an update on %p input blur', (field) => {
it('should emit an update on name input', async() => {
const wrapper = mount(HarvesterEditVolume, {
propsData: { mode: _EDIT, validateRequired: true },
mocks: {
$store: {
getters: {
'harvester/all': jest.fn(),
'i18n/t': jest.fn(),
'i18n/exists': jest.fn(),
}
},
props: { mode: _EDIT, validateRequired: true },
global: {
mocks: {
$store: {
getters: {
'harvester-common/getFeatureEnabled': () => true,
'harvester/all': jest.fn(),
'i18n/t': jest.fn(),
'i18n/exists': jest.fn(),
}
},
}
}
});
const input = wrapper.find(`[data-testid="input-hev-${ field }"]`).find('input');
const newValue = 123;
const before = updates(wrapper);
const input = wrapper.find('[data-testid="input-hev-name"]').find('input');
input.setValue(newValue);
input.trigger('blur');
await input.setValue(123);
expect(wrapper.emitted('update')).toHaveLength(1);
expect(updates(wrapper)).toBeGreaterThan(before);
});
it('should emit an update on size input blur', async() => {
const wrapper = mount(HarvesterEditVolume, {
props: { mode: _EDIT, validateRequired: true },
global: {
mocks: {
$store: {
getters: {
'harvester-common/getFeatureEnabled': () => true,
'harvester/all': jest.fn(),
'i18n/t': jest.fn(),
'i18n/exists': jest.fn(),
}
},
}
}
});
const input = wrapper.find('[data-testid="input-hev-size"]').find('input');
// setting the value already emits an update, so the blur has to add one on top of that
await input.setValue(123);
const afterSetValue = updates(wrapper);
await input.trigger('blur');
expect(updates(wrapper)).toBeGreaterThan(afterSetValue);
});
it.each([
@@ -52,23 +85,27 @@ describe('component: HarvesterEditVolume', () => {
'bus'
])('should emit an update on %p selection change', async(field) => {
const wrapper = mount(HarvesterEditVolume, {
propsData: { mode: _EDIT, validateRequired: true },
mocks: {
$store: {
getters: {
'harvester/all': jest.fn(),
'i18n/t': jest.fn(),
'i18n/exists': jest.fn(),
}
},
props: { mode: _EDIT, validateRequired: true },
global: {
mocks: {
$store: {
getters: {
'harvester-common/getFeatureEnabled': () => true,
'harvester/all': jest.fn(),
'i18n/t': jest.fn(),
'i18n/exists': jest.fn(),
}
},
}
}
});
const before = updates(wrapper);
const select = wrapper.find(`[data-testid="input-hev-${ field }"]`);
select.find('button').trigger('click');
await wrapper.trigger('keydown.down');
await wrapper.trigger('keydown.enter');
expect(wrapper.emitted('update')).toHaveLength(1);
expect(updates(wrapper)).toBeGreaterThan(before);
});
});
@@ -2,6 +2,7 @@
import { LabeledInput } from '@components/Form/LabeledInput';
import LabeledSelect from '@shell/components/form/LabeledSelect';
import InputOrDisplay from '@shell/components/InputOrDisplay';
import LabelValue from '@shell/components/LabelValue';
import { VOLUME_TYPE, InterfaceOption } from '../../../../config/harvester-map';
import { Banner } from '@components/Banner';
import DiskPerformanceOptions from '../DiskPerformanceOptions';
@@ -12,7 +13,7 @@ export default {
emits: ['update'],
components: {
LabeledInput, LabeledSelect, InputOrDisplay, Banner, DiskPerformanceOptions
LabeledInput, LabeledSelect, InputOrDisplay, LabelValue, Banner, DiskPerformanceOptions
},
props: {
@@ -131,11 +132,11 @@ export default {
</InputOrDisplay>
</div>
</div>
<div class="row mb-20">
<div
v-if="value.volumeBackups"
class="col span-6"
>
<div
v-if="value.volumeBackups"
class="row mb-20"
>
<div class="col span-6">
<InputOrDisplay
:name="t('harvester.virtualMachine.volume.readyToUse')"
:value="value.volumeBackups.readyToUse"
@@ -461,11 +461,11 @@ export default {
/>
</div>
</div>
<div class="row mb-20">
<div
v-if="value.volumeBackups && isView"
class="col span-3"
>
<div
v-if="value.volumeBackups && isView"
class="row mb-20"
>
<div class="col span-3">
<LabelValue
:name="t('harvester.virtualMachine.volume.readyToUse')"
:value="readyToUse"
@@ -15,7 +15,9 @@ import { LVM_DRIVER } from '../../../../models/harvester/storage.k8s.io.storagec
import { DATA_ENGINE_V2 } from '../../../../models/harvester/persistentvolumeclaim';
import { GIBIBYTE } from '../../../../utils/unit';
import { isInternalStorageClass } from '../../../../utils/storage-class';
import { VOLUME_MODE } from '@pkg/harvester/config/types';
import { VOLUME_MODE, ACCESS_MODE } from '@pkg/harvester/config/types';
const { READ_WRITE_MANY, READ_WRITE_ONCE } = ACCESS_MODE;
export default {
name: 'HarvesterEditVolume',
@@ -206,7 +208,7 @@ export default {
getAccessMode(storageClassName) {
if (!this.longhornV2LVMSupport) {
return 'ReadWriteMany';
return READ_WRITE_MANY;
}
const storageClass = this.storageClasses.find((sc) => sc.name === storageClassName);
@@ -217,7 +219,7 @@ export default {
readWriteOnce = storageClass.provisioner === LVM_DRIVER || (!this.thirdPartyStorageClassEnabled && storageClass.parameters?.dataEngine === DATA_ENGINE_V2);
}
return readWriteOnce ? 'ReadWriteOnce' : 'ReadWriteMany';
return readWriteOnce ? READ_WRITE_ONCE : READ_WRITE_MANY;
},
update() {
@@ -333,7 +333,7 @@ $xml-height: 350px;
min-height: $xml-height;
font-family: monospace;
& .code-mirror .CodeMirror {
& .code-mirror .cm-editor {
min-height: $xml-height;
}
}
@@ -0,0 +1,37 @@
import VM_MIXIN from '@pkg/harvester/mixins/harvester-vm';
import HarvesterEditVM from '../index.vue';
function saveWith(userScript) {
const buttonCb = jest.fn();
const form = {
userScript,
errors: [],
isSingle: true,
t: (key) => key,
validateCPUMemory: jest.fn(),
validateWindowsSysprep: jest.fn(),
validateCloudInit: VM_MIXIN.methods.validateCloudInit,
saveSingle: jest.fn(),
};
HarvesterEditVM.methods.saveVM.call(form, buttonCb);
return { form, buttonCb };
}
describe('page: kubevirt.io.virtualmachine edit', () => {
it('should stop the save when the cloud config is invalid', () => {
const { form, buttonCb } = saveWith('#cloud-config\nsome words\n');
expect(form.errors).toStrictEqual(['harvester.virtualMachine.cloudConfig.user.invalidYaml']);
expect(buttonCb).toHaveBeenCalledWith(false);
expect(form.saveSingle).not.toHaveBeenCalled();
});
it('should save when the user data is a script', () => {
const { form, buttonCb } = saveWith('#!/bin/bash\napt-get update\n# start it\nsystemctl enable --now nginx\n');
expect(form.errors).toStrictEqual([]);
expect(form.saveSingle).toHaveBeenCalledWith(buttonCb);
});
});
@@ -34,6 +34,7 @@ import CpuMemory from './VirtualMachineCpuMemory';
import CpuModel from './VirtualMachineCpuModel';
import Network from './VirtualMachineNetwork';
import Volume from './VirtualMachineVolume';
import VMPerformanceOptions from './VirtualMachineVolume/VMPerformanceOptions';
import SSHKey from './VirtualMachineSSHKey';
import Reserved from './VirtualMachineReserved';
import Filesystem from './VirtualMachineFilesystem';
@@ -55,6 +56,7 @@ export default {
LabeledSelect,
NameNsDescription,
Volume,
VMPerformanceOptions,
SSHKey,
Network,
CpuMemory,
@@ -379,6 +381,7 @@ export default {
this.validateCPUMemory();
this.validateWindowsSysprep();
this.validateCloudInit();
// block create VM flow if has validation errors
if (this.errors.length) {
@@ -742,6 +745,25 @@ export default {
name="basics"
:label="t('harvester.virtualMachine.detail.tabs.basics')"
>
<div class="row mb-20">
<div class="col span-6">
<LabeledSelect
v-model:value="osType"
label-key="harvester.virtualMachine.osType"
:options="OS"
:disabled="!isCreate"
:tooltip="isCreate ? t('harvester.virtualMachine.osTypeTooltip') : null"
/>
</div>
<div class="col span-6">
<CpuModel
v-model:value="cpuModel"
:mode="mode"
@update:value="updateCpuModel"
/>
</div>
</div>
<CpuMemory
class="mb-20"
:cpu="cpu"
@@ -753,6 +775,87 @@ export default {
@updateCpuMemory="updateCpuMemory"
/>
<div class="mb-20">
<Checkbox
v-if="value.cpuPinningFeatureEnabled"
v-model:value="cpuPinning"
:disabled="!enableCpuPinningCheckbox"
class="check"
type="checkbox"
tooltip-key="harvester.virtualMachine.cpuPinning.tooltip"
label-key="harvester.virtualMachine.cpuPinning.label"
:mode="mode"
/>
<Checkbox
v-model:value="installUSBTablet"
class="check"
type="checkbox"
tooltip-key="harvester.virtualMachine.usbTip"
label-key="harvester.virtualMachine.enableUsb"
:mode="mode"
/>
<Checkbox
v-model:value="tpmEnabled"
class="check"
type="checkbox"
label-key="harvester.virtualMachine.systemOptions.tpm"
:mode="mode"
/>
<Checkbox
v-if="value.tpmPersistentStateFeatureEnabled && tpmEnabled"
v-model:value="tpmPersistentStateEnabled"
class="check"
type="checkbox"
:label="t('harvester.virtualMachine.systemOptions.tpmPersistentState')"
:mode="mode"
/>
<Checkbox
v-model:value="efiEnabled"
class="check"
type="checkbox"
:label="t('harvester.virtualMachine.systemOptions.efiEnabled')"
:mode="mode"
/>
<Checkbox
v-if="value.efiPersistentStateFeatureEnabled && efiEnabled"
v-model:value="efiPersistentStateEnabled"
class="check"
type="checkbox"
:label="t('harvester.virtualMachine.systemOptions.efiPersistentState')"
:mode="mode"
/>
<Checkbox
v-if="efiEnabled"
v-model:value="secureBoot"
class="check"
type="checkbox"
:label="t('harvester.virtualMachine.systemOptions.secureBoot')"
:mode="mode"
/>
</div>
<Banner
v-if="showCpuPinningBanner"
:color="mode === 'create' ? 'info' : 'warning'"
>
<MessageLink
v-if="mode === 'create'"
:to="to"
prefix-label="harvester.virtualMachine.cpuPinning.cpuManager.prefix"
middle-label="harvester.virtualMachine.cpuPinning.cpuManager.middle"
suffix-label="harvester.virtualMachine.cpuPinning.cpuManager.suffix"
/>
<span v-if="mode==='edit'">
{{ t('harvester.virtualMachine.cpuPinning.restartVMMessage') }}
</span>
</Banner>
<SSHKey
v-model:value="sshKey"
class="mb-20"
@@ -772,9 +875,6 @@ export default {
>
<Volume
v-model:value="diskRows"
v-model:block-multi-queue="blockMultiQueue"
v-model:io-threads-policy="ioThreadsPolicy"
v-model:io-thread-count="ioThreadCount"
:mode="mode"
:custom-volume-mode="customVolumeMode"
:namespace="value.metadata.namespace"
@@ -791,6 +891,7 @@ export default {
>
<Network
v-model:value="networkRows"
v-model:network-boot-first="networkBootFirst"
:mode="mode"
:is-single="isSingle"
/>
@@ -968,18 +1069,6 @@ export default {
:mode="mode"
/>
</div>
<div class="col span-6">
<LabeledSelect
v-model:value="osType"
label-key="harvester.virtualMachine.osType"
:options="OS"
:disabled="!isCreate"
/>
</div>
</div>
<div class="row mb-20">
<div class="col span-6">
<LabeledSelect
v-model:value="maintenanceStrategy"
@@ -989,6 +1078,9 @@ export default {
:mode="mode"
/>
</div>
</div>
<div class="row mb-20">
<div class="col span-6">
<Reserved
:reserved-memory="reservedMemory"
@@ -998,16 +1090,6 @@ export default {
</div>
</div>
<div class="row mb-20">
<div class="col span-6">
<CpuModel
v-model:value="cpuModel"
:mode="mode"
@update:value="updateCpuModel"
/>
</div>
</div>
<div class="row mb-20">
<a
v-if="showAdvanced"
@@ -1064,6 +1146,16 @@ export default {
</div>
</div>
<VMPerformanceOptions
v-model:block-multi-queue="blockMultiQueue"
v-model:io-threads-policy="ioThreadsPolicy"
v-model:io-thread-count="ioThreadCount"
:has-virtio-disk="hasVirtioDisk"
:has-dedicated-iothread="hasDedicatedIOThread"
:mode="mode"
class="mb-20"
/>
<CloudConfig
ref="yamlEditor"
:user-script="userScript"
@@ -1074,7 +1166,19 @@ export default {
@updateUserData="updateUserData"
@updateNetworkData="updateNetworkData"
@updateDataTemplateId="updateDataTemplateId"
/>
>
<template #after-user-data>
<Checkbox
v-model:value="installAgent"
class="check mb-20"
type="checkbox"
:disabled="isWindows"
label-key="harvester.virtualMachine.installAgent"
:mode="mode"
@update:value="updateAgent"
/>
</template>
</CloudConfig>
<WindowsSysprep
v-if="isWindows"
@@ -1083,95 +1187,6 @@ export default {
:mode="mode"
:namespace="value.metadata.namespace"
/>
<Checkbox
v-if="value.cpuPinningFeatureEnabled"
v-model:value="cpuPinning"
:disabled="!enableCpuPinningCheckbox"
class="check"
type="checkbox"
tooltip-key="harvester.virtualMachine.cpuPinning.tooltip"
label-key="harvester.virtualMachine.cpuPinning.label"
:mode="mode"
/>
<Checkbox
v-model:value="installUSBTablet"
class="check mt-20"
type="checkbox"
tooltip-key="harvester.virtualMachine.usbTip"
label-key="harvester.virtualMachine.enableUsb"
:mode="mode"
/>
<Checkbox
v-model:value="installAgent"
class="check"
type="checkbox"
:disabled="isWindows"
label-key="harvester.virtualMachine.installAgent"
:mode="mode"
@update:value="updateAgent"
/>
<Checkbox
v-model:value="tpmEnabled"
class="check"
type="checkbox"
label-key="harvester.virtualMachine.advancedOptions.tpm"
:mode="mode"
/>
<Checkbox
v-if="value.tpmPersistentStateFeatureEnabled && tpmEnabled"
v-model:value="tpmPersistentStateEnabled"
class="check"
type="checkbox"
:label="t('harvester.virtualMachine.advancedOptions.tpmPersistentState')"
:mode="mode"
/>
<Checkbox
v-model:value="efiEnabled"
class="check"
type="checkbox"
:label="t('harvester.virtualMachine.advancedOptions.efiEnabled')"
:mode="mode"
/>
<Checkbox
v-if="value.efiPersistentStateFeatureEnabled && efiEnabled"
v-model:value="efiPersistentStateEnabled"
class="check"
type="checkbox"
:label="t('harvester.virtualMachine.advancedOptions.efiPersistentState')"
:mode="mode"
/>
<Checkbox
v-if="efiEnabled"
v-model:value="secureBoot"
class="check"
type="checkbox"
:label="t('harvester.virtualMachine.advancedOptions.secureBoot')"
:mode="mode"
/>
<Banner
v-if="showCpuPinningBanner"
color="warning"
>
<MessageLink
v-if="mode === 'create'"
:to="to"
prefix-label="harvester.virtualMachine.advancedOptions.cpuManager.prefix"
middle-label="harvester.virtualMachine.advancedOptions.cpuManager.middle"
suffix-label="harvester.virtualMachine.advancedOptions.cpuManager.suffix"
/>
<span v-if="mode==='edit'">
{{ t('harvester.virtualMachine.cpuPinning.restartVMMessage') }}
</span>
</Banner>
</Tab>
</Tabbed>
@@ -100,8 +100,7 @@ export default {
},
vmiIp() {
const vmiResources = this.$store.getters[`${ this.inStore }/all`](HCI.VMI);
const resource = vmiResources.find((VMI) => VMI.id === this.value) || null;
const resource = this.$store.getters[`${ this.inStore }/byId`](HCI.VMI, this.value);
const networksName = this.row.networksName || [];
const vmiNetworks = resource?.spec?.networks || [];
@@ -20,7 +20,9 @@ export default {
computed: {
vmiResource() {
return this.$store.getters['harvester/byId'](HCI.VMI, this.vmResource?.id) || null;
const inStore = this.$store.getters['currentProduct'].inStore;
return this.$store.getters[`${ inStore }/byId`](HCI.VMI, this.vmResource?.id) || null;
},
migrationState() {
return this.vmiResource?.migrationState?.status || '';
+12
View File
@@ -6,6 +6,9 @@ import harvesterCommonStore from './store/harvester-common';
import harvesterStore from './store/harvester-store';
import customValidators from './validators';
import { PRODUCT_NAME } from './config/harvester';
import {
hostResolvesL10nGlobals, resolveL10nGlobals, standaloneProductName, PRODUCT_NAME_GLOBAL
} from './utils/l10n-globals';
import { defineAsyncComponent } from 'vue';
import './styles/vue-flow.scss';
@@ -17,6 +20,15 @@ export default function (plugin: IPlugin) {
// Auto-import model, detail, edit from the folders
importTypes(plugin);
if (isSingleVirtualCluster) {
// Standalone: the server-flavor setting picks the product name, see config/harvester-cluster
plugin.register('l10n-global', PRODUCT_NAME_GLOBAL, standaloneProductName);
} else if (!hostResolvesL10nGlobals(plugin.environment?.version)) {
// Hosts older than Rancher 2.16 would show `[[Harvester]]` literally, so resolve the tokens here.
// Mutating the module in place also updates the copy that importTypes registered.
resolveL10nGlobals(require('./l10n/en-us.yaml'));
}
// Provide plugin metadata from package.json
plugin.metadata = require('./package.json');
+184 -80
View File
@@ -25,13 +25,14 @@ generic:
unsupported:
serverVersion: 'Current version: <code>{serverVersion}</code>'
description: Harvester ui only supports Harvester cluster version greater or equal to 1.3.0.
learnMore: Learn more about Harvester from the <a target="_blank" href="https://harvesterhci.io/" rel="noopener noreferrer nofollow">Harvester Web Site</a> or read the <a target="_blank" href="https://docs.harvesterhci.io/" rel="noopener noreferrer nofollow">Harvester Docs</a>
description: '[[Harvester]] ui only supports [[Harvester]] cluster version greater or equal to 1.3.0.'
learnMore: Learn more about [[Harvester]] from the <a target="_blank" href="https://harvesterhci.io/" rel="noopener noreferrer nofollow">[[Harvester]] Web Site</a> or read the <a target="_blank" href="https://docs.harvesterhci.io/" rel="noopener noreferrer nofollow">[[Harvester]] Docs</a>
nav:
group:
networks: Networks
backupAndSnapshot: Backup and Snapshots
hardwareDevices: Hardware Devices
Monitoring: Monitoring
Logging: Logging
'Monitoring and Logging': Monitoring and Logging
@@ -87,10 +88,10 @@ harvester:
primeLabel: '{vendor}'
primeEmptyLabel: ''
logos:
tip: 'Upload a logo to replace the Harvester logo in the top-level navigation header. Image height should be 21 pixels with a max width of 200 pixels. Max file size is 20KB. Accepted formats: JPEG, PNG, SVG.'
tip: 'Upload a logo to replace the [[Harvester]] logo in the top-level navigation header. Image height should be 21 pixels with a max width of 200 pixels. Max file size is 20KB. Accepted formats: JPEG, PNG, SVG.'
favicon:
tip: 'Upload an icon to replace the Harvester favicon in the browser tab. Max file size is 20KB'
productLabel: 'Harvester'
tip: 'Upload an icon to replace the [[Harvester]] favicon in the browser tab. Max file size is 20KB'
productLabel: '[[Harvester]]'
modal:
backup:
success: 'Backup { backUpName } has been initiated.'
@@ -182,7 +183,7 @@ harvester:
delete: Delete
bundle:
title: Generate a Support Bundle
titleDescription: Collect system-related logs in Harvester to assist with troubleshooting and support.
titleDescription: Collect system-related logs in [[Harvester]] to assist with troubleshooting and support.
tip: Each field below specifies an aspect of the support bundle. For detailed explanations, please refer to the <a href="{doc}" target="_blank">documentation</a>.
url: Issue URL
description: Description
@@ -286,6 +287,7 @@ harvester:
createTemplate: Generate Template
enableMaintenance: Enable Maintenance Mode
disableMaintenance: Disable Maintenance Mode
clearMaintenance: Clear Maintenance Mode Error
enableCPUManager: Enable CPU Manager
disableCPUManager: Disable CPU Manager
cordon: Cordon
@@ -335,7 +337,7 @@ harvester:
attachedVM: Attached Virtual Machine
cpuManager: CPU<br>Manager
diskState: Disk
routeConnectivityTooltip: Connectivity between the VM network and the management network, which the Harvester nodes are connected to.
routeConnectivityTooltip: Connectivity between the VM network and the management network, which the [[Harvester]] nodes are connected to.
fingerprint: Fingerprint
value: Value
actions: Actions
@@ -500,7 +502,7 @@ harvester:
aclEmptyError: The fields in subnet access control list rule can not be empty.
dashboard:
label: Dashboard
header: "Harvester Cluster: {cluster}"
header: "[[Harvester]] Cluster: {cluster}"
hardwareResourceGauge:
cpu: CPU
memory: Memory
@@ -511,6 +513,58 @@ harvester:
label: Events
vmMetrics:
label: Virtual Machine Metrics
healthSummary:
component: Component
severity: Severity
errorCount: Errors
warningCount: Warnings
expandAll: Expand All
collapseAll: Collapse All
componentHealth:
label: Components
errors: '{count, plural, =1 {1 error} other {# errors}}'
component: Component
check: Check
severity: Severity
message: Message
affectedCount: Affected Resources
noAffectedResources: No affected resources
noIssues: No issues detected
checksNotLoaded: Unable to load the checks
showIgnored: 'Show ignored ({counts})'
ignoredChecks: '{count, plural, =1 {1 check} other {# checks}}'
ignoredResources: '{count, plural, =1 {1 resource} other {# resources}}'
loadFailed:
healthSummaries: 'Unable to load the health summary: {error}'
componentHealths: 'Unable to load the checks: {error}'
ignoreRules: 'Unable to load the ignore rules: {error}'
ignore:
create: Create Ignore Rule
view: View Ignore Rule
edit: Edit Ignore Rule
delete: Delete Ignore Rule
ignored: Ignored
plusIgnored: '+ {n} ignored'
scope: Scope
scopeResources: Selected resources
scopeCheck: Entire check
resources: Resources
duration: Ignore for
days7: 7 days
days30: 30 days
forever: Forever
expiresOn: 'Expires on {date}'
expiredOn: 'Expired on {date}'
neverExpires: Never expires
willExpireOn: 'Will expire on {date}'
willNeverExpire: Will never expire
staysExpired: 'This rule expired on {date} and stays expired unless you choose how long to ignore for.'
reason: Reason
reasonPlaceholder: Why is it ignored? (optional)
created: The ignore rule of {name} is created
updated: The ignore rule of {name} is updated
attemptingToDelete: You are attempting to delete the ignore rule of
reportedAgain: What it ignores will be reported again.
version: Version
host:
@@ -686,6 +740,7 @@ harvester:
virtualMachine:
label: Virtual Machines
osType: OS Type
osTypeTooltip: Selecting an image with an OS label on the Volumes tab may change the OS Type selection.
cpuModel:
label: CPU Model
fetchError: 'Failed to load CPU model configuration: {error}'
@@ -757,6 +812,10 @@ harvester:
tooltip: Enable CPU Pinning brings better performance and reduce latency for the virtual machine
restartVMMessage: Changing the CPU Pinning setting requires a virtual machine reboot for the change to take effect
migrationMessage: This virtual machine can only be migrated to a target node that has CPU Manager enabled, as CPU Pinning is configured.
cpuManager:
prefix: You must enable CPU Manager for at least one node in
middle: 'host page'
suffix: to enable CPU Pinning for VM
restartNow: |-
{restart, select,
true {Restart}
@@ -766,13 +825,9 @@ harvester:
genericLoginError: Authentication failed. Please re-log in and try again.
installAgent: Install guest agent
enableUsb: Enable USB Tablet
advancedOptions:
systemOptions:
tpm: Enable TPM
tpmPersistentState: TPM Persistent State
cpuManager:
prefix: You must enable CPU Manager for at least one node in
middle: 'host page'
suffix: to enable CPU Pinning for VM
efiEnabled: Booting in EFI mode
efiPersistentState: EFI Persistent State
secureBoot: Secure Boot
@@ -801,19 +856,16 @@ harvester:
saveVolume: Update Volume
encryption: Encryption
performance:
title: Storage Performance Options
expand: Show high-performance options
collapse: Hide high-performance options
profile:
label: Performance Profile
tip: "\"High Performance\" applies a tuned preset (no host cache, native AIO, a dedicated I/O thread on the virtio bus). Choose \"Custom\" to set each option yourself."
default: Default (Balanced)
label: Storage Performance Profile
tip: '"High Performance" switches the disk to the virtio bus, disables the host cache, uses native AIO and gives the disk a dedicated I/O thread. Choose "Custom" to set each option yourself.'
default: Default
highPerformance: High Performance
custom: Custom
highProfileTip: This disk will use the virtio bus with host cache disabled, native AIO and a dedicated I/O thread.
highProfileTip: This disk will use the virtio bus, no host cache, native AIO and a dedicated I/O thread.
cacheMode:
label: Cache Mode
tip: "How the host caches disk I/O. \"None\" (host cache disabled) is best for high-throughput guests on block storage; \"WriteBack\" favours performance; \"WriteThrough\" favours durability."
tip: 'How the host caches disk I/O. "None" is best for high-throughput guests on block storage, "WriteBack" favors performance and "WriteThrough" favors durability.'
default: Default (hypervisor)
none: None (no host cache)
writeback: WriteBack
@@ -821,35 +873,33 @@ harvester:
filesystemWarning: "\"None\" (O_DIRECT) requires storage that supports direct I/O. It is recommended only for Block volume mode; on Filesystem volumes the VM may fail to start."
ioMode:
label: I/O Mode
tip: "How QEMU submits I/O. \"Native\" (Linux AIO) offers the lowest overhead but requires host cache set to \"None\"; \"Threads\" uses a host thread pool."
tip: 'How QEMU submits I/O. "Native" (Linux AIO) has the lowest overhead and needs cache mode "None". "Threads" uses a host thread pool.'
default: Default (hypervisor)
native: Native (AIO)
threads: Threads
nativeRequiresNoCacheTip: Native I/O mode requires cache mode "None"; it has been set for you.
nativeRequiresNoCacheTip: Native I/O mode needs the host cache disabled, so cache mode is set to None.
dedicatedIOThread:
label: Dedicated I/O Thread
tip: Allocate an exclusive libvirt I/O thread to this disk instead of sharing one. Useful for disks with heavy I/O. Enabling this on any disk turns on the VM's I/O threads policy.
busTip: High-performance features work best on the virtio bus.
tip: Give this disk its own I/O thread instead of sharing one. Useful for disks with heavy I/O.
busTip: 'This disk uses the {bus} bus. A dedicated I/O thread needs the virtio bus.'
diskPerformance:
title: High Performance (I/O Threads and Multi-Queue)
description: These settings apply to all volumes in the Virtual Machine and complement the per-volume options above.
expand: Show VM-wide high-performance options
collapse: Hide VM-wide high-performance options
title: Storage Performance
description: These options apply to all volumes of the virtual machine.
blockMultiQueue:
label: Virtio Block Multi-Queue
tip: Map disk I/O to multiple queues so it is processed across multiple CPUs. Applies to virtio disks and requires a fixed CPU allocation (Harvester always sets one).
tip: Spread disk I/O over one queue per vCPU so that it is processed on multiple CPUs.
noVirtioTip: Add at least one disk on the virtio bus to enable Block Multi-Queue.
ioThreadsPolicy:
label: I/O Threads Policy
tip: "How libvirt allocates I/O threads. \"Shared\" uses one thread for all disks; \"Auto\" pools threads round-robin (up to ~2x vCPUs); \"Supplemental Pool\" lets you pick a fixed thread count and adds matching CPUs to the pod."
tip: '"Shared" uses one I/O thread for all disks. "Auto" spreads disks over a pool of threads. "Supplemental Pool" uses a fixed number of threads.'
default: "Disabled (default)"
shared: Shared
auto: Auto
supplementalPool: Supplemental Pool
autoEnabledTip: A disk requests a dedicated I/O thread, so the policy is enabled (defaults to "Shared").
autoEnabledTip: A volume asks for a dedicated I/O thread, so the Shared policy will be used.
ioThreadCount:
label: I/O Thread Count
tip: Number of I/O threads for the supplemental pool. 4-8 is a common range depending on workload.
tip: Number of I/O threads in the supplemental pool.
shareable:
label: Shareable
tip: Allow multiple virtual machines to attach and write to this volume simultaneously.
@@ -871,6 +921,12 @@ harvester:
title: Network
addNetwork: Add Network
addPort: Add Port
networkBoot:
label: Enable network boot (PXE)
tip: Adds this interface to the VM boot order so the guest firmware can boot from the network. Requires a DHCP/TFTP (PXE) server reachable on the selected network; the management network does not provide one.
order: Network boot order
first: Before volumes
last: After volumes
cloudConfig:
title: Cloud Configuration
createTemplateTitle: 'Create {name}'
@@ -882,10 +938,12 @@ harvester:
label: User Data Template
title: "User Data:"
tip: "You can specify user data to configure an instance or run a configuration script during launch. If you launch more than one instance at a time, the user data is available to all the instances in that reservation. <a href='https://cloudinit.readthedocs.io/en/latest/topics/examples.html' target='_blank'>Learn more</a>"
invalidYaml: 'Invalid User Data YAML syntax'
network:
label: Network Data Template
title: "Network Data:"
tip: "The network-data configuration allows you to customize the instance's networking interfaces by assigning subnet configuration, virtual device creation (bonds, bridges, VLANs) routes and DNS configuration. <a href='https://cloudinit.readthedocs.io/en/latest/reference/network-config-format-v1.html' target='_blank'>Learn more</a>"
invalidYaml: 'Invalid Network Data YAML syntax'
sysprep:
title: Windows Unattended & Sysprep Configuration
description: "Configure Windows automated installation using autounattend.xml. The configuration will be stored in a Kubernetes Secret and mounted as a CD-ROM during installation. <a href='https://docs.microsoft.com/en-us/windows-hardware/manufacture/desktop/automate-windows-setup' target='_blank'>Learn more</a>"
@@ -931,7 +989,7 @@ harvester:
displayNamePlaceholder: Virtual machine alias name
displayName: Display Name
filesystem:
description: Harvester supports filesystem volumes for VM via virtiofs.
description: '[[Harvester]] supports filesystem volumes for VM via virtiofs.'
type: Filesystem Type
volume: Volume
resource: Resource
@@ -1014,6 +1072,51 @@ harvester:
tips: Press the record button to capture your keyboard inputs.
send: Send
preferredKeys: Preferred Custom Shortcut Keys
settings:
label: Settings
viewMode:
label: Display
scale: Scale the display to fit the window
none: Manual zoom
zoom: Zoom
viewOnly: View only
quality: JPEG quality
compression: Compression level
fullscreen:
enter: Full Screen
exit: Exit Full Screen
ctrlAltDel: Ctrl+Alt+Del
confirm:
ctrlAltDel:
title: Send Ctrl+Alt+Del?
message: Windows opens its sign-in or security screen. Most Linux systems restart the virtual machine.
button: Send
softReboot:
title: Soft reboot this virtual machine?
message: The guest operating system is asked to restart. Unsaved work inside the virtual machine is lost.
button: Soft Reboot
takeOver:
label: Take Over
title: Take over this console?
confirm: The other VNC session connected to this virtual machine will be disconnected.
failure:
inUse: This console is in use
unavailable: Unable to connect
dropped: Disconnected
error: Connection failed
failureDetail:
inUse: Another VNC session is connected to this virtual machine. Retry once it is released, or take over the console to disconnect the other session.
unavailable: The console is not available. Check that the virtual machine is running, then retry.
dropped: The console connection was closed. Another VNC session may have opened this console.
status:
connecting: Connecting
connected: Connected
connectedViewOnly: Connected (view only)
disconnected: Disconnected
failed: Connection failed
reconnecting: 'Reconnecting {retryTimes} of {maximumRetryTimes}'
credentialsRequired: This console requires credentials that the dashboard cannot provide.
inUse: Another VNC session may be using this console. Retrying until it is released.
terminationGracePeriodSeconds:
label: Termination Grace Period
affinity:
@@ -1140,8 +1243,8 @@ harvester:
selectExisting: Select Existing Image
createRepository: Creating Upgrade Repository
succeeded: Succeeded
releaseTip: Please read the upgrade documentation carefully. You can view details on the <a href="{url}" target="_blank">Harvester Release Notes</a>.
checkReady: I have read and understood the upgrade instructions related to this Harvester version.
releaseTip: Please read the upgrade documentation carefully. You can view details on the <a href="{url}" target="_blank">[[Harvester]] Release Notes</a>.
checkReady: I have read and understood the upgrade instructions related to this [[Harvester]] version.
pending: Pending
upload:
duplicatedFile: The file you are trying to upload already exists.
@@ -1150,7 +1253,7 @@ harvester:
os: OS
kubernetes: Kubernetes
monitoringChart: Monitoring Chart
harvesterChart: Harvester Chart
harvesterChart: '[[Harvester]] Chart'
success: Success
fail: Fail
ongoing: On-going
@@ -1190,7 +1293,7 @@ harvester:
maxFailure:
label: Max Failure
count: Count
tooltip: Max number of consecutive failed backups that could be tolerated. If reach this threshold, Harvester controller will suspend the schedule job. This value should less than retain count
tooltip: Max number of consecutive failed backups that could be tolerated. If reach this threshold, [[Harvester]] controller will suspend the schedule job. This value should less than retain count
virtualMachine:
title: Virtual Machine Name
placeholder: Select a virtual machine
@@ -1204,7 +1307,7 @@ harvester:
title: Restore Virtual Machine
refreshInterval:
label: Refresh Interval
tip: The interval for the backup target to sync data to harvester cluster. Set to 0 to disable refresh mechanism.
tip: The interval for the backup target to sync data to [[Harvester]] cluster. Set to 0 to disable refresh mechanism.
backupTargetTip: The endpoint used to access the backupstore. NFS and S3 are supported.
message:
noSetting:
@@ -1223,7 +1326,7 @@ harvester:
actionLabel: Test connection
waitingLabel: Testing connection...
successLabel: Connection tested
successMessage: 'Harvester can successfully connect to the endpoint {endpoint}'
successMessage: '[[Harvester]] can successfully connect to the endpoint {endpoint}'
restore:
backup: Backup
deletePreviousVolumes: Delete Previous Volumes
@@ -1434,7 +1537,7 @@ harvester:
placeholder: Select a provider network
networkPolicy:
label: Policies
banner: The network policies must be used for VMs attached to overlay networks. Please read the <a href="{url}" target="_blank">harvester document</a> how the network policy works.
banner: The network policies must be used for VMs attached to overlay networks. Please read the <a href="{url}" target="_blank">[[Harvester]] documentation</a> on how network policies work.
network:
label: Virtual Machine Networks
tabs:
@@ -1543,7 +1646,7 @@ harvester:
autoRotateRKE2Certs:
expiringInHours: Expiring in
httpProxy:
warning: 'WARNING: <br/> If you configure "http-proxy" and "https-proxy", you must also put Harvester node&apos;s CIDR into "no-proxy", otherwise the Harvester cluster will be broken.'
warning: 'WARNING: <br/> If you configure "http-proxy" and "https-proxy", you must also put [[Harvester]] node&apos;s CIDR into "no-proxy", otherwise the [[Harvester]] cluster will be broken.'
supportBundleImage:
imagePullPolicy: Pull Policy
repo: Repository
@@ -1595,7 +1698,7 @@ harvester:
strategyType: Strategy Type
concurrency: Concurrency
harvesterMonitoring:
label: Harvester Monitoring
label: '[[Harvester]] Monitoring'
section:
prometheus: Prometheus
prometheusNodeExporter: Prometheus Node Exporter
@@ -1610,10 +1713,10 @@ harvester:
url: URL
insecureSkipTLSVerify: Insecure Skip TLS Verify
tip:
prefix: Harvester secures cluster registration via TLS by default. If opt out "Insecure Skip TLS Verify", you must provide custom CA certificates using the
prefix: '[[Harvester]] secures cluster registration via TLS by default. If opt out "Insecure Skip TLS Verify", you must provide custom CA certificates using the'
middle: 'additional-ca'
suffix: setting.
message: To completely unset the imported Harvester cluster, please also remove it on the Rancher Dashboard UI via the <code> Virtualization Management </code> page.
message: To completely unset the imported [[Harvester]] cluster, please also remove it on the Rancher Dashboard UI via the <code> Virtualization Management </code> page.
ntpServers:
isNotIPV4: The address you entered is not IPv4 or host. Please enter a valid IPv4 address or a host address.
isDuplicate: There are duplicate NTP server configurations.
@@ -1643,19 +1746,19 @@ harvester:
networkData: Network Data
support:
title: Harvester Support
title: '[[Harvester]] Support'
kubeconfig:
title: Download KubeConfig
titleDescription: Download kubeconfig for debugging.
internal:
rancher:
title: Access Embedded Rancher UI
titleDescription: You can only use the embedded Rancher UI for debugging and validation purposes. For more information about how Harvester integrates with Rancher, see the <a target="_blank" href="{url}" rel="noopener noreferrer nofollow">documentation</a>.
titleDescription: You can only use the embedded Rancher UI for debugging and validation purposes. For more information about how [[Harvester]] integrates with Rancher, see the <a target="_blank" href="{url}" rel="noopener noreferrer nofollow">documentation</a>.
longhorn:
title: Access Embedded Longhorn UI
titleDescription: We only support to use the embedded Longhorn UI for debugging and validation purpose.
community:
learnMore: Find out more about SUSE Harvester support
learnMore: Find out more about [[Harvester]] support
pricing: Contact us for pricing
namespace:
@@ -1875,16 +1978,16 @@ harvester:
addons:
descriptions:
'harvester-system/vm-import-controller': vm-import-controller is an add-on to help migrate virtual machine workloads from other source clusters to an existing Harvester cluster.
'harvester-system/pcidevices-controller': pcidevices-controller is an add-on to help discover PCI devices for nodes in your cluster and allow users to prepare devices for PCI Passthrough, for use with Harvester virtual machine and guest clusters.
'cattle-logging-system/rancher-logging': rancher-logging is an add-on to collect versatile logs, events, and audits from the Harvester cluster and route them to many kinds of servers based on flows.
'harvester-system/vm-import-controller': vm-import-controller is an add-on to help migrate virtual machine workloads from other source clusters to an existing [[Harvester]] cluster.
'harvester-system/pcidevices-controller': pcidevices-controller is an add-on to help discover PCI devices for nodes in your cluster and allow users to prepare devices for PCI Passthrough, for use with [[Harvester]] virtual machine and guest clusters.
'cattle-logging-system/rancher-logging': rancher-logging is an add-on to collect versatile logs, events, and audits from the [[Harvester]] cluster and route them to many kinds of servers based on flows.
'harvester-system/rancher-vcluster': rancher-vcluster deploys a virtual cluster (vcluster) with Rancher installed.
'cattle-monitoring-system/rancher-monitoring': rancher-monitoring is an add-on that collects Harvester cluster and virtual machine metrics and allows you to view the metrics on an embedded dashboard and send alert(s) to remote servers.
'vm-import-controller': vm-import-controller is an add-on to help migrate virtual machine workloads from other source clusters to an existing Harvester cluster.
'pcidevices-controller': pcidevices-controller is an add-on to help discover PCI devices for nodes in your cluster and allow users to prepare devices for PCI Passthrough, for use with Harvester virtual machines and guest clusters.
'nvidia-driver-toolkit': 'nvidia-driver-toolkit is an add-on to enable vGPU devices and assign them to Harvester virtual machines.'
'rancher-logging': rancher-logging is an add-on to collect versatile logs, events, and audits from the Harvester cluster and route them to many kinds of servers based on flows.
'rancher-monitoring': rancher-monitoring is an add-on to collect Harvester cluster and virtual machine metrics, view them on the embedded dashboard, and send alert(s) to remote servers.
'cattle-monitoring-system/rancher-monitoring': rancher-monitoring is an add-on that collects [[Harvester]] cluster and virtual machine metrics and allows you to view the metrics on an embedded dashboard and send alert(s) to remote servers.
'vm-import-controller': vm-import-controller is an add-on to help migrate virtual machine workloads from other source clusters to an existing [[Harvester]] cluster.
'pcidevices-controller': pcidevices-controller is an add-on to help discover PCI devices for nodes in your cluster and allow users to prepare devices for PCI Passthrough, for use with [[Harvester]] virtual machines and guest clusters.
'nvidia-driver-toolkit': 'nvidia-driver-toolkit is an add-on to enable vGPU devices and assign them to [[Harvester]] virtual machines.'
'rancher-logging': rancher-logging is an add-on to collect versatile logs, events, and audits from the [[Harvester]] cluster and route them to many kinds of servers based on flows.
'rancher-monitoring': rancher-monitoring is an add-on to collect [[Harvester]] cluster and virtual machine metrics, view them on the embedded dashboard, and send alert(s) to remote servers.
'rancher-vcluster': rancher-vcluster deploys a virtual cluster (vcluster) with Rancher installed.
'k3k': k3k is an add-on to deploy the k3k controller.
'rancher-k3k': rancher-k3k deploys a k3k virtual cluster with Rancher installed.
@@ -1953,7 +2056,7 @@ harvester:
providerSelect: Provider
createNew: Create new provider
requirementsTitle: Requirements
requirementsText: "To migrate virtual machines from VMware, you will need a vCenter Server running version 6.5 or higher with a user account that has at least read permissions, and the source environment must be network-accessible from Harvester Node."
requirementsText: "To migrate virtual machines from VMware, you will need a vCenter Server running version 6.5 or higher with a user account that has at least read permissions, and the source environment must be network-accessible from [[Harvester]] Node."
name: Name
urlLabel: vCenter/ESXi URL
urlPlaceholder: "https://vcenter.example.com/sdk"
@@ -2006,7 +2109,7 @@ harvester:
datastore: Datastore
dashboard:
title: Virtual Machine Migration Overview
description: "Migrate virtual machines from VMware vSphere to Harvester using cold migration for data consistency. Create a migration plan to select VMs, map networks and storage, and prepare a migration to Harvester."
description: "Migrate virtual machines from VMware vSphere to [[Harvester]] using cold migration for data consistency. Create a migration plan to select VMs, map networks and storage, and prepare a migration to [[Harvester]]."
createPlan: Create Migration
tableTitle: Migrations
columns:
@@ -2026,22 +2129,22 @@ harvester:
checkMigratedVm: Click to check migrated VM details
configureMappings:
title: Set Mappings
description: Map VMware networks and datastores to Harvester and Longhorn target resources
description: Map VMware networks and datastores to [[Harvester]] and Longhorn target resources
save: Save Mappings and Continue
noTemplate: Start from scratch
removeMap: Remove mapping
networkMapping:
title: Network Mapping
description: Map VMware port groups to Harvester networks
placeholder: Choose a Harvester network
description: Map VMware port groups to [[Harvester]] networks
placeholder: Choose a [[Harvester]] network
template: Use existing network mapping as template
options:
podNetworking: Management Network
ignored: Ignored (No NIC will be created)
storageMapping:
title: Storage Mapping
description: Map VMware datastores to Harvester storage classes
placeholder: Choose a Harvester Storage Class
description: Map VMware datastores to [[Harvester]] storage classes
placeholder: Choose a [[Harvester]] Storage Class
template: Use existing storage mapping as template
storageDefaults:
title: 'Storage defaults — {name}'
@@ -2360,7 +2463,7 @@ harvester:
vGpuDevices: vGPU Devices
showMore: Show More
parentSriov: Filter By Parent SR-IOV GPU
noPermission: Please contact your system administrator to add Harvester add-ons first.
noPermission: Please contact your system administrator to add [[Harvester]] add-ons first.
goSetting:
prefix: The nvidia-driver-toolkit add-on is not enabled, click
middle: here
@@ -2396,7 +2499,7 @@ harvester:
vgpu:
label: vGPU Devices
noPermission: Please contact system administrator to add Harvester add-ons first.
noPermission: Please contact system administrator to add [[Harvester]] add-ons first.
detachWarning:
title: Cannot Disable vGPU
message: Please detach the device from the VM and save it first before disabling this vGPU device.
@@ -2417,7 +2520,7 @@ harvester:
usb:
label: USB Devices
noPermission: Please contact system admin to add Harvester add-ons first
noPermission: Please contact system admin to add [[Harvester]] add-ons first
goSetting:
prefix: The pcidevices-controller add-on is not enabled, click
middle: here
@@ -2478,7 +2581,7 @@ typeDescription:
# Should fit on one line.
# If you link to anything external, it MUST have
# target="_blank" rel="noopener noreferrer nofollow"
harvester: "Branding allows administrators to globally re-brand the UI by customizing the Harvester product name, logos and color scheme."
harvester: "Branding allows administrators to globally re-brand the UI by customizing the [[Harvester]] product name, logos and color scheme."
advancedSettings:
tags:
@@ -2493,19 +2596,19 @@ advancedSettings:
descriptions:
'harv-vlan': Default Network Interface name of the VLAN network.
'harv-backup-target': Custom backup target to store virtual machine backups.
'branding': Branding allows administrators to globally re-brand the UI by customizing the Harvester product name, logos, and color scheme.
'branding': Branding allows administrators to globally re-brand the UI by customizing the [[Harvester]] product name, logos, and color scheme.
'harv-csi-driver-config': Configure additional information for CSI drivers.
'harv-csi-online-expand-validation': Allow online volume expansion for specific CSI drivers.
'harv-containerd-registry': Containerd Registry Configuration to connect private registries.
'harv-log-level': Configure Harvester server log level. Defaults to Info.
'harv-server-version': Harvester server version.
'harv-server-flavor': "Indicates the Harvester edition: Prime or Community."
'harv-upgrade-checker-enabled': Specifies whether to enable Harvester upgrade check or not. Default is True.
'harv-upgrade-checker-url': Default Harvester upgrade check url. Only used when the <code>upgrade-checker-enabled</code> is equal to True.
'harv-ui-source': Configure how to load the UI source. The `External` option is used to load the UI from a ui-index URL, while the `Bundled` option loads the UI from the local Harvester server.
'harv-log-level': Configure [[Harvester]] server log level. Defaults to Info.
'harv-server-version': '[[Harvester]] server version.'
'harv-server-flavor': "Indicates the [[Harvester]] edition: Prime or Community."
'harv-upgrade-checker-enabled': Specifies whether to enable [[Harvester]] upgrade check or not. Default is True.
'harv-upgrade-checker-url': Default [[Harvester]] upgrade check url. Only used when the <code>upgrade-checker-enabled</code> is equal to True.
'harv-ui-source': Configure how to load the UI source. The `External` option is used to load the UI from a ui-index URL, while the `Bundled` option loads the UI from the local [[Harvester]] server.
'harv-ui-index': 'HTML index location for the UI.'
'harv-cluster-registration-url': Registration URL for multi-cluster management.
'harv-http-proxy': 'HTTP proxy for Harvester to access external services.'
'harv-http-proxy': 'HTTP proxy for [[Harvester]] to access external services.'
'harv-additional-ca': 'Custom CA root certificates for TLS validation.'
'harv-overcommit-config': 'Resource overcommit configuration.'
'harv-support-bundle-timeout': 'Support bundle timeout configuration in minutes, use 0 to disable the timeout.'
@@ -2517,13 +2620,13 @@ advancedSettings:
'harv-storage-network': 'Longhorn storage-network setting.'
'harv-rwx-network': 'Configure RWX network behavior for shared or dedicated storage network usage.'
'harv-support-bundle-namespaces': Select additional namespaces to include in the support bundle.
'harv-auto-disk-provision-paths': Specify the disks(using glob pattern) that Harvester will automatically add as virtual machine storage.
'harv-auto-disk-provision-paths': Specify the disks(using glob pattern) that [[Harvester]] will automatically add as virtual machine storage.
'harv-support-bundle-image': Support bundle image configuration. Find different versions in <a href="https://hub.docker.com/r/rancher/support-bundle-kit/tags" target="_blank">rancher/support-bundle-kit</a>.
'harv-release-download-url': This setting allows you to configure the <code>upgrade release download</code> URL address. Harvester will get the ISO URL and checksum value from the (<code>$URL</code>/<code>$VERSION</code>/version.yaml) file hosted by the configured URL.
'harv-release-download-url': This setting allows you to configure the <code>upgrade release download</code> URL address. [[Harvester]] will get the ISO URL and checksum value from the (<code>$URL</code>/<code>$VERSION</code>/version.yaml) file hosted by the configured URL.
'harv-default-vm-termination-grace-period-seconds': Configure the virtual machine termination grace period for virtual machine stop.
'harv-ntp-servers': Configure NTP server. You can configure multiple IPv4 addresses or host addresses.
'harv-auto-rotate-rke2-certs': The certificate rotation mechanism relies on Rancher. Harvester will automatically update certificates generation to trigger rotation.
'harv-kubeconfig-default-token-ttl-minutes': 'TTL (in minutes) applied on Harvester administration kubeconfig files. Default is 0, which means to never expire.'
'harv-auto-rotate-rke2-certs': The certificate rotation mechanism relies on Rancher. [[Harvester]] will automatically update certificates generation to trigger rotation.
'harv-kubeconfig-default-token-ttl-minutes': 'TTL (in minutes) applied on [[Harvester]] administration kubeconfig files. Default is 0, which means to never expire.'
'harv-longhorn-v2-data-engine-enabled': 'Enable the Longhorn V2 data engine. Default is false. <ul><li>Changing this setting will restart RKE2 on all nodes. This will not affect running VM workloads.</li><li>If you see "not enough hugepages-2Mi capacity" errors when enabling this setting, wait a minute for the error to clear. If the error remains, reboot the affected node.</li></ul>'
'harv-longhorn-v2-data-engine-hugepage-enabled': 'Enable hugepages when using the Longhorn V2 data engine. Default is true. Disabling hugepages reduces memory pressure on low-spec nodes and increases deployment flexibility. However, performance may be lower compared to running with hugepages.'
'harv-longhorn-v2-data-engine-memory-size': 'Configure the amount of memory allocated to the SPDK target daemon when using the Longhorn V2 data engine. Default is 2048 MiB.'
@@ -2535,6 +2638,7 @@ advancedSettings:
'harv-kubevirt-migration': 'Configure cluster-wide KubeVirt live migration parameters.'
'harv-instance-manager-resources': 'Configure resource percentage reservations for Longhorn instance manager V1 and V2. Valid instance manager CPU range between 0 - 40.'
'harv-cluster-pod-security-standard': 'Enforce Kubernetes Pod Security Standards (PSS) at the cluster level.'
'harv-maintenance-mode-drain-timeout': 'Maintenance mode drain timeout in minutes. Use 0 to disable the timeout.'
typeLabel:
kubevirt.io.virtualmachine: |-
@@ -0,0 +1,65 @@
import { MANAGEMENT } from '@shell/config/types';
import SettingsPage from '../harvesterhci.io.setting.vue';
import { HCI } from '../../types';
import { HCI_SETTING } from '../../config/settings';
describe('list: harvesterhci.io.setting', () => {
async function fetchPage({ visibleSettings = [], isSingleProduct = false } = {}) {
const dispatch = jest.fn(() => Promise.resolve([]));
const page = {
initSettings: [],
$store: {
dispatch,
getters: {
isSingleProduct,
currentProduct: { inStore: 'harvester' },
'harvester/visibleSettings': visibleSettings,
}
}
};
await SettingsPage.fetch.call(page);
return { page, dispatch };
}
const visible = (id, config = {}) => ({
id, config, data: { id }
});
it('should list the visible settings sorted by name, a setting with an alias under its alias', async() => {
const { page } = await fetchPage({ visibleSettings: [visible('z-setting'), visible(HCI_SETTING.UI_PL, { alias: 'branding' })] });
expect(page.initSettings.map(({ id }) => id)).toStrictEqual(['branding', 'z-setting']);
});
it('should keep the config and the resource of a setting', async() => {
const { page } = await fetchPage({ visibleSettings: [visible('a-setting', { kind: 'json', canReset: true })] });
expect(page.initSettings[0]).toMatchObject({
id: 'a-setting', kind: 'json', canReset: true, data: { id: 'a-setting' }, hide: true, canHide: true, hasActions: true
});
});
it('should only allow actions on the server version when it is read only', async() => {
const { page } = await fetchPage({
visibleSettings: [
visible('a-setting', { readOnly: true }),
visible(HCI_SETTING.SERVER_VERSION, { readOnly: true }),
]
});
expect(page.initSettings.map(({ hasActions }) => hasActions)).toStrictEqual([false, true]);
});
it('should load the settings of the management store only in a single product', async() => {
const { dispatch: multiCluster } = await fetchPage();
const { dispatch: singleProduct } = await fetchPage({ isSingleProduct: true });
expect(multiCluster.mock.calls).toStrictEqual([['harvester/findAll', { type: HCI.SETTING }]]);
expect(singleProduct.mock.calls).toStrictEqual([
['harvester/findAll', { type: HCI.SETTING }],
['management/findAll', { type: MANAGEMENT.SETTING }],
]);
});
});
@@ -0,0 +1,54 @@
import { mount } from '@vue/test-utils';
import HarvesterVPC from '../kubeovn.io.vpc.vue';
// A table that renders the page's group header for each of the given groups
function resourceTable(groups) {
return {
data: () => ({ groups }),
template: '<div><div v-for="group in groups" :key="group.key" class="group"><slot name="group-by" :group="group" /></div></div>',
};
}
function mountList(groups) {
return mount(HarvesterVPC, {
props: { schema: { id: 'kubeovn.io.vpc' } },
data: () => ({ enabledKubeOvnAddon: true }),
global: {
stubs: {
ResourceTable: resourceTable(groups),
Masthead: true,
Loading: true,
'router-link': { template: '<a><slot /></a>' },
},
mocks: {
$fetchState: { pending: false },
t: (key) => ({ 'harvester.vpc.label': 'Virtual Private Cloud', 'generic.none': 'None' }[key] || key),
$store: {
getters: {
currentProduct: { inStore: 'harvester' },
'harvester/all': () => [],
'harvester/schemaFor': () => ({ collectionMethods: ['POST'] }),
},
},
},
},
});
}
describe('list: kubeovn.io.vpc', () => {
it('should label a group of subnets without a VPC as None and offer no VPC actions', () => {
const wrapper = mountList([{ key: '' }]);
const group = wrapper.find('.group');
expect(group.find('.group-tab').text()).toBe('Virtual Private Cloud: None');
expect(group.find('.right').exists()).toBe(false);
});
it('should label a VPC group with its name and offer the VPC actions', () => {
const wrapper = mountList([{ key: 'ovn-cluster' }]);
const group = wrapper.find('.group');
expect(group.find('.group-tab').text()).toBe('Virtual Private Cloud: ovn-cluster');
expect(group.findAll('.right a, .right button')).toHaveLength(3);
});
});
@@ -24,8 +24,10 @@ import { allDashboardsExist } from '@shell/utils/grafana';
import { isEmpty } from '@shell/utils/object';
import { HCI } from '../types';
import HarvesterUpgrade from '../components/HarvesterUpgrade';
import HealthSummaryTable from '../components/health/HealthSummaryTable';
import { PRODUCT_NAME as HARVESTER_PRODUCT } from '../config/harvester';
import { UNIT_SUFFIX } from '../utils/unit';
import { totalErrorCount } from '../utils/component-health';
dayjs.extend(utc);
dayjs.extend(minMax);
@@ -125,6 +127,7 @@ export default {
DashboardMetrics,
Banner,
MessageLink,
HealthSummaryTable,
},
async fetch() {
@@ -237,6 +240,20 @@ export default {
computed: {
...mapGetters(['currentCluster']),
// the health resources only exist while the resource health addon is installed
componentHealthEnabled() {
const inStore = this.$store.getters['currentProduct'].inStore;
return this.$store.getters['harvester-common/getFeatureEnabled']('componentHealth') &&
!!this.$store.getters[`${ inStore }/schemaFor`](HCI.HEALTH_SUMMARY);
},
componentErrorCount() {
const inStore = this.$store.getters['currentProduct'].inStore;
return totalErrorCount(this.$store.getters[`${ inStore }/all`](HCI.HEALTH_SUMMARY));
},
accessibleResources() {
const inStore = this.$store.getters['currentProduct'].inStore;
@@ -821,6 +838,16 @@ export default {
</template>
</SortableTable>
</Tab>
<Tab
v-if="componentHealthEnabled"
name="components"
:label="t('harvester.dashboard.sections.componentHealth.label')"
:weight="95"
:display-alert-icon="componentErrorCount > 0"
:error-icon-tooltip="t('harvester.dashboard.sections.componentHealth.errors', { count: componentErrorCount })"
>
<HealthSummaryTable />
</Tab>
</Tabbed>
</div>
</section>
+8 -37
View File
@@ -7,7 +7,7 @@ import { allHash } from '@shell/utils/promise';
import Tabbed from '@shell/components/Tabbed/index.vue';
import Tab from '@shell/components/Tabbed/Tab.vue';
import Settings from '@pkg/harvester/components/SettingList.vue';
import { HCI_ALLOWED_SETTINGS, HCI_SINGLE_CLUSTER_ALLOWED_SETTING, HCI_SETTING } from '../config/settings';
import { HCI_SETTING } from '../config/settings';
import { HCI } from '../types';
export default {
@@ -29,47 +29,19 @@ export default {
hash.settings = this.$store.dispatch('management/findAll', { type: MANAGEMENT.SETTING });
}
const rows = await allHash(hash);
await allHash(hash);
let allRows = [];
allRows.push(...rows.harvesterSettings);
if (isSingleProduct) {
allRows = [...rows.settings, ...allRows];
}
// Map settings from array to object keyed by id
const settingsMap = allRows.reduce((res, s) => {
res[s.id] = s;
return res;
}, {});
const initSettings = [];
let SETTINGS = HCI_ALLOWED_SETTINGS;
if (this.isStandaloneHarvester) {
SETTINGS = {
...SETTINGS,
...HCI_SINGLE_CLUSTER_ALLOWED_SETTING,
};
}
Object.keys(SETTINGS).forEach((setting) => {
if (!settingsMap[setting]) {
return;
}
const realSetting = SETTINGS[setting]?.alias || setting;
const initSettings = this.$store.getters[`${ inStore }/visibleSettings`].map(({ id, config, data }) => {
const s = {
...SETTINGS[setting],
id: realSetting,
data: settingsMap[setting],
...config,
id: config.alias || id,
data,
};
s.hide = s.canHide = (s.kind === 'json' || s.kind === 'multiline' || s.customFormatter === 'json' || s.data.customFormatter === 'json');
s.hasActions = s.id === HCI_SETTING.SERVER_VERSION ? true : !s.readOnly;
initSettings.push(s);
return s;
});
this.initSettings = initSettings.sort((a, b) => {
@@ -90,7 +62,6 @@ export default {
computed: {
...mapGetters({ t: 'i18n/t' }),
...mapGetters(['isStandaloneHarvester']),
settings() {
return this.initSettings.map((setting) => {
+6 -2
View File
@@ -139,7 +139,8 @@ export default {
},
methods: {
groupLabel(group) {
return `${ this.t('harvester.vpc.label') }: ${ group.key }`;
// Kube-OVN sets a subnet's VPC (ovn-cluster when none is given), so an empty one is a subnet it hasn't processed
return `${ this.t('harvester.vpc.label') }: ${ group.key || this.t('generic.none') }`;
},
slotName(vpc) {
@@ -226,7 +227,10 @@ export default {
{{ groupLabel(group) }}
</span>
</div>
<div class="right">
<div
v-if="group.key"
class="right"
>
<router-link
v-if="isSubnetCreatable"
class="btn btn-sm role-secondary mr-5"
@@ -151,7 +151,8 @@ export default {
},
rows() {
const matchVMIs = this.allVMIs.filter((VMI) => !this.allVMs.find((VM) => VM.id === VMI.id));
const vmIds = new Set(this.allVMs.map((VM) => VM.id));
const matchVMIs = this.allVMIs.filter((VMI) => !vmIds.has(VMI.id));
return [...this.allVMs, ...matchVMIs];
},
@@ -160,7 +161,11 @@ export default {
* We want to show the progress bar only for Backup's restore; snapshot's restore is immediate.
*/
hasBackUpRestoreInProgress() {
return !!this.rows.find((r) => r.restoreResource && !r.restoreResource.fromSnapshot && !r.restoreResource.isComplete);
return this.rows.some((r) => {
const restore = r.restoreResource;
return restore && !restore.fromSnapshot && !restore.isComplete;
});
},
vmRestartRequiredNames() {
@@ -0,0 +1,140 @@
import VM_MIXIN from '../index';
import impl from '../impl';
const USER_ERROR = 'harvester.virtualMachine.cloudConfig.user.invalidYaml';
const NETWORK_ERROR = 'harvester.virtualMachine.cloudConfig.network.invalidYaml';
const CLOUD_CONFIG = '#cloud-config\npackage_update: true\npackages:\n - qemu-guest-agent\n';
const YAML_SCRIPT = '#!/bin/bash\napt-get update\napt-get install -y nginx\n';
function validate({
userScript, networkScript, isEdit = false, savedCloudInit = {}
}) {
const form = {
userScript,
networkScript,
isEdit,
savedCloudInit,
errors: [],
t: (key) => key,
};
VM_MIXIN.methods.validateCloudInit.call(form);
return form.errors;
}
function userDataFor(userScript) {
const form = {
userScript,
sshKey: [],
$store: { getters: { 'harvester/byId': () => undefined } },
...impl.methods,
...VM_MIXIN.methods,
};
return form.getUserData({ osType: 'linux', installAgent: false });
}
describe('mixin: harvester-vm', () => {
describe('validateCloudInit', () => {
it.each([
['a word after the mapping', `${ CLOUD_CONFIG }some words\n`],
['only words', '#cloud-config\nsome words\n'],
['only words and no header', 'some words\n'],
['a list', '#cloud-config\n- a\n- b\n'],
['bad indentation', '#cloud-config\nusers:\n - name: a\n bad: b\n'],
['an unclosed quote', '#cloud-config\npassword: "abc\n'],
])('should block cloud-config user data with %s', (_, userScript) => {
expect(validate({ userScript })).toStrictEqual([USER_ERROR]);
});
it.each([
['undefined', undefined],
['empty', ''],
['only the header', '#cloud-config\n'],
['a valid cloud-config', CLOUD_CONFIG],
['a mapping without the header', 'password: test\n'],
])('should allow user data that is %s', (_, userScript) => {
expect(validate({ userScript })).toStrictEqual([]);
});
it.each([
['a script that is not valid YAML', '#!/bin/bash\napt-get update\n# start it\nsystemctl enable --now nginx\n'],
['a script that parses as YAML', YAML_SCRIPT],
['a MIME message with a cloud-config part', 'Content-Type: multipart/mixed; boundary="b"\nMIME-Version: 1.0\n\n--b\nContent-Type: text/cloud-config\n\n#cloud-config\npackages:\n - nginx\n--b--\n'],
['a Jinja template', '## template: jinja\n#cloud-config\n{% if v1.region == "us" %}\npackages:\n - a\n{% endif %}\n'],
['a Cloudbase-Init PowerShell script', '#ps1_sysnative\n# enable RDP\nWrite-Host "done: ok"\n'],
['a Cloudbase-Init batch script', 'rem cmd\nnet user admin Passw0rd /add\n'],
['a cloud-config archive', '#cloud-config-archive\n- type: text/x-shellscript\n content: |\n #!/bin/sh\n'],
])('should not parse user data that is %s', (_, userScript) => {
expect(validate({ userScript })).toStrictEqual([]);
});
it.each([
['words', 'some words\n'],
['a list', '- a\n- b\n'],
['bad indentation', 'network:\n version: 1\n bad: x\n'],
])('should block network data with %s', (_, networkScript) => {
expect(validate({ networkScript })).toStrictEqual([NETWORK_ERROR]);
});
it.each([
['undefined', undefined],
['empty', ''],
['only whitespace', ' \n'],
['only a comment', '# nothing yet\n'],
['a valid config', 'network:\n version: 1\n config:\n - type: physical\n name: eth0\n'],
])('should allow network data that is %s', (_, networkScript) => {
expect(validate({ networkScript })).toStrictEqual([]);
});
it('should report both fields when both are invalid', () => {
const errors = validate({ userScript: '#cloud-config\nsome words\n', networkScript: 'some words\n' });
expect(errors).toStrictEqual([USER_ERROR, NETWORK_ERROR]);
});
it('should save an edited VM with the cloud-init it already has', () => {
const savedCloudInit = {
userScript: '#cloud-config\n#!/bin/bash\napt-get update apt-get install -y nginx\n',
networkScript: 'some words\n',
};
const errors = validate({
...savedCloudInit, isEdit: true, savedCloudInit
});
expect(errors).toStrictEqual([]);
});
it('should check cloud-init changed while editing', () => {
const savedCloudInit = { userScript: CLOUD_CONFIG, networkScript: '' };
const errors = validate({
userScript: '#cloud-config\nsome words\n', networkScript: 'some words\n', isEdit: true, savedCloudInit
});
expect(errors).toStrictEqual([USER_ERROR, NETWORK_ERROR]);
});
it('should check cloud-init a new VM takes from a template', () => {
const savedCloudInit = { userScript: '#cloud-config\nsome words\n' };
expect(validate({ ...savedCloudInit, savedCloudInit })).toStrictEqual([USER_ERROR]);
});
});
describe('getUserData', () => {
it.each([
['a script that parses as YAML', YAML_SCRIPT],
['a Cloudbase-Init batch script', 'rem cmd\nnet user admin Passw0rd /add\n'],
['a Cloudbase-Init PowerShell script', '#ps1_sysnative\nWrite-Host done\n'],
['a cloud-config archive', '#cloud-config-archive\n- type: text/x-shellscript\n content: echo hi\n'],
])('should save %s as typed', (_, userScript) => {
expect(userDataFor(userScript)).toStrictEqual(userScript);
});
it('should add the header to cloud-config typed without one', () => {
expect(userDataFor('password: test\n')).toBe('#cloud-config\npassword: test\n');
});
});
});
+12
View File
@@ -35,6 +35,18 @@ export const SSH_EXISTING_TYPE = {
EXISTING_ONLY_CLOUD: 'EXISTING_CLOUD',
};
// Cloud-init and Cloudbase-Init run user data starting with one of these as a script, MIME or another format, not as cloud-config.
const OTHER_USER_DATA_FORMATS = [
'#!', '#include', '#cloud-boothook', '#part-handler', '#cloud-config-archive', '#cloud-config-jsonp', '## template:',
'#ps1', 'rem cmd', '<script>', '<powershell>', 'content-type:', 'mime-version:'
];
export function isCloudConfig(userScript) {
const start = (userScript || '').trimStart().toLowerCase();
return !OTHER_USER_DATA_FORMATS.some((format) => start.startsWith(format));
}
export default {
methods: {
hasCloudConfigComment(userScript) {
+86 -9
View File
@@ -2,6 +2,8 @@ import YAML from 'yaml';
import jsyaml from 'js-yaml';
import isEqual from 'lodash/isEqual';
import isEmpty from 'lodash/isEmpty';
import isNil from 'lodash/isNil';
import isPlainObject from 'lodash/isPlainObject';
import difference from 'lodash/difference';
import { sortBy } from '@shell/utils/sort';
import { set } from '@shell/utils/object';
@@ -23,9 +25,11 @@ import {
import { HCI_SETTING } from '../../config/settings';
import { HCI } from '../../types';
import { parseVolumeClaimTemplates, EMPTY_IMAGE } from '../../utils/vm';
import impl, { QGA_JSON, USB_TABLET } from './impl';
import impl, { isCloudConfig, QGA_JSON, USB_TABLET } from './impl';
import { GIBIBYTE } from '../../utils/unit';
import { VOLUME_MODE, FILESYSTEM_SOURCE_TYPE } from '@pkg/harvester/config/types';
import { VOLUME_MODE, ACCESS_MODE, FILESYSTEM_SOURCE_TYPE } from '@pkg/harvester/config/types';
const { READ_WRITE_MANY } = ACCESS_MODE;
const LONGHORN_V2_DATA_ENGINE = 'longhorn-system/v2-data-engine';
@@ -155,9 +159,12 @@ export default {
installUSBTablet: true,
networkScript: '',
userScript: '',
// The cloud-init the form loaded, so editing a VM never blocks saving it unchanged.
savedCloudInit: {},
imageId: '',
diskRows: [],
networkRows: [],
networkBootFirst: true,
filesystemRows: [],
machineType: '',
machineTypes: [],
@@ -280,13 +287,21 @@ export default {
},
customAccessMode() {
return this.storageClassSetting.accessModes || 'ReadWriteMany';
return this.storageClassSetting.accessModes || READ_WRITE_MANY;
},
isWindows() {
return this.osType === 'windows';
},
hasVirtioDisk() {
return (this.diskRows || []).some((R) => R.type === 'disk' && R.bus === 'virtio');
},
hasDedicatedIOThread() {
return (this.diskRows || []).some((R) => R.dedicatedIOThread);
},
needNewSecret() {
// When creating a template it is always necessary to create a new secret.
return this.isCreate || this.showYaml ? false : this.resourceType === HCI.VM_VERSION;
@@ -382,6 +397,7 @@ export default {
const diskRows = this.getDiskRows(vm, volumeBackups);
const networkRows = this.getNetworkRows(vm, { fromTemplate, init });
const networkBootFirst = this.isNetworkBootFirst(spec);
const hasCreateVolumes = this.getHasCreatedVolumes(spec) || [];
let { userData = undefined, networkData = undefined } = this.getCloudInitNoCloud(spec);
@@ -430,6 +446,7 @@ export default {
this['accessCredentials'] = accessCredentials;
this['userScript'] = userData;
this['networkScript'] = networkData;
this['savedCloudInit'] = { userScript: userData, networkScript: networkData };
this['sshKey'] = sshKey;
this['osType'] = osType;
@@ -459,6 +476,7 @@ export default {
this['hasCreateVolumes'] = hasCreateVolumes;
this['networkRows'] = networkRows;
this['networkBootFirst'] = networkBootFirst;
this['imageId'] = imageId;
this['diskRows'] = diskRows;
@@ -516,7 +534,7 @@ export default {
id: randomStr(5),
source: SOURCE_TYPE.IMAGE,
name: 'disk-0',
accessMode: 'ReadWriteMany', // root disk only support LHv1 volume, should be RWX
accessMode: READ_WRITE_MANY, // root disk only support LHv1 volume, should be RWX
bus,
volumeName: '',
size,
@@ -585,7 +603,7 @@ export default {
const pvcResource = allPVCs.find( (O) => O.id === `${ namespace }/${ volume?.persistentVolumeClaim?.claimName }`);
source = SOURCE_TYPE.ATTACH_VOLUME;
accessMode = pvcResource?.spec?.accessModes?.[0] || 'ReadWriteMany';
accessMode = pvcResource?.spec?.accessModes?.[0] || READ_WRITE_MANY;
size = pvcResource?.spec?.resources?.requests?.storage || '10Gi';
storageClassName = pvcResource?.spec?.storageClassName;
volumeMode = pvcResource?.spec?.volumeMode || VOLUME_MODE.BLOCK;
@@ -674,12 +692,29 @@ export default {
model: I.model,
networkName: isPod ? MANAGEMENT_NETWORK : network?.multus?.networkName,
staticIp: annotations[`${ staticIpPrefix }${ I.name }`] || '',
networkBoot: !!I.bootOrder,
};
});
return out;
},
/**
* Network boot devices are placed either before or after all volumes in the boot sequence.
* Derive which one from an existing spec, so a round trip through the form keeps it.
*/
isNetworkBootFirst(spec) {
const devices = spec?.template?.spec?.domain?.devices || {};
const nicOrders = (devices.interfaces || []).map((I) => I.bootOrder).filter(Boolean);
const diskOrders = (devices.disks || []).map((D) => D.bootOrder).filter(Boolean);
if (nicOrders.length === 0 || diskOrders.length === 0) {
return true;
}
return Math.min(...nicOrders) < Math.min(...diskOrders);
},
parseVM() {
this.userData = this.getUserData({ osType: this.osType, installAgent: this.installAgent });
this.parseOther();
@@ -892,9 +927,10 @@ export default {
const disks = [];
const volumes = [];
const volumeClaimTemplates = [];
const bootOrderOffset = this.networkBootFirst ? this.networkRows.filter((R) => R.networkBoot).length : 0;
disk.forEach( (R, index) => {
const _disk = this.parseDisk(R, index);
const _disk = this.parseDisk(R, index + bootOrderOffset);
disks.push(_disk);
@@ -1152,9 +1188,11 @@ export default {
const networks = [];
const interfaces = [];
let bootOrder = this.networkBootFirst ? 1 : this.diskRows.length + 1;
networkRow.forEach( (R) => {
const _network = this.parseNetwork(R);
const _interface = this.parseInterface(R);
const _interface = this.parseInterface(R, R.networkBoot ? bootOrder++ : undefined);
networks.push(_network);
interfaces.push(_interface);
@@ -1258,6 +1296,11 @@ export default {
* @param config
*/
getUserData(config) {
// Scripts, MIME and the other formats are saved as typed: only cloud-config gets the SSH keys, the guest agent and the header.
if (!isCloudConfig(this.userScript)) {
return this.userScript;
}
try {
// https://github.com/eemeli/yaml/issues/136
let userDataDoc = this.userScript ? YAML.parseDocument(this.userScript) : YAML.parseDocument({});
@@ -1391,8 +1434,9 @@ export default {
case SOURCE_TYPE.IMAGE: {
const image = this.images.find( (I) => R.image === I.id);
out.spec.storageClassName = R.realName ? R.storageClassName : (R.storageClassName || image?.storageClassName);
if (image) {
out.spec.storageClassName = image.storageClassName;
out.metadata.annotations = { [HCI_ANNOTATIONS.IMAGE_ID]: image.id };
} else {
out.metadata.annotations = { [HCI_ANNOTATIONS.IMAGE_ID]: '' };
@@ -1409,7 +1453,7 @@ export default {
return arr.map( (id) => this.getSSHValue(id)).filter( (O) => O !== undefined);
},
parseInterface(R) {
parseInterface(R, bootOrder) {
const _interface = {};
const type = R.type;
@@ -1419,6 +1463,10 @@ export default {
_interface.macAddress = R.macAddress;
}
if (bootOrder) {
_interface.bootOrder = bootOrder;
}
_interface.model = R.model;
_interface.name = R.name;
@@ -1445,6 +1493,30 @@ export default {
this.networkScript = value;
},
validateCloudInit() {
const isYamlMapping = (text) => {
try {
const doc = jsyaml.load(text);
return isNil(doc) || isPlainObject(doc);
} catch (e) {
return false;
}
};
// Editing only checks what changed, so a VM can still be saved with the cloud-init it already has.
const isChanged = (key) => !this.isEdit || this[key] !== this.savedCloudInit[key];
// Scripts, MIME and the other formats are valid without being YAML. Anything else is saved as cloud-config.
if (this.userScript && isChanged('userScript') && isCloudConfig(this.userScript) && !isYamlMapping(this.userScript)) {
this.errors.push(this.t('harvester.virtualMachine.cloudConfig.user.invalidYaml'));
}
if (this.networkScript && isChanged('networkScript') && !isYamlMapping(this.networkScript)) {
this.errors.push(this.t('harvester.virtualMachine.cloudConfig.network.invalidYaml'));
}
},
mergeSSHAuthorizedKeys(yaml) {
try {
const sshAuthorizedKeys = YAML.parseDocument(yaml)
@@ -1926,6 +1998,11 @@ export default {
delete merged['bridge'];
}
// boot order is owned by the form, don't inherit a stale one from the old spec
if (!iface.bootOrder) {
delete merged.bootOrder;
}
return merged;
}
@@ -0,0 +1,398 @@
import { reactive } from 'vue';
import VirtVm from '../kubevirt.io.virtualmachine';
import { POD, PVC } from '@shell/config/types';
import { HCI } from '../../types';
// The Steve base model and the shell resource class pull in most of the dashboard, none of that is needed here
jest.mock('../harvester', () => ({ __esModule: true, default: class {} }));
jest.mock('@shell/plugins/dashboard-store/resource-class', () => ({
colorForState: (state) => (state === 'Running' ? 'text-success' : 'text-info'),
stateSort: (color, display) => `${ color.replace(/^text-/, '') } ${ display }`,
}));
const VM_ID = 'ns1/vm1';
// Creates a VM model with mocked store getters. Like the real store, `all` returns the same array that is mutated in place.
// Reads from the global `$rootGetters` are recorded in `globalReads`.
function createVm({
vm = {}, vmi, pods = [], pvcs = [], restores = [], backups = [], claims = ['disk-pvc'], printableStatus
} = {}) {
const lists = reactive({
[POD]: pods,
[PVC]: pvcs,
[HCI.RESTORE]: restores,
[HCI.BACKUP]: backups,
});
const byId = { [HCI.VMI]: vmi ? [vmi] : [] };
const getters = {
all: (type) => lists[type] || [],
byId: (type, id) => (byId[type] || lists[type] || []).find((x) => x.id === id),
schemaFor: () => undefined,
};
const globalReads = [];
const rootGetters = new Proxy({ 'harvester-common/getFeatureEnabled': () => false }, {
get(target, key) {
globalReads.push(key);
return target[key];
}
});
const obj = Object.create(VirtVm.prototype);
Object.assign(obj, {
id: VM_ID,
type: HCI.VM,
metadata: {
name: 'vm1', namespace: 'ns1', annotations: {}
},
spec: {
runStrategy: 'Always',
template: {
spec: {
domain: { cpu: { cores: 1 }, resources: { limits: { memory: '1Gi' } } },
volumes: claims.map((c) => ({ name: c, persistentVolumeClaim: { claimName: c } })),
}
}
},
status: {
created: true, ready: true, printableStatus: printableStatus || 'Running', conditions: []
},
...vm,
});
Object.defineProperty(obj, '$rootGetters', { value: rootGetters });
Object.defineProperty(obj, '$getters', { value: getters });
Object.defineProperty(obj, 't', { value: (k) => k });
return {
vm: obj, lists, globalReads
};
}
const readyVmi = (extra = {}) => ({
id: VM_ID,
metadata: { name: 'vm1', namespace: 'ns1' },
status: {
phase: 'Running',
conditions: [{ type: 'Ready', status: 'True' }],
...extra
}
});
const pvc = (name, encrypted, ns = 'ns1') => ({
id: `${ ns }/${ name }`,
metadata: { name, namespace: ns },
isEncrypted: encrypted,
});
describe('class VirtVm', () => {
describe('restoreResource', () => {
it('should distinguish snapshots from backups and follow backup updates', () => {
const { vm, lists } = createVm({
vm: {
metadata: {
namespace: 'ns1', name: 'vm1', annotations: { 'restore.harvesterhci.io/name': 'r1' }
}
},
restores: [{
id: 'ns1/r1', isComplete: false, spec: { virtualMachineBackupNamespace: 'ns1', virtualMachineBackupName: 'b1' }
}],
backups: [
{ id: 'ns2/b1', spec: { type: 'snapshot' } },
{ id: 'ns1/b1', spec: { type: 'backup' } },
],
});
expect(vm.restoreResource.fromSnapshot).toBe(false);
expect(vm.restoreState).toBe(false);
lists[HCI.BACKUP][1].spec.type = 'snapshot';
expect(vm.restoreResource.fromSnapshot).toBe(true);
lists[HCI.BACKUP].splice(1, 1);
expect(vm.restoreResource.fromSnapshot).toBe(false);
lists[HCI.RESTORE][0].isComplete = true;
expect(vm.restoreState).toBe(true);
});
});
describe('encryptedVolumeType', () => {
it('should be none without volumes', () => {
const { vm } = createVm({ claims: [] });
expect(vm.encryptedVolumeType).toBe('none');
});
it('should be none if no PVC is encrypted', () => {
const { vm } = createVm({ pvcs: [pvc('disk-pvc', false)] });
expect(vm.encryptedVolumeType).toBe('none');
});
it('should be all if every PVC is encrypted', () => {
const { vm } = createVm({
claims: ['a', 'b'],
pvcs: [pvc('a', true), pvc('b', true), pvc('other', false)]
});
expect(vm.encryptedVolumeType).toBe('all');
});
it('should be partial if some PVCs are encrypted', () => {
const { vm } = createVm({
claims: ['a', 'b'],
pvcs: [pvc('a', true), pvc('b', false)]
});
expect(vm.encryptedVolumeType).toBe('partial');
});
it('should follow PVCs that are added to the store later', () => {
const { vm, lists } = createVm({ claims: ['a'], pvcs: [] });
expect(vm.encryptedVolumeType).toBe('none');
lists[PVC].push(pvc('a', true));
expect(vm.encryptedVolumeType).toBe('all');
});
});
describe('actualState', () => {
it('should be Off if the VM is halted', () => {
const { vm } = createVm({
vm: {
spec: { runStrategy: 'Halted', template: { spec: { volumes: [], domain: {} } } },
status: { created: false, conditions: [] }
}
});
expect(vm.actualState).toBe('Off');
});
it('should be Running if the VMI is running and ready', () => {
const { vm } = createVm({ vmi: readyVmi() });
expect(vm.actualState).toBe('Running');
});
it('should be Not Ready if the VMI is running but not ready', () => {
const { vm } = createVm({ vmi: readyVmi({ conditions: [{ type: 'Ready', status: 'False' }] }) });
expect(vm.actualState).toBe('Not Ready');
});
it('should be Paused if the VMI has the Paused condition', () => {
const { vm } = createVm({ vmi: readyVmi({ conditions: [{ type: 'Ready', status: 'True' }, { type: 'Paused', status: 'True' }] }) });
expect(vm.actualState).toBe('Paused');
});
it('should be Stopping if the VM is not expected to run anymore but the VMI exists', () => {
const { vm } = createVm({
vm: { spec: { runStrategy: 'Halted', template: { spec: { volumes: [], domain: {} } } } },
vmi: readyVmi()
});
expect(vm.actualState).toBe('Stopping');
});
it('should be Starting while the launcher pod is not ready', () => {
const { vm } = createVm({
vmi: readyVmi({ phase: 'Scheduling', conditions: [] }),
pods: [{
metadata: { namespace: 'ns1', ownerReferences: [{ name: 'vm1' }] },
getPodStatus: { status: 'POD_NOT_SCHEDULABLE' }
}]
});
expect(vm.actualState).toBe('Starting');
});
it('should be Unschedulable if the VM is starting and has an unschedulable condition', () => {
const { vm } = createVm({
vmi: readyVmi({ phase: 'Pending', conditions: [] }),
vm: { status: { created: true, conditions: [{ reason: 'Unschedulable', message: 'no node' }] } }
});
expect(vm.actualState).toBe('Unschedulable');
expect(vm.isUnschedulable.message).toBe('no node');
});
it('should not be Unschedulable without an unschedulable condition', () => {
const { vm } = createVm({ vmi: readyVmi() });
expect(vm.isUnschedulable).toBeNull();
expect(vm.actualState).toBe('Running');
});
it('should not be Unschedulable if the VM is neither starting nor stopping', () => {
const { vm } = createVm({
vm: {
spec: { runStrategy: 'Halted', template: { spec: { volumes: [], domain: {} } } },
status: { created: false, conditions: [{ reason: 'Unschedulable' }] }
}
});
expect(vm.isUnschedulable).toBeNull();
expect(vm.actualState).toBe('Off');
});
it('should be Terminating if the VM is being deleted', () => {
const { vm } = createVm({
vmi: readyVmi(),
vm: {
metadata: {
name: 'vm1', namespace: 'ns1', annotations: {}, deletionTimestamp: 'now'
}
}
});
expect(vm.actualState).toBe('Terminating');
});
it('should be VM error if the VM has a failure condition', () => {
const { vm } = createVm({ vm: { status: { created: true, conditions: [{ type: 'Failure', message: 'boom' }] } } });
expect(vm.actualState).toBe('VM error');
});
it('should be Restoring while a restore is in progress', () => {
const { vm } = createVm({
vmi: readyVmi(),
vm: {
metadata: {
name: 'vm1', namespace: 'ns1', annotations: { 'restore.harvesterhci.io/name': 'r1' }
}
},
restores: [{ id: 'ns1/r1', isComplete: false }]
});
expect(vm.actualState).toBe('Restoring');
});
it('should not be Restoring if the restore of the annotation does not exist', () => {
const { vm } = createVm({
vmi: readyVmi(),
vm: {
metadata: {
name: 'vm1', namespace: 'ns1', annotations: { 'restore.harvesterhci.io/name': 'other' }
}
},
restores: [{ id: 'ns1/r1', isComplete: false }]
});
expect(vm.actualState).toBe('Running');
});
});
describe('stateSort', () => {
it('should be built from the same state as stateDisplay and stateColor', () => {
const { vm } = createVm({ vmi: readyVmi() });
expect(vm.stateSort).toBe(`${ vm.stateColor.replace(/^text-/, '') } ${ vm.stateDisplay }`);
});
it('should evaluate the state only once', () => {
const { vm } = createVm({ vmi: readyVmi() });
const spy = jest.spyOn(vm, 'actualState', 'get');
expect(vm.stateSort).toBe('success Running');
expect(spy).toHaveBeenCalledTimes(1);
spy.mockRestore();
});
});
describe('podResource', () => {
it('should find the launcher pod by owner name', () => {
const pod = { metadata: { namespace: 'ns1', ownerReferences: [{ name: 'vm1' }] } };
const { vm } = createVm({ vmi: readyVmi(), pods: [pod] });
expect(vm.podResource).toStrictEqual(pod);
});
it('should return the last pod if several pods have the same owner', () => {
// e.g. the source and the target pod while the VM migrates
const source = {
metadata: {
name: 'launcher-source', namespace: 'ns1', ownerReferences: [{ name: 'vm1' }]
}
};
const target = {
metadata: {
name: 'launcher-target', namespace: 'ns1', ownerReferences: [{ name: 'vm1' }]
}
};
const { vm } = createVm({ vmi: readyVmi(), pods: [source, target] });
expect(vm.podResource.metadata.name).toBe('launcher-target');
});
it('should find pods that are added to the store later', () => {
const { vm, lists } = createVm({ vmi: readyVmi(), pods: [] });
expect(vm.podResource).toBeUndefined();
const pod = { metadata: { namespace: 'ns1', ownerReferences: [{ name: 'vm1' }] } };
lists[POD].push(pod);
expect(vm.podResource).toStrictEqual(pod);
});
it('should not return a pod of a VM with the same name in another namespace', () => {
const other = { metadata: { namespace: 'ns2', ownerReferences: [{ name: 'vm1' }] } };
const mine = { metadata: { namespace: 'ns1', ownerReferences: [{ name: 'vm1' }] } };
const { vm } = createVm({ vmi: readyVmi(), pods: [mine, other] });
expect(vm.podResource).toStrictEqual(mine);
});
it('should not return pods that were removed from the store', () => {
const pod = { metadata: { namespace: 'ns1', ownerReferences: [{ name: 'vm1' }] } };
const { vm, lists } = createVm({ vmi: readyVmi(), pods: [pod] });
expect(vm.podResource).toStrictEqual(pod);
lists[POD].splice(0, 1);
expect(vm.podResource).toBeUndefined();
});
});
describe('store', () => {
it('should read the data of the VM from the store the VM lives in, not from a fixed one', () => {
// The VM model is used with the `harvester` store (Harvester product) and the `cluster` store (Rancher explorer)
const pod = { metadata: { namespace: 'ns1', ownerReferences: [{ name: 'vm1' }] } };
const { vm, globalReads } = createVm({
vmi: readyVmi(),
pods: [pod],
pvcs: [pvc('disk-pvc', false)],
restores: [{ id: 'ns1/r1', isComplete: true }],
vm: {
metadata: {
name: 'vm1', namespace: 'ns1', annotations: { 'restore.harvesterhci.io/name': 'r1' }
}
},
});
expect(vm.vmi.id).toBe(VM_ID);
expect(vm.podResource).toStrictEqual(pod);
expect(vm.volumes).toHaveLength(1);
expect(vm.restoreResource.id).toBe('ns1/r1');
expect(vm.actualState).toBe('Running');
expect(globalReads.filter((key) => /^(harvester|cluster)\//.test(key))).toStrictEqual([]);
});
});
describe('isRestartRequired', () => {
it('should reflect the RestartRequired condition', () => {
const { vm } = createVm({ vm: { status: { conditions: [{ type: 'RestartRequired', status: 'True' }] } } });
expect(vm.isRestartRequired).toBe(true);
});
});
});
@@ -0,0 +1,95 @@
import { reactive } from 'vue';
import VirtVmInstance from '../kubevirt.io.virtualmachineinstance';
import { HCI } from '../../types';
import { HCI as HCI_ANNOTATIONS } from '../../config/labels-annotations';
jest.mock('../harvester', () => ({ __esModule: true, default: class {} }));
jest.mock('@shell/plugins/dashboard-store/resource-class', () => ({ colorForState: () => 'text-info' }));
function migration(namespace, timestamp, phase = 'Running') {
return {
metadata: { namespace, creationTimestamp: timestamp },
spec: { vmiName: 'vm1' },
status: { phase },
};
}
function createVmi(migrations) {
const list = reactive(migrations);
const vmi = Object.create(VirtVmInstance.prototype);
Object.assign(vmi, {
metadata: {
namespace: 'ns1',
name: 'vm1',
annotations: { [HCI_ANNOTATIONS.MIGRATION_STATE]: 'Migrating' },
},
$getters: { all: (type) => type === HCI.VMIM ? list : [] },
});
return { vmi, list };
}
describe('class VirtVmInstance', () => {
it('should select the newest migration in the VMI namespace regardless of list order', () => {
const { vmi } = createVmi([
migration('ns1', '2026-01-03T00:00:00Z'),
migration('ns2', '2026-01-04T00:00:00Z', 'Failed'),
migration('ns1', '2026-01-01T00:00:00Z', 'Failed'),
]);
expect(vmi.vmimResource.metadata.creationTimestamp).toBe('2026-01-03T00:00:00Z');
expect(vmi.migrationState.status).toBe('Migrating');
});
it('should follow additions, timestamp changes, phase changes and removals in the same list', () => {
const { vmi, list } = createVmi([]);
expect(vmi.vmimResource).toStrictEqual([]);
expect(vmi.migrationState).toBeNull();
list.push(migration('ns1', '2026-01-01T00:00:00Z'));
expect(vmi.migrationState.status).toBe('Migrating');
list.push(migration('ns1', '2026-01-02T00:00:00Z', 'Failed'));
expect(vmi.migrationState.status).toBe('Failed');
list[0].metadata.creationTimestamp = '2026-01-03T00:00:00Z';
expect(vmi.vmimResource).toBe(list[0]);
expect(vmi.migrationState.status).toBe('Migrating');
list[0].status.phase = 'Failed';
expect(vmi.migrationState.status).toBe('Failed');
list.splice(0, 2);
expect(vmi.migrationState).toBeNull();
});
it('should follow a migration reassigned to another VMI or namespace', () => {
const { vmi, list } = createVmi([migration('ns1', '2026-01-01T00:00:00Z')]);
expect(vmi.migrationState.status).toBe('Migrating');
list[0].spec.vmiName = 'vm2';
expect(vmi.migrationState).toBeNull();
list[0].spec.vmiName = 'vm1';
list[0].metadata.namespace = 'ns2';
expect(vmi.migrationState).toBeNull();
});
it('should invalidate the index when the store replaces properties on an existing migration', () => {
const { vmi, list } = createVmi([migration('ns1', '2026-01-01T00:00:00Z')]);
expect(vmi.migrationState.status).toBe('Migrating');
const existing = list[0];
for (const key of Object.keys(existing)) {
delete existing[key];
}
Object.assign(existing, migration('ns2', '2026-01-02T00:00:00Z', 'Failed'));
expect(vmi.migrationState).toBeNull();
});
});
+66 -8
View File
@@ -23,6 +23,13 @@ const ALLOW_SYSTEM_LABEL_KEYS = [
const HEALTHY = 'healthy';
const WARNING = 'warning';
const MAINTENANCE_MODE = 'MaintenanceMode';
const MAINTENANCE_ERROR = 'Error';
const MAINTENANCE_ENTERING_REASONS = ['Validating', 'Draining', 'Evacuating'];
const MAINTENANCE_COMPLETED = 'Completed';
// Legacy `harvesterhci.io/maintain-status` annotation values (clusters < v1.10)
const LEGACY_MAINTENANCE_RUNNING = 'running';
const LEGACY_MAINTENANCE_COMPLETED = 'completed';
export default class HciNode extends HarvesterResource {
get _availableActions() {
@@ -58,6 +65,14 @@ export default class HciNode extends HarvesterResource {
total: 1
};
const clearMaintenance = {
action: 'clearMaintenanceMode',
enabled: this.hasAction('clearMaintenanceMode'),
icon: 'icon icon-fw icon-close',
label: this.t('harvester.action.clearMaintenance'),
total: 1
};
const enableCPUManager = {
action: 'enableCPUManager',
enabled: this.cpuPinningFeatureEnabled && this.hasAction('enableCPUManager') && !this.isCPUManagerEnableInProgress && !this.isCPUManagerEnabled && !this.isEtcd, // witness node doesn't have CPU manager
@@ -103,6 +118,7 @@ export default class HciNode extends HarvesterResource {
uncordon,
enableMaintenance,
disableMaintenance,
clearMaintenance,
enableCPUManager,
disableCPUManager,
shutDown,
@@ -198,6 +214,10 @@ export default class HciNode extends HarvesterResource {
}
get stateDisplay() {
if (this.isMaintenanceModeError) {
return super.stateDisplay;
}
if (this.isEnteringMaintenance) {
return 'Entering maintenance mode';
}
@@ -246,6 +266,10 @@ export default class HciNode extends HarvesterResource {
}
get stateDescription() {
if (this.isMaintenanceModeError) {
return super.stateDescription;
}
const currentIP = this.metadata?.annotations?.[HCI_ANNOTATIONS.CURRENT_IP];
const initIP = this.metadata?.annotations?.[HCI_ANNOTATIONS.INIT_IP];
@@ -325,7 +349,11 @@ export default class HciNode extends HarvesterResource {
}
disableMaintenanceMode() {
this.doAction('disableMaintenanceMode', {});
this.doActionGrowl('disableMaintenanceMode', {});
}
clearMaintenanceMode() {
this.doActionGrowl('clearMaintenanceMode', {});
}
enableCPUManager() {
@@ -343,11 +371,32 @@ export default class HciNode extends HarvesterResource {
);
}
get maintenanceModeCondition() {
return (this.status?.conditions || []).find(
(c) => c.type === MAINTENANCE_MODE
);
}
get maintenanceModeConditionsEnabled() {
return this.$rootGetters['harvester-common/getFeatureEnabled']('maintenanceModeConditions');
}
// Clusters < v1.10 only expose the `harvesterhci.io/maintain-status` annotation
get legacyMaintenanceStatus() {
return this.metadata?.annotations?.[HCI_ANNOTATIONS.MAINTENANCE_STATUS];
}
get isMaintenanceModeError() {
return this.maintenanceModeConditionsEnabled && this.maintenanceModeCondition?.reason === MAINTENANCE_ERROR;
}
get isMigratable() {
const states = ['in-progress', 'unavailable'];
const engaged = this.maintenanceModeConditionsEnabled ? this.maintenanceModeCondition?.status === 'True' : !!this.legacyMaintenanceStatus;
return (
!this.metadata?.annotations?.[HCI_ANNOTATIONS.MAINTENANCE_STATUS] &&
!engaged &&
!this.isUnSchedulable &&
!states.includes(this.state)
);
@@ -362,17 +411,26 @@ export default class HciNode extends HarvesterResource {
}
get isEnteringMaintenance() {
if (!this.maintenanceModeConditionsEnabled) {
return this.legacyMaintenanceStatus === LEGACY_MAINTENANCE_RUNNING;
}
const cond = this.maintenanceModeCondition;
return (
this.metadata?.annotations?.[HCI_ANNOTATIONS.MAINTENANCE_STATUS] ===
'running'
cond?.status === 'True' &&
MAINTENANCE_ENTERING_REASONS.includes(cond?.reason)
);
}
get isMaintenance() {
return (
this.metadata?.annotations?.[HCI_ANNOTATIONS.MAINTENANCE_STATUS] ===
'completed'
);
if (!this.maintenanceModeConditionsEnabled) {
return this.legacyMaintenanceStatus === LEGACY_MAINTENANCE_COMPLETED;
}
const cond = this.maintenanceModeCondition;
return cond?.status === 'True' && cond?.reason === MAINTENANCE_COMPLETED;
}
get cpuPinningFeatureEnabled() {
@@ -326,7 +326,7 @@ export default class HciPv extends HarvesterResource {
}
get relatedPV() {
return this.$rootGetters['harvester/all'](PV).find((pv) => pv.metadata?.name === this.spec?.volumeName);
return this.$rootGetters['harvester/byId'](PV, this.spec?.volumeName);
}
get volumeProvider() {
@@ -1,7 +1,7 @@
import { load } from 'js-yaml';
import { omitBy, pickBy } from 'lodash';
import { PRODUCT_NAME as HARVESTER_PRODUCT } from '../config/harvester';
import { colorForState } from '@shell/plugins/dashboard-store/resource-class';
import { colorForState, stateSort } from '@shell/plugins/dashboard-store/resource-class';
import { POD, NODE, PVC } from '@shell/config/types';
import { findBy } from '@shell/utils/array';
import { parseSi } from '@shell/utils/units';
@@ -14,6 +14,7 @@ import { BACKUP_TYPE } from '../config/types';
import { HCI } from '../types';
import HarvesterResource from './harvester';
import { getVmCPUMemoryValues } from '../utils/cpuMemory';
import { sharedComputed } from '../utils/shared-computed';
import { isBackupTargetSettingUnavailable } from '../utils/setting';
export const OFF = 'Off';
@@ -81,42 +82,48 @@ const VMIPhase = {
Unknown: 'Unknown'
};
let productInStore;
// Index of the pods (namespace/ownerName -> pod), shared by all rows. `podList` must be the store list, not a copy.
// If several pods have the same owner (e.g. while a VM migrates), the last one wins.
function getPodOwnerIndex(podList) {
return sharedComputed(podList, 'podOwnerIndex', (pods) => {
const map = new Map(); // namespace/ownerName -> pod
let _podOwnerMap = null;
let _podOwnerMapSource = null;
for (const pod of pods) {
const refName = pod.metadata?.ownerReferences?.[0]?.name;
function getPodByOwnerName(rootGetters, inStore, ownerName) {
const podList = rootGetters[`${ inStore }/all`](POD);
if (refName) {
map.set(`${ pod.metadata.namespace }/${ refName }`, pod);
}
}
return map;
});
}
// `getters` are the getters of the store of the VM (`this.$getters`)
function getPodByOwnerName(getters, namespace, ownerName) {
const podList = getters['all'](POD);
if (!Array.isArray(podList)) {
return undefined;
}
// if not equals (usually means the pod list has been updated), we need to rebuild the map, otherwise we can reuse the map for better performance
if (_podOwnerMapSource !== podList) {
_podOwnerMap = new Map(); // use Map to store ownerReference name and pod mapping
for (const pod of podList) {
const refName = pod.metadata?.ownerReferences?.[0]?.name;
if (refName) {
_podOwnerMap.set(refName, pod);
}
}
_podOwnerMapSource = podList;
}
return _podOwnerMap.get(ownerName);
return getPodOwnerIndex(podList).get(`${ namespace }/${ ownerName }`);
}
function getPvcsByNames(rootGetters, inStore, names) {
const pvcList = rootGetters[`${ inStore }/all`](PVC);
// A VM only uses PVCs of its own namespace, so look them up by id instead of scanning all PVCs
function getPvcsByNames(getters, namespace, names) {
const out = [];
if (!Array.isArray(pvcList)) {
return [];
for (const name of new Set(names)) {
const pvc = getters['byId'](PVC, `${ namespace }/${ name }`);
if (pvc) {
out.push(pvc);
}
}
const uniqueNames = new Set(names);
return pvcList.filter((pvc) => uniqueNames.has(pvc.metadata?.name));
return out;
}
const IgnoreMessages = ['pod has unbound immediate PersistentVolumeClaims'];
@@ -135,7 +142,8 @@ export default class VirtVm extends HarvesterResource {
clone.action = 'goToCloneVM';
}
const canCreateVMSSchedule = !!this.$getters?.['schemaFor']?.(HCI.SCHEDULE_VM_BACKUP)?.collectionMethods?.find((x) => ['post'].includes(x.toLowerCase()));
const scheduleSchema = this.$getters?.['schemaFor']?.(HCI.SCHEDULE_VM_BACKUP);
const canCreateVMSSchedule = !!scheduleSchema && sharedComputed(scheduleSchema, 'canPost', (schema) => !!schema.collectionMethods?.find((x) => ['post'].includes(x.toLowerCase())));
return [
{
@@ -288,14 +296,6 @@ export default class VirtVm extends HarvesterResource {
];
}
get productInStore() {
if (!productInStore) {
productInStore = this.$rootGetters['currentProduct'].inStore;
}
return productInStore;
}
applyDefaults(resources = this, realMode) {
const spec = {
runStrategy: 'RerunOnFailure',
@@ -729,14 +729,13 @@ export default class VirtVm extends HarvesterResource {
}
get podResource() {
const inStore = this.productInStore;
const vmiResource = this.$rootGetters[`${ inStore }/byId`](HCI.VMI, this.id);
const vmiResource = this.$getters['byId'](HCI.VMI, this.id);
if (!vmiResource?.metadata?.name) {
return undefined;
}
return getPodByOwnerName(this.$rootGetters, inStore, vmiResource.metadata.name);
return getPodByOwnerName(this.$getters, vmiResource.metadata.namespace, vmiResource.metadata.name);
}
get isPaused() {
@@ -764,8 +763,7 @@ export default class VirtVm extends HarvesterResource {
}
get nsResourceQuota() {
const inStore = this.productInStore;
const allResQuotas = this.$rootGetters[`${ inStore }/all`](HCI.RESOURCE_QUOTA);
const allResQuotas = this.$getters['all'](HCI.RESOURCE_QUOTA);
return allResQuotas.find( (RQ) => RQ.namespace === this.metadata.namespace);
}
@@ -775,15 +773,13 @@ export default class VirtVm extends HarvesterResource {
}
get vmi() {
const inStore = this.productInStore;
return this.$rootGetters[`${ inStore }/byId`](HCI.VMI, this.id);
return this.$getters['byId'](HCI.VMI, this.id);
}
get volumes() {
const volumeClaimNames = this.spec.template.spec.volumes?.map((v) => v.persistentVolumeClaim?.claimName).filter((v) => !!v) || [];
return getPvcsByNames(this.$rootGetters, this.productInStore, volumeClaimNames);
return getPvcsByNames(this.$getters, this.metadata.namespace, volumeClaimNames);
}
get lvmVolumes() {
@@ -807,13 +803,15 @@ export default class VirtVm extends HarvesterResource {
}
get encryptedVolumeType() {
if (!this.volumes || this.volumes.length === 0) {
const volumes = this.volumes;
if (!volumes || volumes.length === 0) {
return 'none';
}
if (this.volumes.every((vol) => vol.isEncrypted)) {
if (volumes.every((vol) => vol.isEncrypted)) {
return 'all';
} else if (this.volumes.some((vol) => vol.isEncrypted)) {
} else if (volumes.some((vol) => vol.isEncrypted)) {
return 'partial';
} else {
return 'none';
@@ -918,15 +916,14 @@ export default class VirtVm extends HarvesterResource {
}
get isUnschedulable() {
if (this.isStopping || this.isStarting) {
const condition = this.status?.conditions?.find((c) => c.reason === UNSCHEDULABLE);
// Check the cheap condition first
const condition = this.status?.conditions?.find((c) => c.reason === UNSCHEDULABLE);
if (!!condition) {
return {
status: UNSCHEDULABLE,
message: condition.message || 'VM is unschedulable',
};
}
if (condition && (this.isStopping || this.isStarting)) {
return {
status: UNSCHEDULABLE,
message: condition.message || 'VM is unschedulable',
};
}
return null;
@@ -971,16 +968,14 @@ export default class VirtVm extends HarvesterResource {
`metadata.annotations."${ HCI_ANNOTATIONS.RESTORE_NAME }"`
) }`;
const inStore = this.productInStore;
const res = this.$rootGetters[`${ inStore }/byId`](HCI.RESTORE, id);
const res = this.$getters['byId'](HCI.RESTORE, id);
if (res) {
const allBackups = this.$rootGetters[`${ inStore }/all`](HCI.BACKUP);
const backupId = `${ res.spec?.virtualMachineBackupNamespace }/${ res.spec?.virtualMachineBackupName }`;
const backup = this.$getters['byId'](HCI.BACKUP, backupId);
res.fromSnapshot = !!allBackups
.filter((b) => b.spec?.type !== BACKUP_TYPE.BACKUP)
.find((s) => s.id === `${ res.spec?.virtualMachineBackupNamespace }/${ res.spec?.virtualMachineBackupName }`);
// Snapshots and backups are told apart by spec.type
res.fromSnapshot = !!backup && backup.spec?.type !== BACKUP_TYPE.BACKUP;
}
return res;
@@ -1005,11 +1000,13 @@ export default class VirtVm extends HarvesterResource {
}
get restoreState() {
if (!this.restoreResource) {
const restore = this.restoreResource;
if (!restore) {
return true;
}
return this.restoreResource?.isComplete;
return restore.isComplete;
}
get actualState() {
@@ -1110,6 +1107,13 @@ export default class VirtVm extends HarvesterResource {
return colorForState(state);
}
// Evaluate actualState once, the base implementation does it in stateColor and stateDisplay
get stateSort() {
const state = this.actualState;
return stateSort(colorForState(state), state);
}
get networkIps() {
let networkData = '';
const out = [];
@@ -1160,7 +1164,6 @@ export default class VirtVm extends HarvesterResource {
get rootImageId() {
let imageId = '';
const inStore = this.productInStore;
const volumes = this.spec.template.spec.volumes || [];
@@ -1170,7 +1173,7 @@ export default class VirtVm extends HarvesterResource {
});
if (!isNoExistingVolume) {
const existingVolume = this.$rootGetters[`${ inStore }/byId`](PVC, `${ this.metadata.namespace }/${ firstVolumeName }`);
const existingVolume = this.$getters['byId'](PVC, `${ this.metadata.namespace }/${ firstVolumeName }`);
if (existingVolume) {
return existingVolume?.metadata?.annotations?.[
@@ -1366,7 +1369,12 @@ export default class VirtVm extends HarvesterResource {
get isBackupTargetUnavailable() {
const backupTargetSetting = this.$rootGetters['harvester/byId'](HCI.SETTING, 'backup-target');
return isBackupTargetSettingUnavailable(backupTargetSetting);
// sharedComputed needs an object as key
if (!backupTargetSetting) {
return isBackupTargetSettingUnavailable(backupTargetSetting);
}
return sharedComputed(backupTargetSetting, 'unavailable', isBackupTargetSettingUnavailable);
}
setInstanceLabels(val) {
@@ -1,6 +1,7 @@
import { colorForState } from '@shell/plugins/dashboard-store/resource-class';
import { NODE } from '@shell/config/types';
import { HCI as HCI_ANNOTATIONS } from '@pkg/harvester/config/labels-annotations';
import { getLatestMigration } from '@pkg/utils/vm';
import { HCI } from '../types';
import HarvesterResource from './harvester';
@@ -45,32 +46,25 @@ export default class VirtVmInstance extends HarvesterResource {
return colorForState(state);
}
// The newest migration of this VMI, an empty array if there is none
get vmimResource() {
const all = this.$rootGetters['harvester/all'](HCI.VMIM) || [];
const vmimList = all.filter((vmim) => vmim.spec?.vmiName === this.metadata?.name);
const all = this.$getters['all'](HCI.VMIM) || [];
if (vmimList.length === 0) {
return [];
}
vmimList.sort((a, b) => {
return a?.metadata?.creationTimestamp > b?.metadata?.creationTimestamp ? -1 : 1;
});
return vmimList[0];
return getLatestMigration(all, this.metadata?.namespace, this.metadata?.name) || [];
}
get migrationState() {
const state = this.metadata?.annotations?.[HCI_ANNOTATIONS.MIGRATION_STATE];
const migration = this.vmimResource;
if (this.vmimResource?.status?.phase === VMIPhase.Failed) {
if (migration?.status?.phase === VMIPhase.Failed) {
return {
type: 'migration',
status: VMIPhase.Failed
};
}
if (this.vmimResource?.status?.phase && state) {
if (migration?.status?.phase && state) {
return {
type: 'migration',
status: state
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "harvester",
"description": "Rancher UI Extension for Harvester",
"version": "1.9.1-rc5",
"version": "1.10.0-dev",
"private": false,
"rancher": {
"annotations": {
@@ -232,6 +232,7 @@ export default {
this.imageValue.spec.targetStorageClassName = 'longhorn-static';
res = await this.imageValue.save();
res.notifyGeneratedName?.();
this.value.spec.image = res.id;
}
@@ -253,6 +254,7 @@ export default {
this.value.metadata.annotations = { [HCI_ANNOTATIONS.SKIP_SINGLE_REPLICA_DETACHED_VOL]: JSON.stringify(this.skipSingleReplicaDetachedVol) };
}
await this.value.save();
this.value.notifyGeneratedName?.();
this.done();
buttonCb(true);
} catch (e) {
@@ -290,6 +292,7 @@ export default {
const res = await this.imageValue.save();
res.notifyGeneratedName?.();
this.uploadImageId = res.id;
this.uploadController = new AbortController();
@@ -210,7 +210,8 @@ export default {
<FileSelector
:byte-limit="20000"
:read-as-data-url="true"
class="role-secondary"
variant="secondary"
size="large"
:label="t('branding.logos.uploadLight')"
:mode="mode"
@error="setError"
@@ -233,7 +234,8 @@ export default {
<FileSelector
:byte-limit="20000"
:read-as-data-url="true"
class="role-secondary"
variant="secondary"
size="large"
:label="t('branding.logos.uploadDark')"
:mode="mode"
@error="setError"
@@ -274,7 +276,8 @@ export default {
<FileSelector
:byte-limit="20000"
:read-as-data-url="true"
class="role-secondary"
variant="secondary"
size="large"
:label="t('branding.favicon.upload')"
:mode="mode"
@error="setError"
@@ -1,10 +1,18 @@
<script>
import { defineAsyncComponent } from 'vue';
import Loading from '@shell/components/Loading';
import TabTitle from '@shell/components/TabTitle';
import { HCI } from '../../../../../types';
import NovncConsoleWrapper from '../../../../../components/novnc/NovncConsoleWrapper.vue';
export default {
components: { NovncConsoleWrapper, Loading },
components: {
NovncConsoleWrapper: defineAsyncComponent({
loader: () => import('../../../../../components/novnc/NovncConsoleWrapper.vue'),
loadingComponent: Loading,
}),
Loading,
TabTitle
},
async fetch() {
this.rows = await this.$store.dispatch('harvester/findAll', { type: HCI.VMI });
@@ -28,17 +36,21 @@ export default {
mounted() {
window.addEventListener('beforeunload', () => {
this.$refs.console.close();
this.$refs.console?.close();
});
},
head() {
return { title: this.vmi?.metadata?.name };
},
};
</script>
<template>
<TabTitle
v-if="vmi?.metadata?.name"
:breadcrumb="false"
:show-child="false"
>
{{ vmi.metadata.name }}
</TabTitle>
<Loading v-if="$fetchState.pending" />
<NovncConsoleWrapper
v-else
@@ -12,6 +12,7 @@ import { PRODUCT_NAME } from '@pkg/harvester/config/harvester';
import { currentRouter, currentRoute } from '@pkg/harvester/utils/router';
import { decodeSecretValue } from '@pkg/harvester/utils/forklift';
import { HCI } from '@pkg/harvester/types';
import { preventImplicitSubmit } from '@pkg/harvester/utils/wizard';
const store = useStore();
const route = currentRoute();
@@ -258,6 +259,7 @@ init();
:title="wizardTitle"
finish-mode="finish"
class="wizard"
@keydown.enter.capture="preventImplicitSubmit"
@cancel="onCancel"
@finish="onFinish"
>
@@ -10,6 +10,7 @@ import ReviewMigrationStep from '@pkg/harvester/components/vm-migration/ReviewMi
import { PRODUCT_NAME } from '@pkg/harvester/config/harvester';
import { currentRouter } from '@pkg/harvester/utils/router';
import { exceptionToErrorsArray, stringify } from '@shell/utils/error';
import { preventImplicitSubmit } from '@pkg/harvester/utils/wizard';
const store = useStore();
const { t } = useI18n(store);
@@ -269,6 +270,7 @@ const onCancel = () => {
finish-mode="finish"
finish-button-mode="createAndStart"
class="wizard"
@keydown.enter.capture="preventImplicitSubmit"
@cancel="onCancel"
@finish="onFinish"
>
@@ -0,0 +1,49 @@
import { mount, flushPromises } from '@vue/test-utils';
import Banner from '@components/Banner/Banner.vue';
import PromptRemoveIgnoreRule from '../health.harvesterhci.io.healthignorerule.vue';
function ruleOf(checkKey, remove = () => {}) {
return { spec: { componentHealth: 'h', checkKey }, remove: jest.fn(remove) };
}
function mountPrompt(value) {
const close = jest.fn();
const prompt = mount(PromptRemoveIgnoreRule, {
props: { value, close },
global: { mocks: { $store: { getters: { 'i18n/t': (key) => key } } } },
});
return { prompt, close };
}
describe('promptRemove: health.harvesterhci.io.healthignorerule', () => {
it('names the check the rule is for, not the rule', () => {
const { prompt } = mountPrompt([ruleOf('ImageRetryLimitExceeded')]);
expect(prompt.find('b').text()).toBe('ImageRetryLimitExceeded');
});
it('deletes the rule and closes', async() => {
const rule = ruleOf('a');
const { prompt, close } = mountPrompt([rule]);
const buttonDone = jest.fn();
await prompt.vm.remove(buttonDone);
expect(rule.remove).toHaveBeenCalledTimes(1);
expect(close).toHaveBeenCalledWith(buttonDone);
expect(buttonDone).not.toHaveBeenCalled();
});
it('shows why the rule could not be deleted and stays open', async() => {
const { prompt, close } = mountPrompt([ruleOf('a', () => Promise.reject(new Error('forbidden')))]);
const buttonDone = jest.fn();
await prompt.vm.remove(buttonDone);
await flushPromises();
expect(prompt.findComponent(Banner).text()).toContain('forbidden');
expect(close).not.toHaveBeenCalled();
expect(buttonDone).toHaveBeenCalledWith(false);
});
});
@@ -0,0 +1,119 @@
import { mount } from '@vue/test-utils';
import PromptRemoveVm from '../kubevirt.io.virtualmachine.vue';
import { HCI } from '../../types';
function createVm(name, disks) {
return {
id: `default/${ name }`,
type: HCI.VM,
links: { self: `https://harvester/v1/harvester/kubevirt.io.virtualmachines/default/${ name }` },
spec: {
template: {
spec: {
volumes: [
...disks.map((disk) => ({ name: disk, persistentVolumeClaim: { claimName: `${ name }-${ disk }` } })),
{ name: 'cloudinitdisk', cloudInitNoCloud: {} },
],
},
},
},
remove: jest.fn(),
};
}
function mountPrompt(value) {
return mount(PromptRemoveVm, {
props: {
value,
names: value.map((vm) => vm.id),
type: 'Virtual Machine',
close: jest.fn(),
},
global: { mocks: { $store: { getters: { 'i18n/t': (key) => key }, commit: jest.fn() } } },
});
}
// Toggles the checkbox like a click does: flips `checked` and fires `change`
function click(input) {
return input.setValue(!input.element.checked);
}
function removeUrls(prompt, vms) {
prompt.vm.remove();
return vms.map((vm) => vm.remove.mock.calls[0][0].url);
}
describe('promptRemove: kubevirt.io.virtualmachine', () => {
describe('when several VMs are removed', () => {
it('should check "Delete All" by default and remove the disks of every VM', () => {
const vms = [createVm('vm1', ['disk-0']), createVm('vm2', ['disk-0', 'disk-1'])];
const prompt = mountPrompt(vms);
expect(prompt.find('input[type="checkbox"]').element.checked).toBe(true);
expect(removeUrls(prompt, vms)).toStrictEqual([
'/v1/harvester/kubevirt.io.virtualmachines/default/vm1?removedDisks=disk-0&propagationPolicy=Foreground',
'/v1/harvester/kubevirt.io.virtualmachines/default/vm2?removedDisks=disk-0&removedDisks=disk-1&propagationPolicy=Foreground',
]);
});
it('should uncheck "Delete All" with one click and keep the disks', async() => {
const vms = [createVm('vm1', ['disk-0']), createVm('vm2', ['disk-0'])];
const prompt = mountPrompt(vms);
const input = prompt.find('input[type="checkbox"]');
await click(input);
expect(input.element.checked).toBe(false);
expect(removeUrls(prompt, vms)).toStrictEqual([
'/v1/harvester/kubevirt.io.virtualmachines/default/vm1?propagationPolicy=Foreground',
'/v1/harvester/kubevirt.io.virtualmachines/default/vm2?propagationPolicy=Foreground',
]);
});
it('should toggle "Delete All" on every click and remove the disks once it is checked again', async() => {
const vms = [createVm('vm1', ['disk-0']), createVm('vm2', ['disk-0'])];
const prompt = mountPrompt(vms);
const input = prompt.find('input[type="checkbox"]');
const states = [input.element.checked];
await click(input);
states.push(input.element.checked);
await click(input);
states.push(input.element.checked);
expect(states).toStrictEqual([true, false, true]);
expect(removeUrls(prompt, vms)).toStrictEqual([
'/v1/harvester/kubevirt.io.virtualmachines/default/vm1?removedDisks=disk-0&propagationPolicy=Foreground',
'/v1/harvester/kubevirt.io.virtualmachines/default/vm2?removedDisks=disk-0&propagationPolicy=Foreground',
]);
});
});
describe('when one VM is removed', () => {
it('should list its disks with the first one checked by default', () => {
const prompt = mountPrompt([createVm('vm1', ['disk-0', 'disk-1'])]);
const inputs = prompt.findAll('input[type="checkbox"]');
expect(inputs.map((input) => input.element.value)).toStrictEqual(['disk-0', 'disk-1']);
expect(inputs.map((input) => input.element.checked)).toStrictEqual([true, false]);
});
it('should remove only the checked disks', async() => {
const vm = createVm('vm1', ['disk-0', 'disk-1']);
const prompt = mountPrompt([vm]);
const [first, second] = prompt.findAll('input[type="checkbox"]');
await click(first);
await click(second);
expect([first.element.checked, second.element.checked]).toStrictEqual([false, true]);
expect(removeUrls(prompt, [vm])).toStrictEqual(['/v1/harvester/kubevirt.io.virtualmachines/default/vm1?removedDisks=disk-1&propagationPolicy=Foreground']);
});
});
});
@@ -0,0 +1,68 @@
<script>
import { mapGetters } from 'vuex';
import Banner from '@components/Banner/Banner.vue';
import { exceptionToErrorsArray } from '@shell/utils/error';
export default {
name: 'PromptRemoveHealthIgnoreRuleDialog',
components: { Banner },
// the prompt binds all of its own data to this body, none of it belongs on the element
inheritAttrs: false,
props: {
value: {
type: Array,
default: () => {
return [];
}
},
close: {
type: Function,
required: true
},
},
data() {
return { errors: [] };
},
computed: {
...mapGetters({ t: 'i18n/t' }),
// a rule's name means little, the check it is for is what the user knows
checkNames() {
return this.value.map((rule) => rule.spec?.checkKey).join(', ');
},
},
methods: {
// the prompt does not show the errors of a body that removes by itself
async remove(buttonDone) {
try {
await Promise.all(this.value.map((rule) => rule.remove()));
this.close(buttonDone);
} catch (err) {
this.errors = exceptionToErrorsArray(err);
buttonDone(false);
}
}
}
};
</script>
<template>
<div class="mt-10">
<div class="mb-5">
{{ t('harvester.dashboard.sections.componentHealth.ignore.attemptingToDelete') }} <b>{{ checkNames }}</b>. {{ t('harvester.dashboard.sections.componentHealth.ignore.reportedAgain') }}
</div>
<Banner
v-for="(error, i) in errors"
:key="i"
color="error"
:label="error"
/>
</div>
</template>
@@ -164,7 +164,7 @@ export default {
<div v-else>
<label class="checkbox-container mr-15">
<input
v-model="checkedList"
v-model="checkAll"
type="checkbox"
/>
<span
@@ -0,0 +1,421 @@
import {
CONFIG_MAP, COUNT, NETWORK_ATTACHMENT, PVC, STORAGE_CLASS
} from '@shell/config/types';
import harvesterStore from '../index';
import harvesterActions from '../actions';
import harvesterMutations from '../mutations';
import { SERVER_FILTERED_COUNTS, filteredCountRequest } from '../getters';
import { HCI, DATA_VOLUME, VOLUME_SNAPSHOT } from '../../../types';
import { PRODUCT_NAME } from '../../../config/harvester';
const BASE = 'https://harvester/v1/harvester';
// Nav item -> resource type, like `configureType(..., { resource })` in config/harvester-cluster.js
const RESOURCE_MAP: Record<string, string> = {
[HCI.BACKUP]: HCI.BACKUP,
[HCI.VM_SNAPSHOT]: HCI.BACKUP,
[HCI.SNAPSHOT]: VOLUME_SNAPSHOT,
[HCI.STORAGE]: STORAGE_CLASS,
[HCI.CLOUD_TEMPLATE]: CONFIG_MAP,
[HCI.NETWORK_ATTACHMENT]: NETWORK_ATTACHMENT,
[HCI.VOLUME]: PVC,
[DATA_VOLUME]: DATA_VOLUME,
};
const CLUSTER_SCOPED = [STORAGE_CLASS];
const schemaFor = (name: string) => {
const id = RESOURCE_MAP[name];
return id ? {
id, attributes: { namespaced: !CLUSTER_SCOPED.includes(id) }, links: { collection: `${ BASE }/${ id }s` }
} : null;
};
function createGetters({ counts = {} }: any = {}) {
return {
schemaFor,
urlFor: (type: string) => `${ BASE }/${ type }s`,
all: (type: string) => (type === COUNT ? [{ counts }] : []),
};
}
function createRootGetters({
isAllNamespaces = true, hideSystemResources = true, namespaces = { default: true, test: true }, clusterId = 'local'
}: any = {}) {
return {
isAllNamespaces,
currentProduct: { hideSystemResources, inStore: PRODUCT_NAME },
namespaces: () => namespaces,
clusterId,
};
}
function createState() {
return {
filteredCounts: {}, filteredCountRequests: {}, filteredCountWatchers: []
};
}
/**
* A minimal store context for the actions: `commit` runs the real mutations,
* `request` resolves with `responses[url]` (or rejects for an Error).
*/
function createContext({ responses = {}, getters = createGetters(), rootGetters = createRootGetters() }: any = {}) {
const state: any = createState();
const commit = jest.fn((type: string, payload: any) => (harvesterMutations as any)[type](state, payload));
const request = jest.fn(({ url }: any) => {
const res = Object.entries(responses).find(([part]) => url.includes(part))?.[1];
return res instanceof Error ? Promise.reject(res) : Promise.resolve(res || {});
});
const dispatch = jest.fn((action: string, payload: any) => {
if (action === 'request') {
return request(payload);
}
return (harvesterActions as any)[action](context, payload);
});
const context: any = {
state, commit, dispatch, getters, rootGetters
};
return { context, state, request };
}
describe('harvester store: side navigation counts', () => {
it('should have the state of the counts in the store', () => {
expect((harvesterStore.specifics as any).state()).toMatchObject({
filteredCounts: {}, filteredCountRequests: {}, filteredCountWatchers: []
});
});
it('should start the counts when the cluster is loaded', async() => {
const dispatch = jest.fn((action: string) => Promise.resolve(action === 'management/findAll' ? [{ metadata: { name: 'local' } }] : { id: 'local' }));
const context: any = {
state: {},
commit: jest.fn(),
dispatch,
getters: { schemaFor: () => null, filterNamespace: () => [] },
rootGetters: {
'management/schemaFor': () => null,
'harvester-common/getFeatureEnabled': () => true,
'prefs/get': () => ({}),
},
rootState: { managementReady: true },
};
await (harvesterActions as any).loadCluster(context, { id: 'local' });
expect(dispatch).toHaveBeenCalledWith('watchFilteredCounts', { clusterId: 'local' });
});
describe('filteredCountRequest', () => {
it('should request the filtered list with a page size of 1', () => {
const req = filteredCountRequest(createGetters(), createRootGetters({ hideSystemResources: false }), HCI.BACKUP);
expect(req).toStrictEqual({ url: `${ BASE }/${ HCI.BACKUP }s?filter=spec.type!%3Dsnapshot&pagesize=1` });
});
it.each(Object.keys(SERVER_FILTERED_COUNTS))('should build a request for %s', (name) => {
const url = filteredCountRequest(createGetters(), createRootGetters(), name)?.url || '';
expect(url.startsWith(`${ BASE }/${ RESOURCE_MAP[name] }s?`)).toBe(true);
expect(url).toContain('pagesize=1');
});
it('should only request the selected namespaces', () => {
const req = filteredCountRequest(createGetters(), createRootGetters({ isAllNamespaces: false, namespaces: { a: true, b: true } }), HCI.VM_SNAPSHOT);
expect(req?.url).toContain('projectsornamespaces=a%2Cb');
});
it('should leave out system namespaces with "All Namespaces" when system resources are hidden', () => {
const req = filteredCountRequest(createGetters(), createRootGetters({ namespaces: { default: true } }), HCI.CLOUD_TEMPLATE);
expect(req?.url).toContain('projectsornamespaces=default');
});
it('should not filter by namespace with "All Namespaces" when system resources are shown', () => {
const req = filteredCountRequest(createGetters(), createRootGetters({ hideSystemResources: false }), HCI.SNAPSHOT);
expect(req?.url).not.toContain('projectsornamespaces');
});
it.each([HCI.STORAGE, HCI.NETWORK_ATTACHMENT])('should ignore the namespace filter for %s', (name) => {
const req = filteredCountRequest(createGetters(), createRootGetters({ isAllNamespaces: false, namespaces: { a: true } }), name);
expect(req?.url).not.toContain('projectsornamespaces');
});
it('should not send a request for an empty namespace selection', () => {
const req = filteredCountRequest(createGetters(), createRootGetters({ isAllNamespaces: false, namespaces: {} }), HCI.BACKUP);
expect(req).toStrictEqual({ count: 0 });
});
it('should request the volumes without the temporary volumes of CDI', () => {
const req = filteredCountRequest(createGetters(), createRootGetters({ hideSystemResources: false }), HCI.VOLUME);
expect(req).toStrictEqual({ url: `${ BASE }/${ PVC }s?filter=metadata.ownerReferences.kind!%3DPersistentVolumeClaim&pagesize=1` });
});
it('should request the golden image volumes through the DataVolumes owned by a VM image, in the selected namespaces', () => {
const req = filteredCountRequest(createGetters(), createRootGetters({ isAllNamespaces: false, namespaces: { a: true } }), DATA_VOLUME);
expect(req).toStrictEqual({ url: `${ BASE }/${ DATA_VOLUME }s?filter=metadata.ownerReferences.kind%3DVirtualMachineImage&pagesize=1&projectsornamespaces=a` });
});
it('should not send a request for an unknown resource type', () => {
expect(filteredCountRequest(createGetters(), createRootGetters(), 'unknown')).toBeNull();
});
});
describe('fetchFilteredCounts', () => {
it('should save the count of each response', async() => {
const { context, state, request } = createContext({ responses: { 'spec.type!%3D': { count: 9 }, 'spec.type%3D': { count: 2 } } });
await harvesterActions.fetchFilteredCounts(context as any, [HCI.BACKUP, HCI.VM_SNAPSHOT]);
expect(request).toHaveBeenCalledTimes(2);
expect(state.filteredCounts).toStrictEqual({ [HCI.BACKUP]: 9, [HCI.VM_SNAPSHOT]: 2 });
});
it('should request all nav items by default', async() => {
const { context, state, request } = createContext();
await harvesterActions.fetchFilteredCounts(context as any);
expect(request).toHaveBeenCalledTimes(Object.keys(SERVER_FILTERED_COUNTS).length);
expect(Object.keys(state.filteredCounts)).toStrictEqual(Object.keys(SERVER_FILTERED_COUNTS));
});
it('should save 0 when the response has no count, as Steve leaves it out when nothing matches', async() => {
const { context, state } = createContext({ responses: { [STORAGE_CLASS]: { data: [] } } });
await harvesterActions.fetchFilteredCounts(context as any, [HCI.STORAGE]);
expect(state.filteredCounts).toStrictEqual({ [HCI.STORAGE]: 0 });
});
it('should save no count when the response has resources but no count, as Harvester v1.3 ignores the query', async() => {
const { context, state } = createContext({ responses: { [STORAGE_CLASS]: { data: [{}, {}] } } });
await harvesterActions.fetchFilteredCounts(context as any, [HCI.STORAGE]);
expect(state.filteredCounts).toStrictEqual({ [HCI.STORAGE]: null });
});
it('should save no count when the request fails', async() => {
const { context, state } = createContext({ responses: { [CONFIG_MAP]: new Error('500') } });
await harvesterActions.fetchFilteredCounts(context as any, [HCI.CLOUD_TEMPLATE]);
expect(state.filteredCounts).toStrictEqual({ [HCI.CLOUD_TEMPLATE]: null });
});
it('should save 0 without a request for an empty namespace selection', async() => {
const { context, state, request } = createContext({ rootGetters: createRootGetters({ isAllNamespaces: false, namespaces: {} }) });
await harvesterActions.fetchFilteredCounts(context as any, [HCI.BACKUP]);
expect(request).not.toHaveBeenCalled();
expect(state.filteredCounts).toStrictEqual({ [HCI.BACKUP]: 0 });
});
it('should ignore the response of an outdated request', async() => {
const { context, state } = createContext();
let resolveFirst: any;
context.dispatch = jest.fn()
.mockImplementationOnce(() => new Promise((resolve) => {
resolveFirst = resolve;
}))
.mockImplementationOnce(() => Promise.resolve({ count: 5 }));
const first = harvesterActions.fetchFilteredCounts(context as any, [HCI.BACKUP]);
await harvesterActions.fetchFilteredCounts(context as any, [HCI.BACKUP]);
resolveFirst({ count: 3 });
await first;
expect(state.filteredCounts).toStrictEqual({ [HCI.BACKUP]: 5 });
});
it('should ignore the response of a request of the previous cluster', async() => {
const { context, state } = createContext();
let resolveFirst: any;
context.dispatch = jest.fn()
.mockImplementationOnce(() => new Promise((resolve) => {
resolveFirst = resolve;
}))
.mockImplementationOnce(() => Promise.resolve({ count: 5 }));
const first = harvesterActions.fetchFilteredCounts(context as any, [HCI.BACKUP]);
context.commit('resetFilteredCounts');
await harvesterActions.fetchFilteredCounts(context as any, [HCI.BACKUP]);
resolveFirst({ count: 3 });
await first;
expect(state.filteredCounts).toStrictEqual({ [HCI.BACKUP]: 5 });
});
});
describe('watchFilteredCounts', () => {
beforeEach(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.useRealTimers();
});
/**
* Runs `watchFilteredCounts` with a fake `store.watch`, which records the
* watch callbacks by the value of their getter.
*/
function watch(contextArgs: any = {}) {
const { context, state, request } = createContext(contextArgs);
const watchers: { getter: () => any, cb: () => void }[] = [];
const unwatch = jest.fn();
const store = {
watch: jest.fn((getter: () => any, cb: () => void) => {
watchers.push({ getter, cb });
return unwatch;
})
};
const done = harvesterActions.watchFilteredCounts.call(store, context, { clusterId: 'local' });
return {
context, state, request, watchers, unwatch, done
};
}
it('should request all counts right away', async() => {
const { request, done } = watch();
await done;
expect(request).toHaveBeenCalledTimes(Object.keys(SERVER_FILTERED_COUNTS).length);
});
it('should watch the counts endpoint per resource type, and the namespace filter', async() => {
const { watchers, done } = watch({ getters: createGetters({ counts: { [STORAGE_CLASS]: { summary: { count: 4 } } } }) });
await done;
// VirtualMachineBackup, VolumeSnapshot, StorageClass, ConfigMap, NAD, PVC, DataVolume + the namespace filter
expect(watchers).toHaveLength(8);
expect(watchers.map(({ getter }) => getter())).toContain(JSON.stringify({ summary: { count: 4 } }));
});
it('should request the counts of a resource type again, once, when its numbers change', async() => {
const { watchers, request, done } = watch();
await done;
request.mockClear();
// The first watcher is the one of VirtualMachineBackup, the type of the first nav items
const backupWatcher = watchers[0];
backupWatcher.cb();
backupWatcher.cb();
jest.advanceTimersByTime(1000);
await Promise.resolve();
// VM backups and VM snapshots, both VirtualMachineBackup resources
expect(request).toHaveBeenCalledTimes(2);
});
it('should request the namespaced counts again when the namespace filter changes', async() => {
const { watchers, request, done } = watch();
await done;
request.mockClear();
watchers[watchers.length - 1].cb();
await Promise.resolve();
const urls = request.mock.calls.map(([{ url }]: any) => url);
expect(urls).toHaveLength(6);
expect(urls.some((url: string) => url.includes(STORAGE_CLASS) || url.includes(NETWORK_ATTACHMENT))).toBe(false);
});
it('should not request anything once another cluster is shown', async() => {
const rootGetters = createRootGetters();
const { watchers, request, done } = watch({ rootGetters });
await done;
request.mockClear();
rootGetters.clusterId = 'c-other';
watchers[watchers.length - 1].cb();
await Promise.resolve();
expect(request).not.toHaveBeenCalled();
});
it('should not request anything once another product is shown', async() => {
const rootGetters = createRootGetters();
const { watchers, request, done } = watch({ rootGetters });
await done;
request.mockClear();
rootGetters.currentProduct = { inStore: 'cluster' };
watchers[watchers.length - 1].cb();
await Promise.resolve();
expect(request).not.toHaveBeenCalled();
});
it('should not request anything for a change seen just before the watchers were stopped', async() => {
const { context, watchers, request, done } = watch();
await done;
request.mockClear();
watchers[0].cb();
await harvesterActions.watchFilteredCounts.call({ watch: jest.fn(() => jest.fn()) }, context, { clusterId: 'local' });
request.mockClear();
jest.advanceTimersByTime(1000);
await Promise.resolve();
expect(request).not.toHaveBeenCalled();
});
it('should cope with the store module being unregistered when logging out', async() => {
const getters: any = createGetters();
const { watchers, done } = watch({ getters });
await done;
delete getters.all;
expect(watchers[0].getter()).toBe('null');
});
it('should keep the watchers when a cluster left while it was loading finishes loading', async() => {
const { context, unwatch, request, done } = watch();
await done;
request.mockClear();
const store = { watch: jest.fn() };
await harvesterActions.watchFilteredCounts.call(store, context, { clusterId: 'c-left' });
expect(store.watch).not.toHaveBeenCalled();
expect(unwatch).not.toHaveBeenCalled();
expect(request).not.toHaveBeenCalled();
});
it('should stop the watchers of the previous cluster', async() => {
const { context, unwatch, done } = watch();
await done;
await harvesterActions.watchFilteredCounts.call({ watch: jest.fn(() => jest.fn()) }, context, { clusterId: 'local' });
expect(unwatch).toHaveBeenCalledTimes(8);
});
});
});
@@ -0,0 +1,290 @@
import {
CONFIG_MAP, COUNT, NAMESPACE, NETWORK_ATTACHMENT, NODE, PVC, STORAGE_CLASS
} from '@shell/config/types';
import harvesterGetters from '../getters';
import { HCI, DATA_VOLUME, VOLUME_SNAPSHOT } from '../../../types';
import { HCI_SETTING } from '../../../config/settings';
// Nav item -> resource type, like `configureType(..., { resource })` in config/harvester-cluster.js
const RESOURCE_MAP: Record<string, string> = {
[HCI.HOST]: NODE,
[HCI.VOLUME]: PVC,
[HCI.NETWORK_ATTACHMENT]: NETWORK_ATTACHMENT,
[HCI.VM_SNAPSHOT]: HCI.BACKUP,
[HCI.SNAPSHOT]: VOLUME_SNAPSHOT,
[HCI.CLOUD_TEMPLATE]: CONFIG_MAP,
[HCI.STORAGE]: STORAGE_CLASS,
};
const CLUSTER_SCOPED = [NODE, STORAGE_CLASS, NAMESPACE];
const counts = (byNamespace: Record<string, number>) => ({
summary: { count: Object.values(byNamespace).reduce((sum, count) => sum + count, 0) },
namespaces: Object.fromEntries(Object.entries(byNamespace).map(([ns, count]) => [ns, { count }])),
});
/**
* Creates the `count` getter with a minimal store. `counts` is the result of
* Steve's counts endpoint, `filteredCounts` the counts requested by
* `fetchFilteredCounts` and `lists` the loaded store lists.
*/
function createCount({
counts = {}, filteredCounts = {}, lists = {}, visibleSettings = [], isAllNamespaces = true, hideSystemResources = false, namespaces = {}
}: any = {}) {
const schemas = new Map<string, any>();
// Schemas of the resource types used below. `count` only filters by namespace if the
// schema marks the type as namespaced, so a namespaced type without a schema here would be
// counted in all namespaces. RESOURCE_MAP contains the resource types of nav items with a
// different name, the others are nav items named like the resource type they list.
[...Object.values(RESOURCE_MAP), HCI.BACKUP, HCI.SCHEDULE_VM_BACKUP, HCI.VM, HCI.FLOW, NAMESPACE].forEach((id) => {
schemas.set(id, { id, attributes: { namespaced: !CLUSTER_SCOPED.includes(id) } });
});
const state = { types: { schema: { map: schemas } }, filteredCounts };
const rootGetters = {
isAllNamespaces,
namespaces: () => namespaces,
// Empty on purpose: this cache is not necessarily filled yet when the side navigation is
// rendered, e.g. right after loading the dashboard. `count` must use `namespaces()`;
// reading this cache would make the tests that select namespaces fail.
activeNamespaceCache: {},
currentProduct: { hideSystemResources },
'type-map/optionsFor': (type: string) => (RESOURCE_MAP[type] ? { resource: RESOURCE_MAP[type] } : {}),
};
const getters: any = {
normalizeType: (type: string) => type,
haveAll: jest.fn((type: string) => !!lists[type]),
all: jest.fn((type: string) => (type === COUNT ? [{ counts }] : lists[type] || [])),
visibleSettings,
};
getters.schemaFor = harvesterGetters.schemaFor(state, getters, {}, rootGetters);
const count = harvesterGetters.count(state, getters, {}, rootGetters);
return (name: string) => count({ name });
}
describe('harvester store: count', () => {
describe('nav items listing all resources of a type', () => {
it('should look up the count of the underlying resource type', () => {
const count = createCount({ counts: { [NODE]: counts({ '': 3 }) } });
expect(count(HCI.HOST)).toBe(3);
});
it('should only count the selected namespaces', () => {
const count = createCount({
counts: { [HCI.VM]: counts({ default: 4, test: 2 }) },
isAllNamespaces: false,
namespaces: { test: true },
});
expect(count(HCI.VM)).toBe(2);
});
it('should not count system namespaces with "All Namespaces" when system resources are hidden', () => {
const count = createCount({
counts: { [HCI.VM]: counts({ default: 4, 'cattle-monitoring-system': 2 }) },
hideSystemResources: true,
namespaces: { default: true },
});
expect(count(HCI.VM)).toBe(4);
});
it('should count nothing for an empty namespace selection, e.g. a project without namespaces', () => {
const count = createCount({
counts: { [HCI.VM]: counts({ default: 4, test: 2 }) },
isAllNamespaces: false,
namespaces: {},
});
expect(count(HCI.VM)).toBe(0);
});
it('should count all namespaces for lists that ignore the namespace filter', () => {
const count = createCount({
counts: { [HCI.FLOW]: counts({ a: 2, b: 1 }) },
isAllNamespaces: false,
namespaces: { a: true },
});
expect(count(HCI.FLOW)).toBe(3);
});
it('should ignore the namespace filter for cluster-scoped resources', () => {
const count = createCount({
counts: { [NODE]: counts({ '': 3 }) },
isAllNamespaces: false,
namespaces: { test: true },
});
expect(count(HCI.HOST)).toBe(3);
});
it('should count all VM Schedules, whatever their type', () => {
const count = createCount({ counts: { [HCI.SCHEDULE_VM_BACKUP]: counts({ default: 2 }) } });
expect(count(HCI.SCHEDULE_VM_BACKUP)).toBe(2);
});
it('should return null for nav items without counts', () => {
expect(createCount()(HCI.DASHBOARD)).toBeNull();
});
});
describe('nav items listing a subset of a resource type', () => {
it('should show the count requested from the server', () => {
const count = createCount({
counts: { [HCI.BACKUP]: counts({ default: 3 }) },
filteredCounts: { [HCI.BACKUP]: 1, [HCI.VM_SNAPSHOT]: 2 },
});
expect(count(HCI.BACKUP)).toBe(1);
expect(count(HCI.VM_SNAPSHOT)).toBe(2);
});
it.each([
HCI.BACKUP, HCI.VM_SNAPSHOT, HCI.SNAPSHOT, HCI.STORAGE, HCI.CLOUD_TEMPLATE, HCI.NETWORK_ATTACHMENT
])('should not use the total of the counts endpoint for %s before the server count arrives', (name) => {
const count = createCount({ counts: Object.fromEntries(Object.values(RESOURCE_MAP).concat(HCI.BACKUP).map((type) => [type, counts({ default: 3 })])) });
expect(count(name)).toBeNull();
});
it('should show 0 when the server count is 0', () => {
expect(createCount({ filteredCounts: { [HCI.STORAGE]: 0 } })(HCI.STORAGE)).toBe(0);
});
});
describe('volumes', () => {
it('should subtract the golden image volumes from the requested volumes', () => {
const count = createCount({
counts: { [PVC]: counts({ default: 99 }) },
filteredCounts: { [HCI.VOLUME]: 19, [DATA_VOLUME]: 2 },
});
expect(count(HCI.VOLUME)).toBe(17);
});
it('should show 0 when there are no volumes', () => {
expect(createCount({ filteredCounts: { [HCI.VOLUME]: 0, [DATA_VOLUME]: 0 } })(HCI.VOLUME)).toBe(0);
});
it.each([
[{}],
[{ [HCI.VOLUME]: 19 }],
[{ [DATA_VOLUME]: 2 }],
[{ [HCI.VOLUME]: null, [DATA_VOLUME]: 2 }],
[{ [HCI.VOLUME]: 19, [DATA_VOLUME]: null }],
])('should not show a count until both numbers are known: %j', (filteredCounts) => {
expect(createCount({ filteredCounts })(HCI.VOLUME)).toBeNull();
});
it('should not go below 0, as a DataVolume exists briefly before its volume', () => {
expect(createCount({ filteredCounts: { [HCI.VOLUME]: 0, [DATA_VOLUME]: 1 } })(HCI.VOLUME)).toBe(0);
});
});
describe('settings', () => {
it('should count the settings shown by the page, not all the settings', () => {
const count = createCount({
counts: { [HCI.SETTING]: counts({ '': 5 }) },
lists: { [HCI.SETTING]: [{}] },
visibleSettings: [{}, {}],
});
expect(count(HCI.SETTING)).toBe(2);
});
it('should return null until the settings are loaded', () => {
expect(createCount({ visibleSettings: [{}] })(HCI.SETTING)).toBeNull();
});
});
describe('namespaces', () => {
const namespace = (isSystem = false, isFleetManaged = false) => ({ isSystem, isFleetManaged });
it('should not count system and Fleet managed namespaces when system resources are hidden', () => {
const count = createCount({
counts: { [NAMESPACE]: counts({ '': 4 }) },
lists: { [NAMESPACE]: [namespace(), namespace(), namespace(true), namespace(false, true)] },
hideSystemResources: true,
});
expect(count(NAMESPACE)).toBe(2);
});
it('should return null until the namespaces are loaded when system resources are hidden', () => {
const count = createCount({ counts: { [NAMESPACE]: counts({ '': 4 }) }, hideSystemResources: true });
expect(count(NAMESPACE)).toBeNull();
});
it('should count all namespaces when system resources are shown', () => {
const count = createCount({ counts: { [NAMESPACE]: counts({ '': 4 }) } });
expect(count(NAMESPACE)).toBe(4);
});
});
});
describe('harvester store: visibleSettings', () => {
const { BACKUP_TARGET, MAX_HOTPLUG_RATIO, UI_PL } = HCI_SETTING;
const setting = (id: string, source = 'harvester') => ({ id, source });
function visibleSettings({
harvester = [] as string[], management = [] as string[], isSingleProduct = false, isStandaloneHarvester = false, enabledFeatures = [] as string[]
} = {}) {
const rootGetters = {
isSingleProduct,
isStandaloneHarvester,
'management/all': () => management.map((id) => setting(id, 'management')),
'harvester-common/getFeatureEnabled': (feature: string) => enabledFeatures.includes(feature),
};
return harvesterGetters.visibleSettings({}, { all: () => harvester.map((id) => setting(id)) }, {}, rootGetters);
}
const ids = (args: any) => visibleSettings(args).map(({ id }: any) => id);
it('should only show the allowed settings', () => {
expect(ids({ harvester: [BACKUP_TARGET, 'api-ui-version'] })).toStrictEqual([BACKUP_TARGET]);
});
it('should return the config and the resource of a setting', () => {
const [shown] = visibleSettings({ harvester: [BACKUP_TARGET] });
expect(shown.data).toStrictEqual(setting(BACKUP_TARGET));
expect(shown.config.kind).toBe('json');
});
it('should not show allowed settings that do not exist in the cluster', () => {
expect(ids({ harvester: [] })).toStrictEqual([]);
});
it('should only show settings with a feature flag when the version supports it', () => {
expect(ids({ harvester: [MAX_HOTPLUG_RATIO] })).toStrictEqual([]);
expect(ids({ harvester: [MAX_HOTPLUG_RATIO], enabledFeatures: ['cpuMemoryHotplug'] })).toStrictEqual([MAX_HOTPLUG_RATIO]);
});
it('should only show the single cluster settings on a standalone Harvester', () => {
expect(ids({ harvester: [UI_PL] })).toStrictEqual([]);
expect(ids({ harvester: [UI_PL], isStandaloneHarvester: true })).toStrictEqual([UI_PL]);
});
it('should only use the settings of the management store in a single product', () => {
expect(ids({ management: [BACKUP_TARGET] })).toStrictEqual([]);
expect(ids({ management: [BACKUP_TARGET], isSingleProduct: true })).toStrictEqual([BACKUP_TARGET]);
});
it('should prefer the Harvester setting over the management setting with the same id', () => {
const [shown] = visibleSettings({
harvester: [BACKUP_TARGET], management: [BACKUP_TARGET], isSingleProduct: true
});
expect(shown.data.source).toBe('harvester');
});
});
@@ -5,7 +5,12 @@ import { COUNT, NAMESPACE, MANAGEMENT } from '@shell/config/types';
import { allHash } from '@shell/utils/promise';
import { DEV, NAMESPACE_FILTERS } from '@shell/store/prefs';
import { createNamespaceFilterKeyWithId } from '@shell/utils/namespace-filter';
import debounce from 'lodash/debounce';
import { HCI } from '../../types';
import { PRODUCT_NAME } from '../../config/harvester';
import {
SERVER_FILTERED_COUNTS, countedNamespaces, filteredCountRequest, isFilteredByNamespace
} from './getters';
export default {
async loadCluster({
@@ -131,6 +136,8 @@ export default {
getters
}, { root: true });
dispatch('watchFilteredCounts', { clusterId: id });
// Solve compatibility with Rancher v2.6.x, fell remove these codes after not support v2.6.x
const definition = {
def: false,
@@ -166,4 +173,95 @@ export default {
}, { root: true });
}
},
/**
* Requests the side navigation counts of the nav items in SERVER_FILTERED_COUNTS
* (all of them by default), see getters.ts. Responses of an outdated request
* of a nav item (e.g. before a namespace filter change, or of the previous
* cluster) are ignored.
*/
async fetchFilteredCounts({
state, commit, dispatch, getters, rootGetters
}: any, names: string[] = Object.keys(SERVER_FILTERED_COUNTS)) {
await Promise.all(names.map(async(name: string) => {
commit('filteredCountRequested', name);
const requestId = state.filteredCountRequests[name];
const request = filteredCountRequest(getters, rootGetters, name);
let count = request?.count ?? null;
if (request?.url) {
try {
const res = await dispatch('request', { url: request.url });
// Steve leaves out `count` when nothing matches. Harvester v1.3 ignores the query and
// sends all resources without a `count`, which says nothing about the subset.
count = res?.count ?? (res?.data?.length ? null : 0);
} catch (e) {
count = null;
}
}
if (state.filteredCountRequests[name] === requestId) {
commit('setFilteredCount', { name, count });
}
}));
},
/**
* Requests the counts of SERVER_FILTERED_COUNTS, and requests them again when
* they may have changed: when the counts endpoint reports other numbers for
* their resource type (it is kept up to date through the websocket), and when
* the namespace filter changes. A change that leaves these numbers as they are
* (e.g. adding the cloud-init template label to an existing ConfigMap) shows up
* with the next change of that resource type.
*/
watchFilteredCounts({
state, commit, dispatch, getters, rootGetters
}: any, { clusterId }: any) {
// The `loadCluster` of a cluster left while it was loading can finish after the one of the new cluster
if (rootGetters.clusterId !== clusterId) {
return;
}
state.filteredCountWatchers.forEach((unwatch: () => void) => unwatch());
commit('resetFilteredCounts');
// The watchers stay registered after leaving the cluster or the product, until the next `loadCluster`
const refresh = (names: string[]) => {
if (rootGetters.clusterId === clusterId && rootGetters.currentProduct?.inStore === PRODUCT_NAME) {
dispatch('fetchFilteredCounts', names);
}
};
const names = Object.keys(SERVER_FILTERED_COUNTS);
const namesByType: Record<string, string[]> = {};
names.forEach((name) => {
const type = getters.schemaFor(name)?.id;
if (type) {
namesByType[type] = [...(namesByType[type] || []), name];
}
});
const unwatchers = Object.entries(namesByType).map(([type, namesOfType]) => {
const refreshType = debounce(() => refresh(namesOfType), 1000);
// `all` is gone once the store module is unregistered when logging out
const unwatch = this.watch(() => JSON.stringify(getters.all?.(COUNT)?.[0]?.counts?.[type] || null), refreshType);
return () => {
unwatch();
refreshType.cancel();
};
});
unwatchers.push(this.watch(
() => JSON.stringify(countedNamespaces(rootGetters)),
() => refresh(names.filter((name) => isFilteredByNamespace(name, getters.schemaFor(name))))
));
commit('setFilteredCountWatchers', unwatchers);
return dispatch('fetchFilteredCounts');
},
};

Some files were not shown because too many files have changed in this diff Show More