Compare commits

..
Author SHA1 Message Date
Harvester Bot eb77d03b97 chore: bump version to 1.9.0-rc7 (#1132)
Signed-off-by: Harvester Bot <94133267+harvesterhci-io-github-bot@users.noreply.github.com>
2026-09-01 18:47:34 +08:00
22deb0e1f6 feat: LHv2: graduate from "Experimental" to "Preview" (#1129) (#1131)
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



(cherry picked from commit 4fa6470343)

Signed-off-by: Tim Serong <tserong@suse.com>
Co-authored-by: Tim Serong <tserong@suse.com>
Co-authored-by: Volker Theile <vtheile@suse.com>
2026-09-01 12:13:39 +10:00
mergify[bot]andAndy Lee f096147aa3 fix: vGPU doesn't display when creating harvester downstream cluster (#1123) (#1128)
* fix: vGPU doesn't display in edit VM page



* 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.



---------


(cherry picked from commit d550046189)

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
2026-08-25 16:50:27 +08:00
Harvester Bot d73a9413be chore: bump version to 1.9.0-rc6 (#1122)
Signed-off-by: Harvester Bot <94133267+harvesterhci-io-github-bot@users.noreply.github.com>
2026-08-19 18:40:46 +08:00
mergify[bot]andPo Han Huang 63ff8ce8fe feat: improve readability for vm migration UI (#1112) (#1120)
(cherry picked from commit 5f32a9ade5)

Signed-off-by: pohanhuang <pohan.huang@suse.com>
Co-authored-by: Po Han Huang <pohan.huang@suse.com>
2026-08-18 12:41:02 +08:00
mergify[bot] b3b467f7b5 fix: exclude forklift namespace from system classification (#1114) (#1118) 2026-08-17 13:37:43 +08:00
mergify[bot]andAndy Lee 20557ee788 fix: ACCESS_MODE undefined error in forklift mapping page (#1111) (#1113)
(cherry picked from commit f63be73b11)

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
2026-08-14 22:49:01 +08:00
Harvester Bot 8ab432fb52 chore: bump version to 1.9.0-rc5 (#1107)
Signed-off-by: Harvester Bot <94133267+harvesterhci-io-github-bot@users.noreply.github.com>
2026-08-12 14:54:23 +08:00
mergify[bot]andAndy Lee 61624dc0ff fix: prevent duplicated cloud-config for empty user data (#1109) (#1110)
* fix: prevent duplicated cloud-config for empty user data



* refactor: AI review



---------


(cherry picked from commit fabc1cec21)

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
2026-08-12 14:54:09 +08:00
mergify[bot] d1367fc9a9 fix: remove map ownerref writeback and delete maps via plan refs (#1105) (#1106) 2026-08-10 20:58:35 +08:00
mergify[bot]andrenovate[bot] 18c973c8c4 deps: update dependency @types/lodash to v4.17.25 (#1099) (#1104)
(cherry picked from commit 72282ae50e)

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-08-10 10:14:21 +08:00
mergify[bot]andVolker Theile c9b26ab4bb fix: Rename to Windows Unattended & Sysprep (#1096) (#1098)
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


(cherry picked from commit 8fba4e7050)

Signed-off-by: Volker Theile <vtheile@suse.com>
Co-authored-by: Volker Theile <vtheile@suse.com>
2026-08-07 11:29:43 +08:00
Harvester Bot 2b9d093b38 chore: bump version to 1.9.0-rc4 (#1094)
Signed-off-by: Harvester Bot <94133267+harvesterhci-io-github-bot@users.noreply.github.com>
2026-08-05 21:06:57 +08:00
mergify[bot]andAndy Lee 1b3666e15c fix(subnet): support None option for VLAN dropdown (#1085) (#1090)
(cherry picked from commit be6e9b5f06)

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
2026-08-05 14:01:35 +08:00
mergify[bot]andAndy Lee 0bccb9a71f fix: clear keyword should clear highlight (#1088) (#1089)
(cherry picked from commit a88bed9eb4)

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
2026-08-05 00:26:04 +08:00
mergify[bot]andAndy Lee 6d4cd09568 deps: bump @rancher/shell to 3.0.12-rc.7 (#1084) (#1087)
* deps: update rancher/shell to 3.0.12-rc.7



* fix: move filter labels/schedule buttons position



* feat: improve serial console



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



* refactor: clear searach result after close



* refactor: fine tune serial console



---------


(cherry picked from commit f97f14c811)

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
2026-08-04 19:57:02 +08:00
mergify[bot]andAndy Lee 44078bf7cb fix: project resource quota not set in POST API payload (#1082) (#1086)
* fix: project resource quota not set in POST API payload



* fix: guard onQuotasInput against undefined payload



---------


(cherry picked from commit f8a29a1c54)

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
2026-08-04 13:35:47 +08:00
mergify[bot]andfreeze 1d55319aba feat: support attaching volumes as shareable disks (#1026) (#1083)
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


(cherry picked from commit 9a935434c2)

Signed-off-by: Vicente Cheng <vicente.cheng@suse.com>
Co-authored-by: freeze <1615081+Vicente-Cheng@users.noreply.github.com>
2026-08-03 16:53:57 +08:00
mergify[bot]andrenovate[bot] 3b7a0c30a7 deps: update patch dependencies (#1075) (#1080)
(cherry picked from commit d050f21f9a)

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-08-03 16:46:22 +08:00
mergify[bot]andAndy Lee d4562a91d1 feat: add access/volume mode support and improvements for VM migration (#1074) (#1081)
* fix: VM migration tab not appear when first login



* feat: add access/ volume mode model



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



* fix: bugs in VM selection table



* refactor: copilot review



---------


(cherry picked from commit afe632b723)

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
2026-08-03 13:33:26 +08:00
mergify[bot]andAndy Lee 080f9cdb29 fix: prevent VM detail page hang when static IP assigned (#1072) (#1073)
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.


(cherry picked from commit b87f367583)

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
2026-07-31 16:59:16 +08:00
mergify[bot]andAndy Lee b19da16b83 ci: disable footer-max-line-length rule (#1069) (#1070)
(cherry picked from commit 92aa8ec603)

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
2026-07-30 10:13:51 +08:00
16a92c5e96 feat: allow Cloud Config for Windows guests (Cloudbase-Init) (backport #984) (#1068)
Allow users to author and persist Cloud Config (cloud-init) on Windows VMs. Today the Cloud Config editor is hidden entirely when OS Type is set to Windows, and even if user-data/network-data has been supplied elsewhere the cloudinitdisk volume and its Secret are silently dropped from the VM spec. This is more restrictive than what Windows guests actually support: Cloudbase-Init reads cloudinit-style NoCloud datasources on Windows and is a common way to bootstrap Windows guests (install VMDP + qemu-guest-agent, enable OpenSSH server, drop authorized_keys, run first-boot runcmd scripts, join a domain, etc.).

Windows guests today have to hand-edit the VM YAML after the UI creates the VM — a workflow that is fragile, undiscoverable, and defeats the point of a UI. See the linked upstream issue for the same request from the operator side.

Backport of https://github.com/harvester/harvester-ui-extension/issues/984




(cherry picked from commit e013534373)

Signed-off-by: Alejandro Bonilla <abonilla@suse.com>
Signed-off-by: Volker Theile <vtheile@suse.com>
Co-authored-by: Alejandro Bonilla <abonilla@suse.com>
Co-authored-by: Volker Theile <vtheile@suse.com>
2026-07-28 13:57:34 +02:00
Andy Lee 51a76eefe2 revert: PR build artifact (#1067)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-07-28 15:46:54 +08:00
mergify[bot]andAndy Lee 690652f204 ci: trigger standalone build when PR labeled with build-artifact (backport #1058) (#1059)
* 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>
(cherry picked from commit ac26fe2f0e)

* fix: CI_BRANCH

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

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
2026-07-28 14:54:41 +08:00
mergify[bot]andAndy Lee a0f21d5902 feat: add VMware VDDK image input field to VM migration provider (#1057) (#1060)
* 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.



* refactor: copilot review



---------


(cherry picked from commit a6bd7ec00e)

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
2026-07-28 14:33:31 +08:00
mergify[bot]andAndy Lee f0929100f0 feat: validate migration plan name against existing providers and plans (#1053) (#1054)
Show an error banner and disable the Create and Start action when the migration plan name matches an existing provider or migration plan name.


(cherry picked from commit 790cade04d)

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
2026-07-24 16:46:52 +08:00
mergify[bot]andAndy Lee 78ca4bb663 refactor: new design for review page (#1051) (#1052)
* refactor: new design for review page



* refactor: customize empty table rows message



* refactor: fixed the table column



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



* style: remove unneeded overflow css



---------


(cherry picked from commit 2903e86c02)

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
2026-07-24 10:30:00 +08:00
mergify[bot]andAndy Lee eb917c9d18 fix: forklift mapping UX and migration progress fixes (#1049) (#1050)
* refactor: modify relatedResources using ownerReferences uid



* refactor: wordings



* 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.



---------


(cherry picked from commit 2d747e435a)

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
2026-07-23 14:41:01 +08:00
Harvester Bot 8815c70361 chore: bump version to 1.9.0-rc3 (#1048)
Signed-off-by: Harvester Bot <94133267+harvesterhci-io-github-bot@users.noreply.github.com>
2026-07-22 20:01:38 +08:00
mergify[bot]andVolker Theile eb4c0504c8 fix: Creating a VM with no cloud init user data but network data only fails (#1044) (#1045)
Related to: https://github.com/harvester/harvester/issues/11213


(cherry picked from commit a178302f73)

Signed-off-by: Volker Theile <vtheile@suse.com>
Co-authored-by: Volker Theile <vtheile@suse.com>
2026-07-21 11:09:55 +08:00
mergify[bot]andAndy Lee 82e7b0da19 docs: require scope-less conventional commit format in guides (#1042) (#1043)
(cherry picked from commit d376bfb3a5)

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
2026-07-21 11:06:37 +08:00
mergify[bot]andAndy Lee 92f34fa64f fix(vm-migration): show elapsed duration for in-progress plans (#1037) (#1038)
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


(cherry picked from commit 7a84e08f99)

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
2026-07-20 17:07:09 +08:00
mergify[bot]andAndy Lee 6039f21320 docs(agents): clarify agent guide and share it across AI assistants (#1035) (#1036)
* ci: disable header-max-length commit rule



* 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



---------


(cherry picked from commit 3d39626b93)

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
2026-07-20 15:55:10 +08:00
mergify[bot]andAndy Lee 3cbaf97399 refactor(host): update resource usage gauges and table column headers to fit small screen (#1031) (#1034)
* 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



* refactor: add noopener noreferrer rel



---------


(cherry picked from commit 1c3b40b631)

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
2026-07-20 15:52:16 +08:00
mergify[bot]andAndy Lee bcde1744e1 fix(ci): support scoped commit prefixes in PR label extraction (#1032) (#1033)
Strip the scope in parentheses so titles like 'refactor(host): ...'
resolve to the 'refactor' type instead of falling back to 'other'.


(cherry picked from commit 87baf75301)

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
2026-07-20 15:29:24 +08:00
mergify[bot]andAndy Lee e991c9bcc8 feat: improve VM migration dashboard mapping labels and VM detail link (#1029) (#1030)
* 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



* refactor: modify duration column width



* refactor: copilot review comment



---------


(cherry picked from commit a10d651827)

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
2026-07-20 14:42:53 +08:00
mergify[bot]andrenovate[bot] 6e709bc00f deps: update dependency @types/node to v25.9.5 (#1021) (#1028)
(cherry picked from commit 11ff7c8a7c)

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-07-20 12:28:04 +08:00
mergify[bot]andJack Yu 20d40860ce feat: support skip MIG mode configuration in srivogpu (#1009) (#1027)
(cherry picked from commit f6dffe9816)

Signed-off-by: Jack Yu <jack.yu@suse.com>
Co-authored-by: Jack Yu <jack.yu@suse.com>
2026-07-20 12:20:09 +08:00
mergify[bot]andAndy Lee 1496c17f3d docs: add XSS safety comment for VM display name annotation (#1019) (#1020)
(cherry picked from commit b813bc578e)

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
2026-07-17 17:32:24 +08:00
mergify[bot]andAndy Lee e99e4ef34f fix: remove bootable volume validation in VM disk validator (#1016) (#1017)
(cherry picked from commit 7c3b2730ab)

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
2026-07-17 17:00:59 +08:00
73e022172b fix: stale cloud-init secret name reused after VM name change (#1012) (#1015)
* 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




* refactor: copilot review



* refactor: remove console



---------



(cherry picked from commit 429d9e18ad)

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-07-17 15:50:51 +08:00
mergify[bot]andAndy Lee 7e86c9fae0 ci: modify PR template (#1013) (#1014)
* ci: modify PR template



* refactor: review comment



---------


(cherry picked from commit dc166d8fc9)

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
2026-07-17 15:50:41 +08:00
mergify[bot]andAndy Lee b4b49222c3 feat: allow user specify namespace for migrated VM (#1007) (#1011)
* feat: allow user specify namespace for migrated VM



* refactor: not pre-select target namespace



* refactor: ignore option



* refactor: copilot review



---------


(cherry picked from commit 3ff4534294)

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
2026-07-16 16:16:19 +08:00
mergify[bot]andAndy Lee b937a2147b feat: keep upgrade button appear (#1003) (#1008)
* feat: keep upgrade button appear



* refactor: copilot review



---------


(cherry picked from commit d4223ad2ae)

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
2026-07-16 11:46:21 +08:00
mergify[bot]andAndy Lee 07f2b02a9d feat: add migration plan duration time column (#1005) (#1006)
* feat: add migration plan duration time column



* feat: allow duration column to be sorted



---------


(cherry picked from commit 44297ada16)

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
2026-07-15 19:20:06 +08:00
Harvester Bot 35b6949cdc chore: bump version to 1.9.0-rc2 (#1002)
Signed-off-by: Harvester Bot <94133267+harvesterhci-io-github-bot@users.noreply.github.com>
2026-07-15 17:46:50 +08:00
mergify[bot]andAndy Lee c577f589e7 fix: allow input vlan 1 in host network (#999) (#1001)
(cherry picked from commit 9640c87947)

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
2026-07-15 15:25:42 +08:00
mergify[bot]andVolker Theile b1387820ed fix: A disk entry must be either disk or cdrom, never both (backport #998) (#1000)
Related to: https://github.com/harvester/harvester/issues/11154


(cherry picked from commit 2cefd7cb78)

Signed-off-by: Volker Theile <vtheile@suse.com>
Co-authored-by: Volker Theile <vtheile@suse.com>
2026-07-15 09:15:09 +02:00
mergify[bot]andAndy Lee 45f72749f5 refactor: add customized migration plan delete model (#996) (#997)
* refactor: add customized migration plan delete model



* refactor: copilot review



* refactor: copilot review



---------


(cherry picked from commit fb6ffa3c0f)

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
2026-07-14 17:40:44 +08:00
mergify[bot]andAndy Lee a65b3f443e feat: add migration steps tooltip when mouse hover on progress bar (#994) (#995)
* feat: add progress bar tooltip



* refactor: copilot review



---------


(cherry picked from commit e0436bff28)

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
2026-07-14 14:39:59 +08:00
mergify[bot]andAndy Lee 21d415b5f3 refactor: rename pod network to management network (#992) (#993)
(cherry picked from commit 219f39ae52)

Co-authored-by: Andy Lee <andy.lee@suse.com>
2026-07-14 14:27:26 +08:00
mergify[bot]andAndy Lee 7493fe2dfc refactor: forklift UI bug and enhancement (#989) (#991)
* fix: hide Virtul machine migration tabs if forklift addon is not enabled



* fix: rename advanced to configurations



* fix: fixed column width



* refactor: review comment



* revert: power on background color



---------


(cherry picked from commit 41cf44d231)

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
2026-07-14 12:07:06 +08:00
mergify[bot]andJack Yu e71d12f67f feat: prevent users from selecting mounted devices (#987) (#990)
(cherry picked from commit 7d09cb7142)

Signed-off-by: Jack Yu <jack.yu@suse.com>
Co-authored-by: Jack Yu <jack.yu@suse.com>
2026-07-14 11:58:48 +08:00
mergify[bot]andmarcelofukumoto d3b77e2e41 feat: forklift UI (#891) (#988)
* feat: forklift poc first commit



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



* feat(forklift): UI based on the FIGMA



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



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



* feat(forklift): Add the succeded state



* Merge the new APIs



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



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



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



* feat(forklift): Added pagination UI



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



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



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



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



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



* feat(forklift): Remove test flags



* feat(forklift): Changed based on review



* feat(forklift): fixed title and button



* feat(forklift): Design changes



* feat(forklift): Changed to Wizard



* feat(forklift): added the provider wizard



* feat(forklift): Fixed some UI changes



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



* feat(forklift): update size



* feat(forklift): small fixes



* feat(forklift): small fixes after Copilot



* feat(forklift): small fixes after Copilot



* feat(forklift): reverted settings.json changes



* feat(forklift): small fixes after Copilot



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



* feat(forklift): Fixed the type for VMware



* feat(forklift): small changes before rebase



* feat: Added new API for the vms



* feat: Fix some labels



* feat: Added some final fixes to structure



* feat: added loading to provider steps



* feat: added comments from copilot review



---------


(cherry picked from commit 560643d299)

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>
Co-authored-by: marcelofukumoto <marceloyfukumoto@gmail.com>
2026-07-13 17:46:33 +08:00
mergify[bot]andRenuka Devi Rajendran 73126b953c feat: Display mgmt interface details under mgmt cluster network (#974) (#986)
(cherry picked from commit c3bb0ea4be)

Signed-off-by: Renuka Devi Rajendran <renuka.rajendran@suse.com>
Co-authored-by: Renuka Devi Rajendran <renuka.rajendran@suse.com>
2026-07-10 12:01:34 +08:00
mergify[bot]andAndy Lee 937afd9c9a chore: limit the rancher to 2.15.0+ for harvester v1.9.0 (#982) (#985)
(cherry picked from commit 3c37f04ef6)

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
2026-07-10 10:59:31 +08:00
mergify[bot]andVolker Theile 3658caf067 feat: Allow user to customize snapshot/backup deadline (#866) (#980)
* 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



* 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



---------


(cherry picked from commit d98db6ba49)

Signed-off-by: Volker Theile <vtheile@suse.com>
Co-authored-by: Volker Theile <vtheile@suse.com>
2026-07-09 18:34:52 +08:00
mergify[bot]andAndy Lee a067751cba feat: allow user specify static IP when VM creation (#973) (#979)
* feat: allow suer give static IP for VM



* feat: add feature flag



---------


(cherry picked from commit 531ed03796)

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
2026-07-09 13:20:22 +08:00
Harvester Bot 94566b2b54 chore: bump version to 1.9.0-rc1 (#978)
Signed-off-by: Harvester Bot <94133267+harvesterhci-io-github-bot@users.noreply.github.com>
2026-07-08 17:47:16 +08:00
mergify[bot]andAndy Lee d47bf1d712 fix: vpc topology should consume NAD labels (#975) (#976)
(cherry picked from commit 59f260eab8)

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
2026-07-08 13:50:17 +08:00
175 changed files with 3547 additions and 19143 deletions

No files matched your search

-12
View File
@@ -1,12 +0,0 @@
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
+3 -7
View File
@@ -8,16 +8,12 @@
- [ ] Yes, the backend owner is @ - [ ] Yes, the backend owner is @
- [ ] No, frontend-only. - [ ] No, frontend-only.
### Related Issue ### Related Issue #
<!-- Link the issue as harvester/harvester#<issue_number> --> <!-- Link the issue as harvester/harvester#<issue_number> -->
harvester/harvester#<issue_number> harvester/harvester#<issue_number>
### Test Steps ### Test screenshot or video (Required)
<!-- Provide the test steps for reviewer to verify the issue --> <!-- Attach screenshot or video of the changes and eventual comparison if you find it necessary -->
1. Go to ... page
### Test screenshot or video
<!-- Attach screenshot or video of the changes and eventual comparison -->
@@ -125,13 +125,6 @@ jobs:
node-version-file: '.nvmrc' node-version-file: '.nvmrc'
cache: 'yarn' cache: 'yarn'
# Tag builds (RC, formal and sprint releases) ship the tag as the package
# version. RC/formal tags already match package.json; sprint tags
# (vX.Y.Z-dev-YYYYMMDD) only share its prefix, so pin it here for the build.
- name: Pin package version to tag
if: ${{ inputs.CI_BUILD_TAG != '' }}
run: ./scripts/bump_version.sh "${{ inputs.CI_BUILD_TAG }}"
- id: ci-build-pkg - id: ci-build-pkg
name: Build pkg name: Build pkg
run: ./scripts/ci-build-pkg.sh harvester run: ./scripts/ci-build-pkg.sh harvester
@@ -58,12 +58,6 @@ jobs:
- name: Setup Nodejs with yarn install - name: Setup Nodejs with yarn install
uses: ./.github/actions/setup uses: ./.github/actions/setup
# The catalog image is tagged with the package.json version. Sprint tags
# (vX.Y.Z-dev-YYYYMMDD) only share its prefix, so pin it to the tag here.
- name: Pin package version to tag
if: ${{ github.ref_type == 'tag' }}
run: ./scripts/bump_version.sh "${{ github.ref_name }}"
- name: Build and push UI image - name: Build and push UI image
run: | run: |
publish="yarn publish-pkgs -cp -r ${{ inputs.registry_target }} -o ${{ inputs.registry_user }}" publish="yarn publish-pkgs -cp -r ${{ inputs.registry_target }} -o ${{ inputs.registry_user }}"
@@ -1,7 +1,6 @@
name: Build Standalone on PR Merge name: Build Standalone on PR Merge
on: on:
workflow_dispatch: # manually trigger on Github Actions only support PR branch pushed to harvester/harvester-ui-extension
push: push:
branches: branches:
- main - main
@@ -30,35 +29,3 @@ jobs:
id-token: write id-token: write
with: with:
CI_BRANCH: ${{github.ref_name}} 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,11 +71,3 @@ jobs:
GITHUB_HEAD_SHA: ${{ github.event.pull_request.head.sha }} GITHUB_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
GITHUB_BEFORE: ${{ github.event.before }} GITHUB_BEFORE: ${{ github.event.before }}
GITHUB_AFTER: ${{ github.event.after }} 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,8 +59,6 @@ You are an expert Senior Software Engineer specializing in Vue.js and TypeScript
| `yarn serve-pkgs` | Serve the locally built extension for testing | | `yarn serve-pkgs` | Serve the locally built extension for testing |
| `yarn lint` | Run ESLint (zero warnings allowed) | | `yarn lint` | Run ESLint (zero warnings allowed) |
| `yarn lint:fix` | Run ESLint with auto-fix | | `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 clean` | Clean build artifacts |
| `yarn agents:generate` | Regenerate `AGENTS.md` from `docs/agents.md/` sources | | `yarn agents:generate` | Regenerate `AGENTS.md` from `docs/agents.md/` sources |
@@ -97,16 +95,6 @@ You are an expert Senior Software Engineer specializing in Vue.js and TypeScript
- ESLint covers `.js`, `.ts`, and `.vue` files. - ESLint covers `.js`, `.ts`, and `.vue` files.
- Always run `yarn lint:fix` before committing. - 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 ### Commit Conventions
- Commits are validated by [commitlint](https://commitlint.js.org/) via a Husky `commit-msg` hook. - Commits are validated by [commitlint](https://commitlint.js.org/) via a Husky `commit-msg` hook.
@@ -199,19 +187,6 @@ To add a feature in a new release, follow these steps:
See https://github.com/harvester/harvester-ui-tests 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 ## Node Dependencies
Dependencies are managed via `package.json` and `yarn` Dependencies are managed via `package.json` and `yarn`
-12
View File
@@ -15,8 +15,6 @@
| `yarn serve-pkgs` | Serve the locally built extension for testing | | `yarn serve-pkgs` | Serve the locally built extension for testing |
| `yarn lint` | Run ESLint (zero warnings allowed) | | `yarn lint` | Run ESLint (zero warnings allowed) |
| `yarn lint:fix` | Run ESLint with auto-fix | | `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 clean` | Clean build artifacts |
| `yarn agents:generate` | Regenerate `AGENTS.md` from `docs/agents.md/` sources | | `yarn agents:generate` | Regenerate `AGENTS.md` from `docs/agents.md/` sources |
@@ -53,16 +51,6 @@
- ESLint covers `.js`, `.ts`, and `.vue` files. - ESLint covers `.js`, `.ts`, and `.vue` files.
- Always run `yarn lint:fix` before committing. - 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 ### Commit Conventions
- Commits are validated by [commitlint](https://commitlint.js.org/) via a Husky `commit-msg` hook. - Commits are validated by [commitlint](https://commitlint.js.org/) via a Husky `commit-msg` hook.
@@ -1,12 +0,0 @@
## 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
@@ -1,46 +0,0 @@
// 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
@@ -1,106 +0,0 @@
/* 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> "};
});
+10 -35
View File
@@ -1,14 +1,13 @@
{ {
"name": "harvester-ui-extension", "name": "harvester-ui-extension",
"version": "1.10.0-dev", "version": "1.9.0-rc7",
"private": false, "private": false,
"engines": { "engines": {
"node": ">=24.0.0" "node": ">=24.0.0"
}, },
"dependencies": { "dependencies": {
"@babel/plugin-transform-class-static-block": "7.29.7", "@babel/plugin-transform-class-static-block": "7.29.7",
"@novnc/novnc": "1.7.0", "@rancher/shell": "3.0.12-rc.7",
"@rancher/shell": "3.0.14",
"@vue-flow/background": "^1.3.0", "@vue-flow/background": "^1.3.0",
"@vue-flow/controls": "^1.1.1", "@vue-flow/controls": "^1.1.1",
"@vue-flow/core": "^1.33.5", "@vue-flow/core": "^1.33.5",
@@ -16,7 +15,6 @@
"cache-loader": "^4.1.0", "cache-loader": "^4.1.0",
"color": "4.2.3", "color": "4.2.3",
"ip": "2.0.1", "ip": "2.0.1",
"ipaddr.js": "2.4.0",
"@xterm/xterm": "6.0.0", "@xterm/xterm": "6.0.0",
"@xterm/addon-fit": "0.11.0", "@xterm/addon-fit": "0.11.0",
"@xterm/addon-search": "0.16.0", "@xterm/addon-search": "0.16.0",
@@ -29,51 +27,36 @@
"yaml": "^2.5.1" "yaml": "^2.5.1"
}, },
"resolutions": { "resolutions": {
"@novnc/novnc": "1.7.0", "@types/node": "25.9.5",
"@tootallnate/once": "^2.0.1",
"@types/lodash": "4.17.25",
"@types/node": "25.3.3",
"cookie": "0.7.2",
"cronstrue": "2.59.0", "cronstrue": "2.59.0",
"d3-color": "3.1.0", "d3-color": "3.1.0",
"**/diff2html/diff": "5.2.2",
"ejs": "3.1.10", "ejs": "3.1.10",
"follow-redirects": "1.16.0", "follow-redirects": "1.16.0",
"glob": "7.2.3", "glob": "7.2.3",
"glob-parent": "6.0.2", "glob-parent": "6.0.2",
"json5": "2.2.3", "json5": "2.2.3",
"markdown-it": "14.3.1", "@types/lodash": "4.17.25",
"merge": "2.1.1", "merge": "2.1.1",
"node-forge": "1.4.0", "node-forge": "1.4.0",
"nth-check": "2.1.1", "nth-check": "2.1.1",
"postcss": "8.5.26", "qs": "6.15.3",
"postcss-selector-parser": "7.1.6",
"qs": "6.16.0",
"roarr": "7.21.7", "roarr": "7.21.7",
"semver": "7.5.4", "semver": "7.8.5",
"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" "@vue/cli-service/html-webpack-plugin": "^5.0.0"
}, },
"scripts": { "scripts": {
"dev": "NODE_ENV=dev ./node_modules/.bin/vue-cli-service serve", "dev": "NODE_ENV=dev ./node_modules/.bin/vue-cli-service serve",
"build": "./node_modules/.bin/vue-cli-service build", "build": "./node_modules/.bin/vue-cli-service build",
"clean": "./node_modules/@rancher/shell/scripts/clean", "clean": "./node_modules/@rancher/shell/scripts/clean",
"lint": "./node_modules/@rancher/shell/scripts/lint --max-warnings 0 --ext .js,.ts,.vue .", "lint": "./node_modules/.bin/eslint --max-warnings 0 --ext .js,.ts,.vue .",
"lint:fix": "./node_modules/@rancher/shell/scripts/lint --fix --max-warnings 0 --ext .js,.ts,.vue .", "lint:fix": "./node_modules/.bin/eslint --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", "build-pkg": "./node_modules/@rancher/shell/scripts/build-pkg.sh",
"serve-pkgs": "./node_modules/@rancher/shell/scripts/serve-pkgs", "serve-pkgs": "./node_modules/@rancher/shell/scripts/serve-pkgs",
"publish-pkgs": "./node_modules/@rancher/shell/scripts/extension/publish", "publish-pkgs": "./node_modules/@rancher/shell/scripts/extension/publish",
"parse-tag-name": "./node_modules/@rancher/shell/scripts/extension/parse-tag-name", "parse-tag-name": "./node_modules/@rancher/shell/scripts/extension/parse-tag-name",
"commitlint": "commitlint --edit", "commitlint": "commitlint --edit",
"prepare": "husky", "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": { "devDependencies": {
"@commitlint/load": "^19.8.1", "@commitlint/load": "^19.8.1",
@@ -81,14 +64,6 @@
"@commitlint/config-conventional": "^19.8.1", "@commitlint/config-conventional": "^19.8.1",
"eslint-plugin-node": "^11.1.0", "eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^7.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"
} }
} }
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="3326" height="324" data-surface="transparent" viewBox="0 0 3326.24 324.48"><path fill="#30ba78" d="M535.12 100.88c-3.04 2-7.12 2-10.16 0-4.96-3.28-5.44-10.24-1.44-14.24a9.08 9.08 0 0 1 13.04 0c4 4 3.52 10.88-1.44 14.24m14.48-20.16c5.76 24.64-16.32 46.72-40.96 40.96-12.56-2.96-22.48-12.88-25.44-25.44-5.76-24.56 16.32-46.72 40.96-40.96 12.56 2.96 22.48 12.88 25.44 25.36M383.92 213.12c2.8 4.08 5.12 7.92 6.48 11.84.88 2.8 2.08 6.4 4.88 7.92l.48.24c5.04 1.84 17.92 1.52 17.92 1.52h23.76c2 0 19.84 0 19.44-2-2.16-9.52-13.2-11.28-21.6-16.24-7.76-4.64-15.04-9.84-18.4-18.88-1.76-4.64-.72-15.36 2.32-19.28 2.16-2.8 5.36-4.72 8.88-5.44 3.84-.8 7.76-.08 11.6.24 4.72.48 9.36 1.36 14.08 1.92 9.12 1.2 18.24 1.68 27.44 1.44 15.12-.4 30.24-2.8 44.56-7.68 10-3.36 19.84-7.92 28.32-14.24 9.68-7.2 7.12-6.48-2.64-5.52-11.76 1.2-23.6 1.36-35.36.72-10.96-.64-21.84-1.92-31.76-7.04-7.84-4-14.56-8.08-20.72-14.32-.96-.96-1.52-3.68.16-5.44 1.68-1.68 5.12-.72 6.24.16 10.8 9.04 26.96 16.48 43.68 17.28 9.04.48 17.84.64 26.88.24 4.48-.24 11.36-.16 15.84-.24 2.32 0 8.72.64 9.92-1.84.4-.72.32-1.52.32-2.4-1.36-36.16-4-76.96-41.84-94.24-28.24-12.88-70.56-32.88-88.4-41.2-4.16-2-8.96 1.12-8.96 5.76 0 12.08.64 29.44.64 45.2-8.56-8.72-22.96-14.24-34-19.28-12.48-5.76-25.36-10.56-38.48-14.64-26.4-8.16-53.76-13.2-81.2-15.92-31.12-3.12-62.88-1.6-93.52 4.72C130.32 16.96 80.64 41.28 42.96 76.8 19.52 98.56 1.36 129.6.16 161.04c-1.76 44.56 10.72 68.48 33.68 93.12 36.56 39.28 115.28 44.8 147.12-1.84 14.32-20.96 17.44-49.44 7.04-72.56-10.4-23.2-34.32-39.92-59.68-40.8-19.68-.64-40.64 9.36-48.16 27.6-5.76 13.92-2.48 31.04 8 41.84 4.08 4.24 9.6 7.68 15.68 6.32 3.52-.8 6.56-3.44 7.04-7.12.8-5.36-3.84-8.8-6.72-12.88-5.2-7.36-4.16-18.48 2.32-24.72 5.44-5.28 13.6-6.88 21.2-6.88 7.12 0 14.32 1.28 20.48 4.88 8.64 5.04 14.32 14.32 16.32 24.08 5.92 29.28-17.84 53.04-50.08 54.88-16.48.96-33.28-3.36-46.16-13.68-32.56-26.24-40.56-79.84-3.28-108.48 35.36-27.2 80-20.16 106.32-6.08 21.04 11.28 36.8 29.76 48.64 50.24 6 10.24 11.04 21.04 15.76 31.92 4.56 10.48 8.8 21.04 17.84 28.72 6 5.12 13.44 4.88 21.36 4.88h45.04c6.08 0 4.64-4.08 2-6.8-6-6.08-14.56-7.44-22.48-9.68-18.16-4.96-16.32-29.04-11.28-29.04 16.24 0 16.72.48 30.96.32 20.48-.32 26.72-1.44 42.72 4.48 8.56 3.2 16.8 11.52 22.16 19.2"/><path fill="#ffffff" d="M717.92 232.96c48.64 0 81.6-27.84 81.6-70.72 0-80.96-112.64-49.28-112.64-97.92 0-18.88 15.36-31.04 38.72-31.04 17.28 0 30.08 6.72 43.2 19.84l24.96-24.96C778.72 11.2 754.72 0 725.92 0c-47.04 0-78.08 26.56-78.08 68.16 0 77.44 111.68 48.32 111.68 99.84 0 18.88-15.04 31.68-40.32 31.68-18.88 0-34.88-7.36-52.16-24.96l-24.32 24.32c17.28 20.48 41.6 33.92 75.2 33.92m203.2 0c52.48 0 87.04-27.2 87.04-81.92V4.48H968.8v143.36c0 32.64-18.88 48.64-47.68 48.64s-47.36-16-47.36-48.64V4.48H834.4v146.56c0 54.72 33.92 81.92 86.72 81.92m195.2 0c48.64 0 81.6-27.84 81.6-70.72 0-80.96-112.64-49.28-112.64-97.92 0-18.88 15.36-31.04 38.72-31.04 17.28 0 30.08 6.72 43.2 19.84l24.96-24.96C1177.12 11.2 1153.12 0 1124.32 0c-47.04 0-78.08 26.56-78.08 68.16 0 77.44 111.68 48.32 111.68 99.84 0 18.88-15.04 31.68-40.32 31.68-18.88 0-34.88-7.36-52.16-24.96l-24.32 24.32c17.28 20.48 41.6 33.92 75.2 33.92m153.6-4.48h109.12v-35.84h-96c-6.4 0-11.52-5.12-11.52-11.52v-48h100.8V98.88h-100.8V51.84c0-6.4 5.12-11.52 11.52-11.52h96V4.48h-109.12c-21.76 0-37.12 15.68-37.12 37.44v149.12c0 21.76 15.36 37.44 37.12 37.44m293.12 0h29.12l83.52-224h-29.12l-68.8 189.76-69.12-189.76h-28.8zm145.6-187.84h28.8V3.52h-28.8zm1.6 187.84h25.6V74.56h-55.68v22.4h30.08zm73.92 0h25.92v-91.2c0-25.6 14.72-37.76 39.68-37.76h15.04v-25.6h-13.12c-18.88 0-34.88 5.76-42.56 25.28V74.56h-24.96zm163.52 0h23.68V206.4H1948c-9.6 0-17.28-7.36-17.28-17.28V96.96h40.64v-22.4h-40.64V36.48h-25.6v38.08h-27.84v22.4h27.84v90.56c0 29.76 21.44 40.96 42.56 40.96m115.52 3.2c16 0 37.44-6.08 50.24-26.24v23.04h23.04V74.56h-25.6v87.04c0 31.04-19.52 46.4-42.56 46.4-22.4 0-38.72-11.2-38.72-44.16V74.56h-25.92v93.76c0 44.16 25.28 63.36 59.52 63.36m167.36 0c21.44 0 37.44-6.4 46.72-18.56l.32 15.36h23.04c-.64-16.64-.96-33.6-.96-50.56v-49.28c0-38.08-24.32-57.28-60.48-57.28-23.36 0-47.36 8.32-61.12 24l12.16 18.24c12.16-12.8 31.04-18.88 47.68-18.88 22.08 0 36.16 9.92 36.16 35.2v19.2c-9.6-6.72-23.36-10.56-40.32-10.56-34.88 0-61.12 20.16-61.12 47.04 0 27.2 22.72 46.08 57.92 46.08m6.72-19.52c-23.68 0-38.4-11.2-38.4-26.56 0-15.68 14.72-26.24 38.08-26.24 23.68 0 37.44 10.56 37.44 26.24s-13.76 26.56-37.12 26.56m150.08 16.32h16V206.4h-14.72c-9.6 0-16.96-7.04-16.96-16.96V-5.12h-54.08v22.08h28.16v172.16c0 24 16.64 39.36 41.6 39.36m52.48-187.84h28.8V3.52h-28.8zm1.6 187.84h25.6V74.56h-55.68v22.4h30.08zm61.44 0h116.8v-22.72h-86.08l84.8-110.4v-20.8h-114.56V97.6h82.88l-83.84 110.72zm198.4 3.2c21.44 0 37.44-6.4 46.72-18.56l.32 15.36h23.04c-.64-16.64-.96-33.6-.96-50.56v-49.28c0-38.08-24.32-57.28-60.48-57.28-23.36 0-47.36 8.32-61.12 24l12.16 18.24c12.16-12.8 31.04-18.88 47.68-18.88 22.08 0 36.16 9.92 36.16 35.2v19.2c-9.6-6.72-23.36-10.56-40.32-10.56-3Line truncated

Before

Width:  |  Height:  |  Size: 5.8 KiB

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="3326" height="324" data-surface="transparent" viewBox="0 0 3326.24 324.48"><path fill="#30ba78" d="M535.12 100.88c-3.04 2-7.12 2-10.16 0-4.96-3.28-5.44-10.24-1.44-14.24a9.08 9.08 0 0 1 13.04 0c4 4 3.52 10.88-1.44 14.24m14.48-20.16c5.76 24.64-16.32 46.72-40.96 40.96-12.56-2.96-22.48-12.88-25.44-25.44-5.76-24.56 16.32-46.72 40.96-40.96 12.56 2.96 22.48 12.88 25.44 25.36M383.92 213.12c2.8 4.08 5.12 7.92 6.48 11.84.88 2.8 2.08 6.4 4.88 7.92l.48.24c5.04 1.84 17.92 1.52 17.92 1.52h23.76c2 0 19.84 0 19.44-2-2.16-9.52-13.2-11.28-21.6-16.24-7.76-4.64-15.04-9.84-18.4-18.88-1.76-4.64-.72-15.36 2.32-19.28 2.16-2.8 5.36-4.72 8.88-5.44 3.84-.8 7.76-.08 11.6.24 4.72.48 9.36 1.36 14.08 1.92 9.12 1.2 18.24 1.68 27.44 1.44 15.12-.4 30.24-2.8 44.56-7.68 10-3.36 19.84-7.92 28.32-14.24 9.68-7.2 7.12-6.48-2.64-5.52-11.76 1.2-23.6 1.36-35.36.72-10.96-.64-21.84-1.92-31.76-7.04-7.84-4-14.56-8.08-20.72-14.32-.96-.96-1.52-3.68.16-5.44 1.68-1.68 5.12-.72 6.24.16 10.8 9.04 26.96 16.48 43.68 17.28 9.04.48 17.84.64 26.88.24 4.48-.24 11.36-.16 15.84-.24 2.32 0 8.72.64 9.92-1.84.4-.72.32-1.52.32-2.4-1.36-36.16-4-76.96-41.84-94.24-28.24-12.88-70.56-32.88-88.4-41.2-4.16-2-8.96 1.12-8.96 5.76 0 12.08.64 29.44.64 45.2-8.56-8.72-22.96-14.24-34-19.28-12.48-5.76-25.36-10.56-38.48-14.64-26.4-8.16-53.76-13.2-81.2-15.92-31.12-3.12-62.88-1.6-93.52 4.72C130.32 16.96 80.64 41.28 42.96 76.8 19.52 98.56 1.36 129.6.16 161.04c-1.76 44.56 10.72 68.48 33.68 93.12 36.56 39.28 115.28 44.8 147.12-1.84 14.32-20.96 17.44-49.44 7.04-72.56-10.4-23.2-34.32-39.92-59.68-40.8-19.68-.64-40.64 9.36-48.16 27.6-5.76 13.92-2.48 31.04 8 41.84 4.08 4.24 9.6 7.68 15.68 6.32 3.52-.8 6.56-3.44 7.04-7.12.8-5.36-3.84-8.8-6.72-12.88-5.2-7.36-4.16-18.48 2.32-24.72 5.44-5.28 13.6-6.88 21.2-6.88 7.12 0 14.32 1.28 20.48 4.88 8.64 5.04 14.32 14.32 16.32 24.08 5.92 29.28-17.84 53.04-50.08 54.88-16.48.96-33.28-3.36-46.16-13.68-32.56-26.24-40.56-79.84-3.28-108.48 35.36-27.2 80-20.16 106.32-6.08 21.04 11.28 36.8 29.76 48.64 50.24 6 10.24 11.04 21.04 15.76 31.92 4.56 10.48 8.8 21.04 17.84 28.72 6 5.12 13.44 4.88 21.36 4.88h45.04c6.08 0 4.64-4.08 2-6.8-6-6.08-14.56-7.44-22.48-9.68-18.16-4.96-16.32-29.04-11.28-29.04 16.24 0 16.72.48 30.96.32 20.48-.32 26.72-1.44 42.72 4.48 8.56 3.2 16.8 11.52 22.16 19.2"/><path fill="#0c322c" d="M717.92 232.96c48.64 0 81.6-27.84 81.6-70.72 0-80.96-112.64-49.28-112.64-97.92 0-18.88 15.36-31.04 38.72-31.04 17.28 0 30.08 6.72 43.2 19.84l24.96-24.96C778.72 11.2 754.72 0 725.92 0c-47.04 0-78.08 26.56-78.08 68.16 0 77.44 111.68 48.32 111.68 99.84 0 18.88-15.04 31.68-40.32 31.68-18.88 0-34.88-7.36-52.16-24.96l-24.32 24.32c17.28 20.48 41.6 33.92 75.2 33.92m203.2 0c52.48 0 87.04-27.2 87.04-81.92V4.48H968.8v143.36c0 32.64-18.88 48.64-47.68 48.64s-47.36-16-47.36-48.64V4.48H834.4v146.56c0 54.72 33.92 81.92 86.72 81.92m195.2 0c48.64 0 81.6-27.84 81.6-70.72 0-80.96-112.64-49.28-112.64-97.92 0-18.88 15.36-31.04 38.72-31.04 17.28 0 30.08 6.72 43.2 19.84l24.96-24.96C1177.12 11.2 1153.12 0 1124.32 0c-47.04 0-78.08 26.56-78.08 68.16 0 77.44 111.68 48.32 111.68 99.84 0 18.88-15.04 31.68-40.32 31.68-18.88 0-34.88-7.36-52.16-24.96l-24.32 24.32c17.28 20.48 41.6 33.92 75.2 33.92m153.6-4.48h109.12v-35.84h-96c-6.4 0-11.52-5.12-11.52-11.52v-48h100.8V98.88h-100.8V51.84c0-6.4 5.12-11.52 11.52-11.52h96V4.48h-109.12c-21.76 0-37.12 15.68-37.12 37.44v149.12c0 21.76 15.36 37.44 37.12 37.44m293.12 0h29.12l83.52-224h-29.12l-68.8 189.76-69.12-189.76h-28.8zm145.6-187.84h28.8V3.52h-28.8zm1.6 187.84h25.6V74.56h-55.68v22.4h30.08zm73.92 0h25.92v-91.2c0-25.6 14.72-37.76 39.68-37.76h15.04v-25.6h-13.12c-18.88 0-34.88 5.76-42.56 25.28V74.56h-24.96zm163.52 0h23.68V206.4H1948c-9.6 0-17.28-7.36-17.28-17.28V96.96h40.64v-22.4h-40.64V36.48h-25.6v38.08h-27.84v22.4h27.84v90.56c0 29.76 21.44 40.96 42.56 40.96m115.52 3.2c16 0 37.44-6.08 50.24-26.24v23.04h23.04V74.56h-25.6v87.04c0 31.04-19.52 46.4-42.56 46.4-22.4 0-38.72-11.2-38.72-44.16V74.56h-25.92v93.76c0 44.16 25.28 63.36 59.52 63.36m167.36 0c21.44 0 37.44-6.4 46.72-18.56l.32 15.36h23.04c-.64-16.64-.96-33.6-.96-50.56v-49.28c0-38.08-24.32-57.28-60.48-57.28-23.36 0-47.36 8.32-61.12 24l12.16 18.24c12.16-12.8 31.04-18.88 47.68-18.88 22.08 0 36.16 9.92 36.16 35.2v19.2c-9.6-6.72-23.36-10.56-40.32-10.56-34.88 0-61.12 20.16-61.12 47.04 0 27.2 22.72 46.08 57.92 46.08m6.72-19.52c-23.68 0-38.4-11.2-38.4-26.56 0-15.68 14.72-26.24 38.08-26.24 23.68 0 37.44 10.56 37.44 26.24s-13.76 26.56-37.12 26.56m150.08 16.32h16V206.4h-14.72c-9.6 0-16.96-7.04-16.96-16.96V-5.12h-54.08v22.08h28.16v172.16c0 24 16.64 39.36 41.6 39.36m52.48-187.84h28.8V3.52h-28.8zm1.6 187.84h25.6V74.56h-55.68v22.4h30.08zm61.44 0h116.8v-22.72h-86.08l84.8-110.4v-20.8h-114.56V97.6h82.88l-83.84 110.72zm198.4 3.2c21.44 0 37.44-6.4 46.72-18.56l.32 15.36h23.04c-.64-16.64-.96-33.6-.96-50.56v-49.28c0-38.08-24.32-57.28-60.48-57.28-23.36 0-47.36 8.32-61.12 24l12.16 18.24c12.16-12.8 31.04-18.88 47.68-18.88 22.08 0 36.16 9.92 36.16 35.2v19.2c-9.6-6.72-23.36-10.56-40.32-10.56-3Line truncated

Before

Width:  |  Height:  |  Size: 5.8 KiB

+5 -39
View File
@@ -6,30 +6,26 @@ import ModalWithCard from '@shell/components/ModalWithCard';
import LabeledSelect from '@shell/components/form/LabeledSelect'; import LabeledSelect from '@shell/components/form/LabeledSelect';
import { Banner } from '@components/Banner'; import { Banner } from '@components/Banner';
import { HCI as HCI_ANNOTATIONS } from '@pkg/harvester/config/labels-annotations'; import { HCI as HCI_ANNOTATIONS } from '@pkg/harvester/config/labels-annotations';
import { STORAGE_CLASS } from '@shell/config/types';
import { HCI } from '../types'; import { HCI } from '../types';
import UpgradeInfo from './UpgradeInfo'; import UpgradeInfo from './UpgradeInfo';
import UpgradeRepositoryStorageClass, { getUpgradeRepositoryStorageClassDefault } from './UpgradeRepositoryStorageClass';
export default { export default {
name: 'HarvesterUpgrade', name: 'HarvesterUpgrade',
components: { components: {
Checkbox, ModalWithCard, LabeledSelect, Banner, UpgradeInfo, UpgradeRepositoryStorageClass Checkbox, ModalWithCard, LabeledSelect, Banner, UpgradeInfo
}, },
async fetch() { async fetch() {
const inStore = this.$store.getters['currentProduct'].inStore; const inStore = this.$store.getters['currentProduct'].inStore;
const res = await allHash({ const res = await allHash({
upgradeVersion: this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.SETTING }), upgradeVersion: this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.SETTING }),
versions: this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.VERSION }), versions: this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.VERSION }),
upgrade: this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.UPGRADE }), upgrade: this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.UPGRADE }),
storageClasses: this.$store.dispatch(`${ inStore }/findAll`, { type: STORAGE_CLASS }),
}); });
this.upgrade = res.upgrade; this.upgrade = res.upgrade;
this.storageClassName = getUpgradeRepositoryStorageClassDefault(res.storageClasses);
}, },
data() { data() {
@@ -39,7 +35,6 @@ export default {
errors: '', errors: '',
selectMode: true, selectMode: true,
version: '', version: '',
storageClassName: '',
enableLogging: true, enableLogging: true,
skipSingleReplicaDetachedVol: false, skipSingleReplicaDetachedVol: false,
readyReleaseNote: false, readyReleaseNote: false,
@@ -64,10 +59,6 @@ export default {
return this.versionOptions.length > 0 && !this.isUpgradeInProgress; return this.versionOptions.length > 0 && !this.isUpgradeInProgress;
}, },
canSubmitUpgrade() {
return this.readyReleaseNote && (!this.repositoryStorageClassEnabled || !!this.storageClassName);
},
versionOptions() { versionOptions() {
const versions = this.$store.getters['harvester/all'](HCI.VERSION) || []; const versions = this.$store.getters['harvester/all'](HCI.VERSION) || [];
@@ -84,16 +75,6 @@ export default {
return this.$store.getters['harvester/schemaFor'](HCI.UPGRADE_LOG); return this.$store.getters['harvester/schemaFor'](HCI.UPGRADE_LOG);
}, },
storageClasses() {
const inStore = this.$store.getters['currentProduct'].inStore;
return this.$store.getters[`${ inStore }/all`](STORAGE_CLASS) || [];
},
repositoryStorageClassEnabled() {
return this.$store.getters['harvester-common/getFeatureEnabled']('repositoryStorageClass');
},
skipSingleReplicaDetachedVolFeatureEnabled() { skipSingleReplicaDetachedVolFeatureEnabled() {
return this.$store.getters['harvester-common/getFeatureEnabled']('skipSingleReplicaDetachedVol'); return this.$store.getters['harvester-common/getFeatureEnabled']('skipSingleReplicaDetachedVol');
}, },
@@ -143,18 +124,10 @@ export default {
upgradeValue.spec.logEnabled = this.enableLogging; upgradeValue.spec.logEnabled = this.enableLogging;
} }
if (this.repositoryStorageClassEnabled && this.storageClassName) {
upgradeValue.metadata.annotations = {
...upgradeValue.metadata.annotations,
[HCI_ANNOTATIONS.UPGRADE_STORAGE_CLASS]: this.storageClassName
};
}
const proxyResource = await this.$store.dispatch('harvester/create', upgradeValue); const proxyResource = await this.$store.dispatch('harvester/create', upgradeValue);
try { try {
await proxyResource.save(); await proxyResource.save();
proxyResource.notifyGeneratedName?.();
this.cancel(); this.cancel();
} catch (err) { } catch (err) {
@@ -230,13 +203,6 @@ export default {
:clearable="true" :clearable="true"
/> />
<UpgradeRepositoryStorageClass
v-if="repositoryStorageClassEnabled"
v-model:value="storageClassName"
class="mb-10"
:storage-classes="storageClasses"
/>
<div <div
v-if="canEnableLogging" v-if="canEnableLogging"
class="mb-5" class="mb-5"
@@ -296,7 +262,7 @@ export default {
<t k="generic.close" /> <t k="generic.close" />
</button> </button>
<button <button
:disabled="!canSubmitUpgrade" :disabled="!readyReleaseNote"
class="btn role-tertiary bg-primary" class="btn role-tertiary bg-primary"
@click.prevent="handleUpgrade" @click.prevent="handleUpgrade"
> >
+10 -4
View File
@@ -10,7 +10,6 @@ import { docLink } from '../utils/feature-flags';
const CATEGORY = { const CATEGORY = {
ui: [ ui: [
'branding', 'branding',
HCI_SETTING.SERVER_FLAVOR,
'ui-source', 'ui-source',
'ui-index', 'ui-index',
] ]
@@ -54,7 +53,7 @@ export default {
}; };
}, },
computed: { ...mapGetters({ t: 'i18n/t', isHarvesterPrime: 'harvester-common/isHarvesterPrime' }) }, computed: { ...mapGetters({ t: 'i18n/t' }) },
watch: { watch: {
settings: { settings: {
@@ -141,6 +140,10 @@ export default {
filterCategorySettings() { filterCategorySettings() {
return this.settings.filter((s) => { return this.settings.filter((s) => {
if (!this.getFeatureEnabled(s.featureFlag)) {
return false;
}
if (this.category !== 'advanced') { if (this.category !== 'advanced') {
return (CATEGORY[this.category] || []).find((item) => item === s.id); return (CATEGORY[this.category] || []).find((item) => item === s.id);
} else if (this.category === 'advanced') { } else if (this.category === 'advanced') {
@@ -151,6 +154,10 @@ export default {
}) || []; }) || [];
}, },
getFeatureEnabled(id) {
return id ? this.$store.getters['harvester-common/getFeatureEnabled'](id) : true;
},
getSettingOption(id) { getSettingOption(id) {
return HCI_ALLOWED_SETTINGS.find((setting) => setting.id === id); return HCI_ALLOWED_SETTINGS.find((setting) => setting.id === id);
}, },
@@ -262,8 +269,7 @@ export default {
v-if="!setting.hide" v-if="!setting.hide"
class="settings-value" class="settings-value"
> >
<pre v-if="setting.id === 'branding' && isHarvesterPrime">{{ $store.getters['harvester-common/privateLabel'] }}</pre> <pre v-if="setting.kind === 'json'">{{ setting.json }}</pre>
<pre v-else-if="setting.kind === 'json'">{{ setting.json }}</pre>
<pre v-else-if="setting.kind === 'multiline'">{{ setting.data.value || setting.data.default }}</pre> <pre v-else-if="setting.kind === 'multiline'">{{ setting.data.value || setting.data.default }}</pre>
<pre v-else-if="setting.kind === 'enum'">{{ t(setting.enum) }}</pre> <pre v-else-if="setting.kind === 'enum'">{{ t(setting.enum) }}</pre>
<pre v-else-if="setting.kind === 'custom' && setting.custom">{{ setting.custom }}</pre> <pre v-else-if="setting.kind === 'custom' && setting.custom">{{ setting.custom }}</pre>
@@ -1,83 +0,0 @@
<script>
import LabeledSelect from '@shell/components/form/LabeledSelect';
import { LVM_DRIVER } from '../models/harvester/storage.k8s.io.storageclass';
import { isInternalStorageClass } from '../utils/storage-class';
export function getUpgradeRepositoryStorageClassDefault(storageClasses) {
return storageClasses.find((storageClass) => storageClass.isDefault &&
!storageClass.parameters?.backingImage &&
storageClass.provisioner !== LVM_DRIVER &&
!isInternalStorageClass(storageClass.name))?.name || '';
}
export default {
name: 'UpgradeRepositoryStorageClass',
components: { LabeledSelect },
props: {
value: {
type: String,
default: '',
},
storageClasses: {
type: Array,
default: () => [],
},
disabled: {
type: Boolean,
default: false,
},
},
emits: ['update:value'],
computed: {
storageClassOptions() {
const t = this.$store.getters['i18n/t'];
return this.storageClasses
.filter((storageClass) => !storageClass.parameters?.backingImage && storageClass.provisioner !== LVM_DRIVER)
.map((storageClass) => {
let label = storageClass.isDefault ? `${ storageClass.name } (${ t('generic.default') })` : storageClass.name;
let disabled = false;
if (isInternalStorageClass(storageClass.name)) {
label += ` (${ t('harvester.storage.internal.label') })`;
disabled = true;
}
return {
label,
value: storageClass.name,
disabled
};
});
},
},
};
</script>
<template>
<LabeledSelect
:value="value"
:label="t('harvester.upgradePage.repositoryStorageClass')"
:tooltip="t('harvester.upgradePage.repositoryStorageClassTooltip')"
:placeholder="t('harvester.upgradePage.repositoryStorageClassPlaceholder')"
:options="storageClassOptions"
:disabled="disabled"
required
@update:value="$emit('update:value', $event)"
>
<template #no-options="{ searching }">
<span
v-if="!searching"
class="text-muted"
>
{{ t('harvester.upgradePage.repositoryStorageClassNoOptions', null, true) }}
</span>
</template>
</LabeledSelect>
</template>
@@ -1,86 +0,0 @@
import { HCI as HCI_ANNOTATIONS } from '@pkg/harvester/config/labels-annotations';
import HarvesterUpgrade from '../HarvesterUpgrade.vue';
const save = jest.fn().mockResolvedValue();
const upgrade = { notifyGeneratedName: jest.fn(), save };
function createForm(storageClassName = '', repositoryStorageClassEnabled = true) {
return {
version: 'v1.10.0',
storageClassName,
repositoryStorageClassEnabled,
canEnableLogging: false,
enableLogging: true,
skipSingleReplicaDetachedVolFeatureEnabled: false,
skipSingleReplicaDetachedVol: false,
cancel: jest.fn(),
errors: '',
$store: { dispatch: jest.fn().mockResolvedValue(upgrade) }
};
}
describe('component: HarvesterUpgrade', () => {
it('uses the shared Upgrade Repository StorageClass selector', () => {
expect(HarvesterUpgrade.components.UpgradeRepositoryStorageClass).toBeDefined();
});
it('leaves the default empty when it is unavailable for upgrade repositories', async() => {
const form = {
upgrade: [],
storageClassName: 'previous',
$store: {
getters: { currentProduct: { inStore: 'harvester' } },
dispatch: jest.fn()
.mockResolvedValueOnce([])
.mockResolvedValueOnce([])
.mockResolvedValueOnce([])
.mockResolvedValueOnce([
{
name: 'lvm-local', isDefault: true, provisioner: 'lvm.driver.harvesterhci.io'
},
{ name: 'fast' }
])
}
};
await HarvesterUpgrade.fetch.call(form);
expect(form.storageClassName).toBe('');
});
it('blocks the upgrade when no StorageClass is selected', () => {
const canSubmitUpgrade = HarvesterUpgrade.computed.canSubmitUpgrade;
expect(canSubmitUpgrade.call({
readyReleaseNote: true,
repositoryStorageClassEnabled: true,
storageClassName: ''
})).toBe(false);
});
it('saves the selected StorageClass as an Upgrade annotation', async() => {
const form = createForm('fast');
await HarvesterUpgrade.methods.handleUpgrade.call(form);
expect(form.$store.dispatch).toHaveBeenCalledWith('harvester/create', expect.objectContaining({
metadata: expect.objectContaining({ annotations: { [HCI_ANNOTATIONS.UPGRADE_STORAGE_CLASS]: 'fast' } }),
spec: { version: 'v1.10.0' }
}));
});
it('omits the repository StorageClass when the feature is disabled', async() => {
const form = createForm('fast', false);
await HarvesterUpgrade.methods.handleUpgrade.call(form);
expect(form.$store.dispatch).toHaveBeenCalledWith('harvester/create', {
type: 'harvesterhci.io.upgrade',
metadata: {
generateName: 'hvst-upgrade-',
namespace: 'harvester-system'
},
spec: { version: 'v1.10.0' }
});
});
});
@@ -1,40 +0,0 @@
import UpgradeRepositoryStorageClass, { getUpgradeRepositoryStorageClassDefault } from '../UpgradeRepositoryStorageClass.vue';
const storageClasses = [
{ name: 'fast', isDefault: true },
{ name: 'image-cache', parameters: { backingImage: 'image' } },
{ name: 'lvm-local', provisioner: 'lvm.driver.harvesterhci.io' },
{ name: 'longhorn-static' },
{ name: 'slow' }
];
describe('component: UpgradeRepositoryStorageClass', () => {
it('omits backing-image and LVM StorageClasses while disabling internal classes', () => {
const form = {
storageClasses,
$store: { getters: { 'i18n/t': (key) => key } }
};
expect(UpgradeRepositoryStorageClass.computed.storageClassOptions.call(form)).toStrictEqual([
{
label: 'fast (generic.default)', value: 'fast', disabled: false
},
{
label: 'longhorn-static (harvester.storage.internal.label)', value: 'longhorn-static', disabled: true
},
{
label: 'slow', value: 'slow', disabled: false
},
]);
});
it('does not use an unavailable StorageClass as the default', () => {
expect(getUpgradeRepositoryStorageClassDefault([
{
name: 'lvm-local', isDefault: true, provisioner: 'lvm.driver.harvesterhci.io'
},
{ name: 'longhorn-static' },
{ name: 'fast' }
])).toBe('');
});
});
@@ -1,357 +0,0 @@
<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, hasIgnored, ignoreRuleName, ignoredResourceCount, resourceIgnoredBy, severityColor
} from '../../utils/component-health';
const props = defineProps({
rows: {
type: Array,
required: true,
},
ignoreRules: {
type: Array,
default: () => [],
},
// 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([]);
const shownIgnoredIds = ref([]);
// a check ignored as a whole lists all its resources, the others only the ones still reported
function listedResourceNames(row) {
return row.ignored ? allAffectedResourceNames(row) : activeAffectedResourceNames(row);
}
function ignoredResourceNames(row) {
const active = activeAffectedResourceNames(row);
return allAffectedResourceNames(row).filter((name) => !active.includes(name));
}
// 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);
}
// the ignored resources come after the others, once their link is used
function visibleAffectedResourceNames(row) {
const names = listedResourceNames(row);
const shown = expandedResourceIds.value.includes(row.id) ? names : names.slice(0, AFFECTED_RESOURCES_TRUNCATE_COUNT);
return shownIgnoredIds.value.includes(row.id) ? [...shown, ...ignoredResourceNames(row)] : shown;
}
function remainingAffectedResourcesCount(row) {
return Math.max(listedResourceNames(row).length - AFFECTED_RESOURCES_TRUNCATE_COUNT, 0);
}
function isResourceIgnored(row, name) {
return row.ignored || !!resourceIgnoredBy(row, name);
}
// the ignored resources of a check that is still reported, which have a link of their own
function ignoredLinkCount(row) {
return row.ignored ? 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, 'has-ignored': hasIgnored(row) }">
{{ 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="allAffectedResourceNames(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>
<div
v-if="remainingAffectedResourcesCount(row) || ignoredLinkCount(row)"
class="affected-links"
>
<RcButton
v-if="remainingAffectedResourcesCount(row)"
variant="link"
size="small"
class="compact-link more-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>
<RcButton
v-if="ignoredLinkCount(row)"
variant="link"
size="small"
class="compact-link ignored-link"
:aria-expanded="shownIgnoredIds.includes(row.id)"
@click="toggleId(shownIgnoredIds, row.id)"
>
{{ shownIgnoredIds.includes(row.id) ? t('harvester.dashboard.sections.componentHealth.ignore.hideIgnored') : t('harvester.dashboard.sections.componentHealth.ignore.plusIgnored', { n: ignoredLinkCount(row) }) }}
</RcButton>
</div>
</div>
<span v-else>
{{ t('harvester.dashboard.sections.componentHealth.noAffectedResources') }}
</span>
</template>
</SortableTable>
</template>
<style lang="scss" scoped>
// a check with anything ignored stands out, in the colour of a warning banner
:deep(tbody tr.main-row:has(.has-ignored)) {
background-color: var(--warning-banner-bg);
}
// 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;
}
.affected-links {
display: flex;
flex-wrap: wrap;
gap: 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>
@@ -1,350 +0,0 @@
<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 { RcCounterBadge } from '@components/Pill';
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, affectedResourceKind, affectedResourceLabel,
allAffectedResourceNames, componentOf, healthSummarySeverity, 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),
// the ignored resources too, they are behind a link like the ones past the first few
...allAffectedResourceNames(check),
].join(' ').toLowerCase(),
})));
// the checks ignored as a whole, the ones the checkbox brings back
const ignoredCheckCount = computed(() => checks.value.filter((check) => check.ignored).length);
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="ignoredCheckCount"
class="show-ignored"
>
<!-- the label holds the badge, so the checkbox is named here -->
<Checkbox
v-model:value="showIgnored"
type="checkbox"
:alternate-label="`${ t('harvester.dashboard.sections.componentHealth.showIgnored') } ${ ignoredCheckCount }`"
>
<template #label>
<span class="show-ignored-label">
{{ t('harvester.dashboard.sections.componentHealth.showIgnored') }}
<RcCounterBadge
:count="ignoredCheckCount"
type="inactive"
/>
</span>
</template>
</Checkbox>
</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"
: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%;
}
.show-ignored-label {
display: inline-flex;
align-items: center;
gap: 6px;
}
.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>
@@ -1,327 +0,0 @@
<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'),
// the shell's RadioGroup still takes the arrow keys once it is clicked, even when disabled
set: (value) => {
if (!locked.value && !isView.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)));
// an expired rule applies to nothing, so it only takes changes once it has a new expiration
const locked = computed(() => hasExpired && !isView.value && !duration.value);
// a rule that lists no resource would ignore the entire check
const canSave = computed(() => !locked.value && (scope.value === 'check' || selectedResources.value.length > 0) && 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"
>
<Banner
v-if="hasExpired && !isView"
class="m-0"
color="warning"
data-testid="component-health-ignore-expired"
:label="t('harvester.dashboard.sections.componentHealth.ignore.expiredBanner', { date: dateTimeFormat(expiresAt, store) })"
/>
<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>
<!-- first, as an expired rule's other fields wait for it -->
<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>
<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"
:disabled="locked"
: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"
:disabled="locked"
@update:value="selected = $event"
/>
</div>
</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"
:disabled="locked"
/>
<Banner
v-for="(err, i) in errors"
:key="i"
class="m-0"
color="error"
:label="err"
/>
<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>
@@ -1,992 +0,0 @@
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, hasIgnored, ignoreRuleName, 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'),
scopeGroup: () => w.findAllComponents(RadioGroup).find((group) => group.props('name') === 'ignore-scope'),
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', 'vm-hidden'].forEach((text) => expect(filterText()).toContain(text));
});
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.findComponent(Checkbox).text()).toContain('showIgnored');
expect(w.findComponent(Checkbox).findComponent(RcCounterBadge).props('count')).toBe(1);
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' } })],
});
// its ignored resources have a link of their own in the row
const resourcesOnly = await mountSummary({
healthSummaries: [summaryOf({ x: { warningCount: 1 } })],
componentHealths: [healthOf('h', 'x', { b: { severity: 'Warning', affectedResources: { names: { one: { ignored: true }, two: {} } } } })],
});
expect(clean.findComponent(Checkbox).exists()).toBe(false);
expect(resourcesOnly.findComponent(Checkbox).exists()).toBe(false);
});
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 shows the ignored resources from their own link', async() => {
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 w = mountChecks({ rows: [row] }, { SortableTable: table });
const link = () => w.find('.ignored-link');
expect(w.findComponent(RcCounterBadge).props('count')).toBe(2);
expect(w.findAllComponents(RcTag).map((tag) => tag.find('.name').text())).toStrictEqual(['two']);
expect(link().text()).toContain('ignore.plusIgnored');
expect(link().attributes('aria-expanded')).toBe('false');
await link().trigger('click');
expect(w.findAllComponents(RcTag).map((tag) => tag.find('.name').text())).toStrictEqual(['two', 'one']);
expect(link().text()).toContain('ignore.hideIgnored');
expect(link().attributes('aria-expanded')).toBe('true');
await link().trigger('click');
expect(w.findAllComponents(RcTag)).toHaveLength(1);
});
it('puts the ignored link after the more link, and leaves it out when the whole check is ignored', () => {
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'].map((name) => [name, {}]));
const row = {
...CHECK,
affectedCount: 6,
affectedResources: {
kind: 'Volume',
names: {
...names, e: { ignored: true }, f: { ignored: true }
}
}
};
const links = (r) => mountChecks({ rows: [r] }, { SortableTable: table }).findAll('.affected-links button').map((button) => (button.classes('ignored-link') ? 'ignored' : 'more'));
expect(links(row)).toStrictEqual(['more', 'ignored']);
expect(links({ ...row, ignored: true })).toStrictEqual(['more']);
});
it('tells which checks have anything ignored', () => {
expect(hasIgnored({ ignored: true })).toBe(true);
expect(hasIgnored({ affectedResources: { names: { a: { ignored: true }, b: {} } } })).toBe(true);
expect(hasIgnored({ affectedResources: { names: { a: {} } } })).toBe(false);
expect(hasIgnored(undefined)).toBe(false);
});
it('marks the checks that have anything ignored, for their background', () => {
const table = { props: ['rows'], template: '<div><slot v-for="row in rows" name="cell:checkName" :row="row" :value="row.checkName" /></div>' };
const rows = [
{
...CHECK, id: 'whole', ignored: true
},
{
...CHECK, id: 'partly', affectedResources: { kind: 'Volume', names: { one: { ignored: true }, two: {} } }
},
{ ...CHECK, id: 'clean' },
];
const w = mountChecks({ rows }, { SortableTable: table });
expect(w.findAll('span').filter((span) => span.text().startsWith('a')).map((span) => span.classes().includes('has-ignored'))).toStrictEqual([true, true, false]);
});
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', async() => {
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] }, { SortableTable: table });
const whole = mountChecks({ rows: [wholeRow] }, { SortableTable: table });
await partly.find('.ignored-link').trigger('click');
expect(tags(partly)).toStrictEqual([
{
ignored: false, disabled: false, says: false
},
{
ignored: true, disabled: true, says: true
},
]);
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', async() => {
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 = async(props) => {
const w = mountChecks(props, { SortableTable: table });
await w.find('.ignored-link').trigger('click');
return w.text().replace(/\s+/g, ' ');
};
const partlyText = await textOf({ rows: [row] });
expect(partlyText).toMatch(/two ?one ?\(%harvester\.dashboard\.sections\.componentHealth\.ignore\.ignored%\)/);
expect(partlyText).not.toContain('a (%harvester');
expect(mountChecks({ rows: [{ ...row, ignored: true }] }, { SortableTable: table }).text().replace(/\s+/g, ' ')).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 { confirm, scopeGroup, duration: durationGroup } = mountRuleModal();
const scope = scopeGroup();
const duration = durationGroup();
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, scopeGroup
} = mountRuleModal({ rule, mode: 'edit' });
const scope = scopeGroup();
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).find((group) => group.props('name') === 'ignore-scope');
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('opens an expired rule with a warning on top, and only its expiration can change until a new one is set', async() => {
const {
w, confirm, duration, warning, scopeGroup
} = mountRuleModal({ rule: ruleOf({ expiresAt: LAST_WEEK, resources: ['one'] }), mode: 'edit' });
const locked = () => ({
scope: w.findAllComponents(RadioGroup).find((group) => group.props('name') === 'ignore-scope').props('disabled'),
resources: w.findComponent(LabeledSelect).props('disabled'),
reason: w.findComponent(LabeledInput).props('disabled'),
expiration: duration().props('disabled'),
save: confirm().attributes('disabled') !== undefined,
});
expect(warning().props('label')).toContain('ignore.expiredBanner');
expect(w.find('[data-testid="rc-modal-body"]').element.firstElementChild.getAttribute('data-testid')).toBe('component-health-ignore-expired');
expect(locked()).toStrictEqual({
scope: true, resources: true, reason: true, expiration: false, save: true
});
expect(w.findAllComponents(RadioGroup).map((group) => group.props('name'))).toStrictEqual(['ignore-duration', 'ignore-scope']);
// what the shell's RadioGroup sends for a click and the Up key, although it is disabled
await scopeGroup().vm.$emit('update:value', 'check');
await flushPromises();
expect(scopeGroup().props('value')).toBe('resources');
await duration().vm.$emit('update:value', 'days7');
await flushPromises();
expect(locked()).toStrictEqual({
scope: false, resources: false, reason: false, expiration: false, save: false
});
expect(warning().props('label')).toContain('ignore.expiredBanner');
await scopeGroup().vm.$emit('update:value', 'check');
await flushPromises();
expect(scopeGroup().props('value')).toBe('check');
});
it('neither warns nor locks a rule that has not expired, or an expired one that is only viewed', async() => {
const { w, warning } = mountRuleModal({ rule: ruleOf({ expiresAt: IN_A_WEEK }), mode: 'edit' });
expect(warning()).toBeUndefined();
expect(w.findComponent(LabeledInput).props('disabled')).toBe(false);
const viewed = mountRuleModal({ rule: ruleOf({ expiresAt: LAST_WEEK }), mode: 'view' });
expect(viewed.warning()).toBeUndefined();
});
it('opens a rule without resources on the entire check, and selects them all when asked', async() => {
const {
w, confirm, duration, currentExpiry, scopeGroup
} = mountRuleModal({ rule: ruleOf(), mode: 'edit' });
const scope = scopeGroup();
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, scopeGroup
} = mountRuleModal({
rule: ruleOf({
resources: ['two'], expiresAt: IN_A_WEEK, reason: 'known issue'
}),
mode: 'view'
});
await scopeGroup().vm.$emit('update:value', 'check');
await flushPromises();
expect(scopeGroup().props('value')).toBe('resources');
[...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();
});
});
});
@@ -1,224 +0,0 @@
<script>
import { RcButton } from '@components/RcButton';
import { RcDropdown, RcDropdownItem, RcDropdownSeparator, RcDropdownTrigger } from '@components/RcDropdown';
import { RcIcon } from '@components/RcIcon';
import RcStatusIndicator from '@components/Pill/RcStatusIndicator';
import { CONSOLE_STATUS } from './NovncConsole';
export const CONNECTION_STATE = {
CONNECTING: 'connecting',
CONNECTED: 'connected',
DISCONNECTED: 'disconnected',
NOT_RUNNING: 'notRunning',
};
export default {
name: 'NovncConnectionStatus',
components: {
RcButton, RcDropdown, RcDropdownItem, RcDropdownSeparator, RcDropdownTrigger, RcIcon, RcStatusIndicator
},
props: {
status: {
type: String,
default: CONSOLE_STATUS.CONNECTING,
},
label: {
type: String,
default: '',
},
vmName: {
type: String,
default: '',
},
},
emits: ['reconnect'],
computed: {
// The console reports five states; the toolbar only tells the user whether they can type.
state() {
if (this.status === CONNECTION_STATE.NOT_RUNNING) {
return CONNECTION_STATE.NOT_RUNNING;
}
if (this.status === CONSOLE_STATUS.CONNECTED) {
return CONNECTION_STATE.CONNECTED;
}
if (this.status === CONSOLE_STATUS.DISCONNECTED || this.status === CONSOLE_STATUS.FAILED) {
return CONNECTION_STATE.DISCONNECTED;
}
return CONNECTION_STATE.CONNECTING;
},
},
};
</script>
<template>
<div class="connection-status">
<!-- Only the label is announced, not the menu that opens next to it. -->
<span
class="sr-only"
role="status"
aria-live="polite"
>{{ label }}</span>
<rc-dropdown
v-if="state === 'connected'"
:aria-label="t('harvester.virtualMachine.detail.console.connection.menuLabel')"
placement="bottom-start"
>
<rc-dropdown-trigger
variant="ghost"
size="small"
class="connection-status__pill"
data-testid="vnc-connection-status"
>
<template #before>
<rc-status-indicator
shape="disc"
status="success"
/>
</template>
{{ label }}
<template #after>
<rc-icon
type="chevron-down"
size="inherit"
/>
</template>
</rc-dropdown-trigger>
<template #dropdownCollection>
<p class="connection-status__description">
{{ t('harvester.virtualMachine.detail.console.connection.description', { name: vmName }) }}
</p>
<rc-dropdown-separator />
<rc-dropdown-item
data-testid="vnc-connection-reconnect"
@click="$emit('reconnect')"
>
<template #before>
<rc-icon
type="refresh"
size="inherit"
/>
</template>
{{ t('harvester.action.reconnect') }}
</rc-dropdown-item>
</template>
</rc-dropdown>
<span
v-else-if="state === 'notRunning'"
class="connection-status__pill"
data-testid="vnc-connection-status"
>
<rc-status-indicator
shape="disc"
status="unknown"
/>
{{ label }}
</span>
<span
v-else-if="state === 'connecting'"
class="connection-status__pill"
data-testid="vnc-connection-status"
>
<rc-icon
type="spinner"
size="inherit"
class="icon-spin"
/>
{{ label }}
</span>
<span
v-else
class="connection-status__pill connection-status__pill--disconnected"
data-testid="vnc-connection-status"
>
<rc-status-indicator
shape="disc"
status="error"
/>
{{ label }}
<span
class="connection-status__divider"
aria-hidden="true"
/>
<rc-button
variant="ghost"
size="small"
class="connection-status__reconnect"
data-testid="vnc-connection-reconnect"
@click="$emit('reconnect')"
>
<template #before>
<rc-icon
type="refresh"
size="inherit"
/>
</template>
{{ t('harvester.action.reconnect') }}
</rc-button>
</span>
</div>
</template>
<style lang="scss" scoped>
.connection-status {
display: flex;
align-items: center;
// Shared by the dropdown trigger and the plain pills, so every state has the same shape.
&__pill {
display: inline-flex;
align-items: center;
gap: 8px;
height: 32px;
padding: 0 10px 0 12px;
// The connected pill is an RcButton, which takes its padding from this property.
--rc-button-padding: 0 10px 0 12px;
border: 1px solid var(--border);
border-radius: 16px;
color: var(--body-text);
font-size: 12px;
line-height: 18px;
white-space: nowrap;
&--disconnected {
border-color: var(--error);
}
}
&__divider {
width: 1px;
height: 16px;
background: var(--error);
}
// An RcButton keeps to its own small height, so its focus ring stays inside the pill.
&__reconnect {
--rc-button-padding: 0;
color: var(--error);
}
&__description {
max-width: 248px;
margin: 0;
padding: 4px 17px 8px;
color: var(--body-text);
font-size: 12px;
font-weight: 400;
line-height: 18px;
white-space: normal;
}
}
</style>
+83 -536
View File
@@ -1,606 +1,153 @@
<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> <script>
import { RcButton } from '@components/RcButton'; import RFB from '@novnc/novnc/core/rfb';
import { RcIcon } from '@components/RcIcon'; import BrandImage from '@shell/components/BrandImage';
import { RcModal } from '@components/RcModal';
import NovncStatusCard from './NovncStatusCard';
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;
// A VM that just started can refuse VNC for a moment; refusals this soon are retried, not reported.
const STARTUP_GRACE = 60000;
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 { export default {
name: 'NovncConsole',
components: {
RcButton, RcIcon, RcModal, NovncStatusCard
},
props: { props: {
url: { url: {
type: String, type: String,
default: '' 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
},
vmName: {
type: String,
default: ''
},
// When the VM was seen starting to run on this page (ms), or 0.
startedAt: {
type: Number,
default: 0
},
}, },
emits: ['status-changed', 'capabilities'], components: { BrandImage },
data() { data() {
return { return {
rfb: null, rfb: null,
status: CONSOLE_STATUS.CONNECTING, connected: false,
statusDetail: '', disconnected: false,
desktopName: '', reconnectDelay: 3000,
reconnecting: false,
maximumRetryTimes: 10,
retryTimes: 0, retryTimes: 0,
maximumRetryTimes: MAXIMUM_RETRY_TIMES, setTimeout: null,
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);
},
// Only another session holding the console is something taking over can fix.
canTakeOver() {
return this.preserveSession && !this.isClosed && this.failure === CONSOLE_FAILURE.IN_USE;
},
failureTitle() {
return this.t(`harvester.virtualMachine.detail.console.failure.${ this.failure || CONSOLE_FAILURE.ERROR }`);
},
showConnecting() {
return this.status === CONSOLE_STATUS.CONNECTING || 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() { 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.$nextTick(() => {
this.connect(); this.connect();
}); });
}, },
beforeUnmount() { beforeUnmount() {
this.$refs.view?.removeEventListener('focusin', this.onFocusIn); this.clearTimeout();
this.$refs.view?.removeEventListener('focusout', this.onFocusOut);
this.isClosed = true;
this.clearReconnectTimer();
this.teardown();
}, },
methods: { methods: {
connect(takeOver = false) { connect() {
if (!this.url || this.isClosed) { const rfb = new RFB(this.$refs.view, this.url);
return;
}
this.teardown(); rfb.addEventListener('connect', () => {
this.clearTimeout();
this.failure = ''; this.connected = true;
this.status = this.retryTimes > 0 ? CONSOLE_STATUS.RECONNECTING : CONSOLE_STATUS.CONNECTING; this.retryTimes = 0;
this.reconnecting = false;
});
let rfb; rfb.addEventListener('disconnect', (e) => {
this.clearTimeout();
try { this.disconnected = true;
const url = new URL(this.url); this.rfb = null;
this.reconnect();
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;
}
// noVNC paints its own grey behind the framebuffer; let the console area show through.
rfb.background = 'transparent';
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.rfb = rfb;
this.applySettings();
}, },
reconnect() { reconnect() {
this.clearReconnectTimer();
this.isClosed = false;
this.retryTimes = 0;
this.statusDetail = '';
this.connect();
},
// Skip the wait before the next retry, still counting it as one, so a held console keeps
// being retried instead of turning into the in-use failure.
retryNow() {
this.clearReconnectTimer();
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.isStartingUp() ? '' : this.t('harvester.virtualMachine.detail.console.status.inUse');
this.scheduleReconnect();
} else if (this.isStartingUp()) {
this.scheduleReconnect();
} else {
this.clearReconnectTimer();
this.fail(this.preserveSession && this.vmRunning ? CONSOLE_FAILURE.IN_USE : CONSOLE_FAILURE.UNAVAILABLE);
}
},
isStartingUp() {
return !!this.startedAt && Date.now() - this.startedAt < STARTUP_GRACE;
},
// 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) { if (this.retryTimes >= this.maximumRetryTimes) {
this.fail(this.vmRunning ? CONSOLE_FAILURE.IN_USE : CONSOLE_FAILURE.UNAVAILABLE); this.reconnecting = false;
this.connected = true;
this.disconnected = true;
return; return;
} }
this.retryTimes += 1; this.retryTimes += 1;
this.status = CONSOLE_STATUS.RECONNECTING; this.reconnecting = true;
this.connected = false;
this.disconnected = false;
const delay = Math.min(BASE_RECONNECT_DELAY * (2 ** (this.retryTimes - 1)), MAXIMUM_RECONNECT_DELAY); this.setTimeout = setTimeout(() => {
this.reconnectTimer = setTimeout(() => {
this.reconnectTimer = null;
this.connect(); this.connect();
}, delay); }, this.reconnectDelay);
}, },
clearReconnectTimer() { clearTimeout() {
if (this.reconnectTimer) { if (this.setTimeout) {
clearTimeout(this.reconnectTimer); clearTimeout(this.setTimeout);
this.reconnectTimer = null;
} }
}, },
teardown(disconnect = true) { disconnect() {
const rfb = this.rfb; this.rfb.disconnect();
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 || {};
// View only shows the screen but sends no mouse or keyboard input.
rfb.viewOnly = !!settings.viewOnly;
rfb.edgeToEdge = !!settings.edgeToEdge;
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() { ctrlAltDelete() {
this.rfb?.sendCtrlAltDel(); this.rfb.sendCtrlAltDel();
}, },
sendKey(keysym, code, down) { sendKey(keysym, code, down) {
this.rfb?.sendKey(keysym, code, down); this.rfb.sendKey(keysym, code, down);
}, }
} }
}; };
</script> </script>
<template>
<div
class="novnc-console"
:class="{ 'is-live': status === 'connected' }"
>
<div
ref="view"
class="novnc-screen"
:class="{ 'is-focused': focused, 'is-edge-to-edge': settings.edgeToEdge }"
/>
<div
v-if="showError || showConnecting"
class="novnc-overlay"
data-testid="vnc-overlay"
>
<NovncStatusCard
v-if="showError"
:title="failureTitle"
:detail="statusDetail"
>
<RcButton
variant="primary"
data-testid="vnc-overlay-reconnect"
@click="reconnect"
>
{{ t('harvester.action.reconnect') }}
</RcButton>
<RcButton
v-if="canTakeOver"
variant="secondary"
data-testid="vnc-take-over"
@click="takeOver"
>
{{ t('harvester.virtualMachine.detail.console.takeOver.label') }}
</RcButton>
</NovncStatusCard>
<div
v-else
class="novnc-overlay__connecting"
>
<span class="novnc-overlay__spinner">
<RcIcon
type="spinner"
size="inherit"
class="icon-spin"
/>
</span>
<p class="novnc-overlay__connecting-label">
{{ t('harvester.virtualMachine.detail.console.overlay.connecting', { name: vmName }) }}
</p>
<p
v-if="retryTimes > 0"
class="novnc-overlay__detail"
>
{{ t('harvester.virtualMachine.detail.console.overlay.attempt', { retryTimes, maximumRetryTimes }) }}
<template v-if="statusDetail">
{{ statusDetail }}
</template>
</p>
<RcButton
v-if="retryTimes > 0"
variant="secondary"
data-testid="vnc-reconnect-now"
@click="retryNow"
>
{{ t('harvester.virtualMachine.detail.console.overlay.reconnectNow') }}
</RcButton>
</div>
</div>
<RcModal
:show="showTakeOverModal"
size="small"
:title="t('harvester.virtualMachine.detail.console.takeOver.title')"
data-testid="vnc-take-over-modal"
@close="cancelTakeOver"
>
<p>{{ t('harvester.virtualMachine.detail.console.takeOver.confirm') }}</p>
<template #primary-action>
<RcButton
variant="primary"
size="large"
data-testid="vnc-take-over-confirm"
@click="confirmTakeOver"
>
{{ t('harvester.virtualMachine.detail.console.takeOver.label') }}
</RcButton>
</template>
</RcModal>
</div>
</template>
<style lang="scss" scoped> <style lang="scss" scoped>
// Without a live picture the screen is black like a monitor, so the overlays read the same in .error {
// every theme; once connected the framebuffer is the screen and the page shows around it.
.novnc-console {
position: relative;
box-sizing: border-box;
height: 100%;
overflow: hidden; overflow: hidden;
background: #000;
&.is-live { .row {
background: transparent;
}
}
.novnc-screen {
height: 100%;
}
// The overlay sits on the black screen, so its text is light whatever the theme.
.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.6);
color: #fff;
text-align: center;
&__detail {
margin: 0;
color: rgba(255, 255, 255, 0.8);
font-size: 13px;
line-height: 16px;
}
&__connecting {
display: flex;
flex-direction: column;
align-items: center; align-items: center;
gap: 16px;
max-width: 480px;
padding: 0 20px;
} }
// RcIcon has no 20px size, the one the design uses here, so it inherits it. h1 {
&__spinner { font-size: 5rem;
display: flex;
font-size: 20px;
} }
&__connecting-label { .desert-landscape {
margin: 0; img {
font-size: 16px; max-width: 100%;
line-height: 21px; }
} }
} }
</style> </style>
<style lang="scss">
// noVNC sets an inline `outline: none` on its canvas, so frame the screen with a ring instead:
// a thin border at rest and, while it holds the keyboard, a 2px ring set 2px off the screen so it
// never blends into a dark framebuffer edge (the SUSE light focus colour is a very dark green).
.novnc-screen canvas {
box-shadow: 0 0 0 1px var(--border);
}
.novnc-screen.is-focused canvas {
box-shadow: 0 0 0 2px var(--body-bg), 0 0 0 4px var(--primary-keyboard-focus);
}
.novnc-screen.is-edge-to-edge canvas {
box-shadow: none;
}
</style>
@@ -1,355 +1,264 @@
<script> <script>
import { STEVE } from '@shell/config/types'; import { STEVE } from '@shell/config/types';
import { stringify } from '@shell/utils/error';
import Banner from '@components/Banner/Banner.vue'; import Banner from '@components/Banner/Banner.vue';
import { RcButton } from '@components/RcButton'; import AsyncButton from '@shell/components/AsyncButton';
import { RcIcon } from '@components/RcIcon'; import ModalWithCard from '@shell/components/ModalWithCard';
import { RcModal } from '@components/RcModal';
import RcTag from '@components/Pill/RcTag'; const PREFERED_SHORTCUT_KEYS = 'prefered-shortcut-keys';
import { LabeledInput } from '@components/Form/LabeledInput';
import NovncKeyRecorder from './NovncKeyRecorder';
import { readShortcuts, shortcutId, shortcutLabels, writeShortcuts } from './shortcuts';
export default { export default {
name: 'NovncConsoleCustomKeys', name: 'NovncConsoleCustomKeys',
components: {
Banner, RcButton, RcIcon, RcModal, RcTag, LabeledInput, NovncKeyRecorder
},
props: {
show: {
type: Boolean,
default: false,
},
},
emits: ['close'], emits: ['close'],
components: {
ModalWithCard, Banner, AsyncButton
},
data() { data() {
return { return {
keys: [], keysRecord: [],
name: '', addedShortcutKeys: [],
saving: false, preferredShortcutKeys: [],
error: '', isRecording: false,
}; };
}, },
computed: { computed: {
preference() { savedShortcutKeys() {
return this.$store.getters['management/all'](STEVE.PREFERENCE)?.[0]; const preference = this.$store.getters['management/all'](STEVE.PREFERENCE);
const preferedShortcutKeys = preference?.[0]?.data?.[PREFERED_SHORTCUT_KEYS];
let out = [];
if (!preferedShortcutKeys) {
return out;
}
try {
out = JSON.parse(preferedShortcutKeys);
} catch (err) {
this.$store.dispatch('growl/fromError', {
title: this.t('generic.notification.title.error', { name: this.t('harvester.virtualMachine.detail.console.customShortcutKeys') }),
err,
}, { root: true });
}
return out;
}, },
shortcuts() { displayedKeys() {
return readShortcuts(this.preference).map((shortcut) => ({ ...shortcut, labels: shortcutLabels(shortcut) })); const out = this.addedShortcutKeys.concat(this.preferredShortcutKeys).map((item) => {
const out = item.map((K) => ` <code>${ K.key.charAt(0).toUpperCase() + K.key.slice(1) }</code>`);
return out.join(',');
});
return out;
}, },
isDuplicate() { recordButton() {
const id = shortcutId({ keys: this.keys }); if (this.isRecording) {
return 'harvester.virtualMachine.detail.console.record.stop';
}
return !!this.keys.length && this.shortcuts.some((shortcut) => shortcutId(shortcut) === id); return 'harvester.virtualMachine.detail.console.record.start';
},
keysRecordFormat() {
if (!this.isRecording && this.keysRecord.length === 0) {
return this.t('harvester.virtualMachine.detail.console.record.tips');
}
const out = this.keysRecord.map((item) => ` <code>${ item.key.charAt(0).toUpperCase() + item.key.slice(1) }</code>`);
return `Keys: ${ out.join(',') }`;
}, },
canAdd() { canAdd() {
return !!this.keys.length && !this.isDuplicate; const hasRecord = this.keysRecord.length > 0;
let validationList = [].concat(this.preferredShortcutKeys, this.addedShortcutKeys);
if (!hasRecord) {
return false;
}
validationList.push(this.keysRecord);
validationList = validationList.map((item) => {
const out = item.map((K) => K.key);
return out.join(',');
});
return validationList.length === new Set(validationList).size;
}, },
}, },
watch: { watch: {
show(show) { savedShortcutKeys: {
if (!show) { handler() {
this.error = ''; this.preferredShortcutKeys = [].concat(this.savedShortcutKeys) || [];
} },
immediate: true
}, },
}, },
methods: { methods: {
clear() { closeRecordingModal() {
this.keys = []; window.removeEventListener('keydown', this.handleShortcut);
this.name = ''; this.$emit('close');
}, },
// The buttons stay enabled while a change saves: disabling the one that was pressed would drop the toggleRecording() {
// keyboard's focus to the page. this.isRecording = !this.isRecording;
async add() {
if (!this.canAdd || this.saving) {
return;
}
const { name, keys } = this; if (this.isRecording) {
const shortcuts = [...this.shortcuts, { name: name.trim(), keys }]; this.keysRecord = [];
window.addEventListener('keydown', this.handleShortcut);
// The list shows the new shortcut while it saves, and a form still holding it would say it is already } else {
// saved, so the form empties now. Add shortcut turns disabled with it, so the recorder takes the focus. window.removeEventListener('keydown', this.handleShortcut);
this.clear();
this.$refs.recorder?.$el?.focus();
const added = await this.save(shortcuts);
// A failed save takes the shortcut out of the list again, so it goes back in the form, unless the next
// one was started meanwhile.
if (!added && !this.keys.length && !this.name) {
this.keys = keys;
this.name = name;
} }
}, },
async remove(index) { handleShortcut(event) {
if (this.saving) { event.preventDefault();
return;
}
const removed = await this.save(this.shortcuts.filter((_, i) => i !== index)); const {
key, keyCode, code, location, charCode
} = event;
// The row may be gone with the button that had the focus: the delete button now in its place, or this.keysRecord.push({
// the last one, takes it, and the recorder once the list is empty. key, keyCode, code, location, charCode
if (removed) { });
this.$nextTick(() => {
const buttons = this.$refs.list?.querySelectorAll('button') || [];
(buttons[index] || buttons[buttons.length - 1] || this.$refs.recorder?.$el)?.focus();
});
}
}, },
// Every change is saved straight away, so closing the modal can never lose one. addShortcutKey() {
async save(shortcuts) { this.addedShortcutKeys.push([].concat(this.keysRecord));
this.saving = true; },
this.error = '';
removeKey(keys) {
const key = keys.replace(/(\s*)<code>|<\/code>/g, '').replace(/\s*,\s*/g, ',');
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;
});
},
async saveKeys(buttonCb) {
const out = [].concat(this.preferredShortcutKeys, this.addedShortcutKeys);
const preference = this.$store.getters['management/all'](STEVE.PREFERENCE)?.[0];
try { try {
await writeShortcuts(this.preference, shortcuts.map(({ name, keys }) => ({ name, keys }))); preference.data[PREFERED_SHORTCUT_KEYS] = JSON.stringify(out);
await preference.save();
return true; this.closeRecordingModal();
buttonCb(true);
} catch (err) { } catch (err) {
// The console page has no growls, so the dialog says it itself. buttonCb(false);
const title = this.t('harvester.virtualMachine.detail.console.customKeys.saveError');
const reason = stringify(err);
this.error = reason ? `${ title }: ${ reason }` : title;
return false;
} finally {
this.saving = false;
} }
}, },
}, }
}; };
</script> </script>
<template> <template>
<RcModal <ModalWithCard
:show="show" name="recordShortcutKeys"
size="medium" :width="550"
:title="t('harvester.virtualMachine.detail.console.customKeys.title')"
data-testid="vnc-custom-keys-modal"
@close="$emit('close')"
> >
<Banner <template #title>
v-if="error" <t k="harvester.virtualMachine.detail.console.customShortcutKeys" />
color="error"
role="alert"
data-testid="vnc-custom-keys-error"
>
{{ error }}
</Banner>
<p class="custom-keys__intro">
{{ t('harvester.virtualMachine.detail.console.customKeys.description') }}
</p>
<section class="custom-keys__new">
<h3 class="custom-keys__heading">
{{ t('harvester.virtualMachine.detail.console.customKeys.new') }}
</h3>
<div class="custom-keys__field">
<span
id="vnc-key-combination-label"
class="custom-keys__label"
>{{ t('harvester.virtualMachine.detail.console.customKeys.combination') }}</span>
<NovncKeyRecorder
ref="recorder"
v-model:value="keys"
aria-labelledby="vnc-key-combination-label"
/>
<p
v-if="isDuplicate"
class="custom-keys__error"
role="alert"
>
{{ t('harvester.virtualMachine.detail.console.customKeys.duplicate') }}
</p>
<p class="custom-keys__help">
{{ t('harvester.virtualMachine.detail.console.customKeys.reserved') }}
</p>
</div>
<LabeledInput
v-model:value="name"
:label="t('harvester.virtualMachine.detail.console.customKeys.name')"
data-testid="vnc-shortcut-name"
@keyup.enter="add"
/>
<div class="custom-keys__new-actions">
<RcButton
variant="secondary"
:disabled="!keys.length && !name"
@click="clear"
>
{{ t('harvester.virtualMachine.detail.console.customKeys.clear') }}
</RcButton>
<RcButton
variant="primary"
data-testid="vnc-add-shortcut"
:disabled="!canAdd"
@click="add"
>
{{ t('harvester.virtualMachine.detail.console.customKeys.add') }}
</RcButton>
</div>
</section>
<section v-if="shortcuts.length">
<h3 class="custom-keys__heading">
{{ t('harvester.virtualMachine.detail.console.customKeys.saved', { count: shortcuts.length }) }}
</h3>
<ul
ref="list"
class="custom-keys__list"
>
<li
v-for="(shortcut, index) in shortcuts"
:key="index"
class="custom-keys__item"
data-testid="vnc-custom-shortcut"
>
<span class="custom-keys__item-name">{{ shortcut.name || shortcut.labels.join('+') }}</span>
<span class="custom-keys__item-keys">
<RcTag
v-for="(label, i) in shortcut.labels"
:key="i"
type="active"
>
{{ label }}
</RcTag>
</span>
<RcButton
variant="tertiary"
:aria-label="t('harvester.virtualMachine.detail.console.customKeys.delete', { name: shortcut.name || shortcut.labels.join('+') }, true)"
@click="remove(index)"
>
<RcIcon
type="trash"
size="inherit"
/>
</RcButton>
</li>
</ul>
</section>
<template #actions="{ close }">
<RcButton
variant="primary"
size="large"
data-testid="vnc-custom-keys-done"
@click="close"
>
{{ t('harvester.virtualMachine.detail.console.customKeys.done') }}
</RcButton>
</template> </template>
</RcModal>
<template #content>
<div class="row">
<div class="col span-12">
<Banner color="info">
<span v-clean-html="keysRecordFormat"></span>
</Banner>
</div>
</div>
<div class="row">
<div class="col span-12">
<button
class="btn bg-primary"
@click="toggleRecording"
>
<t :k="recordButton" />
<i
class="icon icon-fw"
:class="isRecording ? 'icon-dot-open' : 'icon-dot'"
/>
</button>
<button
:disabled="!canAdd"
class="btn bg-primary"
@click="addShortcutKey"
>
<t k="generic.add" />
</button>
</div>
</div>
<hr>
<div class="displayed-keys mt-20">
<h4
v-clean-html="t('harvester.virtualMachine.detail.console.record.preferredKeys')"
class="text-default-text"
/>
<div class="displayed-banners">
<Banner
v-for="(keys,index) in displayedKeys"
:key="index"
>
<span v-clean-html="keys"></span>
</Banner>
</div>
</div>
</template>
<template #footer>
<div class="actions">
<button
class="btn role-secondary mr-20"
@click.prevent="closeRecordingModal"
>
<t k="generic.close" />
</button>
<AsyncButton
mode="done"
@click="saveKeys"
/>
</div>
</template>
</ModalWithCard>
</template> </template>
<style lang="scss" scoped> <style lang="scss" scoped>
.custom-keys { .displayed-keys {
&__intro { .banner {
margin: 0; margin: 0;
} }
}
&__new { .displayed-banners {
display: flex; max-height: 155px;
flex-direction: column; overflow: auto;
gap: 16px; }
padding: 16px 20px 20px;
border: 1px solid var(--border);
border-radius: 8px;
}
&__heading { .actions {
margin: 0 0 12px; width: 100%;
font-size: 14px; display: flex;
font-weight: 700; justify-content: flex-end;
line-height: 21px;
.custom-keys__new & {
margin: 0;
}
}
&__field {
display: flex;
flex-direction: column;
gap: 8px;
}
&__label {
color: var(--input-label);
font-size: 14px;
line-height: 21px;
}
&__help,
&__error {
margin: 0;
font-size: 12px;
line-height: 18px;
}
&__help {
color: var(--muted);
}
&__error {
color: var(--error);
}
&__new-actions {
display: flex;
justify-content: flex-end;
gap: 12px;
}
&__list {
display: flex;
flex-direction: column;
gap: 12px;
margin: 0;
padding: 0;
list-style: none;
}
&__item {
display: flex;
align-items: center;
gap: 12px;
padding: 12px 8px 12px 20px;
border: 1px solid var(--border);
border-radius: 8px;
}
&__item-name {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
&__item-keys {
display: flex;
gap: 6px;
}
} }
</style> </style>
@@ -0,0 +1,108 @@
<script>
export default {
name: 'NovncConsoleItem',
emits: ['send-keys', 'update'],
props: {
items: {
type: Object,
required: true,
default: () => {
return {};
}
},
path: {
type: Array,
required: true,
default: () => {
return [];
}
},
pos: {
type: Number,
required: true,
default: 0,
}
},
methods: {
keysDown(key, pos) {
this.addKeys({ key, pos });
this.$emit('send-keys');
},
addKeys({ key, pos }) {
this.$emit('update', { key, pos });
},
sendKeys() {
this.$emit('send-keys');
},
getOpenStatus(key, pos) {
return this.path[pos] === key;
}
}
};
</script>
<template>
<ul class="list-unstyled dropdown combination-keys__container">
<li
v-for="(item, key) in items"
:key="key"
>
<v-dropdown
v-if="!!item.keys"
placement="right-start"
trigger="click"
:container="false"
>
<span
:class="{ open: getOpenStatus(key, pos) }"
class="p-10 hand"
@click="addKeys({ key, pos })"
>{{ item.label }}</span>
<template #popper>
<novnc-console-item
:items="item.keys"
:path="path"
:pos="pos+1"
@update="addKeys"
@send-keys="sendKeys"
/>
</template>
</v-dropdown>
<span
v-else
class="p-10 hand"
@click="keysDown(key, pos)"
>{{ item.label }}</span>
</li>
</ul>
</template>
<style lang="scss" scoped>
.combination-keys__container {
max-width: 60px;
DIV, SPAN {
display: block;
text-align: center;
}
SPAN {
border-radius: 3px;
&:hover, &.open {
color: var(--primary-hover-text);
background: var(--primary-hover-bg);
}
}
}
</style>
@@ -1,41 +1,15 @@
<script> <script>
import { STEVE } from '@shell/config/types'; import { STEVE } from '@shell/config/types';
import { RcButton } from '@components/RcButton';
import { RcModal } from '@components/RcModal';
import { Checkbox } from '@components/Form/Checkbox';
import { escapeHtml } from '@shell/utils/string'; import { escapeHtml } from '@shell/utils/string';
import { allHash } from '@shell/utils/promise'; import { allHash } from '@shell/utils/promise';
import KeyTable from '@novnc/novnc/core/input/keysym'; import KeyTable from '@novnc/novnc/core/input/keysym';
import * as KeyboardUtil from '@novnc/novnc/core/input/util'; import * as KeyboardUtil from '@novnc/novnc/core/input/util';
import { HCI } from '../../types'; import { HCI } from '../../types';
import NovncConsole, { CONSOLE_STATUS } from './NovncConsole'; import NovncConsole from './NovncConsole';
import NovncConsoleItem from './NovncConsoleItem';
import NovncConsoleCustomKeys from './NovncConsoleCustomKeys'; import NovncConsoleCustomKeys from './NovncConsoleCustomKeys';
import NovncConnectionStatus, { CONNECTION_STATE } from './NovncConnectionStatus';
import NovncIcon from './NovncIcon';
import NovncShortcutKeysMenu from './NovncShortcutKeysMenu';
import NovncStatusCard from './NovncStatusCard';
import NovncViewOptions, { VIEW_MODE } from './NovncViewOptions';
import { baseKey, readShortcuts } from './shortcuts';
import { normalizeZoom } from './ZoomableRFB';
// The previous console saved its defaults under its key the first time it opened, so they can't tell a const PREFERED_SHORTCUT_KEYS = 'prefered-shortcut-keys';
// choice from a default. This one keeps its own key and writes it only once the user changes a setting.
const CONSOLE_SETTINGS_KEY = 'harvester-vnc-console-view';
// Only View only is taken from the previous console: it was off unless the user turned it on.
const PREVIOUS_SETTINGS_KEY = 'harvester-vnc-console-settings';
export const CONFIRM_ACTION = {
CTRL_ALT_DEL: 'ctrlAltDel',
SOFT_REBOOT: 'softReboot',
};
const DEFAULT_SETTINGS = {
viewMode: VIEW_MODE.SCALE,
zoomPercent: 100,
viewOnly: false,
qualityLevel: 6,
compressionLevel: 2,
};
const SHORT_KEYS = { const SHORT_KEYS = {
ControlLeft: { ControlLeft: {
@@ -132,29 +106,15 @@ const F_KEYS = {
export default { export default {
name: 'NovncConsoleWrapper', name: 'NovncConsoleWrapper',
components: { components: {
RcButton, RcModal, Checkbox, NovncConsole, NovncConsoleCustomKeys, NovncConnectionStatus, NovncIcon, NovncShortcutKeysMenu, NovncStatusCard, NovncViewOptions NovncConsole, NovncConsoleItem, NovncConsoleCustomKeys
}, },
// A VM that is not running has no instance, so find it by the uid in the route instead.
async fetch() { async fetch() {
if (this.value?.id) { const _hash = { vmResource: this.$store.dispatch('harvester/find', { type: HCI.VM, id: this.value.id }) };
const hash = await allHash({ vmResource: this.$store.dispatch('harvester/find', { type: HCI.VM, id: this.value.id }) });
this.vmResource = hash.vmResource; const hash = await allHash(_hash);
return; this.vmResource = hash.vmResource;
}
const uid = this.$route?.params?.uid;
try {
const vms = uid ? await this.$store.dispatch('harvester/findAll', { type: HCI.VM }) : [];
this.vmResource = (vms || []).find((vm) => vm.metadata?.uid === uid) || {};
} catch (err) {
// Only the name is missing then; the not-running card still shows.
this.vmResource = {};
}
}, },
props: { props: {
@@ -169,89 +129,45 @@ export default {
data() { data() {
return { return {
keysRecord: [],
vmResource: {}, vmResource: {},
renderKeysModal: false, renderKeysModal: false,
settings: { ...DEFAULT_SETTINGS }, currentUser: null,
capabilities: {}, hideCustomKeysBar: false,
isFullscreen: false,
confirmAction: null,
startedAt: 0,
consoleStatus: {
status: 'connecting',
retryTimes: 0,
maximumRetryTimes: 0,
desktopName: '',
},
}; };
}, },
computed: { computed: {
preference() { savedShortcutKeys() {
return this.$store.getters['management/all'](STEVE.PREFERENCE)?.[0]; 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;
}
if (!preferedShortcutKeys) {
return out;
}
try {
out = 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 out;
}, },
// Custom keys are stored in the user preference, which is not available everywhere.
hideCustomKeysBar() {
return !this.preference?.data;
},
preferredShortcutKeys() {
return readShortcuts(this.preference);
},
isConnected() {
return this.consoleStatus.status === CONSOLE_STATUS.CONNECTED;
},
// A console that just went away can still report connected for a moment.
canSendKeys() {
return !this.isDown && this.isConnected && !this.settings.viewOnly;
},
// Shared by the toolbar and the full screen bar.
shortcutMenuProps() {
return {
canSend: this.canSendKeys,
blockedReason: this.sendBlockedReason,
canManage: !this.hideCustomKeysBar,
disabled: !!this.settings.viewOnly || (!this.canSendKeys && this.hideCustomKeysBar),
shortcuts: this.preferredShortcutKeys,
};
},
sendBlockedReason() {
return this.canSendKeys ? '' : this.t('harvester.virtualMachine.detail.console.shortcutMenu.blockedDisconnected');
},
vmName() {
return this.value?.metadata?.name || this.vmResource?.metadata?.name || '';
},
vmNamespace() {
return this.value?.metadata?.namespace || this.vmResource?.metadata?.namespace || '';
},
// Without an instance there is no console to connect to, so the toolbar says so.
connectionStatus() {
return this.isDown ? CONNECTION_STATE.NOT_RUNNING : this.consoleStatus.status;
},
// VNC only exists while the instance runs. A starting instance (Pending, Scheduling) would refuse
// the first connection and leave "Unable to connect", so the console waits for Running instead.
isDown() { isDown() {
return this.isEmpty(this.value) || !this.vmRunning; return this.isEmpty(this.value);
},
isStarting() {
return !this.isEmpty(this.value) && ['Pending', 'Scheduling', 'Scheduled'].includes(this.value?.status?.phase);
},
preserveSession() {
return !!this.$store.getters['harvester-common/getFeatureEnabled']('vncPreserveSession');
},
vmRunning() {
return this.value?.status?.phase === 'Running';
}, },
url() { url() {
@@ -269,132 +185,84 @@ export default {
}; };
}, },
keymap() {
const out = {
...SHORT_KEYS,
PrintScreen: FUNCTION_KEYS.PrintScreen,
...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 }
},
...NORMAL_KEYS,
};
return out;
},
hasSoftRebootAction() { hasSoftRebootAction() {
return !!this.vmResource?.actions?.softreboot; return !!this.vmResource?.actions?.softreboot;
}, },
rfbSettings() { preferredShortcutKeys() {
return { return (this.savedShortcutKeys || []).map((item) => {
viewOnly: !!this.settings.viewOnly, return {
// Full screen always fills the window; the saved mode is back on leaving it. label: item.map((K) => K.key.charAt(0).toUpperCase() + K.key.slice(1)).join('+'),
scaleViewport: this.isFullscreen || this.settings.viewMode === VIEW_MODE.SCALE, value: item
edgeToEdge: this.isFullscreen,
zoomPercent: normalizeZoom(this.settings.zoomPercent),
resizeSession: false,
clipViewport: false,
dragViewport: false,
qualityLevel: this.settings.qualityLevel,
compressionLevel: this.settings.compressionLevel,
};
},
// The pill has one label per state it shows; retries are counted on the console overlay.
statusLabel() {
if (this.isDown) {
return this.t('harvester.virtualMachine.detail.console.status.notRunning');
}
const { status } = this.consoleStatus;
if (status === CONSOLE_STATUS.RECONNECTING) {
return this.t('harvester.virtualMachine.detail.console.status.connecting');
}
if (status === CONSOLE_STATUS.FAILED) {
return this.t('harvester.virtualMachine.detail.console.status.disconnected');
}
return this.t(`harvester.virtualMachine.detail.console.status.${ status }`);
},
},
watch: {
// The console unmounts without a last status, so start over as connecting for when it is back.
isDown(down, wasDown) {
if (down) {
this.consoleStatus = {
status: CONSOLE_STATUS.CONNECTING, retryTimes: 0, maximumRetryTimes: 0, desktopName: ''
}; };
} else if (wasDown) { });
this.startedAt = Date.now();
}
}, },
}, },
mounted() {
this.loadSettings();
document.addEventListener('fullscreenchange', this.onFullscreenChange);
},
beforeUnmount() {
document.removeEventListener('fullscreenchange', this.onFullscreenChange);
},
methods: { methods: {
isEmpty(o) { isEmpty(o) {
return o !== undefined && Object.keys(o).length === 0; return o !== undefined && Object.keys(o).length === 0;
}, },
close() { close() {
this.$refs.novncConsole?.disconnect(); this.$refs.novncConsole.disconnect();
}, },
// Press the keys in order, then release them in reverse, e.g. Ctrl+Alt+F2. update({ key, pos }) {
sendKeys(keys) { this.keysRecord.splice(pos, this.keysRecord.length - pos, key);
if (!this.canSendKeys || !this.$refs.novncConsole) { },
return;
}
keys.forEach((key) => { // Send function key, e.g. ALT + F
sendKeys() {
this.keysRecord.forEach((key) => {
this.$refs.novncConsole.sendKey(this.allKeys[key].value, key, true); this.$refs.novncConsole.sendKey(this.allKeys[key].value, key, true);
}); });
[...keys].reverse().forEach((key) => { this.keysRecord.reverse().forEach((key) => {
this.$refs.novncConsole.sendKey(this.allKeys[key].value, key, false); this.$refs.novncConsole.sendKey(this.allKeys[key].value, key, false);
}); });
this.focusConsole(); this.$refs.popover.isOpen = false;
this.keysRecord = [];
}, },
sendCustomKeys(keys) { sendCustomKeys(keys) {
if (!this.canSendKeys || !this.$refs.novncConsole) { const keyList = [].concat(keys);
return;
}
const combination = [].concat(keys);
const keyList = combination.map((K) => baseKey(K, combination));
keyList.forEach((K) => { keyList.forEach((K) => {
this.$refs.novncConsole.sendKey(KeyboardUtil.getKeysym(K), KeyboardUtil.getKeycode(K), true); 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); this.$refs.novncConsole.sendKey(KeyboardUtil.getKeysym(K), KeyboardUtil.getKeycode(K), false);
}); });
this.focusConsole();
}, },
// The shortcut menu hands focus back to its trigger as it closes, so take it on the next tick. reconnect() {
focusConsole() { this.$refs.novncConsole.reconnect();
this.$nextTick(() => this.$refs.novncConsole?.focus());
}, },
// RcModal's focus trap returns focus to the opener in a timeout once the modal unmounts, softReboot() {
// so queue ours behind it. this.vmResource.doSoftReboot();
focusConsoleAfterModal() {
this.$nextTick(() => setTimeout(() => this.$refs.novncConsole?.focus()));
},
// Closing the View panel from the keyboard (Esc) leaves the focus nowhere; give it back to the
// View button, as the menus do. A click elsewhere keeps the focus it moved.
onViewHide() {
const focused = document.activeElement;
// floating-vue hides the panel without removing it, so the focus is still in it at this point.
if (!focused || focused === document.body || focused.closest('.v-popper__popper')) {
this.$refs.viewButton?.focus();
}
}, },
showKeysModal() { showKeysModal() {
@@ -403,516 +271,116 @@ export default {
hideKeysModal() { hideKeysModal() {
this.renderKeysModal = false; this.renderKeysModal = false;
this.focusConsoleAfterModal();
}, },
reconnect() {
this.$refs.novncConsole?.reconnect();
},
loadSettings() {
try {
const saved = JSON.parse(window.localStorage.getItem(CONSOLE_SETTINGS_KEY) || 'null');
const previous = saved ? null : JSON.parse(window.localStorage.getItem(PREVIOUS_SETTINGS_KEY) || 'null');
this.settings = {
viewMode: Object.values(VIEW_MODE).includes(saved?.viewMode) ? saved.viewMode : DEFAULT_SETTINGS.viewMode,
zoomPercent: normalizeZoom(saved?.zoomPercent ?? DEFAULT_SETTINGS.zoomPercent),
viewOnly: (saved || previous)?.viewOnly === true,
qualityLevel: saved?.qualityLevel ?? DEFAULT_SETTINGS.qualityLevel,
compressionLevel: saved?.compressionLevel ?? DEFAULT_SETTINGS.compressionLevel,
};
} catch (err) {
this.settings = { ...DEFAULT_SETTINGS };
}
},
saveSettings() {
window.localStorage.setItem(CONSOLE_SETTINGS_KEY, JSON.stringify(this.settings));
},
updateSettings(settings) {
this.settings = settings;
this.saveSettings();
},
// Back to sending input, the keyboard should reach the VM without clicking the screen first.
setViewOnly(viewOnly) {
this.settings = { ...this.settings, viewOnly };
this.saveSettings();
if (!viewOnly) {
this.focusConsole();
}
},
// View only belongs to the toolbar, not the View panel, so the panel's reset leaves it as it is.
resetSettings() {
this.settings = { ...DEFAULT_SETTINGS, viewOnly: this.settings.viewOnly };
this.saveSettings();
},
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() {
if (!this.settings.viewOnly) {
this.confirmAction = CONFIRM_ACTION.SOFT_REBOOT;
}
},
// RcModal hands focus back to the toolbar button that opened it; the screen should get it.
cancelConfirm() {
this.confirmAction = null;
this.focusConsoleAfterModal();
},
runConfirmedAction() {
const action = this.confirmAction;
this.confirmAction = null;
this.focusConsoleAfterModal();
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, not just the console: menus and modals render outside it.
await document.documentElement.requestFullscreen();
// Keyboard lock (Chromium) lets browser shortcuts such as Ctrl+W, Ctrl+T, Ctrl+N and F11
// reach the guest; outside full screen the browser keeps them.
await navigator.keyboard?.lock?.(['KeyW', 'KeyT', 'KeyN', 'F11']);
}
this.focusConsole();
} catch (err) {
this.$store.dispatch('growl/fromError', {
title: this.t('generic.notification.title.error', { name: escapeHtml(this.vmName) }),
err,
}, { root: true });
}
},
onFullscreenChange() {
this.isFullscreen = !!document.fullscreenElement;
if (!this.isFullscreen) {
navigator.keyboard?.unlock?.();
}
},
} }
}; };
</script> </script>
<template> <template>
<div id="app"> <div id="app">
<div <div class="vm-console">
ref="consoleContainer" <div class="combination-keys">
class="vm-console" <v-dropdown
:class="{ 'vm-console--fullscreen': isFullscreen }" ref="popover"
> placement="top"
<div trigger="click"
v-if="isFullscreen" :container="false"
class="fullscreen-bar" @auto-hide="keysRecord = []"
data-testid="vnc-fullscreen-bar"
>
<span class="fullscreen-bar__name">{{ vmName }}</span>
<NovncConnectionStatus
:status="connectionStatus"
:label="statusLabel"
:vm-name="vmName"
@reconnect="reconnect"
/>
<span
class="console-toolbar__divider"
aria-hidden="true"
/>
<NovncShortcutKeysMenu
v-bind="shortcutMenuProps"
@send-keys="sendKeys"
@send-shortcut="sendCustomKeys"
@manage="showKeysModal"
@ctrl-alt-del="ctrlAltDelete"
/>
<span
class="console-toolbar__divider"
aria-hidden="true"
/>
<RcButton
variant="tertiary"
data-testid="vnc-exit-fullscreen"
@click="toggleFullscreen"
> >
<template #before> <button class="btn btn-sm bg-primary">
<NovncIcon type="minimize" /> {{ t("harvester.virtualMachine.detail.console.shortcutKeys") }}
</button>
<template #popper>
<novnc-console-item
:items="keymap"
:path="keysRecord"
:pos="0"
@update="update"
@send-keys="sendKeys"
/>
</template> </template>
{{ t('harvester.virtualMachine.detail.console.fullscreen.exit') }} </v-dropdown>
</RcButton>
</div>
<header <button
v-else v-if="hasSoftRebootAction"
class="console-toolbar" class="btn btn-sm bg-primary"
> @click="softReboot"
<div class="console-toolbar__identity"> >
<div class="console-toolbar__vm"> {{ t("harvester.action.softreboot") }}
<span </button>
class="console-toolbar__vm-name"
data-testid="vnc-vm-name"
>{{ vmName }}</span>
<span class="console-toolbar__vm-namespace">{{ vmNamespace }}</span>
</div>
<NovncConnectionStatus <button
:status="connectionStatus" class="btn btn-sm bg-primary"
:label="statusLabel" @click="reconnect"
:vm-name="vmName" >
@reconnect="reconnect" {{ t("harvester.action.reconnect") }}
/> </button>
<Checkbox <v-dropdown
class="console-toolbar__view-only" v-if="!hideCustomKeysBar"
:value="!!settings.viewOnly" ref="customKeyPopover"
:label="t('harvester.virtualMachine.detail.console.viewOnly')" placement="top"
use-body-text-color trigger="click"
data-testid="vnc-view-only" :container="false"
@update:value="setViewOnly" >
/> <button class="btn btn-sm bg-primary">
</div> {{ t("harvester.virtualMachine.detail.console.customShortcutKeys") }}
</button>
<div class="console-toolbar__group"> <template #popper>
<NovncShortcutKeysMenu <div>
v-bind="shortcutMenuProps" <button
@send-keys="sendKeys" class="btn btn-sm bg-primary"
@send-shortcut="sendCustomKeys" @click="showKeysModal"
@manage="showKeysModal" >
@ctrl-alt-del="ctrlAltDelete" {{ t("harvester.virtualMachine.detail.console.management") }}
/> </button>
</div> </div>
<span <hr>
class="console-toolbar__divider"
aria-hidden="true"
/>
<div class="console-toolbar__group"> <div
<RcButton v-for="(keys, index) in preferredShortcutKeys"
variant="tertiary" :key="index"
data-testid="vnc-ctrl-alt-del"
:disabled="!canSendKeys"
@click="ctrlAltDelete"
>
<template #before>
<NovncIcon type="power" />
</template>
{{ t("harvester.virtualMachine.detail.console.ctrlAltDel") }}
</RcButton>
<RcButton
v-if="hasSoftRebootAction"
variant="tertiary"
left-icon="refresh-alt"
data-testid="vnc-soft-reboot"
:disabled="!!settings.viewOnly"
@click="softReboot"
>
{{ t("harvester.virtualMachine.detail.console.softReboot") }}
</RcButton>
</div>
<span class="console-toolbar__spacer" />
<div class="console-toolbar__group">
<v-dropdown
placement="bottom-end"
trigger="click"
:container="false"
@hide="onViewHide"
>
<RcButton
ref="viewButton"
variant="tertiary"
left-icon="show"
right-icon="chevron-down"
data-testid="vnc-view"
> >
{{ t("harvester.virtualMachine.detail.console.view") }} <button
</RcButton> class="btn btn-sm bg-primary"
@click="sendCustomKeys(keys.value)"
>
{{ keys.label }}
</button>
</div>
</template>
</v-dropdown>
<template #popper> <NovncConsoleCustomKeys
<NovncViewOptions v-if="renderKeysModal"
:settings="settings" :current-user="currentUser"
@update="updateSettings" @close="hideKeysModal"
@reset="resetSettings"
/>
</template>
</v-dropdown>
<RcButton
variant="tertiary"
data-testid="vnc-fullscreen"
@click="toggleFullscreen"
>
<template #before>
<NovncIcon :type="isFullscreen ? 'minimize' : 'maximize'" />
</template>
{{ isFullscreen ? t('harvester.virtualMachine.detail.console.fullscreen.exit') : t('harvester.virtualMachine.detail.console.fullscreen.enter') }}
</RcButton>
</div>
</header>
<div class="console-area">
<NovncConsole
v-if="url && !isDown"
ref="novncConsole"
:url="url"
:settings="rfbSettings"
:preserve-session="preserveSession"
:vm-running="vmRunning"
:vm-name="vmName"
:started-at="startedAt"
@status-changed="onStatusChanged"
@capabilities="onCapabilities"
/> />
<div
v-if="isDown"
class="console-area__down"
data-testid="vnc-not-running"
>
<NovncStatusCard
icon="power"
:title="t(`harvester.virtualMachine.detail.console.notRunning.${ isStarting ? 'startingTitle' : 'title' }`)"
:detail="t(`harvester.virtualMachine.detail.console.notRunning.${ isStarting ? 'startingDetail' : 'detail' }`)"
/>
</div>
<p
v-if="!isFullscreen && !isDown"
class="console-area__hint"
>
{{ t(settings.viewOnly ? 'harvester.virtualMachine.detail.console.hintViewOnly' : 'harvester.virtualMachine.detail.console.hint', {}, true) }}
</p>
</div> </div>
<NovncConsole
<RcModal v-if="url && !isDown"
:show="!!confirmAction" ref="novncConsole"
size="small" :url="url"
:title="confirmAction ? t(`harvester.virtualMachine.detail.console.confirm.${ confirmAction }.title`, { name: vmName }) : ''"
data-testid="vnc-confirm-modal"
@close="cancelConfirm"
>
<p v-if="confirmAction">
{{ t(`harvester.virtualMachine.detail.console.confirm.${ confirmAction }.message`) }}
</p>
<template #primary-action>
<RcButton
v-if="confirmAction"
variant="primary"
size="large"
class="confirm-modal__danger"
data-testid="vnc-confirm-action"
@click="runConfirmedAction"
>
{{ t(`harvester.virtualMachine.detail.console.confirm.${ confirmAction }.button`) }}
</RcButton>
</template>
</RcModal>
<NovncConsoleCustomKeys
:show="renderKeysModal"
@close="hideKeysModal"
/> />
<p v-if="isDown">
{{ t("harvester.virtualMachine.detail.console.down") }}
</p>
</div> </div>
</div> </div>
</template> </template>
<style lang="scss" scoped> <style lang="scss" scoped>
.vm-console { .vm-console {
height: 100vh; height: 100%;
height: 100dvh;
display: grid; display: grid;
grid-template-columns: minmax(0, 1fr); grid-template-rows: 30px auto;
grid-template-rows: auto minmax(0, 1fr);
background: var(--body-bg);
// The toolbar gives way to a bar floating over the screen, which takes the whole window. A picture
// of another shape keeps its proportions, with black around it like on a monitor.
&--fullscreen {
position: relative;
grid-template-rows: minmax(0, 1fr);
background: #000;
.console-area {
gap: 0;
padding: 0;
}
}
} }
.fullscreen-bar { .combination-keys {
// vnc.vue stretches the console's child divs to full height; the bar keeps its own. background: rgb(40, 40, 40);
height: auto;
position: absolute;
top: 16px;
left: 50%;
z-index: 2;
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: center;
gap: 12px;
// From left: 50% it would only get half the window and squeeze its buttons; it wraps when it has to.
width: max-content;
max-width: calc(100vw - 16px);
padding: 4px 4px 4px 16px;
border: 1px solid var(--border);
border-radius: 24px;
background: var(--nav-bg);
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
opacity: 0.7;
transform: translateX(-50%);
transition: opacity 0.15s ease;
// Solid while in use: the pointer is on it, the keyboard is in it, or one of its menus is open.
&:hover,
&:has(:focus-visible),
&:has([aria-expanded='true']) {
opacity: 1;
}
&__name {
color: var(--body-text);
font-size: 12px;
font-weight: 700;
line-height: 18px;
}
}
// Narrow windows wrap the toolbar instead of pushing the screen out of view.
.console-toolbar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px 12px;
padding: 10px 16px;
background: var(--nav-bg);
&__identity {
display: flex;
align-items: center;
gap: 16px;
padding-right: 8px;
}
&__vm {
display: flex;
flex-direction: column;
gap: 2px;
min-width: 0;
}
&__vm-name {
color: var(--body-text);
font-size: 14px;
font-weight: 700;
line-height: 21px;
}
&__vm-namespace {
color: var(--muted);
font-size: 12px;
line-height: 18px;
}
// A Checkbox keeps 10px after its label for its place in a form; here the toolbar sets the gap.
&__view-only {
margin-right: -10px;
}
&__group {
display: flex;
align-items: center;
gap: 4px;
}
&__divider {
width: 1px;
height: 24px;
background: var(--border);
}
&__spacer {
flex: 1;
}
}
.console-area {
display: flex;
flex-direction: column;
gap: 14px;
min-height: 0;
padding: 24px;
// vnc.vue stretches every nested div to the full height; the hint needs its row.
> .novnc-console {
flex: 1 1 auto;
height: auto;
min-height: 0;
}
&__down {
display: flex;
flex: 1 1 auto;
align-items: center;
justify-content: center;
min-height: 0;
background: #000;
}
&__hint {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 18px;
text-align: center;
}
}
// RcButton has no destructive variant; this is how the shell's own dialogs colour one. The class
// is doubled to outrank RcButton's variant rules instead of relying on stylesheet order.
.confirm-modal__danger.confirm-modal__danger.rc-button {
&,
&:focus,
&.focused {
background-color: var(--error);
color: var(--error-text);
}
&:hover:not(:disabled) {
background-color: var(--error-hover-bg);
color: var(--error-hover-text);
}
} }
</style> </style>
@@ -1,73 +0,0 @@
<script>
// Icons the console needs that RcIcon does not have yet. Paths come from the VNC console design, on
// its 24px grid.
const ICONS = {
power: {
viewBox: '0 0 24 24',
paths: [
'M11.1253 12V2C11.1253 1.51675 11.517 1.125 12.0003 1.125C12.4835 1.125 12.8753 1.51675 12.8753 2V12C12.8753 12.4832 12.4835 12.875 12.0003 12.875C11.517 12.875 11.1253 12.4832 11.1253 12Z',
'M17.7812 5.98086C18.123 5.63921 18.6779 5.64006 19.0195 5.98184C20.398 7.361 21.337 9.11746 21.7187 11.0297C22.1004 12.9421 21.9076 14.9251 21.1641 16.7279C20.4204 18.5309 19.1592 20.0733 17.54 21.1605C15.921 22.2477 14.0166 22.8311 12.0664 22.8373C10.1161 22.8434 8.20695 22.2728 6.58105 21.1957C4.95519 20.1186 3.68464 18.5838 2.92968 16.7855C2.1748 14.9875 1.96928 13.006 2.33886 11.0912C2.70859 9.17628 3.63766 7.41274 5.00781 6.0248C5.3473 5.68128 5.90132 5.67771 6.24511 6.01699C6.58896 6.35643 6.59224 6.91038 6.25292 7.2543C5.12564 8.39621 4.36185 9.84678 4.05761 11.4223C3.75341 12.9978 3.92278 14.6283 4.54394 16.1078C5.16512 17.5874 6.21008 18.8505 7.54785 19.7367C8.88557 20.6229 10.4559 21.0923 12.0605 21.0873C13.6651 21.0823 15.2323 20.6028 16.5644 19.7084C17.8966 18.8138 18.934 17.5443 19.5459 16.0609C20.1578 14.5775 20.317 12.9461 20.0029 11.3725C19.6888 9.79885 18.9157 8.35303 17.7812 7.21816C17.4399 6.87639 17.4396 6.3224 17.7812 5.98086Z',
],
},
maximize: {
viewBox: '0 0 24 24',
paths: [
'M2.125 19V16C2.125 15.5168 2.51675 15.125 3 15.125C3.48325 15.125 3.875 15.5168 3.875 16V19C3.875 19.2984 3.99312 19.5849 4.2041 19.7959C4.41508 20.0069 4.70163 20.125 5 20.125H8C8.48325 20.125 8.875 20.5168 8.875 21C8.875 21.4832 8.48325 21.875 8 21.875H5C4.2375 21.875 3.50596 21.5724 2.9668 21.0332C2.42763 20.494 2.125 19.7625 2.125 19ZM20.125 19V16C20.125 15.5168 20.5168 15.125 21 15.125C21.4832 15.125 21.875 15.5168 21.875 16V19C21.875 19.7625 21.5724 20.494 21.0332 21.0332C20.494 21.5724 19.7625 21.875 19 21.875H16C15.5168 21.875 15.125 21.4832 15.125 21C15.125 20.5168 15.5168 20.125 16 20.125H19C19.2984 20.125 19.5849 20.0069 19.7959 19.7959C20.0069 19.5849 20.125 19.2984 20.125 19ZM2.125 8V5C2.125 4.2375 2.42763 3.50596 2.9668 2.9668C3.50596 2.42763 4.2375 2.125 5 2.125H8C8.48325 2.125 8.875 2.51675 8.875 3C8.875 3.48325 8.48325 3.875 8 3.875H5C4.70163 3.875 4.41508 3.99312 4.2041 4.2041C3.99312 4.41508 3.875 4.70163 3.875 5V8C3.875 8.48325 3.48325 8.875 3 8.875C2.51675 8.875 2.125 8.48325 2.125 8ZM20.125 8V5C20.125 4.70163 20.0069 4.41508 19.7959 4.2041C19.5849 3.99312 19.2984 3.875 19 3.875H16C15.5168 3.875 15.125 3.48325 15.125 3C15.125 2.51675 15.5168 2.125 16 2.125H19C19.7625 2.125 20.494 2.42763 21.0332 2.9668C21.5724 3.50596 21.875 4.2375 21.875 5V8C21.875 8.48325 21.4832 8.875 21 8.875C20.5168 8.875 20.125 8.48325 20.125 8Z',
],
},
minimize: {
viewBox: '0 0 24 24',
paths: [
'M7.125 21V18C7.125 17.7016 7.00688 17.4151 6.7959 17.2041C6.58492 16.9931 6.29837 16.875 6 16.875H3C2.51675 16.875 2.125 16.4832 2.125 16C2.125 15.5168 2.51675 15.125 3 15.125H6C6.7625 15.125 7.49404 15.4276 8.0332 15.9668C8.57237 16.506 8.875 17.2375 8.875 18V21C8.875 21.4832 8.48325 21.875 8 21.875C7.51675 21.875 7.125 21.4832 7.125 21ZM15.125 21V18C15.125 17.2375 15.4276 16.506 15.9668 15.9668C16.506 15.4276 17.2375 15.125 18 15.125H21C21.4832 15.125 21.875 15.5168 21.875 16C21.875 16.4832 21.4832 16.875 21 16.875H18C17.7016 16.875 17.4151 16.9931 17.2041 17.2041C16.9931 17.4151 16.875 17.7016 16.875 18V21C16.875 21.4832 16.4832 21.875 16 21.875C15.5168 21.875 15.125 21.4832 15.125 21ZM7.125 6V3C7.125 2.51675 7.51675 2.125 8 2.125C8.48325 2.125 8.875 2.51675 8.875 3V6C8.875 6.7625 8.57237 7.49404 8.0332 8.0332C7.49404 8.57237 6.7625 8.875 6 8.875H3C2.51675 8.875 2.125 8.48325 2.125 8C2.125 7.51675 2.51675 7.125 3 7.125H6C6.29837 7.125 6.58492 7.00688 6.7959 6.7959C7.00688 6.58492 7.125 6.29837 7.125 6ZM15.125 6V3C15.125 2.51675 15.5168 2.125 16 2.125C16.4832 2.125 16.875 2.51675 16.875 3V6C16.875 6.29837 16.9931 6.58492 17.2041 6.7959C17.4151 7.00688 17.7016 7.125 18 7.125H21C21.4832 7.125 21.875 7.51675 21.875 8C21.875 8.48325 21.4832 8.875 21 8.875H18C17.2375 8.875 16.506 8.57237 15.9668 8.0332C15.4276 7.49404 15.125 6.7625 15.125 6Z',
],
},
'wifi-off': {
viewBox: '0 0 24 24',
paths: [
'M1.38128 1.38128C1.72299 1.03957 2.27785 1.03957 2.61956 1.38128L22.6196 21.3813C22.9613 21.723 22.9613 22.2779 22.6196 22.6196C22.2779 22.9613 21.723 22.9613 21.3813 22.6196L15.9448 17.183C15.6121 17.3797 15.1772 17.3385 14.8881 17.0551C14.117 16.2993 13.0802 15.8764 12.0004 15.8764C10.9207 15.8764 9.88381 16.2993 9.11273 17.0551C8.76768 17.3933 8.21371 17.3883 7.87542 17.0434C7.53715 16.6983 7.54301 16.1434 7.88812 15.8051C8.98629 14.7288 10.4628 14.1264 12.0004 14.1264C12.3272 14.1264 12.651 14.1543 12.9692 14.2075L9.88714 11.1254C8.27735 11.5087 6.79851 12.3224 5.61273 13.4848C5.26764 13.8231 4.71371 13.8182 4.37542 13.4731C4.03714 13.128 4.04303 12.5741 4.38812 12.2358C5.55033 11.0965 6.94797 10.2366 8.47503 9.71331L5.98577 7.22405C4.74971 7.80461 3.60363 8.56219 2.58343 9.47308C2.22296 9.79494 1.66993 9.76324 1.34808 9.40277C1.02629 9.04229 1.05697 8.48925 1.41741 8.16741C2.40785 7.28308 3.5045 6.52832 4.68011 5.91839L1.38128 2.61956C1.03957 2.27785 1.03957 1.72299 1.38128 1.38128ZM12.0102 19.1254C12.4934 19.1254 12.8852 19.5172 12.8852 20.0004C12.8852 20.4837 12.4934 20.8754 12.0102 20.8754H12.0004C11.5172 20.8754 11.1254 20.4837 11.1254 20.0004C11.1254 19.5172 11.5172 19.1254 12.0004 19.1254H12.0102ZM16.2426 10.9028C16.4843 10.4845 17.0195 10.341 17.4379 10.5825C18.2294 11.0398 18.9602 11.5956 19.6127 12.2358C19.9576 12.5741 19.9636 13.1281 19.6254 13.4731C19.287 13.818 18.7331 13.8231 18.3881 13.4848C17.8406 12.9476 17.2271 12.4818 16.5629 12.0981C16.1445 11.8563 16.001 11.3212 16.2426 10.9028ZM10.6352 4.1889C12.7929 4.00208 14.9661 4.25848 17.0209 4.94281C19.0757 5.62716 20.9686 6.72516 22.5834 8.16839C22.9436 8.49044 22.9748 9.04348 22.6528 9.40374C22.3308 9.76385 21.7777 9.7949 21.4174 9.47308C19.9807 8.18898 18.2964 7.21188 16.4682 6.60296C14.6399 5.99405 12.7055 5.7658 10.7856 5.93206C10.3043 5.97356 9.88011 5.61739 9.83831 5.13616C9.79662 4.65472 10.1537 4.23059 10.6352 4.1889Z',
],
},
};
export default {
name: 'NovncIcon',
props: {
type: {
type: String,
required: true,
validator: (value) => Object.keys(ICONS).includes(value),
},
},
computed: {
icon() {
return ICONS[this.type];
},
},
};
</script>
<template>
<svg
class="novnc-icon"
:viewBox="icon.viewBox"
fill="currentColor"
aria-hidden="true"
focusable="false"
>
<path
v-for="(d, i) in icon.paths"
:key="i"
:d="d"
/>
</svg>
</template>
<style lang="scss" scoped>
.novnc-icon {
width: 16px;
height: 16px;
flex-shrink: 0;
}
</style>
@@ -1,232 +0,0 @@
<script>
import RcStatusIndicator from '@components/Pill/RcStatusIndicator';
import RcTag from '@components/Pill/RcTag';
import { MODIFIER_KEYS, baseKey, keyLabel, recordKey } from './shortcuts';
export default {
name: 'NovncKeyRecorder',
components: { RcStatusIndicator, RcTag },
props: {
// The recorded keys, as stored for a shortcut.
value: {
type: Array,
default: () => [],
},
ariaLabelledby: {
type: String,
default: undefined,
},
},
emits: ['update:value'],
data() {
return { recording: false, pending: [] };
},
computed: {
state() {
if (this.recording) {
return 'recording';
}
return this.value.length ? 'captured' : 'empty';
},
labels() {
return this.value.map((K) => keyLabel(baseKey(K, this.value).key));
},
valueId() {
return `vnc-key-recorder-value-${ this.$.uid }`;
},
// Read out with the field's label, so screen readers hear what is recorded.
announcement() {
if (this.state === 'recording') {
return this.t('harvester.virtualMachine.detail.console.customKeys.recorder.recordingStatus');
}
return this.labels.join('+');
},
},
methods: {
start() {
this.pending = [];
this.recording = true;
},
stop() {
this.recording = false;
this.pending = [];
},
// Modifiers wait for the key they go with; the first other key ends the combination.
onKeydown(event) {
if (!this.recording) {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
this.start();
}
return;
}
// Esc or Tab on their own leave the field, so it never traps the keyboard; with a modifier
// they are part of the combination (Ctrl+Shift+Esc).
if (!this.pending.length && (event.key === 'Escape' || event.key === 'Tab')) {
if (event.key === 'Escape') {
event.preventDefault();
event.stopPropagation();
}
this.stop();
return;
}
event.preventDefault();
event.stopPropagation();
if (event.repeat) {
return;
}
if (MODIFIER_KEYS.includes(event.key)) {
if (!this.pending.some((K) => K.key === event.key)) {
this.pending.push(recordKey(event));
}
return;
}
this.$emit('update:value', [...this.pending, recordKey(event, this.pending)]);
this.stop();
},
// Modifiers released before any other key are the combination themselves, such as the Windows key on
// its own. It waits for the last one, so Ctrl+Shift can be let go one key at a time.
onKeyup(event) {
if (!this.recording || !this.pending.length || !MODIFIER_KEYS.includes(event.key)) {
return;
}
if (event.ctrlKey || event.altKey || event.shiftKey || event.metaKey) {
return;
}
event.preventDefault();
event.stopPropagation();
this.$emit('update:value', [...this.pending]);
this.stop();
},
},
};
</script>
<template>
<div
class="key-recorder"
:class="`key-recorder--${ state }`"
role="button"
tabindex="0"
:aria-labelledby="ariaLabelledby ? `${ ariaLabelledby } ${ valueId }` : valueId"
:aria-pressed="recording"
data-testid="vnc-key-recorder"
@click="start"
@keydown="onKeydown"
@keyup="onKeyup"
@blur="stop"
>
<span
:id="valueId"
class="sr-only"
aria-live="polite"
>{{ announcement }}</span>
<template v-if="state === 'recording'">
<span class="key-recorder__hint">{{ t('harvester.virtualMachine.detail.console.customKeys.recorder.recording') }}</span>
<span class="key-recorder__status">
<RcStatusIndicator
shape="disc"
status="error"
/>
{{ t('harvester.virtualMachine.detail.console.customKeys.recorder.recordingStatus') }}
</span>
</template>
<template v-else-if="state === 'captured'">
<span class="key-recorder__keys">
<RcTag
v-for="(label, i) in labels"
:key="i"
type="active"
>
{{ label }}
</RcTag>
</span>
<span class="key-recorder__again">{{ t('harvester.virtualMachine.detail.console.customKeys.recorder.again') }}</span>
</template>
<span
v-else
class="key-recorder__hint"
>{{ t('harvester.virtualMachine.detail.console.customKeys.recorder.empty') }}</span>
</div>
</template>
<style lang="scss" scoped>
.key-recorder {
display: flex;
align-items: center;
gap: 8px;
min-height: 48px;
padding: 0 14px;
border: 1px solid var(--input-border);
border-radius: 4px;
background: var(--input-bg);
cursor: pointer;
&--empty {
border-style: dashed;
}
&--recording {
border: 2px solid var(--primary-keyboard-focus);
padding: 0 13px;
}
&:focus-visible {
@include focus-outline;
}
&__hint {
color: var(--muted);
font-size: 14px;
line-height: 21px;
}
&__keys {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
&__status,
&__again {
display: inline-flex;
align-items: center;
gap: 8px;
margin-left: auto;
font-size: 12px;
line-height: 18px;
}
&__again {
color: var(--muted);
}
}
</style>
@@ -1,404 +0,0 @@
<script>
import { h, inject } from 'vue';
import {
RcDropdown, RcDropdownGroup, RcDropdownItem, RcDropdownItemCheckbox, RcDropdownSeparator, RcDropdownTrigger
} from '@components/RcDropdown';
import { RcIcon } from '@components/RcIcon';
import { shortcutLabels } from './shortcuts';
export const MODIFIERS = [
{ key: 'ControlLeft', label: 'Ctrl' },
{ key: 'AltLeft', label: 'Alt' },
];
export const FUNCTION_KEYS = ['F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12'];
// Ctrl alone offers the browser shortcuts the guest cannot get from the keyboard (the browser keeps
// Ctrl+N/T/W for itself), as the old cascading menu did.
export const CTRL_KEYS = [
{ key: 'KeyN', label: 'N' },
{ key: 'KeyT', label: 'T' },
{ key: 'KeyW', label: 'W' },
{ key: 'KeyY', label: 'Y' },
];
// RcDropdown collects its items when the menu opens, and the arrow keys walk that list. Holding a modifier
// swaps the keys below it while the menu is open, so, as RcDropdown does for its submenus, the items are
// collected again on each key press and the arrows reach the keys shown now.
export const ShortcutMenuBody = {
name: 'ShortcutMenuBody',
setup(_props, { slots }) {
const dropdown = inject('dropdownContext', null);
const collectItems = (event) => {
const menu = event.currentTarget.closest('[dropdown-menu-collection]');
if (dropdown?.dropdownItems && menu) {
dropdown.dropdownItems.value = [...menu.querySelectorAll('[dropdown-menu-item]')];
}
};
return () => h('div', { class: 'shortcut-menu', onKeydownCapture: collectItems }, slots.default?.());
},
};
export default {
name: 'NovncShortcutKeysMenu',
components: {
RcDropdown, RcDropdownGroup, RcDropdownItem, RcDropdownItemCheckbox, RcDropdownSeparator, RcDropdownTrigger, RcIcon, ShortcutMenuBody
},
props: {
disabled: {
type: Boolean,
default: false,
},
// Saved custom shortcuts, as { name, keys }.
shortcuts: {
type: Array,
default: () => [],
},
// Keys only go out over a connected console; the menu still opens to manage shortcuts.
canSend: {
type: Boolean,
default: true,
},
// Why keys cannot be sent right now, shown at the top of the menu.
blockedReason: {
type: String,
default: '',
},
// Custom shortcuts are stored in the user preference, which standalone setups may not have.
canManage: {
type: Boolean,
default: true,
},
},
emits: ['send-keys', 'send-shortcut', 'manage', 'ctrl-alt-del'],
data() {
return { held: [] };
},
computed: {
modifiers() {
return MODIFIERS;
},
functionKeys() {
return FUNCTION_KEYS;
},
holdsCtrl() {
return this.held.includes('ControlLeft');
},
holdsAlt() {
return this.held.includes('AltLeft');
},
// What the keys below the toggles offer follows what is held, so the menu sends the same
// combinations as the old one: Ctrl+N/T/W/Y, Ctrl+Alt+Del, Alt+Print Screen and Alt+F1-F12, plus
// Ctrl+Alt+F1-F12 to switch Linux consoles.
keyOptions() {
if (this.holdsCtrl && this.holdsAlt) {
return [{ key: 'Delete', label: 'Del' }];
}
if (this.holdsCtrl) {
return CTRL_KEYS;
}
return [{ key: 'PrintScreen', label: this.t('harvester.virtualMachine.detail.console.shortcutMenu.printScreen') }];
},
showFunctionKeys() {
return !this.holdsCtrl || this.holdsAlt;
},
heldCombo() {
return MODIFIERS.filter((M) => this.held.includes(M.key)).map((M) => M.label).join('+');
},
items() {
return this.shortcuts.map((shortcut, index) => {
const label = shortcutLabels(shortcut).join('+');
return {
index, name: shortcut.name || label, label, keys: shortcut.keys
};
});
},
},
methods: {
// Held modifiers belong to this visit of the menu; closing it without a key lets them go.
onOpen(open) {
if (!open) {
this.held = [];
}
},
toggleModifier(key, on) {
this.held = on ? [...this.held, key] : this.held.filter((K) => K !== key);
},
// Held modifiers apply to the next key only, then the toggles reset.
sendKey(key) {
const modifiers = MODIFIERS.map((M) => M.key).filter((K) => this.held.includes(K));
// Ctrl+Alt+Del restarts most guests, so it goes through the same confirmation as its button.
if (key === 'Delete' && this.holdsCtrl && this.holdsAlt) {
this.$emit('ctrl-alt-del');
} else {
this.$emit('send-keys', [...modifiers, key]);
}
this.held = [];
},
},
};
</script>
<template>
<rc-dropdown
:aria-label="t('harvester.virtualMachine.detail.console.shortcutKeys')"
placement="bottom-start"
@update:open="onOpen"
>
<rc-dropdown-trigger
variant="tertiary"
data-testid="vnc-shortcut-keys"
:disabled="disabled"
>
<template #before>
<rc-icon
type="keyboard"
size="inherit"
/>
</template>
{{ t('harvester.virtualMachine.detail.console.shortcutKeys') }}
<template #after>
<rc-icon
type="chevron-down"
size="inherit"
/>
</template>
</rc-dropdown-trigger>
<template #dropdownCollection>
<shortcut-menu-body>
<p
v-if="!canSend && blockedReason"
class="shortcut-menu__blocked"
data-testid="vnc-shortcut-blocked"
>
{{ blockedReason }}
</p>
<template v-if="canManage && items.length">
<rc-dropdown-group :label="t('harvester.virtualMachine.detail.console.shortcutMenu.yourShortcuts')">
<rc-dropdown-item
v-for="item in items"
:key="item.index"
:disabled="!canSend"
class="shortcut-menu__saved"
data-testid="vnc-saved-shortcut"
:title="item.name"
@click="$emit('send-shortcut', item.keys)"
>
<span class="shortcut-menu__saved-name">{{ item.name }}</span>
<template #after>
<span class="shortcut-menu__chip">{{ item.label }}</span>
</template>
</rc-dropdown-item>
</rc-dropdown-group>
<rc-dropdown-separator />
</template>
<rc-dropdown-group :label="t('harvester.virtualMachine.detail.console.shortcutMenu.holdModifiers')">
<div class="shortcut-menu__row">
<rc-dropdown-item-checkbox
v-for="modifier in modifiers"
:key="modifier.key"
:disabled="!canSend"
indicator="checkmark"
class="shortcut-menu__chip shortcut-menu__toggle"
:class="{ 'is-on': held.includes(modifier.key) }"
:data-testid="`vnc-hold-${ modifier.label.toLowerCase() }`"
:model-value="held.includes(modifier.key)"
@update:model-value="toggleModifier(modifier.key, $event)"
>
{{ modifier.label }}
</rc-dropdown-item-checkbox>
</div>
<p
v-if="heldCombo"
class="shortcut-menu__help"
>
{{ t('harvester.virtualMachine.detail.console.shortcutMenu.holdHint', { combo: heldCombo }) }}
</p>
</rc-dropdown-group>
<rc-dropdown-separator />
<rc-dropdown-group :label="t('harvester.virtualMachine.detail.console.shortcutMenu.keys')">
<div class="shortcut-menu__row">
<rc-dropdown-item
v-for="option in keyOptions"
:key="option.key"
:disabled="!canSend"
class="shortcut-menu__chip"
:data-testid="`vnc-key-${ option.key }`"
@click="sendKey(option.key)"
>
{{ option.label }}
</rc-dropdown-item>
</div>
</rc-dropdown-group>
<rc-dropdown-group
v-if="showFunctionKeys"
:label="t('harvester.virtualMachine.detail.console.shortcutMenu.functionKeys')"
>
<div class="shortcut-menu__grid">
<rc-dropdown-item
v-for="key in functionKeys"
:key="key"
:disabled="!canSend"
class="shortcut-menu__chip"
:data-testid="`vnc-key-${ key }`"
@click="sendKey(key)"
>
{{ key }}
</rc-dropdown-item>
</div>
</rc-dropdown-group>
<template v-if="canManage">
<rc-dropdown-separator />
<rc-dropdown-item
class="shortcut-menu__manage"
data-testid="vnc-manage-shortcuts"
@click="$emit('manage')"
>
<template #before>
<rc-icon
type="edit"
size="inherit"
/>
</template>
{{ t('harvester.virtualMachine.detail.console.shortcutMenu.manage') }}
</rc-dropdown-item>
</template>
</shortcut-menu-body>
</template>
</rc-dropdown>
</template>
<style lang="scss" scoped>
// The menu items are styled as the key chips of the design; `.shortcut-menu` raises the
// specificity above RcDropdownItem's own item styles.
.shortcut-menu {
width: 320px;
&__row,
&__grid {
display: flex;
flex-wrap: wrap;
gap: 6px;
padding: 4px 16px 8px;
}
&__grid {
display: grid;
grid-template-columns: repeat(6, 1fr);
}
// The chips are the design's small secondary buttons, so they take RcButton's secondary tokens
// (with its fallbacks) and follow the brand like every other button.
.shortcut-menu__chip {
justify-content: center;
min-height: 24px;
margin: 0;
padding: 0 8px;
border: 1px solid var(--secondary-border, var(--primary));
border-radius: 4px;
background: var(--secondary, transparent);
color: var(--on-secondary, var(--primary));
font-size: 12px;
line-height: 16px;
white-space: nowrap;
&:hover {
background: var(--secondary-hover, var(--accent-btn));
}
}
.shortcut-menu__chip[disabled],
.shortcut-menu__saved[disabled] .shortcut-menu__chip {
&,
&:hover {
border-color: var(--disabled-bg, var(--border));
background: transparent;
color: var(--disabled-text);
cursor: not-allowed;
}
}
&__blocked {
margin: 0;
padding: 4px 16px 8px;
color: var(--muted);
font-size: 12px;
line-height: 18px;
}
.shortcut-menu__toggle.is-on {
&,
&:hover {
border-color: var(--active, var(--primary));
background: var(--active, var(--primary));
color: var(--on-active, var(--primary-text));
}
}
.shortcut-menu__saved {
margin: 0 9px;
padding: 4px 8px;
font-size: 14px;
// Long names stay on two lines; the full one is in the tooltip.
.shortcut-menu__saved-name {
display: -webkit-box;
min-width: 0;
overflow: hidden;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
line-clamp: 2;
}
.shortcut-menu__chip {
display: inline-flex;
align-items: center;
}
}
&__help {
margin: 0;
padding: 0 16px 8px;
color: var(--muted);
font-size: 12px;
line-height: 18px;
}
// The design's tertiary button.
.shortcut-menu__manage {
color: var(--on-tertiary, var(--primary));
}
}
</style>
@@ -1,104 +0,0 @@
<script>
import NovncIcon from './NovncIcon';
// The card the console shows on its black screen when there is nothing to type into: a failed
// connection, or a virtual machine that is not running.
export default {
name: 'NovncStatusCard',
components: { NovncIcon },
props: {
icon: {
type: String,
default: 'wifi-off',
},
title: {
type: String,
required: true,
},
detail: {
type: String,
default: '',
},
},
};
</script>
<template>
<div class="status-card">
<span
class="status-card__badge"
aria-hidden="true"
>
<NovncIcon :type="icon" />
</span>
<h3 class="status-card__title">
{{ title }}
</h3>
<p
v-if="detail"
class="status-card__detail"
>
{{ detail }}
</p>
<div
v-if="$slots.default"
class="status-card__actions"
>
<slot />
</div>
</div>
</template>
<style lang="scss" scoped>
// Always on the black screen, whatever the theme, so the text is light.
.status-card {
display: flex;
flex-direction: column;
align-items: center;
gap: 12px;
max-width: 480px;
padding: 32px;
color: #fff;
text-align: center;
&__badge {
display: flex;
align-items: center;
justify-content: center;
width: 56px;
height: 56px;
border-radius: 50%;
background: rgba(255, 255, 255, 0.12);
color: rgba(255, 255, 255, 0.8);
.novnc-icon {
width: 24px;
height: 24px;
}
}
&__title {
margin: 0;
color: #fff;
font-size: 16px;
font-weight: 700;
}
&__detail {
margin: 0;
color: rgba(255, 255, 255, 0.8);
font-size: 13px;
line-height: 16px;
}
&__actions {
display: flex;
gap: 12px;
padding-top: 8px;
}
}
</style>
@@ -1,302 +0,0 @@
<script>
import ButtonGroup from '@shell/components/ButtonGroup';
import { RcButton } from '@components/RcButton';
import { RcIcon } from '@components/RcIcon';
import { MAXIMUM_ZOOM, MINIMUM_ZOOM, ZOOM_STEP } from './ZoomableRFB';
export const VIEW_MODE = {
SCALE: 'scale',
NONE: 'none',
};
const MAXIMUM_LEVEL = 9;
export default {
name: 'NovncViewOptions',
components: {
ButtonGroup, RcButton, RcIcon
},
props: {
settings: {
type: Object,
required: true,
},
},
emits: ['update', 'reset'],
computed: {
modeOptions() {
return [
{ value: VIEW_MODE.SCALE, label: this.t('harvester.virtualMachine.detail.console.viewOptions.automatic') },
{ value: VIEW_MODE.NONE, label: this.t('harvester.virtualMachine.detail.console.viewOptions.manual') },
];
},
isManual() {
return this.settings.viewMode === VIEW_MODE.NONE;
},
zoom() {
return {
min: MINIMUM_ZOOM, max: MAXIMUM_ZOOM, step: ZOOM_STEP
};
},
maximumLevel() {
return MAXIMUM_LEVEL;
},
},
methods: {
update(key, value) {
this.$emit('update', { ...this.settings, [key]: value });
},
stepZoom(direction) {
const next = this.settings.zoomPercent + (direction * ZOOM_STEP);
this.update('zoomPercent', Math.min(Math.max(next, MINIMUM_ZOOM), MAXIMUM_ZOOM));
},
// Feeds the filled part of the track, which native range inputs do not draw on their own.
fill(value, min, max) {
return { '--fill': `${ ((value - min) / (max - min)) * 100 }%` };
},
},
};
</script>
<template>
<div
class="view-options"
data-testid="vnc-view-options"
>
<section class="view-options__section">
<span class="view-options__label">{{ t('harvester.virtualMachine.detail.console.viewOptions.scaling') }}</span>
<ButtonGroup
class="view-options__mode"
size="medium"
:value="settings.viewMode"
:options="modeOptions"
@update:value="update('viewMode', $event)"
/>
<p class="view-options__help">
{{ t(`harvester.virtualMachine.detail.console.viewOptions.${ isManual ? 'manualHelp' : 'automaticHelp' }`) }}
</p>
</section>
<section class="view-options__section">
<label
for="vnc-zoom"
class="view-options__row"
>
<span class="view-options__label">{{ t('harvester.virtualMachine.detail.console.viewOptions.zoom') }}</span>
<span class="view-options__value">{{ settings.zoomPercent }}%</span>
</label>
<div class="view-options__zoom">
<RcButton
variant="secondary"
size="small"
:aria-label="t('harvester.virtualMachine.detail.console.viewOptions.zoomOut')"
:disabled="!isManual || settings.zoomPercent <= zoom.min"
@click="stepZoom(-1)"
>
<RcIcon
type="minus"
size="inherit"
/>
</RcButton>
<input
id="vnc-zoom"
class="view-options__slider"
type="range"
:min="zoom.min"
:max="zoom.max"
:step="zoom.step"
:value="settings.zoomPercent"
:disabled="!isManual"
:aria-valuetext="`${ settings.zoomPercent }%`"
:style="fill(settings.zoomPercent, zoom.min, zoom.max)"
@input="update('zoomPercent', Number($event.target.value))"
>
<RcButton
variant="secondary"
size="small"
:aria-label="t('harvester.virtualMachine.detail.console.viewOptions.zoomIn')"
:disabled="!isManual || settings.zoomPercent >= zoom.max"
@click="stepZoom(1)"
>
<RcIcon
type="plus"
size="inherit"
/>
</RcButton>
</div>
</section>
<hr class="view-options__divider">
<section
v-for="level in ['qualityLevel', 'compressionLevel']"
:key="level"
class="view-options__section"
>
<label
:for="`vnc-${ level }`"
class="view-options__row"
>
<span class="view-options__label">{{ t(`harvester.virtualMachine.detail.console.viewOptions.${ level }.label`) }}</span>
<span class="view-options__value">{{ t('harvester.virtualMachine.detail.console.viewOptions.levelOf', { value: settings[level], max: maximumLevel }) }}</span>
</label>
<input
:id="`vnc-${ level }`"
class="view-options__slider"
type="range"
min="0"
:max="maximumLevel"
step="1"
:value="settings[level]"
:style="fill(settings[level], 0, maximumLevel)"
@input="update(level, Number($event.target.value))"
>
<p class="view-options__help">
{{ t(`harvester.virtualMachine.detail.console.viewOptions.${ level }.help`) }}
</p>
</section>
<RcButton
variant="link"
class="view-options__reset"
data-testid="vnc-view-reset"
@click="$emit('reset')"
>
{{ t('harvester.virtualMachine.detail.console.viewOptions.reset') }}
</RcButton>
</div>
</template>
<style lang="scss" scoped>
.view-options {
display: flex;
flex-direction: column;
gap: 18px;
width: 336px;
padding: 16px;
box-sizing: border-box;
&__section {
display: flex;
flex-direction: column;
gap: 8px;
}
&__row {
display: flex;
justify-content: space-between;
gap: 8px;
margin: 0;
}
&__label {
color: var(--body-text);
font-size: 12px;
font-weight: 700;
line-height: 18px;
}
&__value,
&__help {
color: var(--muted);
font-size: 12px;
line-height: 18px;
font-variant-numeric: tabular-nums;
}
&__help {
margin: 0;
}
&__mode {
display: flex;
button {
flex: 1;
}
}
&__zoom {
display: flex;
align-items: center;
gap: 8px;
// Between the zoom buttons the slider takes the room that is left. In the other sections, which
// are columns, the same rule would set its height and squash it to the track.
.view-options__slider {
flex: 1;
}
}
&__divider {
margin: 0;
border: 0;
border-top: 1px solid var(--border);
}
// Links sit flush with the panel text instead of carrying button padding.
&__reset {
align-self: flex-start;
--rc-button-padding: 0;
}
&__slider {
width: 100%;
height: 20px;
margin: 0;
background: transparent;
cursor: pointer;
appearance: none;
&::-webkit-slider-runnable-track {
height: 4px;
border-radius: 2px;
background: linear-gradient(to right, var(--primary) var(--fill), var(--muted) var(--fill));
}
&::-moz-range-track {
height: 4px;
border-radius: 2px;
background: linear-gradient(to right, var(--primary) var(--fill), var(--muted) var(--fill));
}
&::-webkit-slider-thumb {
width: 16px;
height: 16px;
margin-top: -6px;
border: 2px solid var(--nav-bg);
border-radius: 50%;
background: var(--primary);
appearance: none;
}
&::-moz-range-thumb {
width: 12px;
height: 12px;
border: 2px solid var(--nav-bg);
border-radius: 50%;
background: var(--primary);
}
&:focus-visible {
@include focus-outline;
}
&:disabled {
cursor: not-allowed;
opacity: 0.5;
}
}
}
</style>
@@ -1,73 +0,0 @@
import RFB from '@novnc/novnc/core/rfb';
export const MINIMUM_ZOOM = 50;
export const MAXIMUM_ZOOM = 200;
export const ZOOM_STEP = 10;
// The focus ring and the gap before it, drawn outside the canvas.
const FOCUS_RING_WIDTH = 4;
export function normalizeZoom(value) {
const percent = Number(value);
if (!Number.isFinite(percent)) {
return 100;
}
return Math.min(MAXIMUM_ZOOM, Math.max(MINIMUM_ZOOM, Math.round(percent / ZOOM_STEP) * ZOOM_STEP));
}
export default class ZoomableRFB extends RFB {
get zoomPercent() {
return this._zoomPercent ?? 100;
}
set zoomPercent(value) {
this._zoomPercent = normalizeZoom(value);
this._updateScale();
}
// The screen takes all the room it has, without a focus ring around it.
get edgeToEdge() {
return !!this._edgeToEdge;
}
set edgeToEdge(value) {
this._edgeToEdge = value;
this._updateScale();
}
_updateScale() {
if (this.scaleViewport) {
// Fit inside the focus ring the console draws around the canvas, instead of under it.
const size = this._screenSize();
const inset = this.edgeToEdge ? 0 : 2 * FOCUS_RING_WIDTH;
this._display.autoscale(size.w - inset, size.h - inset);
this._fixScrollbars();
} else {
this._display.scale = this.zoomPercent / 100;
this._fixScrollbars();
}
}
// noVNC only stops a click on the screen, which Firefox delivers there (others to the page, past
// noVNC's mouse capture). An open menu would never see the click outside it and would stay open.
_handleMouse(ev) {
if (ev.type !== 'click') {
super._handleMouse(ev);
}
}
// noVNC hides the mouse over the screen until the guest sends a pointer image, and a text console
// or a guest that draws its own pointer never does. Show the system pointer unless one arrives.
_refreshCursor() {
super._refreshCursor();
const hasGuestPointer = this._cursorImage.rgbaPixels.some((value, index) => index % 4 === 3 && value > 0);
if (!hasGuestPointer) {
this._canvas.style.cursor = 'default';
}
}
}
@@ -1,19 +0,0 @@
import { shallowMount } from '@vue/test-utils';
import { RcButton } from '@components/RcButton';
import NovncConnectionStatus from '../NovncConnectionStatus.vue';
jest.mock('../ZoomableRFB', () => ({}));
describe('component: NovncConnectionStatus', () => {
// A plain button takes the global 40px button height, taller than the 32px pill around it.
it('should offer Reconnect as an RcButton when the console is disconnected', () => {
const wrapper = shallowMount(NovncConnectionStatus, { props: { status: 'disconnected', label: 'Disconnected' } });
const reconnect = wrapper.findComponent(RcButton);
expect(reconnect.attributes('data-testid')).toBe('vnc-connection-reconnect');
reconnect.vm.$emit('click');
expect(wrapper.emitted('reconnect')).toHaveLength(1);
});
});
@@ -1,241 +0,0 @@
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);
expect(wrapper.vm.canTakeOver).toBe(false);
});
it('should retry, not report in use, when a VM that just started refuses the first connection', async() => {
const wrapper = mountConsole({ startedAt: Date.now() });
await jest.runOnlyPendingTimersAsync();
lastRFB().emit('disconnect');
expect(wrapper.vm.status).toBe(CONSOLE_STATUS.RECONNECTING);
expect(wrapper.vm.failure).toBe('');
});
it('should keep counting retries when Reconnect now skips the wait', async() => {
const wrapper = mountConsole();
await jest.runOnlyPendingTimersAsync();
lastRFB().emit('connect');
lastRFB().emit('disconnect');
expect(wrapper.vm.retryTimes).toBe(1);
wrapper.vm.retryNow();
expect(wrapper.vm.retryTimes).toBe(1);
expect(wrapper.vm.status).toBe(CONSOLE_STATUS.RECONNECTING);
// Still held by the other session: back to waiting, not the in-use failure.
lastRFB().emit('disconnect');
expect(wrapper.vm.status).toBe(CONSOLE_STATUS.RECONNECTING);
expect(wrapper.vm.retryTimes).toBe(2);
});
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');
});
it('should drop the focus ring and its room when the screen goes edge to edge', async() => {
const wrapper = mountConsole();
const view = wrapper.find('.novnc-screen');
await jest.runOnlyPendingTimersAsync();
expect(view.classes()).not.toContain('is-edge-to-edge');
expect(lastRFB().edgeToEdge).toBe(false);
await wrapper.setProps({ settings: { edgeToEdge: true } });
expect(view.classes()).toContain('is-edge-to-edge');
expect(lastRFB().edgeToEdge).toBe(true);
});
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);
});
});
@@ -1,161 +0,0 @@
import { reactive } from 'vue';
import { flushPromises, mount, shallowMount } from '@vue/test-utils';
import { RcButton } from '@components/RcButton';
import NovncConsoleCustomKeys from '../NovncConsoleCustomKeys.vue';
import { SHORTCUTS_PREFERENCE, SHORTCUT_NAMES_PREFERENCE } from '../shortcuts';
const key = (value, code) => ({ key: value, code });
const CTRL_F2 = [key('Control', 'ControlLeft'), key('F2', 'F2')];
const CTRL_SPACE = [key('Control', 'ControlLeft'), key(' ', 'Space')];
const ALT_T = [key('Alt', 'AltLeft'), key('t', 'KeyT')];
// `rendered` mounts the buttons and the recorder for real, in the document, so the focus can be checked.
const mountKeys = (saved = [], { rendered = false } = {}) => {
// Reactive like the store's, so the list follows what is saved.
const preference = reactive({
data: { [SHORTCUTS_PREFERENCE]: JSON.stringify(saved) },
save: jest.fn().mockResolvedValue(),
});
const wrapper = (rendered ? mount : shallowMount)(NovncConsoleCustomKeys, {
props: { show: true },
attachTo: rendered ? document.body : undefined,
global: {
mocks: { $store: { getters: { 'management/all': () => [preference] } } },
stubs: {
RcModal: { template: '<div><slot /></div>' }, Banner: { template: '<div><slot /></div>' }, LabeledInput: true
},
},
});
return { wrapper, preference };
};
const listed = (wrapper) => wrapper.findAll('[data-testid="vnc-custom-shortcut"]');
const removeShortcut = async(wrapper, index) => {
listed(wrapper)[index].findComponent(RcButton).vm.$emit('click');
await flushPromises();
};
const savedKeys = (preference) => JSON.parse(preference.data[SHORTCUTS_PREFERENCE]);
describe('component: NovncConsoleCustomKeys', () => {
it('should offer to remove every saved shortcut', () => {
const { wrapper } = mountKeys([CTRL_F2, ALT_T]);
expect(listed(wrapper).map((item) => item.findComponent(RcButton).exists())).toStrictEqual([true, true]);
});
it('should save the list without the shortcut that was removed', async() => {
const { wrapper, preference } = mountKeys([CTRL_F2, ALT_T]);
await removeShortcut(wrapper, 0);
expect(preference.save).toHaveBeenCalledTimes(1);
expect(savedKeys(preference)).toStrictEqual([ALT_T]);
expect(listed(wrapper)).toHaveLength(1);
});
it('should remove a shortcut with the Space key in it', async() => {
const { wrapper, preference } = mountKeys([CTRL_SPACE, ALT_T]);
await removeShortcut(wrapper, 0);
expect(savedKeys(preference)).toStrictEqual([ALT_T]);
});
it('should keep the shortcut when removing it cannot be saved, and say so in the dialog', async() => {
const { wrapper, preference } = mountKeys([CTRL_F2, ALT_T]);
preference.save.mockRejectedValue(new Error('forbidden'));
await removeShortcut(wrapper, 0);
expect(savedKeys(preference)).toStrictEqual([CTRL_F2, ALT_T]);
expect(listed(wrapper)).toHaveLength(2);
expect(wrapper.find('[data-testid="vnc-custom-keys-error"]').text()).toBe('%harvester.virtualMachine.detail.console.customKeys.saveError%: forbidden');
await wrapper.setProps({ show: false });
expect(wrapper.find('[data-testid="vnc-custom-keys-error"]').exists()).toBe(false);
});
it('should not start a second save while one is running', async() => {
const { wrapper, preference } = mountKeys([CTRL_F2, ALT_T]);
wrapper.vm.remove(0);
wrapper.vm.remove(1);
await flushPromises();
expect(preference.save).toHaveBeenCalledTimes(1);
});
it('should keep the focus on a delete button after a removal, and hand it to the recorder once the list is empty', async() => {
const { wrapper } = mountKeys([CTRL_F2, ALT_T], { rendered: true });
const deleteButtons = () => wrapper.findAll('[data-testid="vnc-custom-shortcut"] button');
deleteButtons()[1].element.focus();
await deleteButtons()[1].trigger('click');
await flushPromises();
expect(document.activeElement).toBe(deleteButtons()[0].element);
await deleteButtons()[0].trigger('click');
await flushPromises();
expect(document.activeElement).toBe(wrapper.find('[data-testid="vnc-key-recorder"]').element);
wrapper.unmount();
});
it('should give the recorder the focus after a shortcut is added', async() => {
const { wrapper } = mountKeys([CTRL_F2], { rendered: true });
wrapper.vm.keys = ALT_T;
await wrapper.vm.$nextTick();
wrapper.find('[data-testid="vnc-add-shortcut"]').element.focus();
await wrapper.find('[data-testid="vnc-add-shortcut"]').trigger('click');
await flushPromises();
expect(document.activeElement).toBe(wrapper.find('[data-testid="vnc-key-recorder"]').element);
wrapper.unmount();
});
it('should empty the form as soon as a shortcut is added, so it does not say it is already saved while it saves', async() => {
const { wrapper, preference } = mountKeys([CTRL_F2]);
preference.save.mockReturnValue(new Promise(() => {}));
wrapper.vm.keys = ALT_T;
wrapper.vm.add();
await wrapper.vm.$nextTick();
expect(listed(wrapper)).toHaveLength(2);
expect(wrapper.vm.keys).toStrictEqual([]);
expect(wrapper.find('.custom-keys__error').exists()).toBe(false);
});
it('should put the shortcut back in the form when it cannot be saved', async() => {
const { wrapper, preference } = mountKeys([CTRL_F2]);
preference.save.mockRejectedValue(new Error('forbidden'));
wrapper.vm.keys = ALT_T;
wrapper.vm.name = 'Task manager';
await wrapper.vm.add();
expect(listed(wrapper)).toHaveLength(1);
expect(wrapper.vm.keys).toStrictEqual(ALT_T);
expect(wrapper.vm.name).toBe('Task manager');
});
it('should save a new shortcut straight away, with its name', async() => {
const { wrapper, preference } = mountKeys([CTRL_F2]);
wrapper.vm.keys = ALT_T;
wrapper.vm.name = ' Task manager ';
await wrapper.vm.add();
expect(savedKeys(preference)).toStrictEqual([CTRL_F2, ALT_T]);
expect(JSON.parse(preference.data[SHORTCUT_NAMES_PREFERENCE])).toStrictEqual({ 'AltLeft+KeyT': 'Task manager' });
expect(wrapper.vm.keys).toStrictEqual([]);
});
});
@@ -1,321 +0,0 @@
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 CHECKBOX = { name: 'Checkbox' };
const mountWrapper = ({ preferences = [], storage = {} } = {}) => {
// The console settings are saved there, so one test's would load in the next.
window.localStorage.clear();
Object.entries(storage).forEach(([key, value]) => window.localStorage.setItem(key, JSON.stringify(value)));
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': () => preferences,
'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 keep the shortcut menu open to use while keys cannot be sent, and say why', () => {
const wrapper = mountWrapper();
wrapper.vm.onStatusChanged({ status: 'reconnecting' });
expect(wrapper.vm.shortcutMenuProps.canSend).toBe(false);
expect(wrapper.vm.sendBlockedReason).toBe('%harvester.virtualMachine.detail.console.shortcutMenu.blockedDisconnected%');
// Without a user preference there is nothing to manage either, so only then is it disabled.
expect(wrapper.vm.shortcutMenuProps.disabled).toBe(true);
});
it('should keep the shortcut menu enabled while disconnected when there are shortcuts to manage', () => {
const wrapper = mountWrapper({ preferences: [{ data: {} }] });
wrapper.vm.onStatusChanged({ status: 'reconnecting' });
expect(wrapper.vm.shortcutMenuProps.canSend).toBe(false);
expect(wrapper.vm.shortcutMenuProps.disabled).toBe(false);
});
it('should disable the shortcut menu, managing shortcuts included, while view only is on', () => {
const wrapper = mountWrapper({ preferences: [{ data: {} }] });
expect(wrapper.vm.shortcutMenuProps.disabled).toBe(false);
wrapper.vm.setViewOnly(true);
expect(wrapper.vm.shortcutMenuProps.disabled).toBe(true);
});
it('should disable Ctrl+Alt+Del and Soft reboot while view only is on', async() => {
const wrapper = mountWrapper();
const doSoftReboot = jest.fn();
const button = (id) => wrapper.find(`[data-testid="${ id }"]`);
wrapper.vm.vmResource = { doSoftReboot, actions: { softreboot: 'url' } };
await wrapper.vm.$nextTick();
expect(button('vnc-soft-reboot').attributes('disabled')).toBe('false');
expect(button('vnc-ctrl-alt-del').attributes('disabled')).toBe('false');
wrapper.vm.setViewOnly(true);
await wrapper.vm.$nextTick();
expect(button('vnc-soft-reboot').attributes('disabled')).toBe('true');
expect(button('vnc-ctrl-alt-del').attributes('disabled')).toBe('true');
wrapper.vm.softReboot();
wrapper.vm.ctrlAltDelete();
expect(wrapper.vm.confirmAction).toBeNull();
expect(doSoftReboot).not.toHaveBeenCalled();
});
it('should say so under the console while view only is on', async() => {
const wrapper = mountWrapper();
const hint = () => wrapper.find('.console-area__hint').text();
expect(hint()).toBe('%harvester.virtualMachine.detail.console.hint%');
wrapper.vm.setViewOnly(true);
await wrapper.vm.$nextTick();
expect(hint()).toBe('%harvester.virtualMachine.detail.console.hintViewOnly%');
});
it('should not send keys while view only is on', () => {
const wrapper = mountWrapper();
wrapper.vm.setViewOnly(true);
expect(wrapper.vm.canSendKeys).toBe(false);
});
it('should switch view only with the checkbox, and not repeat it in the connection status', async() => {
const wrapper = mountWrapper();
const checkbox = () => wrapper.findComponent(CHECKBOX);
expect(checkbox().props('value')).toBe(false);
checkbox().vm.$emit('update:value', true);
await wrapper.vm.$nextTick();
expect(wrapper.vm.settings.viewOnly).toBe(true);
expect(checkbox().props('value')).toBe(true);
expect(wrapper.vm.statusLabel).toBe('%harvester.virtualMachine.detail.console.status.connected%');
});
it('should give the console the keyboard when view only is turned off, not when it is turned on', async() => {
const wrapper = mountWrapper();
wrapper.vm.setViewOnly(true);
await wrapper.vm.$nextTick();
expect(consoleRef.focus).not.toHaveBeenCalled();
wrapper.vm.setViewOnly(false);
await wrapper.vm.$nextTick();
expect(consoleRef.focus).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();
});
describe('view settings', () => {
it('should not take what the previous console saved on its first open as a choice', () => {
const wrapper = mountWrapper({
storage: {
'harvester-vnc-console-settings': {
viewMode: 'none', zoomPercent: 100, viewOnly: false, qualityLevel: 6, compressionLevel: 2
}
}
});
expect(wrapper.vm.settings.viewMode).toBe('scale');
});
it('should carry view only over from the previous console, which saved it on only when the user turned it on', () => {
const wrapper = mountWrapper({
storage: {
'harvester-vnc-console-settings': {
viewMode: 'none', zoomPercent: 150, viewOnly: true, qualityLevel: 9, compressionLevel: 0
}
}
});
expect(wrapper.vm.settings).toMatchObject({
viewOnly: true, viewMode: 'scale', zoomPercent: 100
});
});
it('should take view only from its own settings once it has saved them', () => {
const wrapper = mountWrapper({
storage: {
'harvester-vnc-console-settings': { viewOnly: true },
'harvester-vnc-console-view': { viewOnly: false },
}
});
expect(wrapper.vm.settings.viewOnly).toBe(false);
});
it('should save the settings only once the user changes one, and load them next time', async() => {
const wrapper = mountWrapper();
await wrapper.vm.$nextTick();
expect(window.localStorage).toHaveLength(0);
wrapper.vm.updateSettings({
...wrapper.vm.settings, viewMode: 'none', zoomPercent: 150
});
const reopened = mountWrapper({ storage: { 'harvester-vnc-console-view': JSON.parse(window.localStorage.getItem('harvester-vnc-console-view')) } });
expect(reopened.vm.settings).toMatchObject({ viewMode: 'none', zoomPercent: 150 });
});
it('should keep view only on when the View panel resets its settings', () => {
const wrapper = mountWrapper();
wrapper.vm.setViewOnly(true);
wrapper.vm.updateSettings({ ...wrapper.vm.settings, zoomPercent: 150 });
wrapper.vm.resetSettings();
expect(wrapper.vm.settings).toMatchObject({ viewOnly: true, zoomPercent: 100 });
expect(wrapper.vm.rfbSettings.viewOnly).toBe(true);
});
});
describe('in full screen', () => {
it('should fill the window whatever the saved view mode, and go back to it afterwards', () => {
const wrapper = mountWrapper();
wrapper.vm.updateSettings({ ...wrapper.vm.settings, viewMode: 'none' });
expect(wrapper.vm.rfbSettings).toMatchObject({ scaleViewport: false, edgeToEdge: false });
wrapper.vm.isFullscreen = true;
expect(wrapper.vm.rfbSettings).toMatchObject({ scaleViewport: true, edgeToEdge: true });
wrapper.vm.isFullscreen = false;
expect(wrapper.vm.rfbSettings).toMatchObject({ scaleViewport: false, edgeToEdge: false });
});
it('should leave the view only checkbox out of the bar, and keep view only as it was', async() => {
const wrapper = mountWrapper();
wrapper.vm.setViewOnly(true);
wrapper.vm.isFullscreen = true;
await wrapper.vm.$nextTick();
expect(wrapper.findComponent(CHECKBOX).exists()).toBe(false);
expect(wrapper.vm.rfbSettings.viewOnly).toBe(true);
expect(wrapper.vm.shortcutMenuProps.disabled).toBe(true);
wrapper.vm.isFullscreen = false;
await wrapper.vm.$nextTick();
expect(wrapper.findComponent(CHECKBOX).props('value')).toBe(true);
});
it('should leave Ctrl+Alt+Del out of the bar', async() => {
const wrapper = mountWrapper();
wrapper.vm.isFullscreen = true;
await wrapper.vm.$nextTick();
expect(wrapper.find('[data-testid="vnc-fullscreen-bar"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="vnc-ctrl-alt-del"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="vnc-fullscreen-ctrl-alt-del"]').exists()).toBe(false);
});
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;
});
});
});
@@ -1,91 +0,0 @@
import { shallowMount } from '@vue/test-utils';
import NovncKeyRecorder from '../NovncKeyRecorder.vue';
const key = (k, code, extra = {}) => ({
key: k, code, keyCode: 0, location: 0, charCode: 0, repeat: false, preventDefault: jest.fn(), stopPropagation: jest.fn(), ...extra
});
describe('component: NovncKeyRecorder', () => {
it('should hold modifiers until another key ends the combination', () => {
const wrapper = shallowMount(NovncKeyRecorder);
wrapper.vm.start();
wrapper.vm.onKeydown(key('Control', 'ControlLeft'));
wrapper.vm.onKeydown(key('Shift', 'ShiftLeft'));
wrapper.vm.onKeydown(key('Control', 'ControlLeft', { repeat: true }));
wrapper.vm.onKeydown(key('Escape', 'Escape'));
expect(wrapper.emitted('update:value')[0][0].map((K) => K.code)).toStrictEqual(['ControlLeft', 'ShiftLeft', 'Escape']);
expect(wrapper.vm.recording).toBe(false);
});
it('should keep the browser from acting on keys while recording', () => {
const wrapper = shallowMount(NovncKeyRecorder);
const event = key('w', 'KeyW');
wrapper.vm.start();
wrapper.vm.onKeydown(event);
expect(event.preventDefault).toHaveBeenCalledWith();
});
it('should record a modifier pressed and released on its own, such as the Windows key', () => {
const wrapper = shallowMount(NovncKeyRecorder);
wrapper.vm.start();
wrapper.vm.onKeydown(key('Meta', 'MetaLeft'));
wrapper.vm.onKeyup(key('Meta', 'MetaLeft'));
expect(wrapper.emitted('update:value')[0][0].map((K) => K.code)).toStrictEqual(['MetaLeft']);
expect(wrapper.vm.recording).toBe(false);
});
it('should wait for the last modifier to be released before recording them', () => {
const wrapper = shallowMount(NovncKeyRecorder);
wrapper.vm.start();
wrapper.vm.onKeydown(key('Control', 'ControlLeft'));
wrapper.vm.onKeydown(key('Shift', 'ShiftLeft'));
wrapper.vm.onKeyup(key('Shift', 'ShiftLeft', { ctrlKey: true }));
expect(wrapper.emitted('update:value')).toBeUndefined();
wrapper.vm.onKeyup(key('Control', 'ControlLeft'));
expect(wrapper.emitted('update:value')[0][0].map((K) => K.code)).toStrictEqual(['ControlLeft', 'ShiftLeft']);
});
it('should drop a combination of modifiers only when it loses focus', () => {
const wrapper = shallowMount(NovncKeyRecorder);
wrapper.vm.start();
wrapper.vm.onKeydown(key('Alt', 'AltLeft'));
wrapper.vm.stop();
expect(wrapper.emitted('update:value')).toBeUndefined();
expect(wrapper.vm.state).toBe('empty');
});
it('should stop recording on Esc or Tab alone, without recording them', () => {
const wrapper = shallowMount(NovncKeyRecorder);
const tab = key('Tab', 'Tab');
wrapper.vm.start();
wrapper.vm.onKeydown(key('Escape', 'Escape'));
expect(wrapper.vm.recording).toBe(false);
wrapper.vm.start();
wrapper.vm.onKeydown(tab);
expect(wrapper.vm.recording).toBe(false);
expect(tab.preventDefault).not.toHaveBeenCalled();
expect(wrapper.emitted('update:value')).toBeUndefined();
});
it('should record a letter by its key, not the symbol a layout made of it', () => {
const wrapper = shallowMount(NovncKeyRecorder);
wrapper.vm.start();
wrapper.vm.onKeydown(key('Alt', 'AltLeft'));
wrapper.vm.onKeydown(key('©', 'KeyG'));
expect(wrapper.emitted('update:value')[0][0].map((K) => K.key)).toStrictEqual(['Alt', 'g']);
});
});
@@ -1,158 +0,0 @@
import { ref } from 'vue';
import { mount, shallowMount } from '@vue/test-utils';
import NovncShortcutKeysMenu, { ShortcutMenuBody } from '../NovncShortcutKeysMenu.vue';
import {
keyLabel, normalizeShortcut, readShortcuts, shortcutLabels, writeShortcuts, SHORTCUTS_PREFERENCE, SHORTCUT_NAMES_PREFERENCE
} from '../shortcuts';
const mountMenu = (props = {}) => shallowMount(NovncShortcutKeysMenu, { props });
describe('component: NovncShortcutKeysMenu', () => {
it('should send a key on its own when no modifier is held', () => {
const wrapper = mountMenu();
wrapper.vm.sendKey('F5');
expect(wrapper.emitted('send-keys')).toStrictEqual([[['F5']]]);
});
it('should send held modifiers with the next key and then release them', () => {
const wrapper = mountMenu();
wrapper.vm.toggleModifier('AltLeft', true);
wrapper.vm.toggleModifier('ControlLeft', true);
expect(wrapper.vm.heldCombo).toBe('Ctrl+Alt');
wrapper.vm.sendKey('F2');
expect(wrapper.emitted('send-keys')).toStrictEqual([[['ControlLeft', 'AltLeft', 'F2']]]);
expect(wrapper.vm.held).toStrictEqual([]);
});
it('should offer the keys that go with what is held, like the old menu', async() => {
const wrapper = mountMenu();
const keys = () => wrapper.vm.keyOptions.map((K) => K.key);
expect(keys()).toStrictEqual(['PrintScreen']);
expect(wrapper.vm.showFunctionKeys).toBe(true);
wrapper.vm.toggleModifier('ControlLeft', true);
expect(keys()).toStrictEqual(['KeyN', 'KeyT', 'KeyW', 'KeyY']);
expect(wrapper.vm.showFunctionKeys).toBe(false);
wrapper.vm.toggleModifier('AltLeft', true);
expect(keys()).toStrictEqual(['Delete']);
expect(wrapper.vm.showFunctionKeys).toBe(true);
wrapper.vm.toggleModifier('ControlLeft', false);
expect(keys()).toStrictEqual(['PrintScreen']);
expect(wrapper.vm.showFunctionKeys).toBe(true);
});
it('should send Ctrl+W from the menu', () => {
const wrapper = mountMenu();
wrapper.vm.toggleModifier('ControlLeft', true);
wrapper.vm.sendKey('KeyW');
expect(wrapper.emitted('send-keys')).toStrictEqual([[['ControlLeft', 'KeyW']]]);
});
it('should hand Ctrl+Alt+Del to the confirmation instead of sending it', () => {
const wrapper = mountMenu();
wrapper.vm.toggleModifier('ControlLeft', true);
wrapper.vm.toggleModifier('AltLeft', true);
wrapper.vm.sendKey('Delete');
expect(wrapper.emitted('ctrl-alt-del')).toHaveLength(1);
expect(wrapper.emitted('send-keys')).toBeUndefined();
expect(wrapper.vm.held).toStrictEqual([]);
});
it('should let held modifiers go when the menu closes without a key', () => {
const wrapper = mountMenu();
wrapper.vm.toggleModifier('ControlLeft', true);
wrapper.vm.onOpen(false);
expect(wrapper.vm.held).toStrictEqual([]);
});
it('should name saved shortcuts by their keys when they have no name', () => {
const wrapper = mountMenu({
shortcuts: [
{ name: 'Open terminal', keys: [{ key: 'Control' }, { key: 'Alt' }, { key: 't' }] },
{ name: '', keys: [{ key: 'Escape' }] },
]
});
expect(wrapper.vm.items.map(({ name, label }) => [name, label])).toStrictEqual([
['Open terminal', 'Ctrl+Alt+T'],
['Esc', 'Esc'],
]);
});
it('should give the arrow keys the items shown after a modifier swapped them', async() => {
const dropdownItems = ref([]);
const keys = ref(['PrintScreen']);
const wrapper = mount({
components: { ShortcutMenuBody },
setup: () => ({ keys }),
template: '<div dropdown-menu-collection><shortcut-menu-body><div v-for="key in keys" :key="key" dropdown-menu-item>{{ key }}</div></shortcut-menu-body></div>',
}, { global: { provide: { dropdownContext: { dropdownItems } } } });
keys.value = ['KeyN', 'KeyT'];
await wrapper.vm.$nextTick();
await wrapper.find('[dropdown-menu-item]').trigger('keydown', { key: 'ArrowDown' });
expect(dropdownItems.value.map((item) => item.textContent)).toStrictEqual(['KeyN', 'KeyT']);
});
});
describe('shortcuts', () => {
it('should read both the old list format and the named format', () => {
const keys = [{ key: 'Control', code: 'ControlLeft' }];
expect(normalizeShortcut(keys)).toStrictEqual({ name: '', keys });
expect(normalizeShortcut({ name: 'Task manager', keys })).toStrictEqual({ name: 'Task manager', keys });
expect(normalizeShortcut({ name: 'Broken' })).toStrictEqual({ name: 'Broken', keys: [] });
});
it('should label keys the way the console menus show them', () => {
expect(keyLabel('Control')).toBe('Ctrl');
expect(keyLabel('a')).toBe('A');
expect(keyLabel('F2')).toBe('F2');
expect(shortcutLabels({ keys: [{ key: 'Shift' }, { key: ' ' }] })).toStrictEqual(['Shift', 'Space']);
expect(shortcutLabels({ keys: [{ key: 'Alt', code: 'AltLeft' }, { key: '©', code: 'KeyG' }] })).toStrictEqual(['Alt', 'G']);
// Real keys of other layouts stay as typed: AZERTY comma on KeyM, Windows AltGr (Ctrl+Alt) letters.
expect(shortcutLabels({ keys: [{ key: 'Control', code: 'ControlLeft' }, { key: ',', code: 'KeyM' }] })).toStrictEqual(['Ctrl', ',']);
expect(shortcutLabels({ keys: [{ key: 'Control', code: 'ControlLeft' }, { key: 'Alt', code: 'AltRight' }, { key: 'ą', code: 'KeyA' }] })).toStrictEqual(['Ctrl', 'Alt', 'Ą']);
expect(shortcutLabels({ keys: [{ key: 'Alt', code: 'AltLeft' }, { key: 'Dead', code: 'KeyE' }] })).toStrictEqual(['Alt', 'E']);
});
it('should keep the key list in the format older versions read and store names apart', async() => {
const keys = [{ key: 'Control', code: 'ControlLeft' }, { key: 't', code: 'KeyT' }];
const preference = { data: {}, save: jest.fn().mockResolvedValue() };
await writeShortcuts(preference, [{ name: 'Open terminal', keys }, { name: '', keys: [{ key: 'F2', code: 'F2' }] }]);
expect(JSON.parse(preference.data[SHORTCUTS_PREFERENCE])).toStrictEqual([keys, [{ key: 'F2', code: 'F2' }]]);
expect(JSON.parse(preference.data[SHORTCUT_NAMES_PREFERENCE])).toStrictEqual({ 'ControlLeft+KeyT': 'Open terminal' });
expect(readShortcuts(preference).map((shortcut) => shortcut.name)).toStrictEqual(['Open terminal', '']);
});
it('should put the preference back when the save fails', async() => {
const saved = JSON.stringify([[{ key: 'F2', code: 'F2' }]]);
const preference = { data: { [SHORTCUTS_PREFERENCE]: saved }, save: jest.fn().mockRejectedValue(new Error('403')) };
await expect(writeShortcuts(preference, [])).rejects.toThrow('403');
expect(preference.data).toStrictEqual({ [SHORTCUTS_PREFERENCE]: saved });
});
it('should read nothing from a preference it cannot parse', () => {
expect(readShortcuts({ data: { [SHORTCUTS_PREFERENCE]: '{not json' } })).toStrictEqual([]);
expect(readShortcuts(undefined)).toStrictEqual([]);
});
});
@@ -1,36 +0,0 @@
import { shallowMount } from '@vue/test-utils';
import NovncViewOptions, { VIEW_MODE } from '../NovncViewOptions.vue';
jest.mock('../ZoomableRFB', () => ({
MINIMUM_ZOOM: 50, MAXIMUM_ZOOM: 200, ZOOM_STEP: 10
}));
const settings = {
viewMode: VIEW_MODE.NONE, zoomPercent: 100, qualityLevel: 6, compressionLevel: 2
};
const mountOptions = (overrides = {}) => shallowMount(NovncViewOptions, { props: { settings: { ...settings, ...overrides } } });
describe('component: NovncViewOptions', () => {
it('should emit the whole settings object with the changed value', () => {
const wrapper = mountOptions();
wrapper.vm.update('qualityLevel', 9);
expect(wrapper.emitted('update')).toStrictEqual([[{ ...settings, qualityLevel: 9 }]]);
});
it('should step the zoom and stop at its limits', () => {
const wrapper = mountOptions({ zoomPercent: 200 });
wrapper.vm.stepZoom(1);
wrapper.vm.stepZoom(-1);
expect(wrapper.emitted('update').map(([value]) => value.zoomPercent)).toStrictEqual([200, 190]);
});
it('should only treat the manual mode as manual', () => {
expect(mountOptions().vm.isManual).toBe(true);
expect(mountOptions({ viewMode: VIEW_MODE.SCALE }).vm.isManual).toBe(false);
});
});
@@ -1,109 +0,0 @@
import ZoomableRFB from '../ZoomableRFB';
const GUEST_POINTER = 'url(guest-pointer) 0 0, default';
jest.mock('@novnc/novnc/core/rfb', () => ({
__esModule: true,
default: class {
constructor() {
this.scaleViewport = true;
this._canvas = { style: {} };
this._cursorImage = { rgbaPixels: new Uint8Array() };
this._display = { autoscale: jest.fn() };
}
_screenSize() {
return { w: 1000, h: 500 };
}
_fixScrollbars() {}
_handleMouse(ev) {
ev.stopPropagation();
}
// As noVNC does: nothing visible hides the mouse, an image is shown as the pointer.
_refreshCursor() {
this._canvas.style.cursor = this._cursorImage.rgbaPixels.length ? 'url(guest-pointer) 0 0, default' : 'none';
}
},
}), { virtual: true });
describe('zoomableRFB', () => {
describe('the pointer over the screen', () => {
it('should be the system one while the guest sends no pointer image', () => {
const rfb = new ZoomableRFB();
rfb._refreshCursor();
expect(rfb._canvas.style.cursor).toBe('default');
});
it('should be the system one when the image the guest sends is fully transparent', () => {
const rfb = new ZoomableRFB();
rfb._cursorImage = { rgbaPixels: new Uint8Array([255, 255, 255, 0, 0, 0, 0, 0]) };
rfb._refreshCursor();
expect(rfb._canvas.style.cursor).toBe('default');
});
it('should be the one the guest sends when it has visible pixels', () => {
const rfb = new ZoomableRFB();
rfb._cursorImage = { rgbaPixels: new Uint8Array([0, 0, 0, 0, 0, 0, 0, 255]) };
rfb._refreshCursor();
expect(rfb._canvas.style.cursor).toBe(GUEST_POINTER);
});
it('should go back to the system one when the guest stops sending an image', () => {
const rfb = new ZoomableRFB();
rfb._cursorImage = { rgbaPixels: new Uint8Array([0, 0, 0, 255]) };
rfb._refreshCursor();
rfb._cursorImage = { rgbaPixels: [] };
rfb._refreshCursor();
expect(rfb._canvas.style.cursor).toBe('default');
});
});
describe('mouse events on the screen', () => {
it('should let a click through, so an open menu sees it as a click outside', () => {
const rfb = new ZoomableRFB();
const stopPropagation = jest.fn();
rfb._handleMouse({ type: 'click', stopPropagation });
expect(stopPropagation).not.toHaveBeenCalled();
});
it('should leave the others to noVNC', () => {
const rfb = new ZoomableRFB();
const stopPropagation = jest.fn();
rfb._handleMouse({ type: 'mousedown', stopPropagation });
expect(stopPropagation).toHaveBeenCalledTimes(1);
});
});
describe('the fitted screen', () => {
it('should keep room for the focus ring', () => {
const rfb = new ZoomableRFB();
rfb._updateScale();
expect(rfb._display.autoscale).toHaveBeenLastCalledWith(992, 492);
});
it('should take all the room when it is edge to edge', () => {
const rfb = new ZoomableRFB();
rfb.edgeToEdge = true;
expect(rfb._display.autoscale).toHaveBeenLastCalledWith(1000, 500);
});
});
});
-118
View File
@@ -1,118 +0,0 @@
// Saved custom shortcuts live in the Rancher user preference, which every Harvester UI the user opens
// shares. The keys stay a list of recorded keydown events per shortcut, the format older versions read;
// names go in a separate preference so those versions keep working.
export const SHORTCUTS_PREFERENCE = 'prefered-shortcut-keys';
export const SHORTCUT_NAMES_PREFERENCE = 'vnc-shortcut-names';
const KEY_LABELS = {
Control: 'Ctrl',
Escape: 'Esc',
Delete: 'Del',
' ': 'Space',
};
export const MODIFIER_KEYS = ['Control', 'Shift', 'Alt', 'Meta'];
export function keyLabel(key = '') {
if (KEY_LABELS[key]) {
return KEY_LABELS[key];
}
return key.length === 1 ? key.toUpperCase() : key;
}
// macOS Option turns a letter into a symbol (Option+G gives ©, Option+E a dead key). The key that was
// pressed is still in `code`, so in that case the letter is named after it. Only with Alt and no Ctrl:
// AZERTY's comma on KeyM, Dvorak's punctuation or Cyrillic letters are real keys, and Windows AltGr
// reports Ctrl+Alt with a real character.
export function baseKey(K, combination = []) {
const letter = /^Key([A-Z])$/.exec(K?.code || '');
if (!letter || /^[a-z]$/i.test(K.key || '')) {
return K;
}
const held = combination.map((M) => M.key);
const isOptionSymbol = held.includes('Alt') && !held.includes('Control');
return K.key === 'Dead' || isOptionSymbol ? { ...K, key: letter[1].toLowerCase() } : K;
}
export function normalizeShortcut(item) {
if (Array.isArray(item)) {
return { name: '', keys: item };
}
return { name: item?.name || '', keys: Array.isArray(item?.keys) ? item.keys : [] };
}
export function shortcutLabels(shortcut) {
const keys = shortcut?.keys || [];
return keys.map((K) => keyLabel(baseKey(K, keys).key));
}
// Two shortcuts are the same when they press the same keys, whatever they are called.
export function shortcutId(shortcut) {
return (shortcut?.keys || []).map((K) => K.code || K.key).join('+');
}
// Only what sending a shortcut needs, so a recorded KeyboardEvent can be stored.
export function recordKey(event, combination = []) {
const {
key, keyCode, code, location, charCode
} = event;
return baseKey({
key, keyCode, code, location, charCode
}, combination);
}
function parse(value, fallback) {
try {
return value ? JSON.parse(value) : fallback;
} catch (err) {
return fallback;
}
}
export function readShortcuts(preference) {
const list = parse(preference?.data?.[SHORTCUTS_PREFERENCE], []);
const names = parse(preference?.data?.[SHORTCUT_NAMES_PREFERENCE], {});
return (Array.isArray(list) ? list : [])
.map(normalizeShortcut)
.filter((shortcut) => shortcut.keys.length)
.map((shortcut) => ({ ...shortcut, name: shortcut.name || names?.[shortcutId(shortcut)] || '' }));
}
export function writeShortcuts(preference, shortcuts) {
const names = {};
shortcuts.forEach((shortcut) => {
if (shortcut.name) {
names[shortcutId(shortcut)] = shortcut.name;
}
});
const previous = {
[SHORTCUTS_PREFERENCE]: preference.data[SHORTCUTS_PREFERENCE],
[SHORTCUT_NAMES_PREFERENCE]: preference.data[SHORTCUT_NAMES_PREFERENCE],
};
preference.data[SHORTCUTS_PREFERENCE] = JSON.stringify(shortcuts.map((shortcut) => shortcut.keys));
preference.data[SHORTCUT_NAMES_PREFERENCE] = JSON.stringify(names);
// The lists read straight from the preference, so a failed save must not leave the change showing.
return preference.save().catch((err) => {
Object.entries(previous).forEach(([key, value]) => {
if (value === undefined) {
delete preference.data[key];
} else {
preference.data[key] = value;
}
});
throw err;
});
}
@@ -1,79 +0,0 @@
import { shallowMount } from '@vue/test-utils';
import UpgradeConfig from '@pkg/harvester/components/settings/upgrade-config.vue';
const DEFAULT = JSON.stringify({
imagePreloadOption: { strategy: { type: 'sequential' } },
nodeUpgradeOption: { strategy: { mode: 'auto' } },
restoreVM: false,
});
const mountConfig = (config, featureEnabled) => shallowMount(UpgradeConfig, {
props: {
mode: 'edit',
value: { default: DEFAULT, value: config ? JSON.stringify(config) : '' },
},
global: {
mocks: {
$store: {
dispatch: jest.fn(),
getters: {
currentProduct: { inStore: 'harvester' },
'harvester/all': () => [],
'i18n/t': (key) => key,
'harvester-common/getFeatureEnabled': (name) => name === 'shutdownVMOnMigrationFailure' && featureEnabled,
},
},
},
},
});
const savedValue = (wrapper) => JSON.parse(wrapper.props('value').value);
describe('component: upgrade-config', () => {
it('should default shutdownVMOnMigrationFailure to false when the field is missing', () => {
const wrapper = mountConfig(undefined, true);
expect(savedValue(wrapper).shutdownVMOnMigrationFailure).toBe(false);
expect(wrapper.findComponent('[name="shutdownVMOnMigrationFailure"]').exists()).toBe(true);
});
it('should keep an enabled shutdownVMOnMigrationFailure', () => {
const wrapper = mountConfig({ shutdownVMOnMigrationFailure: true }, true);
expect(savedValue(wrapper).shutdownVMOnMigrationFailure).toBe(true);
});
it('should save the value selected in its radio group', async() => {
const wrapper = mountConfig(undefined, true);
await wrapper.findComponent('[name="shutdownVMOnMigrationFailure"]').vm.$emit('update:value', true);
expect(savedValue(wrapper).shutdownVMOnMigrationFailure).toBe(true);
expect(savedValue(wrapper).restoreVM).toBe(false);
await wrapper.findComponent('[name="restoreVM"]').vm.$emit('update:value', true);
expect(savedValue(wrapper).shutdownVMOnMigrationFailure).toBe(true);
expect(savedValue(wrapper).restoreVM).toBe(true);
});
it('should name the radio groups for screen readers', () => {
const wrapper = mountConfig(undefined, true);
expect(wrapper.findComponent('[name="restoreVM"]').attributes('aria-label')).toBe('harvester.setting.upgrade.restoreVM');
expect(wrapper.findComponent('[name="shutdownVMOnMigrationFailure"]').attributes('aria-label')).toBe('harvester.setting.upgrade.shutdownVMOnMigrationFailure');
});
it('should hide the control and not add the field on clusters without the feature', () => {
const wrapper = mountConfig(undefined, false);
expect(savedValue(wrapper)).not.toHaveProperty('shutdownVMOnMigrationFailure');
expect(wrapper.findComponent('[name="shutdownVMOnMigrationFailure"]').exists()).toBe(false);
});
it('should keep a field set outside the UI on clusters without the feature', () => {
const wrapper = mountConfig({ shutdownVMOnMigrationFailure: true }, false);
expect(savedValue(wrapper).shutdownVMOnMigrationFailure).toBe(true);
});
});
@@ -19,8 +19,7 @@ export default {
<div class="row mb-20"> <div class="row mb-20">
<div class="col span-12"> <div class="col span-12">
<FileSelector <FileSelector
variant="primary" class="btn btn-sm bg-primary mb-10"
class="mb-10"
:label="t('generic.readFromFile')" :label="t('generic.readFromFile')"
@selected="onKeySelected" @selected="onKeySelected"
/> />
@@ -191,8 +191,7 @@ export default {
> >
<div class="col span-12"> <div class="col span-12">
<FileSelector <FileSelector
variant="primary" class="btn btn-sm bg-primary mb-10"
class="mb-10"
:label="t('generic.readFromFile')" :label="t('generic.readFromFile')"
@selected="onKeySelected" @selected="onKeySelected"
/> />
@@ -214,7 +213,9 @@ $yaml-height: 540px;
:deep() .yaml-editor{ :deep() .yaml-editor{
flex: 1; flex: 1;
min-height: $yaml-height; min-height: $yaml-height;
& .code-mirror .cm-editor { & .code-mirror .CodeMirror {
position: initial;
height: auto;
min-height: $yaml-height; min-height: $yaml-height;
} }
} }
@@ -3,7 +3,7 @@ import { LabeledInput } from '@components/Form/LabeledInput';
import LabeledSelect from '@shell/components/form/LabeledSelect.vue'; import LabeledSelect from '@shell/components/form/LabeledSelect.vue';
import { RadioGroup } from '@components/Form/Radio'; import { RadioGroup } from '@components/Form/Radio';
import ArrayList from '@shell/components/form/ArrayList'; import ArrayList from '@shell/components/form/ArrayList';
import { isValidCIDR } from '@pkg/harvester/utils/regular'; import { isValidCIDR } from '@shell/utils/validators/cidr';
import { _EDIT } from '@shell/config/query-params'; import { _EDIT } from '@shell/config/query-params';
import { Banner } from '@components/Banner'; import { Banner } from '@components/Banner';
import { allHash } from '@shell/utils/promise'; import { allHash } from '@shell/utils/promise';
@@ -62,8 +62,7 @@ export default {
<div class="chooseFile"> <div class="chooseFile">
<FileSelector <FileSelector
:include-file-name="true" :include-file-name="true"
variant="primary" class="btn btn-sm bg-primary mr-20"
class="mr-20"
label="Choose File" label="Choose File"
@selected="onKeySelectedCa('publicCertificate', $event)" @selected="onKeySelectedCa('publicCertificate', $event)"
/> />
@@ -81,8 +80,7 @@ export default {
<div class="chooseFile"> <div class="chooseFile">
<FileSelector <FileSelector
:include-file-name="true" :include-file-name="true"
variant="primary" class="btn btn-sm bg-primary mr-20"
class="mr-20"
label="Choose File" label="Choose File"
@selected="onKeySelectedCa('privateKey', $event)" @selected="onKeySelectedCa('privateKey', $event)"
/> />
@@ -100,8 +98,7 @@ export default {
<div class="chooseFile"> <div class="chooseFile">
<FileSelector <FileSelector
:include-file-name="true" :include-file-name="true"
variant="primary" class="btn btn-sm bg-primary mr-20"
class="mr-20"
label="Choose File" label="Choose File"
@selected="onKeySelectedCa('ca', $event)" @selected="onKeySelectedCa('ca', $event)"
/> />
@@ -3,7 +3,7 @@ import { LabeledInput } from '@components/Form/LabeledInput';
import LabeledSelect from '@shell/components/form/LabeledSelect.vue'; import LabeledSelect from '@shell/components/form/LabeledSelect.vue';
import { RadioGroup } from '@components/Form/Radio'; import { RadioGroup } from '@components/Form/Radio';
import ArrayList from '@shell/components/form/ArrayList'; import ArrayList from '@shell/components/form/ArrayList';
import { isValidCIDR } from '@pkg/harvester/utils/regular'; import { isValidCIDR } from '@shell/utils/validators/cidr';
import { _EDIT } from '@shell/config/query-params'; import { _EDIT } from '@shell/config/query-params';
import { Banner } from '@components/Banner'; import { Banner } from '@components/Banner';
import Tip from '@shell/components/Tip'; import Tip from '@shell/components/Tip';
@@ -74,10 +74,6 @@ export default {
}, },
methods: { methods: {
// A method, as normalizeValue also runs in data(), before computed properties are available
shutdownVMOnMigrationFailureEnabled() {
return this.$store.getters['harvester-common/getFeatureEnabled']('shutdownVMOnMigrationFailure');
},
normalizeValue(obj) { normalizeValue(obj) {
// handle nodeUpgradeOption.strategy // handle nodeUpgradeOption.strategy
if (obj?.nodeUpgradeOption?.strategy?.mode === 'auto') { if (obj?.nodeUpgradeOption?.strategy?.mode === 'auto') {
@@ -111,9 +107,6 @@ export default {
if (typeof obj.restoreVM !== 'boolean') { if (typeof obj.restoreVM !== 'boolean') {
obj.restoreVM = false; obj.restoreVM = false;
} }
if (this.shutdownVMOnMigrationFailureEnabled() && typeof obj.shutdownVMOnMigrationFailure !== 'boolean') {
obj.shutdownVMOnMigrationFailure = false;
}
return obj; return obj;
}, },
@@ -186,24 +179,10 @@ export default {
v-model:value="parseDefaultValue.restoreVM" v-model:value="parseDefaultValue.restoreVM"
class="mb-20" class="mb-20"
name="restoreVM" name="restoreVM"
:aria-label="t('harvester.setting.upgrade.restoreVM')"
:options="[true, false]" :options="[true, false]"
:labels="[t('generic.enabled'), t('generic.disabled')]" :labels="[t('generic.enabled'), t('generic.disabled')]"
@update:value="update" @update:value="update"
/> />
<div v-if="shutdownVMOnMigrationFailureEnabled()">
<label class="mb-5"><b>{{ t('harvester.setting.upgrade.shutdownVMOnMigrationFailure') }}</b></label>
<RadioGroup
v-model:value="parseDefaultValue.shutdownVMOnMigrationFailure"
class="mb-20"
name="shutdownVMOnMigrationFailure"
:aria-label="t('harvester.setting.upgrade.shutdownVMOnMigrationFailure')"
:mode="mode"
:options="[true, false]"
:labels="[t('generic.enabled'), t('generic.disabled')]"
@update:value="update"
/>
</div>
<div v-if="resumeUpgradePausedNodeEnabled"> <div v-if="resumeUpgradePausedNodeEnabled">
<label class="mb-5"><b>{{ t('harvester.setting.upgrade.nodeUpgradeOption') }}</b></label> <label class="mb-5"><b>{{ t('harvester.setting.upgrade.nodeUpgradeOption') }}</b></label>
<LabeledSelect <LabeledSelect
@@ -5,7 +5,7 @@ import { RadioGroup } from '@components/Form/Radio';
import { Banner } from '@components/Banner'; import { Banner } from '@components/Banner';
import ArrayList from '@shell/components/form/ArrayList'; import ArrayList from '@shell/components/form/ArrayList';
import { allHash } from '@shell/utils/promise'; import { allHash } from '@shell/utils/promise';
import { isValidCIDR } from '@pkg/harvester/utils/regular'; import { isValidCIDR } from '@shell/utils/validators/cidr';
import { NODE } from '@shell/config/types'; import { NODE } from '@shell/config/types';
import { _EDIT } from '@shell/config/query-params'; import { _EDIT } from '@shell/config/query-params';
import { HCI } from '../../types'; import { HCI } from '../../types';
-13
View File
@@ -56,7 +56,6 @@ const FEATURE_FLAGS = {
'kubevirtMigration', 'kubevirtMigration',
'hotplugNic', 'hotplugNic',
'resumeUpgradePausedNode', 'resumeUpgradePausedNode',
'vncPreserveSession',
], ],
'v1.7.1': [], 'v1.7.1': [],
'v1.8.0': [ 'v1.8.0': [
@@ -78,18 +77,6 @@ const FEATURE_FLAGS = {
'staticIPForVM', 'staticIPForVM',
'fsFreezeDeadline', 'fsFreezeDeadline',
], ],
'v1.9.1': [
'lvmDmThinOnly',
'highPerformanceStorage',
],
'v1.10.0': [
'maintenanceModeConditions',
'maintenanceModeDrainTimeoutSetting',
'componentHealth',
'repositoryStorageClass',
'shutdownVMOnMigrationFailure',
'vmListPagination',
],
}; };
const generateFeatureFlags = () => { const generateFeatureFlags = () => {
+20 -125
View File
@@ -54,17 +54,9 @@ import {
FORKLIFT_PLAN_TARGET_NS, FORKLIFT_PLAN_TARGET_NS,
FORKLIFT_PLAN_VM_COUNT, FORKLIFT_PLAN_VM_COUNT,
FORKLIFT_MIGRATION_PLAN, FORKLIFT_MIGRATION_PLAN,
VM_HEADERS,
VM_PAGINATION_HEADERS,
} from './table-headers'; } from './table-headers';
import { ADD_ONS } from './harvester-map'; import { ADD_ONS } from './harvester-map';
import { registerAddonSideNav } from '../utils/dynamic-nav'; import { registerAddonSideNav } from '../utils/dynamic-nav';
import { setStandalonePrime } from '../utils/l10n-globals';
import { setVendor } from '@shell/config/private-label';
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 TEMPLATE = HCI.VM_VERSION;
const MONITORING_GROUP = 'Monitoring & Logging::Monitoring'; const MONITORING_GROUP = 'Monitoring & Logging::Monitoring';
@@ -117,57 +109,15 @@ export function init($plugin, store) {
} }
}; };
store.watch( store.dispatch('setIsSingleProduct', {
(_state, getters) => JSON.stringify([ productName: PRODUCT_NAME,
!!getters['harvester-common/isHarvesterPrime'], logo: require(`@shell/assets/images/providers/harvester.svg`),
getters['prefs/theme'] === 'dark', productNameKey: 'harvester.productLabel',
getters['harvester-common/privateLabel'] getVersionInfo: (store) => store.getters[`${ PRODUCT_NAME }/byId`]?.(HCI.SETTING, 'server-version')?.value || 'unknown',
]), afterLoginRoute: home,
(value) => { logoRoute: home,
const [isHarvesterPrime, isDark, privateLabel] = JSON.parse(value); supportCustomLogo: true
const primeLogo = isDark ? require('../assets/images/dark/suse-virtualization.svg') : require('../assets/images/suse-virtualization.svg'); });
setStandalonePrime(isHarvesterPrime);
setVendor(privateLabel || '');
const primeLabelKey = privateLabel ? 'harvester.branding.primeLabel' : 'harvester.branding.primeEmptyLabel';
store.dispatch('setIsSingleProduct', {
productName: PRODUCT_NAME,
logo: isHarvesterPrime ? primeLogo : require(`@shell/assets/images/providers/harvester.svg`),
productNameKey: isHarvesterPrime ? primeLabelKey : 'harvester.productLabel',
getVersionInfo: (store) => store.getters[`${ PRODUCT_NAME }/byId`]?.(HCI.SETTING, 'server-version')?.value || 'unknown',
afterLoginRoute: home,
logoRoute: home,
supportCustomLogo: !isHarvesterPrime
});
},
{ 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({ product({
@@ -259,7 +209,6 @@ export function init($plugin, store) {
basicType([HCI.VM]); basicType([HCI.VM]);
configureType(HCI.VM, { canYaml: false }); configureType(HCI.VM, { canYaml: false });
headers(HCI.VM, VM_HEADERS, VM_PAGINATION_HEADERS);
virtualType({ virtualType({
labelKey: 'harvester.virtualMachine.label', labelKey: 'harvester.virtualMachine.label',
group: 'root', group: 'root',
@@ -665,7 +614,7 @@ export function init($plugin, store) {
); );
basicType( basicType(
[HCI.VPC_NAT_GATEWAY, HCI.VPC_EGRESS_GATEWAY], [HCI.VPC_NAT_GATEWAY],
GATEWAYS_GROUP GATEWAYS_GROUP
); );
@@ -713,24 +662,16 @@ export function init($plugin, store) {
basicType( basicType(
[ [
TEMPLATE,
HCI.SSH,
HCI.CLOUD_TEMPLATE,
HCI.STORAGE,
HCI.SR_IOV, HCI.SR_IOV,
HCI.PCI_DEVICE, HCI.PCI_DEVICE,
HCI.SR_IOVGPU_DEVICE, HCI.SR_IOVGPU_DEVICE,
HCI.VGPU_DEVICE, HCI.VGPU_DEVICE,
HCI.MIG_CONFIGURATION, HCI.MIG_CONFIGURATION,
HCI.USB_DEVICE, HCI.USB_DEVICE,
],
'hardwareDevices'
);
weightGroup('hardwareDevices', 488, true);
basicType(
[
TEMPLATE,
HCI.SSH,
HCI.CLOUD_TEMPLATE,
HCI.STORAGE,
HCI.ADD_ONS, HCI.ADD_ONS,
HCI.SECRET, HCI.SECRET,
HCI.SETTING HCI.SETTING
@@ -856,52 +797,6 @@ export function init($plugin, store) {
ifHaveType: HCI.VPC_NAT_GATEWAY, ifHaveType: HCI.VPC_NAT_GATEWAY,
}); });
configureType(HCI.VPC_EGRESS_GATEWAY, { hiddenNamespaceGroupButton: true, canYaml: false });
headers(HCI.VPC_EGRESS_GATEWAY, [
STATE,
NAME_COL,
NAMESPACE_COL,
{
name: 'vpc',
labelKey: 'harvester.egressGateway.vpc.label',
value: 'spec.vpc',
sort: ['spec.vpc'],
},
{
name: 'replicas',
labelKey: 'harvester.egressGateway.replicas.label',
value: 'spec.replicas',
sort: ['spec.replicas'],
},
{
name: 'externalSubnet',
labelKey: 'harvester.egressGateway.externalSubnet.label',
value: 'spec.externalSubnet',
sort: ['spec.externalSubnet'],
},
{
name: 'externalIPs',
labelKey: 'harvester.egressGateway.ips.external.label',
value: 'status.externalIPs',
formatter: 'List',
},
AGE
]);
virtualType({
labelKey: 'harvester.egressGateway.label',
name: HCI.VPC_EGRESS_GATEWAY,
namespaced: true,
weight: 193,
route: {
name: `${ PRODUCT_NAME }-c-cluster-resource`,
params: { resource: HCI.VPC_EGRESS_GATEWAY }
},
exact: false,
ifHaveType: HCI.VPC_EGRESS_GATEWAY,
});
configureType(HCI.IPTABLES_EIP, { hiddenNamespaceGroupButton: true, canYaml: false }); configureType(HCI.IPTABLES_EIP, { hiddenNamespaceGroupButton: true, canYaml: false });
virtualType({ virtualType({
@@ -1174,7 +1069,7 @@ export function init($plugin, store) {
virtualType({ virtualType({
label: 'PCI Devices', label: 'PCI Devices',
group: 'hardwareDevices', group: 'advanced',
weight: 14, weight: 14,
name: HCI.PCI_DEVICE, name: HCI.PCI_DEVICE,
namespaced: false, namespaced: false,
@@ -1210,7 +1105,7 @@ export function init($plugin, store) {
virtualType({ virtualType({
ifHaveType: HCI.SR_IOV, ifHaveType: HCI.SR_IOV,
labelKey: 'harvester.sriov.label', labelKey: 'harvester.sriov.label',
group: 'hardwareDevices', group: 'advanced',
weight: 15, weight: 15,
name: HCI.SR_IOV, name: HCI.SR_IOV,
namespaced: false, namespaced: false,
@@ -1230,7 +1125,7 @@ export function init($plugin, store) {
virtualType({ virtualType({
ifHaveType: HCI.SR_IOVGPU_DEVICE, ifHaveType: HCI.SR_IOVGPU_DEVICE,
labelKey: 'harvester.sriovgpu.label', labelKey: 'harvester.sriovgpu.label',
group: 'hardwareDevices', group: 'advanced',
weight: 13, weight: 13,
name: HCI.SR_IOVGPU_DEVICE, name: HCI.SR_IOVGPU_DEVICE,
namespaced: false, namespaced: false,
@@ -1249,7 +1144,7 @@ export function init($plugin, store) {
virtualType({ virtualType({
labelKey: 'harvester.vgpu.label', labelKey: 'harvester.vgpu.label',
group: 'hardwareDevices', group: 'advanced',
weight: 12, weight: 12,
name: HCI.VGPU_DEVICE, name: HCI.VGPU_DEVICE,
namespaced: false, namespaced: false,
@@ -1277,7 +1172,7 @@ export function init($plugin, store) {
virtualType({ virtualType({
labelKey: 'harvester.migconfiguration.label', labelKey: 'harvester.migconfiguration.label',
group: 'hardwareDevices', group: 'advanced',
weight: 12, weight: 12,
name: HCI.MIG_CONFIGURATION, name: HCI.MIG_CONFIGURATION,
namespaced: false, namespaced: false,
@@ -1297,7 +1192,7 @@ export function init($plugin, store) {
virtualType({ virtualType({
labelKey: 'harvester.usb.label', labelKey: 'harvester.usb.label',
group: 'hardwareDevices', group: 'advanced',
weight: 11, weight: 11,
name: HCI.USB_DEVICE, name: HCI.USB_DEVICE,
namespaced: false, namespaced: false,
-15
View File
@@ -39,21 +39,6 @@ export const VOLUME_TYPE = [{
value: 'cd-rom' value: 'cd-rom'
}]; }];
// KubeVirt high-performance disk features
// https://kubevirt.io/user-guide/storage/disks_and_volumes/#high-performance-features
export const DISK_CACHE_MODE = ['', 'none', 'writeback', 'writethrough'];
export const DISK_IO_MODE = ['', 'native', 'threads'];
export const IO_THREADS_POLICY = ['', 'shared', 'auto', 'supplementalPool'];
// "Easy-to-consume" presets layered on top of the raw KubeVirt fields.
export const DISK_PERFORMANCE_PROFILE = {
DEFAULT: 'default',
HIGH: 'highPerformance',
CUSTOM: 'custom',
};
export const VOLUME_HOTPLUG_ACTION = { export const VOLUME_HOTPLUG_ACTION = {
INSERT_CDROM_IMAGE: 'INSERT_CDROM_IMAGE', INSERT_CDROM_IMAGE: 'INSERT_CDROM_IMAGE',
EJECT_CDROM_IMAGE: 'EJECT_CDROM_IMAGE', EJECT_CDROM_IMAGE: 'EJECT_CDROM_IMAGE',
+1 -8
View File
@@ -21,9 +21,8 @@ export const HCI = {
VM_NAME: 'harvesterhci.io/vmName', VM_NAME: 'harvesterhci.io/vmName',
VM_NAME_PREFIX: 'harvesterhci.io/vmNamePrefix', VM_NAME_PREFIX: 'harvesterhci.io/vmNamePrefix',
VM_DISPLAY_NAME: 'harvesterhci.io/vmDisplayName', VM_DISPLAY_NAME: 'harvesterhci.io/vmDisplayName',
VMI_CREATED_BY: 'kubevirt.io/created-by',
VM_RESERVED_MEMORY: 'harvesterhci.io/reservedMemory', VM_RESERVED_MEMORY: 'harvesterhci.io/reservedMemory',
MAINTENANCE_STATUS: 'harvesterhci.io/maintain-status', // Deprecated >= v1.10.0 MAINTENANCE_STATUS: 'harvesterhci.io/maintain-status',
HOST_CUSTOM_NAME: 'harvesterhci.io/host-custom-name', HOST_CUSTOM_NAME: 'harvesterhci.io/host-custom-name',
HOST_CONSOLE_URL: 'harvesterhci.io/host-console-url', HOST_CONSOLE_URL: 'harvesterhci.io/host-console-url',
RESTORE_NAME: 'restore.harvesterhci.io/name', RESTORE_NAME: 'restore.harvesterhci.io/name',
@@ -34,11 +33,6 @@ export const HCI = {
CLONE_BACKEND_STORAGE_STATUS: 'harvesterhci.io/clone-backend-storage-status', CLONE_BACKEND_STORAGE_STATUS: 'harvesterhci.io/clone-backend-storage-status',
MIGRATION_STATE: 'harvesterhci.io/migrationState', MIGRATION_STATE: 'harvesterhci.io/migrationState',
VOLUME_CLAIM_TEMPLATE: 'harvesterhci.io/volumeClaimTemplates', VOLUME_CLAIM_TEMPLATE: 'harvesterhci.io/volumeClaimTemplates',
// Default KubeVirt high-performance disk settings, applied when the volume is
// attached to a VM as a disk. See disks_and_volumes.md#high-performance-features.
DISK_CACHE_MODE: 'harvesterhci.io/disk-cache-mode',
DISK_IO_MODE: 'harvesterhci.io/disk-io-mode',
DISK_DEDICATED_IOTHREAD: 'harvesterhci.io/disk-dedicated-iothread',
IMAGE_NAME: 'harvesterhci.io/image-name', IMAGE_NAME: 'harvesterhci.io/image-name',
INIT_IP: 'etcd.rke2.cattle.io/node-address', INIT_IP: 'etcd.rke2.cattle.io/node-address',
NODE_SCHEDULABLE: 'kubevirt.io/schedulable', NODE_SCHEDULABLE: 'kubevirt.io/schedulable',
@@ -48,7 +42,6 @@ export const HCI = {
OS_UPGRADE_IMAGE: 'harvesterhci.io/os-upgrade-image', OS_UPGRADE_IMAGE: 'harvesterhci.io/os-upgrade-image',
LATEST_UPGRADE: 'harvesterhci.io/latestUpgrade', LATEST_UPGRADE: 'harvesterhci.io/latestUpgrade',
UPGRADE_STATE: 'harvesterhci.io/upgradeState', UPGRADE_STATE: 'harvesterhci.io/upgradeState',
UPGRADE_STORAGE_CLASS: 'harvesterhci.io/upgrade-storage-class',
REAY_MESSAGE: 'harvesterhci.io/read-message', REAY_MESSAGE: 'harvesterhci.io/read-message',
DYNAMIC_SSHKEYS_NAMES: 'harvesterhci.io/dynamic-ssh-key-names', DYNAMIC_SSHKEYS_NAMES: 'harvesterhci.io/dynamic-ssh-key-names',
DYNAMIC_SSHKEYS_USERS: 'harvesterhci.io/dynamic-ssh-key-users', DYNAMIC_SSHKEYS_USERS: 'harvesterhci.io/dynamic-ssh-key-users',
+1 -7
View File
@@ -3,7 +3,6 @@ export const HCI_SETTING = {
CONTAINERD_REGISTRY: 'containerd-registry', CONTAINERD_REGISTRY: 'containerd-registry',
LOG_LEVEL: 'log-level', LOG_LEVEL: 'log-level',
SERVER_VERSION: 'server-version', SERVER_VERSION: 'server-version',
SERVER_FLAVOR: 'server-flavor',
UI_INDEX: 'ui-index', UI_INDEX: 'ui-index',
UPGRADE_CHECKER_ENABLED: 'upgrade-checker-enabled', UPGRADE_CHECKER_ENABLED: 'upgrade-checker-enabled',
UPGRADE_CHECKER_URL: 'upgrade-checker-url', UPGRADE_CHECKER_URL: 'upgrade-checker-url',
@@ -45,8 +44,7 @@ export const HCI_SETTING = {
MAX_HOTPLUG_RATIO: 'max-hotplug-ratio', MAX_HOTPLUG_RATIO: 'max-hotplug-ratio',
KUBEVIRT_MIGRATION: 'kubevirt-migration', KUBEVIRT_MIGRATION: 'kubevirt-migration',
INSTANCE_MANAGER_RESOURCES: 'instance-manager-resources', 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 = { export const HCI_ALLOWED_SETTINGS = {
@@ -70,7 +68,6 @@ export const HCI_ALLOWED_SETTINGS = {
kind: 'json', from: 'import', featureFlag: 'csiOnlineExpandValidation' kind: 'json', from: 'import', featureFlag: 'csiOnlineExpandValidation'
}, },
[HCI_SETTING.SERVER_VERSION]: { readOnly: true }, [HCI_SETTING.SERVER_VERSION]: { readOnly: true },
[HCI_SETTING.SERVER_FLAVOR]: { readOnly: true },
[HCI_SETTING.UPGRADE_CHECKER_ENABLED]: { kind: 'boolean' }, [HCI_SETTING.UPGRADE_CHECKER_ENABLED]: { kind: 'boolean' },
[HCI_SETTING.UPGRADE_CHECKER_URL]: { kind: 'url' }, [HCI_SETTING.UPGRADE_CHECKER_URL]: { kind: 'url' },
[HCI_SETTING.HTTP_PROXY]: { kind: 'json', from: 'import' }, [HCI_SETTING.HTTP_PROXY]: { kind: 'json', from: 'import' },
@@ -149,9 +146,6 @@ export const HCI_ALLOWED_SETTINGS = {
}, },
[HCI_SETTING.CLUSTER_POD_SECURITY_STANDARD]: { [HCI_SETTING.CLUSTER_POD_SECURITY_STANDARD]: {
kind: 'json', from: 'import', canReset: true, featureFlag: 'clusterPodSecurityStandardSetting' kind: 'json', from: 'import', canReset: true, featureFlag: 'clusterPodSecurityStandardSetting'
},
[HCI_SETTING.MAINTENANCE_MODE_DRAIN_TIMEOUT]: {
kind: 'number', canReset: true, featureFlag: 'maintenanceModeDrainTimeoutSetting'
} }
}; };
+1 -86
View File
@@ -1,10 +1,7 @@
/** /**
* Harvester * Harvester
*/ */
import { import { DESCRIPTION } from '@shell/config/table-headers';
DESCRIPTION, STATE, AGE, NAME, NAMESPACE
} from '@shell/config/table-headers';
import { HCI as HCI_ANNOTATIONS } from './labels-annotations';
// image // image
export const IMAGE_DOWNLOAD_SIZE = { export const IMAGE_DOWNLOAD_SIZE = {
@@ -300,85 +297,3 @@ export const FORKLIFT_MIGRATION_PLAN = {
sort: 'spec.plan.name', sort: 'spec.plan.name',
align: 'left', align: 'left',
}; };
// Virtual machine list
export const VM_HEADERS = [
STATE,
{
...NAME,
width: 350,
value: 'nameDisplay',
sort: ['nameDisplay'],
},
NAMESPACE,
{
name: 'CPU',
label: 'CPU',
sort: ['displayCPU'],
value: 'displayCPU',
align: 'center',
dashIfEmpty: true,
},
{
name: 'Memory',
value: 'displayMemory',
sort: ['memorySort'],
align: 'center',
labelKey: 'tableHeaders.memory',
formatter: 'Si',
formatterOpts: {
opts: {
increment: 1024, addSuffix: true, maxExponent: 3, minExponent: 3, suffix: 'i',
},
needParseSi: true
},
},
{
name: 'ip',
label: 'IP Address',
value: 'id',
formatter: 'HarvesterIpAddress',
labelKey: 'tableHeaders.ipAddress',
sort: ['id'],
},
// The VM list only shows it when the cluster's nodes can be seen
{
name: 'node',
label: 'Node',
value: 'nodeName',
sort: ['realAttachNodeName'],
formatter: 'HarvesterHost',
labelKey: 'harvester.tableHeaders.vm.node'
},
// The VM list only shows it while a backup is being restored
{
name: 'restoreProgress',
labelKey: 'harvester.tableHeaders.restore',
value: 'restoreProgress',
align: 'left',
formatter: 'HarvesterBackupProgressBar',
width: 200,
},
{
...AGE,
sort: 'metadata.creationTimestamp:desc',
}
];
// With server-side pagination the API sorts and searches, so only the fields it indexes can be used. CPU, memory, IP,
// node and restore progress come from the VM model or other resources. The VM's printer columns are listed as Name, Age, Status, Ready, so its
// Status is `metadata.fields.2`
const VM_PAGINATION_FIELDS = {
[STATE.name]: { sort: ['metadata.fields.2'], search: false },
[NAME.name]: {
sort: ['metadata.name'],
search: ['metadata.name', `metadata.annotations[${ HCI_ANNOTATIONS.VM_DISPLAY_NAME }]`],
},
[NAMESPACE.name]: { sort: ['metadata.namespace'], search: 'metadata.namespace' },
[AGE.name]: { search: false },
};
export const VM_PAGINATION_HEADERS = VM_HEADERS.map((header) => ({
...header,
...(VM_PAGINATION_FIELDS[header.name] || { sort: false, search: false }),
}));
-7
View File
@@ -15,13 +15,6 @@ export const VOLUME_MODE = {
FILE_SYSTEM: 'Filesystem' 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 = { export const NETWORK_PROTOCOL = {
IPv4: 'IPv4', IPv4: 'IPv4',
IPv6: 'IPv6', IPv6: 'IPv6',
@@ -15,7 +15,6 @@ import OverviewKeypairs from '../kubevirt.io.virtualmachine/VirtualMachineTabs/V
import Volume from '../../edit/kubevirt.io.virtualmachine/VirtualMachineVolume'; import Volume from '../../edit/kubevirt.io.virtualmachine/VirtualMachineVolume';
import Network from '../../edit/kubevirt.io.virtualmachine/VirtualMachineNetwork'; import Network from '../../edit/kubevirt.io.virtualmachine/VirtualMachineNetwork';
import CloudConfig from '../../edit/kubevirt.io.virtualmachine/VirtualMachineCloudConfig'; import CloudConfig from '../../edit/kubevirt.io.virtualmachine/VirtualMachineCloudConfig';
import { getBootDevices } from '../../utils/vm';
const UNDEFINED = 'n/a'; const UNDEFINED = 'n/a';
export default { export default {
@@ -75,8 +74,18 @@ export default {
return image?.spec?.displayName || '-'; return image?.spec?.displayName || '-';
}, },
bootDevices() { disks() {
return getBootDevices(this?.spec?.template?.spec?.domain?.devices); 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;
});
}, },
cdroms() { cdroms() {
@@ -92,10 +101,8 @@ export default {
getDeviceType(o) { getDeviceType(o) {
if (o.disk) { if (o.disk) {
return 'Disk'; return 'Disk';
} else if (o.cdrom) {
return 'CD-ROM';
} else { } else {
return 'Network'; return 'CD-ROM';
} }
}, },
isEmpty(o) { isEmpty(o) {
@@ -177,10 +184,10 @@ export default {
<div> <div>
<ul> <ul>
<li <li
v-for="(device, i) in bootDevices" v-for="(disk, i) in disks"
:key="i" :key="i"
> >
{{ device.bootOrder }}. {{ device.name }} ({{ getDeviceType(device) }}) {{ disk.bootOrder }}. {{ disk.name }} ({{ getDeviceType(disk) }})
</li> </li>
</ul> </ul>
</div> </div>
@@ -226,7 +233,6 @@ export default {
> >
<Network <Network
v-model:value="networkRows" v-model:value="networkRows"
:network-boot-first="networkBootFirst"
:mode="mode" :mode="mode"
/> />
</Tab> </Tab>
@@ -15,7 +15,6 @@ import OverviewKeypairs from '../kubevirt.io.virtualmachine/VirtualMachineTabs/V
import Volume from '../../edit/kubevirt.io.virtualmachine/VirtualMachineVolume'; import Volume from '../../edit/kubevirt.io.virtualmachine/VirtualMachineVolume';
import Network from '../../edit/kubevirt.io.virtualmachine/VirtualMachineNetwork'; import Network from '../../edit/kubevirt.io.virtualmachine/VirtualMachineNetwork';
import CloudConfig from '../../edit/kubevirt.io.virtualmachine/VirtualMachineCloudConfig'; import CloudConfig from '../../edit/kubevirt.io.virtualmachine/VirtualMachineCloudConfig';
import { getBootDevices } from '../../utils/vm';
const UNDEFINED = 'n/a'; const UNDEFINED = 'n/a';
export default { export default {
@@ -75,8 +74,18 @@ export default {
return image?.spec?.displayName || '-'; return image?.spec?.displayName || '-';
}, },
bootDevices() { disks() {
return getBootDevices(this?.spec?.template?.spec?.domain?.devices); 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;
});
}, },
cdroms() { cdroms() {
@@ -92,10 +101,8 @@ export default {
getDeviceType(o) { getDeviceType(o) {
if (o.disk) { if (o.disk) {
return 'Disk'; return 'Disk';
} else if (o.cdrom) {
return 'CD-ROM';
} else { } else {
return 'Network'; return 'CD-ROM';
} }
}, },
isEmpty(o) { isEmpty(o) {
@@ -177,10 +184,10 @@ export default {
<div> <div>
<ul> <ul>
<li <li
v-for="(device, i) in bootDevices" v-for="(disk, i) in disks"
:key="i" :key="i"
> >
{{ device.bootOrder }}. {{ device.name }} ({{ getDeviceType(device) }}) {{ disk.bootOrder }}. {{ disk.name }} ({{ getDeviceType(disk) }})
</li> </li>
</ul> </ul>
</div> </div>
@@ -227,7 +234,6 @@ export default {
> >
<Network <Network
v-model:value="networkRows" v-model:value="networkRows"
:network-boot-first="networkBootFirst"
:mode="mode" :mode="mode"
/> />
</Tab> </Tab>
@@ -6,7 +6,6 @@ import HarvesterIpAddress from '../../../formatters/HarvesterIpAddress';
import VMConsoleBar from '../../../components/VMConsoleBar'; import VMConsoleBar from '../../../components/VMConsoleBar';
import { HCI } from '../../../types'; import { HCI } from '../../../types';
import { getVmCPUMemoryValues } from '../../../utils/cpuMemory'; import { getVmCPUMemoryValues } from '../../../utils/cpuMemory';
import { getBootDevices } from '../../../utils/vm';
const UNDEFINED = 'n/a'; const UNDEFINED = 'n/a';
@@ -70,8 +69,18 @@ export default {
return image?.spec?.displayName || 'N/A'; return image?.spec?.displayName || 'N/A';
}, },
bootDevices() { disks() {
return getBootDevices(this.value?.spec?.template?.spec?.domain?.devices); 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;
});
}, },
cdroms() { cdroms() {
@@ -113,10 +122,8 @@ export default {
getDeviceType(o) { getDeviceType(o) {
if (o.disk) { if (o.disk) {
return 'Disk'; return 'Disk';
} else if (o.cdrom) {
return 'CD-ROM';
} else { } else {
return 'Network'; return 'CD-ROM';
} }
}, },
isEmpty(o) { isEmpty(o) {
@@ -212,16 +219,16 @@ export default {
<div class="col span-6"> <div class="col span-6">
<InputOrDisplay <InputOrDisplay
:name="t('harvester.virtualMachine.detail.details.bootOrder')" :name="t('harvester.virtualMachine.detail.details.bootOrder')"
:value="bootDevices" :value="disks"
:mode="mode" :mode="mode"
> >
<template #value> <template #value>
<ul> <ul>
<li <li
v-for="(device, i) in bootDevices" v-for="(disk, i) in disks"
:key="i" :key="i"
> >
{{ device.bootOrder }}. {{ device.name }} ({{ getDeviceType(device) }}) {{ disk.bootOrder }}. {{ disk.name }} ({{ getDeviceType(disk) }})
</li> </li>
</ul> </ul>
</template> </template>
@@ -14,11 +14,9 @@ import Labels from '@shell/components/form/Labels';
import LabelValue from '@shell/components/LabelValue'; import LabelValue from '@shell/components/LabelValue';
import { HCI } from '../../types'; import { HCI } from '../../types';
import VM_MIXIN from '../../mixins/harvester-vm'; import VM_MIXIN from '../../mixins/harvester-vm';
import { getLatestMigration } from '../../utils/vm';
import CloudConfig from '../../edit/kubevirt.io.virtualmachine/VirtualMachineCloudConfig'; import CloudConfig from '../../edit/kubevirt.io.virtualmachine/VirtualMachineCloudConfig';
import Volume from '../../edit/kubevirt.io.virtualmachine/VirtualMachineVolume'; 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 Network from '../../edit/kubevirt.io.virtualmachine/VirtualMachineNetwork';
import AccessCredentials from '../../edit/kubevirt.io.virtualmachine/VirtualMachineAccessCredentials'; import AccessCredentials from '../../edit/kubevirt.io.virtualmachine/VirtualMachineAccessCredentials';
import Events from './VirtualMachineTabs/VirtualMachineEvents'; import Events from './VirtualMachineTabs/VirtualMachineEvents';
@@ -41,7 +39,6 @@ export default {
OverviewBasics, OverviewBasics,
LabelValue, LabelValue,
Volume, Volume,
VMPerformanceOptions,
Network, Network,
OverviewKeypairs, OverviewKeypairs,
CloudConfig, CloudConfig,
@@ -142,7 +139,18 @@ export default {
const inStore = this.$store.getters['currentProduct'].inStore; const inStore = this.$store.getters['currentProduct'].inStore;
const vmimList = this.$store.getters[`${ inStore }/all`](HCI.VMIM) || []; const vmimList = this.$store.getters[`${ inStore }/all`](HCI.VMIM) || [];
return getLatestMigration(vmimList, this.vmi?.metadata?.namespace, this.vmi?.name) || null; 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;
}, },
migrationEvents() { migrationEvents() {
@@ -206,15 +214,6 @@ export default {
this['diskRows'] = diskRows; this['diskRows'] = diskRows;
this['networkRows'] = this.getNetworkRows(neu, { fromTemplate: false, init: false }); 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.
const domain = neu?.spec?.template?.spec?.domain;
this['blockMultiQueue'] = domain?.devices?.blockMultiQueue || false;
this['ioThreadsPolicy'] = domain?.ioThreadsPolicy || '';
this['ioThreadCount'] = domain?.ioThreads?.supplementalPoolThreadCount || 2;
}, },
deep: true deep: true
} }
@@ -256,15 +255,6 @@ export default {
:vm="value" :vm="value"
:resource-type="value.type" :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> </Tab>
<Tab <Tab
@@ -275,7 +265,6 @@ export default {
> >
<Network <Network
v-model:value="networkRows" v-model:value="networkRows"
:network-boot-first="networkBootFirst"
mode="view" mode="view"
:vm="value" :vm="value"
/> />
@@ -5,7 +5,7 @@ import SortableTable from '@shell/components/SortableTable';
import { HCI } from '@pkg/harvester/types'; import { HCI } from '@pkg/harvester/types';
import { allHash } from '@shell/utils/promise'; import { allHash } from '@shell/utils/promise';
import { KEY, VALUE } from '@shell/config/table-headers'; import { KEY, VALUE } from '@shell/config/table-headers';
import { VM_HEADERS } from '@pkg/harvester/config/table-headers'; import { VM_HEADERS } from '@pkg/harvester/list/kubevirt.io.virtualmachine';
import { matching } from '@shell/utils/selector'; import { matching } from '@shell/utils/selector';
import { IP_POOL_HEADERS } from '../config/harvester-cluster'; import { IP_POOL_HEADERS } from '../config/harvester-cluster';
@@ -103,7 +103,7 @@ export default {
}, },
vmHeaders() { vmHeaders() {
const filterNames = ['state', 'ip', 'node', 'restoreProgress']; const filterNames = ['state', 'ip', 'node'];
return VM_HEADERS.filter((h) => !filterNames.includes(h.name)); return VM_HEADERS.filter((h) => !filterNames.includes(h.name));
}, },
@@ -30,9 +30,9 @@ export default {
}, },
async fetch() { async fetch() {
this.allPVCs = await this.actionResource.findInNamespace(PVC); this.allPVCs = await this.$store.dispatch('harvester/findAll', { type: PVC });
this.allStorageClasses = await this.$store.dispatch('harvester/findAll', { type: STORAGE_CLASS }); this.allStorageClasses = await this.$store.dispatch('harvester/findAll', { type: STORAGE_CLASS });
this.allVMs = await this.actionResource.findInNamespace(HCI.VM); this.allVMs = await this.$store.dispatch('harvester/findAll', { type: HCI.VM });
}, },
data() { data() {
-164
View File
@@ -1,164 +0,0 @@
<script>
import merge from 'lodash/merge';
import jsyaml from 'js-yaml';
import { mapGetters } from 'vuex';
import { Card } from '@components/Card';
import { LabeledInput } from '@components/Form/LabeledInput';
import AsyncButton from '@shell/components/AsyncButton';
import { escapeHtml } from '@shell/utils/string';
const DEFAULT_VALUE = {
rancher: {
hostname: '',
version: '',
bootstrapPassword: '',
},
};
export default {
name: 'HarvesterEnableK3k',
emits: ['close'],
components: {
AsyncButton,
Card,
LabeledInput,
},
props: {
resources: {
type: Array,
required: true
}
},
data() {
const addon = this.resources[0];
let valuesContentJson;
try {
valuesContentJson = merge({}, DEFAULT_VALUE, jsyaml.load(addon.spec.valuesContent));
} catch (e) {
valuesContentJson = merge({}, DEFAULT_VALUE);
}
return { valuesContentJson };
},
computed: {
...mapGetters({ t: 'i18n/t' }),
buttonDisabled() {
const { rancher } = this.valuesContentJson;
return !(rancher?.hostname || '').trim() || !(rancher?.version || '').trim() || !(rancher?.bootstrapPassword || '').trim();
}
},
methods: {
close() {
this.$emit('close');
},
async enable(buttonCb) {
const addon = this.resources[0];
try {
addon.spec.valuesContent = jsyaml.dump(this.valuesContentJson);
addon.spec.enabled = true;
await addon.save();
buttonCb(true);
this.close();
} catch (err) {
addon.spec.enabled = false;
this.$store.dispatch('growl/fromError', {
title: this.t('generic.notification.title.error', { name: escapeHtml(addon.metadata.name) }),
err,
}, { root: true });
buttonCb(false);
}
}
}
};
</script>
<template>
<Card :show-highlight-border="false">
<template #title>
<h4
v-clean-html="t('harvester.addons.rancherK3k.enable.title')"
class="text-default-text"
/>
</template>
<template #body>
<div class="body">
<div class="row mb-15">
<div class="col span-6">
<LabeledInput
v-model:value="valuesContentJson.rancher.hostname"
:required="true"
:label="t('harvester.addons.rancherK3k.hostname')"
placeholder="rancher.$vip.nip.io"
/>
</div>
<div class="col span-6">
<LabeledInput
v-model:value="valuesContentJson.rancher.version"
:required="true"
:label="t('harvester.addons.rancherK3k.version')"
placeholder="v1.14.0"
/>
</div>
</div>
<div class="row mb-15">
<div class="col span-12">
<LabeledInput
v-model:value="valuesContentJson.rancher.bootstrapPassword"
:required="true"
type="password"
:label="t('harvester.addons.rancherK3k.password')"
:tooltip="t('harvester.addons.rancherK3k.passwordTooltip')"
/>
</div>
</div>
</div>
</template>
<template #actions>
<div class="buttons actions">
<button
class="btn role-secondary mr-10"
@click="close"
>
{{ t('generic.cancel') }}
</button>
<AsyncButton
mode="enable"
:disabled="buttonDisabled"
@click="enable"
/>
</div>
</template>
</Card>
</template>
<style lang="scss" scoped>
.body {
display: flex;
flex-direction: column;
min-width: 400px;
}
.actions {
width: 100%;
}
.buttons {
display: flex;
justify-content: flex-end;
width: 100%;
}
</style>
@@ -2,6 +2,7 @@
import { mapGetters } from 'vuex'; import { mapGetters } from 'vuex';
import { randomStr } from '@shell/utils/string'; import { randomStr } from '@shell/utils/string';
import { allHash } from '@shell/utils/promise';
import { exceptionToErrorsArray } from '@shell/utils/error'; import { exceptionToErrorsArray } from '@shell/utils/error';
import { Card } from '@components/Card'; import { Card } from '@components/Card';
@@ -23,7 +24,9 @@ export default {
}, },
async fetch() { async fetch() {
this.backups = await this.actionResource.findInNamespace(HCI.BACKUP); const hash = await allHash({ backups: this.$store.dispatch('harvester/findAll', { type: HCI.BACKUP }) });
this.backups = hash.backups;
}, },
props: { props: {
@@ -29,13 +29,7 @@ export default {
}, },
async fetch() { async fetch() {
const [pvcs, vms] = await Promise.all([ this.allPVCs = await this.$store.dispatch('harvester/findAll', { type: PVC });
this.actionResource.findInNamespace(PVC),
this.actionResource.findInNamespace(HCI.VM),
]);
this.allPVCs = pvcs;
this.namespaceVMs = vms;
}, },
data() { data() {
@@ -44,7 +38,6 @@ export default {
targetVolume: '', targetVolume: '',
errors: [], errors: [],
allPVCs: [], allPVCs: [],
namespaceVMs: [],
}; };
}, },
@@ -75,9 +68,10 @@ export default {
}, },
vmUsedVolumeNames() { vmUsedVolumeNames() {
const allVMs = this.$store.getters['harvester/all'](HCI.VM) || [];
const names = new Set(); const names = new Set();
this.namespaceVMs.forEach((vm) => { allVMs.forEach((vm) => {
// Collect volume names from spec.template.spec.volumes (both PVC and DataVolume references) // Collect volume names from spec.template.spec.volumes (both PVC and DataVolume references)
const volumes = vm.spec?.template?.spec?.volumes || []; const volumes = vm.spec?.template?.spec?.volumes || [];
@@ -1,55 +0,0 @@
import { PVC, STORAGE_CLASS } from '@shell/config/types';
import HotplugVolumeModal from '../HarvesterAddHotplugVolumeModal.vue';
import StorageMigrationDialog from '../HarvesterStorageMigrationDialog.vue';
import RestoreDialog from '../HarvesterRestoreDialog.vue';
import { HCI } from '../../types';
// The dialogs of the VM list read the VMs, PVCs and backups of the VM's namespace through the VM, so a paged VM list
// keeps its page (see `findInNamespace` in the VM model)
describe('dialogs of the VM list', () => {
const vm = (claims = []) => ({
metadata: { namespace: 'default', name: 'vm' },
spec: { template: { spec: { volumes: claims.map((claimName) => ({ persistentVolumeClaim: { claimName } })) } } },
findInNamespace: jest.fn((type) => Promise.resolve([{ type }])),
});
it('should load the PVCs and VMs of Add Volume through the VM', async() => {
const actionResource = vm();
const dispatch = jest.fn(() => Promise.resolve([]));
const dialog = { actionResource, $store: { dispatch } };
await HotplugVolumeModal.fetch.call(dialog);
expect(actionResource.findInNamespace.mock.calls).toStrictEqual([[PVC], [HCI.VM]]);
expect(dialog.allPVCs).toStrictEqual([{ type: PVC }]);
expect(dialog.allVMs).toStrictEqual([{ type: HCI.VM }]);
expect(dispatch.mock.calls).toStrictEqual([['harvester/findAll', { type: STORAGE_CLASS }]]);
});
it('should load the PVCs and VMs of Storage Migration through the VM', async() => {
const actionResource = vm();
const dialog = { actionResource };
await StorageMigrationDialog.fetch.call(dialog);
expect(actionResource.findInNamespace.mock.calls).toStrictEqual([[PVC], [HCI.VM]]);
expect(dialog.allPVCs).toStrictEqual([{ type: PVC }]);
expect(dialog.namespaceVMs).toStrictEqual([{ type: HCI.VM }]);
});
it('should exclude the volumes of the loaded VMs from the Storage Migration targets', () => {
const used = StorageMigrationDialog.computed.vmUsedVolumeNames.call({ namespaceVMs: [vm(['a-disk']), vm(['b-disk'])] });
expect([...used]).toStrictEqual(['default/a-disk', 'default/b-disk']);
});
it('should load the backups of Restore through the VM', async() => {
const actionResource = vm();
const dialog = { actionResource };
await RestoreDialog.fetch.call(dialog);
expect(actionResource.findInNamespace.mock.calls).toStrictEqual([[HCI.BACKUP]]);
expect(dialog.backups).toStrictEqual([{ type: HCI.BACKUP }]);
});
});
@@ -1,141 +0,0 @@
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 });
});
});
@@ -1,36 +0,0 @@
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 });
});
});
@@ -1,99 +0,0 @@
import EditVPC from '../kubeovn.io.vpc/index.vue';
const { validateBfdPort, bfdPortIPError, applyBfdPort } = EditVPC.methods;
const { validationPassed, gatewaysNeedingBfdPort } = EditVPC.computed;
const t = (key) => key;
function createContext(form = {}, spec = {}, model = {}) {
const value = {
metadata: { name: 'commonvpc' }, spec, subnetResources: [], bfdEgressGateways: [], ...model
};
return {
t,
value,
...EditVPC.data.call({ value }),
bfdPortIPError,
...form,
};
}
describe('edit: kubeovn.io.vpc', () => {
it('should load the BFD port of an existing VPC', () => {
const context = createContext({}, { bfdPort: { enabled: true, ip: '10.255.255.255' } });
expect(context.bfdPortEnabled).toBe(true);
expect(context.bfdPortIP).toBe('10.255.255.255');
});
it('should not add a BFD port to a VPC that has none while it stays disabled', () => {
const context = createContext({}, { staticRoutes: [] });
expect(validateBfdPort.call(context)).toStrictEqual([]);
applyBfdPort.call(context);
expect(context.value.spec).toStrictEqual({ staticRoutes: [] });
});
it('should enable the BFD port with its IP and keep its node selector', () => {
const nodeSelector = { matchLabels: { 'kubernetes.io/os': 'linux' } };
const context = createContext({ bfdPortEnabled: true, bfdPortIP: ' 10.255.255.255 , fd00::ffff ' }, { bfdPort: { enabled: false, nodeSelector } });
expect(validateBfdPort.call(context)).toStrictEqual([]);
applyBfdPort.call(context);
expect(context.value.spec.bfdPort).toStrictEqual({
enabled: true, ip: '10.255.255.255,fd00::ffff', nodeSelector
});
});
it('should keep the IP when the BFD port is disabled', () => {
const context = createContext({ bfdPortEnabled: false }, { bfdPort: { enabled: true, ip: '10.255.255.255' } });
applyBfdPort.call(context);
expect(context.value.spec.bfdPort).toStrictEqual({ enabled: false, ip: '10.255.255.255' });
});
it('should reject a BFD port IP inside one of the VPC subnets', () => {
const subnet = {
id: 'subnetinternal', spec: { cidrBlock: '172.20.10.0/24' }, containsIP: (ip) => ip.startsWith('172.20.10.')
};
const context = createContext({ bfdPortEnabled: true, bfdPortIP: '172.20.10.200' }, {}, { subnetResources: [subnet] });
const errors = validateBfdPort.call(context);
expect(errors).toHaveLength(1);
expect(errors[0]).toContain('harvester.vpc.bfdPort.validation.subnet');
});
it.each([
['a name and a valid BFD port', {}, true],
['no name', { value: { metadata: {} } }, false],
['an invalid BFD port', { bfdPortErrors: ['error'] }, false],
])('should allow the save with %s', (_, form, passed) => {
expect(validationPassed.call({
value: { metadata: { name: 'commonvpc' } }, bfdPortErrors: [], ...form
})).toBe(passed);
});
it('should list the gateways that need the BFD port only while it is disabled', () => {
const bfdEgressGateways = [{ id: 'default/gateway1' }];
expect(gatewaysNeedingBfdPort.call({ bfdPortEnabled: false, value: { bfdEgressGateways } })).toStrictEqual(bfdEgressGateways);
expect(gatewaysNeedingBfdPort.call({ bfdPortEnabled: true, value: { bfdEgressGateways } })).toStrictEqual([]);
});
it.each([
['no IP', '', 'validation.required'],
['an invalid IP', '10.255.255.256', 'harvester.vpc.bfdPort.validation.ip'],
['a CIDR', '10.255.255.255/32', 'harvester.vpc.bfdPort.validation.ip'],
['two IPv4 addresses', '10.255.255.254,10.255.255.255', 'harvester.vpc.bfdPort.validation.ip'],
['three addresses', '10.255.255.255,fd00::1,fd00::2', 'harvester.vpc.bfdPort.validation.ip'],
])('should reject an enabled BFD port with %s', (_, bfdPortIP, errorKey) => {
const errors = validateBfdPort.call(createContext({ bfdPortEnabled: true, bfdPortIP }));
expect(errors).toHaveLength(1);
expect(errors[0]).toContain(errorKey);
});
});
@@ -1,452 +0,0 @@
import EditVpcEgressGateway from '../kubeovn.io.vpcegressgateway.vue';
const {
validate, validateTabs, ipError, ipCountError, policyError, policiesSpec, toSpec, bfdSpec, saveGateway
} = EditVpcEgressGateway.methods;
const { vpc: onVpcChange, externalNetworkMode: onExternalNetworkModeChange } = EditVpcEgressGateway.watch;
const {
showExternalNetworkMode, vpcBfdPortDisabled, vpcEditLocation, internalSubnetOptions, externalSubnetOptions, externalSubnetRules, internalSubnetPlaceholder, snatSubnetOptions, noSnatSubnetOptions, policySubnetsPlaceholder
} = EditVpcEgressGateway.computed;
const { requiredError } = EditVpcEgressGateway.methods;
const t = (key, args) => (args ? `${ key } ${ JSON.stringify(args) }` : key);
function createContext(form = {}, spec = {}) {
const value = { metadata: { name: 'gateway1', namespace: 'default' }, spec };
const context = {
t,
value,
...EditVpcEgressGateway.data.call({ value }),
vpc: 'commonvpc',
replicas: 2,
internalSubnet: 'subnetinternal',
externalSubnet: 'subnetexternal',
snatSubnets: ['subnetinternal'],
...form,
};
Object.assign(context, {
bfdSpec, validateTabs, ipError, ipCountError, policyError, policiesSpec
});
return context;
}
// A subnet as the store returns it, with the model getters the form reads
function subnet(id, spec, model = {}) {
return {
id, spec, isOverlayAttachment: false, networkAttachment: null, canAssignIP: () => true, ...model
};
}
describe('edit: kubeovn.io.vpcegressgateway', () => {
it('should start a new gateway with one replica, no subnets and BFD off', () => {
const data = EditVpcEgressGateway.data.call({ value: { metadata: {} } });
expect(data.replicas).toBe(1);
expect([data.snatSubnets, data.noSnatSubnets, data.ipBlockPolicies]).toStrictEqual([[], [], []]);
expect(data.bfd).toStrictEqual({
enabled: false, minRX: 1000, minTX: 1000, multiplier: 3
});
});
it('should build the spec from the form and leave out empty optional fields', () => {
const spec = toSpec.call(createContext());
expect(spec).toStrictEqual({
vpc: 'commonvpc',
replicas: 2,
internalSubnet: 'subnetinternal',
externalSubnet: 'subnetexternal',
policies: [{ snat: true, subnets: ['subnetinternal'] }],
bfd: {
enabled: false, minRX: 1000, minTX: 1000, multiplier: 3
},
});
});
it('should build the spec with IPs, BFD and bandwidth', () => {
const spec = toSpec.call(createContext({
internalIPs: ['172.20.10.41', ' 172.20.10.51 ', ''],
externalIPs: ['10.115.48.220', '10.115.48.221'],
bfd: {
enabled: true, minRX: '50', minTX: 50, multiplier: 3
},
bandwidthIngress: 10,
bandwidthEgress: null,
}));
expect(spec.internalIPs).toStrictEqual(['172.20.10.41', '172.20.10.51']);
expect(spec.externalIPs).toStrictEqual(['10.115.48.220', '10.115.48.221']);
expect(spec.bfd).toStrictEqual({
enabled: true, minRX: 50, minTX: 50, multiplier: 3
});
expect(spec.bandwidth).toStrictEqual({ ingress: 10 });
});
it('should keep a bandwidth quantity as a string and a whole number as Mbps', () => {
const context = createContext({ bandwidthIngress: ' 1Gi ', bandwidthEgress: '100' });
expect(validate.call(context)).toStrictEqual([]);
expect(toSpec.call(context).bandwidth).toStrictEqual({ ingress: '1Gi', egress: 100 });
});
it('should send the BFD defaults for intervals cleared while BFD is off', () => {
const context = createContext({
bfd: {
enabled: false, minRX: '', minTX: 50, multiplier: null
}
});
expect(validate.call(context)).toStrictEqual([]);
expect(toSpec.call(context).bfd).toStrictEqual({
enabled: false, minRX: 1000, minTX: 50, multiplier: 3
});
});
it('should list only the subnets of the VPC that sit on a virtual machine network as internal subnets', () => {
const vpcSubnets = [
subnet('ovn-default', { vpc: 'ovn-cluster', provider: 'ovn' }),
subnet('subnetinternal', { vpc: 'commonvpc', provider: 'vmnet.default.ovn' }, { isOverlayAttachment: true }),
];
expect(internalSubnetOptions.call({ vpcSubnets })).toStrictEqual([{ label: 'subnetinternal', value: 'subnetinternal' }]);
});
it('should list only the subnets attached to a network as external subnets', () => {
const allSubnets = [
subnet('join', { vpc: 'ovn-cluster', provider: 'ovn' }),
subnet('subnetexternal', { vpc: 'commonvpc', provider: 'extnet.default' }, { networkAttachment: { name: 'extnet', namespace: 'default' } }),
];
expect(externalSubnetOptions.call({ allSubnets })).toStrictEqual([{ label: 'subnetexternal', value: 'subnetexternal' }]);
});
it('should check the IPs against the subnet they belong to', () => {
const internalSubnetResource = subnet('subnetinternal', { cidrBlock: '172.20.10.0/24' }, { canAssignIP: (ip) => ip.startsWith('172.20.10.') });
const errors = validate.call(createContext({ internalSubnetResource, internalIPs: ['172.20.10.41', '10.0.0.1'] }));
expect(errors).toHaveLength(1);
expect(errors[0]).toContain('harvester.egressGateway.validation.ipSubnet');
expect(errors[0]).toContain('172.20.10.0/24');
});
it('should put each error on the tab that holds the field', () => {
const errors = validateTabs.call(createContext({
replicas: 11,
snatSubnets: [],
externalIPs: ['10.115.48.300'],
bfd: {
enabled: true, minRX: 0, minTX: 50, multiplier: 3
},
bandwidthIngress: '10Mbps',
}));
expect(Object.fromEntries(Object.entries(errors).map(([tab, messages]) => [tab, messages.length]))).toStrictEqual({
basic: 1, policies: 1, ips: 1, bfd: 1, bandwidth: 1
});
expect(errors.policies[0]).toContain('harvester.egressGateway.validation.policyRequired');
});
it.each([
['empty', '', 'validation.required'],
['the internal subnet', 'subnetinternal', 'harvester.egressGateway.validation.sameSubnet'],
])('should explain an external subnet that is %s', (_, value, errorKey) => {
const [rule] = externalSubnetRules.call(createContext({ requiredError }));
expect(rule(value)).toContain(errorKey);
});
it('should accept an external subnet other than the internal one', () => {
const [rule] = externalSubnetRules.call(createContext({ requiredError }));
expect(rule('subnetexternal')).toBeUndefined();
});
it('should ask for a VPC before the internal subnet', () => {
expect(internalSubnetPlaceholder.call({
t: (key) => key, vpc: '', internalSubnetOptions: []
})).toBe('harvester.egressGateway.internalSubnet.noVpc');
});
it('should say when the VPC has no subnet on a virtual machine network', () => {
const t = (key, args) => (args ? `${ key } ${ args.vpc }` : key);
expect(internalSubnetPlaceholder.call({
t, vpc: 'ovn-cluster', internalSubnetOptions: []
})).toBe('harvester.egressGateway.internalSubnet.none ovn-cluster');
expect(internalSubnetPlaceholder.call({
t, vpc: 'commonvpc', internalSubnetOptions: [{ value: 'subnetinternal' }]
})).toBe('harvester.egressGateway.internalSubnet.placeholder');
});
it('should leave an empty IP row to the save, which drops it', () => {
expect(ipError.call(createContext(), 'internalIPs', ' ')).toBeUndefined();
});
it('should read the policies as Kube-OVN applies them', () => {
const data = EditVpcEgressGateway.data.call({
value: {
spec: {
policies: [
{ snat: true, subnets: ['a', 'b'] },
{ snat: true, subnets: ['c', 'a'] },
{ snat: false, subnets: ['b', 'd'] },
{ snat: false, ipBlocks: ['10.0.0.0/24'] },
]
}
}
});
expect(data.snatSubnets).toStrictEqual(['a', 'c']);
expect(data.noSnatSubnets).toStrictEqual(['b', 'd']);
expect(data.ipBlockPolicies).toStrictEqual([{ snat: false, ipBlocks: ['10.0.0.0/24'] }]);
});
it('should write one policy for each group and keep the IP block policies', () => {
const context = createContext({
snatSubnets: ['a', 'c'], noSnatSubnets: ['b'], ipBlockPolicies: [{ snat: true, ipBlocks: ['10.0.0.0/24'] }]
});
expect(policiesSpec.call(context)).toStrictEqual([
{ snat: true, subnets: ['a', 'c'] },
{ snat: false, subnets: ['b'] },
{ snat: true, ipBlocks: ['10.0.0.0/24'] },
]);
});
it('should leave out a group without subnets', () => {
expect(policiesSpec.call(createContext({ snatSubnets: [], noSnatSubnets: ['b'] }))).toStrictEqual([{ snat: false, subnets: ['b'] }]);
});
it.each([
['no VPC is chosen', '', [], 'harvester.egressGateway.policies.noVpc'],
['the VPC has no subnets', 'emptyvpc', [], 'harvester.egressGateway.policies.noSubnets emptyvpc'],
['the VPC has subnets', 'commonvpc', [{ value: 'a' }], 'harvester.egressGateway.policies.placeholder'],
])('should explain the policy lists when %s', (_, vpc, vpcSubnetOptions, placeholder) => {
const t = (key, args) => (args ? `${ key } ${ args.vpc }` : key);
expect(policySubnetsPlaceholder.call({
t, vpc, vpcSubnetOptions
})).toBe(placeholder);
});
it('should not offer a subnet of one group in the other, nor the external subnet', () => {
const vpcSubnetOptions = ['a', 'b', 'c', 'ext'].map((value) => ({ label: value, value }));
const context = {
vpcSubnetOptions, snatSubnets: ['a'], noSnatSubnets: ['b'], externalSubnet: 'ext'
};
expect(snatSubnetOptions.call(context).map((option) => option.value)).toStrictEqual(['a', 'c']);
expect(noSnatSubnetOptions.call(context).map((option) => option.value)).toStrictEqual(['b', 'c']);
});
it('should reject the external subnet as a policy source', () => {
const error = policyError.call(createContext({ snatSubnets: ['subnetexternal'] }));
expect(error).toContain('harvester.egressGateway.validation.policyExternalSubnet');
expect(error).toContain('subnetexternal');
});
it.each([
['subnets with SNAT', { snatSubnets: ['a'] }],
['subnets without SNAT', { snatSubnets: [], noSnatSubnets: ['b'] }],
['only IP blocks', { snatSubnets: [], ipBlockPolicies: [{ snat: false, ipBlocks: ['10.0.0.0/24'] }] }],
])('should accept a gateway with %s', (_, form) => {
expect(policyError.call(createContext(form))).toBeUndefined();
});
it('should stop the save when the form has errors', async() => {
const buttonCb = jest.fn();
const context = createContext({
vpc: '', validate, save: jest.fn()
});
await saveGateway.call(context, buttonCb);
expect(buttonCb).toHaveBeenCalledWith(false);
expect(context.save).not.toHaveBeenCalled();
expect(context.errors).toHaveLength(1);
});
it('should save the spec built from the form', async() => {
const buttonCb = jest.fn();
const context = createContext({
validate, toSpec, save: jest.fn()
});
await saveGateway.call(context, buttonCb);
expect(context.save).toHaveBeenCalledWith(buttonCb);
expect(context.value.spec.vpc).toBe('commonvpc');
expect(context.value.spec.policies).toStrictEqual([{ snat: true, subnets: ['subnetinternal'] }]);
});
it('should keep the fields the form does not show', () => {
const existing = {
trafficPolicy: 'Local',
selectors: [{ namespaceSelector: { matchLabels: { app: 'web' } } }],
policies: [{ snat: false, ipBlocks: ['10.0.0.0/24'] }],
};
const context = createContext({ snatSubnets: [] }, existing);
const { snatSubnets, noSnatSubnets, ipBlockPolicies } = EditVpcEgressGateway.data.call({ value: context.value });
Object.assign(context, {
snatSubnets, noSnatSubnets, ipBlockPolicies
});
const spec = toSpec.call(context);
expect(spec.trafficPolicy).toBe('Local');
expect(spec.selectors).toStrictEqual(existing.selectors);
expect(spec.policies).toStrictEqual([{ snat: false, ipBlocks: ['10.0.0.0/24'] }]);
expect(validate.call(context)).toStrictEqual([]);
});
it.each([
['has', true],
['does not have', false],
])('should offer Primary CNI when the CRD %s externalNetworkMode', async(_, hasField) => {
const schema = { fetchResourceFields: jest.fn().mockResolvedValue({}) };
const getters = {
currentProduct: { inStore: 'harvester' },
'harvester/schemaFor': () => schema,
'harvester/pathExistsInSchema': jest.fn(() => hasField),
};
const context = { $store: { getters, dispatch: jest.fn().mockResolvedValue([]) }, supportsPrimaryCNI: false };
await EditVpcEgressGateway.fetch.call(context);
expect(schema.fetchResourceFields).toHaveBeenCalledWith();
expect(getters['harvester/pathExistsInSchema']).toHaveBeenCalledWith('kubeovn.io.vpcegressgateway', 'spec.externalNetworkMode');
expect(context.supportsPrimaryCNI).toBe(hasField);
});
it.each([
['a CRD with the mode', { supportsPrimaryCNI: true, usesPrimaryCNI: false }, true],
['a CRD without the mode', { supportsPrimaryCNI: false, usesPrimaryCNI: false }, false],
['an existing Primary CNI gateway', { supportsPrimaryCNI: false, usesPrimaryCNI: true }, true],
])('should show the external network choice for %s', (_, context, shown) => {
expect(showExternalNetworkMode.call(context)).toBe(shown);
});
it('should start a new gateway on an external subnet and leave the mode to the CRD default', () => {
const context = createContext();
expect(context.externalNetworkMode).toBe('Attachment');
expect(toSpec.call(context)).not.toHaveProperty('externalNetworkMode');
});
it('should write a PrimaryCNI gateway without an external subnet', () => {
const spec = toSpec.call(createContext({ externalNetworkMode: 'PrimaryCNI', externalSubnet: '' }));
expect(spec.externalNetworkMode).toBe('PrimaryCNI');
expect(spec).not.toHaveProperty('externalSubnet');
expect(spec).not.toHaveProperty('externalIPs');
expect(spec).not.toHaveProperty('bandwidth');
});
it('should clear the external fields when PrimaryCNI is chosen', () => {
const context = createContext({
externalIPs: ['10.115.48.220'], bandwidthIngress: 10, bandwidthEgress: '1Gi'
});
onExternalNetworkModeChange.call(context, 'PrimaryCNI');
expect([context.externalSubnet, context.externalIPs, context.bandwidthIngress, context.bandwidthEgress]).toStrictEqual(['', [], '', '']);
});
it('should save a PrimaryCNI gateway made outside the form', () => {
const existing = {
vpc: 'commonvpc',
replicas: 1,
externalNetworkMode: 'PrimaryCNI',
internalSubnet: 'subnetinternal',
policies: [{ snat: true, subnets: ['subnetinternal'] }],
};
const value = { metadata: { name: 'gateway1', namespace: 'default' }, spec: existing };
const context = createContext(EditVpcEgressGateway.data.call({ value }), existing);
expect(context.externalNetworkMode).toBe('PrimaryCNI');
expect(validate.call(context)).toStrictEqual([]);
expect(toSpec.call(context)).toStrictEqual({
...existing,
bfd: {
enabled: false, minRX: 1000, minTX: 1000, multiplier: 3
},
});
});
it('should accept a complete form', () => {
expect(validate.call(createContext())).toStrictEqual([]);
});
it.each([
['no VPC', { vpc: '' }, 'validation.required'],
['no internal subnet', { internalSubnet: '' }, 'validation.required'],
['no external subnet', { externalSubnet: '' }, 'validation.required'],
['the same internal and external subnet', { externalSubnet: 'subnetinternal', snatSubnets: ['subnetother'] }, 'harvester.egressGateway.validation.sameSubnet'],
['too many replicas', { replicas: 11 }, 'harvester.egressGateway.validation.replicas'],
['no subnet with or without SNAT', { snatSubnets: [] }, 'harvester.egressGateway.validation.policyRequired'],
['an invalid IP', { externalIPs: ['10.115.48.300', '10.115.48.221'] }, 'harvester.egressGateway.validation.ipList'],
['fewer IPs than replicas', { internalIPs: ['172.20.10.41'] }, 'harvester.egressGateway.validation.ipCount'],
['a repeated IP', { externalIPs: ['10.115.48.220', ' 10.115.48.220'] }, 'harvester.egressGateway.validation.ipDuplicate'],
['a BFD interval of 0', {
bfd: {
enabled: true, minRX: 0, minTX: 50, multiplier: 3
}
}, 'harvester.egressGateway.validation.bfd'],
['a BFD multiplier of 0', {
bfd: {
enabled: true, minRX: 50, minTX: 50, multiplier: 0
}
}, 'harvester.egressGateway.validation.bfdMultiplier'],
['a negative bandwidth', { bandwidthEgress: -1 }, 'harvester.egressGateway.validation.bandwidth'],
['a bandwidth with an unknown unit', { bandwidthEgress: '10Mbps' }, 'harvester.egressGateway.validation.bandwidth'],
])('should reject %s', (_, form, errorKey) => {
const errors = validate.call(createContext(form));
expect(errors).toHaveLength(1);
expect(errors[0]).toContain(errorKey);
});
it('should drop the subnets of the previous VPC when the VPC changes', () => {
const context = createContext({
vpc: 'othervpc',
internalSubnet: 'subnetinternal',
snatSubnets: ['subnetinternal', 'othersubnet'],
noSnatSubnets: ['subnetinternal'],
vpcSubnetOptions: [{ label: 'othersubnet', value: 'othersubnet' }],
internalSubnetOptions: [{ label: 'othersubnet', value: 'othersubnet' }],
});
onVpcChange.call(context, 'othervpc', 'commonvpc');
expect(context.internalSubnet).toBe('');
expect(context.snatSubnets).toStrictEqual(['othersubnet']);
expect(context.noSnatSubnets).toStrictEqual([]);
});
it.each([
['has no BFD port', { bfdPortEnabled: false }, true],
['has a BFD port', { bfdPortEnabled: true }, false],
])('should warn about BFD when the selected VPC %s', (_, selectedVpc, warning) => {
expect(vpcBfdPortDisabled.call({ selectedVpc })).toBe(warning);
});
it('should not warn about BFD before a VPC is selected', () => {
expect(vpcBfdPortDisabled.call({ selectedVpc: null })).toBe(false);
});
it('should link the BFD warning to the BFD Port tab of the selected VPC', () => {
const selectedVpc = { detailLocation: { name: 'harvester-c-cluster-resource-id', params: { resource: 'kubeovn.io.vpc', id: 'commonvpc' } } };
expect(vpcEditLocation.call({ selectedVpc })).toStrictEqual({
name: 'harvester-c-cluster-resource-id',
params: { resource: 'kubeovn.io.vpc', id: 'commonvpc' },
query: { mode: 'edit' },
hash: '#bfdPort',
});
});
});
@@ -1,167 +0,0 @@
<script>
import merge from 'lodash/merge';
import jsyaml from 'js-yaml';
import { LabeledInput } from '@components/Form/LabeledInput';
import { RadioGroup } from '@components/Form/Radio';
const DEFAULT_VALUE = {
certManagerVersion: 'v1.20.2',
rancher: {
hostname: '',
version: '',
bootstrapPassword: '',
},
k3kCluster: {
servers: 1,
version: 'v1.35.4-k3s1',
storageClassName: 'harvester-longhorn',
},
};
export default {
name: 'EditAddonRancherK3k',
components: { LabeledInput, RadioGroup },
inheritAttrs: false,
props: {
value: {
type: Object,
required: true,
},
mode: {
type: String,
required: true
},
registerBeforeHook: {
type: Function,
required: true,
},
},
data() {
let valuesContentJson = {};
try {
valuesContentJson = merge({}, DEFAULT_VALUE, jsyaml.load(this.value.spec.valuesContent));
} catch (err) {
valuesContentJson = merge({}, DEFAULT_VALUE);
this.$store.dispatch('growl/fromError', {
title: this.$store.getters['i18n/t']('generic.notification.title.error'),
err: err.data || err,
}, { root: true });
}
return { valuesContentJson };
},
created() {
if (this.registerBeforeHook) {
this.registerBeforeHook(this.willSave, 'willSave');
}
},
methods: {
willSave() {
const errors = [];
if (!this.value.spec.enabled) {
return Promise.resolve();
}
if (!this.valuesContentJson.rancher.hostname) {
errors.push(this.t('validation.required', { key: this.t('harvester.addons.rancherK3k.hostname') }, true));
}
if (!this.valuesContentJson.rancher.version) {
errors.push(this.t('validation.required', { key: this.t('harvester.addons.rancherK3k.version') }, true));
}
if (!this.valuesContentJson.rancher.bootstrapPassword) {
errors.push(this.t('validation.required', { key: this.t('harvester.addons.rancherK3k.password') }, true));
}
if (errors.length > 0) {
return Promise.reject(errors);
} else {
return Promise.resolve();
}
},
},
watch: {
valuesContentJson: {
handler(neu) {
this.value.spec['valuesContent'] = jsyaml.dump(neu);
},
deep: true,
immediate: true
},
},
};
</script>
<template>
<div>
<div class="row">
<div class="col span-12">
<RadioGroup
v-model:value="value.spec.enabled"
class="mb-20"
name="model"
:mode="mode"
:options="[true,false]"
:labels="[t('generic.enabled'), t('generic.disabled')]"
/>
</div>
</div>
<template v-if="value.spec.enabled">
<div class="row mb-20">
<div class="col span-6">
<LabeledInput
v-model:value="valuesContentJson.rancher.hostname"
label-key="harvester.addons.rancherK3k.hostname"
:required="true"
:mode="mode"
placeholder="rancher.$vip.nip.io"
/>
</div>
<div class="col span-6">
<LabeledInput
v-model:value="valuesContentJson.rancher.version"
label-key="harvester.addons.rancherK3k.version"
:required="true"
:mode="mode"
placeholder="v1.14.0"
/>
</div>
</div>
<div class="row mt-20">
<div class="col span-6">
<LabeledInput
v-model:value="valuesContentJson.rancher.bootstrapPassword"
label-key="harvester.addons.rancherK3k.password"
:mode="mode"
:required="true"
type="password"
:tooltip="t('harvester.addons.rancherK3k.passwordTooltip')"
/>
</div>
</div>
</template>
</div>
</template>
<style lang="scss" scoped>
:deep() .radio-group {
display: flex;
.radio-container {
margin-right: 30px;
}
}
</style>
@@ -7,7 +7,6 @@ import NameNsDescription from '@shell/components/form/NameNsDescription';
import YamlEditor from '@shell/components/YamlEditor'; import YamlEditor from '@shell/components/YamlEditor';
import CreateEditView from '@shell/mixins/create-edit-view'; import CreateEditView from '@shell/mixins/create-edit-view';
import FormValidation from '@shell/mixins/form-validation';
import { HCI } from '@pkg/harvester/config/labels-annotations'; import { HCI } from '@pkg/harvester/config/labels-annotations';
export default { export default {
@@ -24,19 +23,14 @@ export default {
NameNsDescription, NameNsDescription,
}, },
mixins: [CreateEditView, FormValidation], mixins: [CreateEditView],
inheritAttrs: false, inheritAttrs: false,
data() { data() {
return { return {
config: this.value.data?.cloudInit || '', config: this.value.data?.cloudInit || '',
type: this.value?.metadata?.labels?.[HCI.CLOUD_INIT] || 'user', type: this.value?.metadata?.labels?.[HCI.CLOUD_INIT] || 'user',
fvFormRuleSets: [{
path: 'metadata.name',
rules: ['required'],
translationKey: 'nameNsDescription.name.label',
}],
}; };
}, },
@@ -59,8 +53,8 @@ export default {
}, },
methods: { methods: {
update(config) { update() {
this.value.data = { cloudInit: config }; this.value.data = { cloudInit: this.config };
}, },
updateBeforeSave() { updateBeforeSave() {
@@ -84,7 +78,6 @@ export default {
:resource="value" :resource="value"
:errors="errors" :errors="errors"
:apply-hooks="applyHooks" :apply-hooks="applyHooks"
:validation-passed="fvFormIsValid"
@finish="save" @finish="save"
@cancel="done" @cancel="done"
@error="e=>errors=e" @error="e=>errors=e"
@@ -93,7 +86,6 @@ export default {
:value="value" :value="value"
:mode="mode" :mode="mode"
:namespaced="true" :namespaced="true"
:rules="{ name: fvGetAndReportPathRules('metadata.name') }"
@update:value="$emit('update:value', $event)" @update:value="$emit('update:value', $event)"
/> />
@@ -119,7 +111,7 @@ export default {
:mode="mode" :mode="mode"
class="yaml-editor" class="yaml-editor"
:editor-mode="mode === 'view' ? 'VIEW_CODE' : 'EDIT_CODE'" :editor-mode="mode === 'view' ? 'VIEW_CODE' : 'EDIT_CODE'"
@update:value="update" @onChanges="update"
/> />
</div> </div>
</Tab> </Tab>
@@ -133,7 +125,9 @@ export default {
:deep() .yaml-editor{ :deep() .yaml-editor{
flex: 1; flex: 1;
min-height: $yaml-height; min-height: $yaml-height;
& .code-mirror .cm-editor { & .code-mirror .CodeMirror {
position: initial;
height: auto;
min-height: $yaml-height; min-height: $yaml-height;
} }
} }
@@ -88,8 +88,7 @@ export default {
<div class="header mb-20"> <div class="header mb-20">
<FileSelector <FileSelector
v-if="isCreate" v-if="isCreate"
variant="primary" class="btn btn-sm bg-primary mt-10"
class="mt-10"
:label="t('generic.readFromFile')" :label="t('generic.readFromFile')"
accept=".pub" accept=".pub"
@selected="onKeySelected" @selected="onKeySelected"
@@ -16,8 +16,6 @@ import isEmpty from 'lodash/isEmpty';
import jsyaml from 'js-yaml'; import jsyaml from 'js-yaml';
import { createYaml } from '@shell/utils/create-yaml'; import { createYaml } from '@shell/utils/create-yaml';
import YamlEditor, { EDITOR_MODES } from '@shell/components/YamlEditor'; 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'; import { FLOW_TYPE } from '../config/harvester-map';
const LOGGING_EVENT = 'Logging/Event'; const LOGGING_EVENT = 'Logging/Event';
@@ -174,9 +172,10 @@ export default {
}); });
} }
}, },
onYamlEditorReady(view) { onYamlEditorReady(cm) {
foldAllComments(view); cm.getMode().fold = 'yamlcomments';
unfoldCode(view); cm.execCommand('foldAll');
cm.execCommand('unfold');
}, },
} }
}; };
@@ -1,5 +1,5 @@
<script> <script>
import { VOLUME_MODE, ACCESS_MODE } from '@pkg/harvester/config/types'; import { VOLUME_MODE } from '@pkg/harvester/config/types';
import { HCI as HCI_ANNOTATIONS } from '@pkg/harvester/config/labels-annotations'; import { HCI as HCI_ANNOTATIONS } from '@pkg/harvester/config/labels-annotations';
import ArrayList from '@shell/components/form/ArrayList'; import ArrayList from '@shell/components/form/ArrayList';
import { Checkbox } from '@components/Form/Checkbox'; import { Checkbox } from '@components/Form/Checkbox';
@@ -10,10 +10,6 @@ import { HCI_SETTING } from '../../config/settings';
import { allHash } from '@shell/utils/promise'; import { allHash } from '@shell/utils/promise';
import { _EDIT, _CREATE } from '@shell/config/query-params'; 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 { export default {
name: 'CDISettings', name: 'CDISettings',
@@ -94,10 +90,10 @@ export default {
accessModeOptions() { accessModeOptions() {
return [ return [
{ label: READ_WRITE_ONCE, value: READ_WRITE_ONCE }, { label: 'ReadWriteOnce', value: 'ReadWriteOnce' },
{ label: READ_ONLY_MANY, value: READ_ONLY_MANY }, { label: 'ReadOnlyMany', value: 'ReadOnlyMany' },
{ label: READ_WRITE_MANY, value: READ_WRITE_MANY }, { label: 'ReadWriteMany', value: 'ReadWriteMany' },
{ label: READ_WRITE_ONCE_POD, value: READ_WRITE_ONCE_POD }, { label: 'ReadWriteOncePod', value: 'ReadWriteOncePod' },
]; ];
}, },
@@ -7,12 +7,8 @@ import { allHash } from '@shell/utils/promise';
import { clone } from '@shell/utils/object'; import { clone } from '@shell/utils/object';
import { HCI } from '../../../types'; import { HCI } from '../../../types';
import { NODE } from '@shell/config/types'; import { NODE } from '@shell/config/types';
import { _CREATE, _CLONE } from '@shell/config/query-params';
import { LVM_TOPOLOGY_LABEL } from '../index.vue'; import { LVM_TOPOLOGY_LABEL } from '../index.vue';
const STRIPED_TYPE = 'striped';
const DM_THIN_TYPE = 'dm-thin';
const DEFAULT_PARAMETERS = [ const DEFAULT_PARAMETERS = [
'type', 'type',
'vgName' 'vgName'
@@ -58,17 +54,8 @@ export default {
data() { data() {
const node = (this.value.allowedTopologies?.[0]?.matchLabelExpressions || []).find((t) => t.key === LVM_TOPOLOGY_LABEL)?.values[0]; const node = (this.value.allowedTopologies?.[0]?.matchLabelExpressions || []).find((t) => t.key === LVM_TOPOLOGY_LABEL)?.values[0];
// striped is dropped once the LVM add-on reaches GA (v1.9.1); dm-thin is the only supported type.
const dmThinOnly = this.$store.getters['harvester-common/getFeatureEnabled']('lvmDmThinOnly');
const volumeGroupTypes = dmThinOnly ? [DM_THIN_TYPE] : [STRIPED_TYPE, DM_THIN_TYPE];
// Default new storage classes to dm-thin, and reset a cloned striped type that is no longer selectable.
if (dmThinOnly && [_CREATE, _CLONE].includes(this.realMode) && !volumeGroupTypes.includes(this.value.parameters.type)) {
this.value.parameters.type = DM_THIN_TYPE;
}
return { return {
volumeGroupTypes, volumeGroupTypes: ['striped', 'dm-thin'],
node, node,
}; };
}, },
@@ -173,7 +173,6 @@ export default {
try { try {
await proxyResource.save(); await proxyResource.save();
proxyResource.notifyGeneratedName?.();
buttonCb(true); buttonCb(true);
this.$router.push({ this.$router.push({
@@ -299,7 +299,6 @@ export default {
const res = await this.value.save(); const res = await this.value.save();
res.notifyGeneratedName?.();
res.uploadImage(file); res.uploadImage(file);
buttonCb(true); buttonCb(true);
@@ -21,7 +21,6 @@ import { HCI } from '../types';
import VM_MIXIN from '../mixins/harvester-vm'; import VM_MIXIN from '../mixins/harvester-vm';
import Reserved from './kubevirt.io.virtualmachine/VirtualMachineReserved'; import Reserved from './kubevirt.io.virtualmachine/VirtualMachineReserved';
import Volume from './kubevirt.io.virtualmachine/VirtualMachineVolume'; import Volume from './kubevirt.io.virtualmachine/VirtualMachineVolume';
import VMPerformanceOptions from './kubevirt.io.virtualmachine/VirtualMachineVolume/VMPerformanceOptions';
import Network from './kubevirt.io.virtualmachine/VirtualMachineNetwork'; import Network from './kubevirt.io.virtualmachine/VirtualMachineNetwork';
import CpuMemory from './kubevirt.io.virtualmachine/VirtualMachineCpuMemory'; import CpuMemory from './kubevirt.io.virtualmachine/VirtualMachineCpuMemory';
import CpuModel from './kubevirt.io.virtualmachine/VirtualMachineCpuModel'; import CpuModel from './kubevirt.io.virtualmachine/VirtualMachineCpuModel';
@@ -38,7 +37,6 @@ export default {
Tab, Tab,
SSHKey, SSHKey,
Volume, Volume,
VMPerformanceOptions,
Tabbed, Tabbed,
Network, Network,
Checkbox, Checkbox,
@@ -179,17 +177,8 @@ export default {
}, },
async saveVMT(buttonCb) { async saveVMT(buttonCb) {
this.errors = [];
this.parseVM(); this.parseVM();
this.validateCloudInit();
if (this.errors.length) {
buttonCb(false);
return;
}
const templates = await this.$store.dispatch('harvester/findAll', { type: HCI.VM_TEMPLATE }); const templates = await this.$store.dispatch('harvester/findAll', { type: HCI.VM_TEMPLATE });
const template = templates.find( (O) => O.metadata.name === this.templateValue.metadata.name); const template = templates.find( (O) => O.metadata.name === this.templateValue.metadata.name);
@@ -289,25 +278,6 @@ export default {
name="Basics" name="Basics"
:label="t('harvester.vmTemplate.tabs.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 <CpuMemory
class="mb-20" class="mb-20"
:cpu="cpu" :cpu="cpu"
@@ -319,69 +289,6 @@ export default {
@updateCpuMemory="updateCpuMemory" @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"> <div class="mb-20">
<SSHKey <SSHKey
v-model:value="sshKey" v-model:value="sshKey"
@@ -414,7 +321,6 @@ export default {
> >
<Network <Network
v-model:value="networkRows" v-model:value="networkRows"
v-model:network-boot-first="networkBootFirst"
:mode="mode" :mode="mode"
/> />
</Tab> </Tab>
@@ -536,6 +442,18 @@ export default {
:mode="mode" :mode="mode"
/> />
</div> </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"> <div class="col span-6">
<LabeledSelect <LabeledSelect
v-model:value="maintenanceStrategy" v-model:value="maintenanceStrategy"
@@ -545,9 +463,6 @@ export default {
:mode="mode" :mode="mode"
/> />
</div> </div>
</div>
<div class="row mb-20">
<div class="col span-6"> <div class="col span-6">
<Reserved <Reserved
:reserved-memory="reservedMemory" :reserved-memory="reservedMemory"
@@ -557,6 +472,16 @@ export default {
</div> </div>
</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"> <div class="row mb-20">
<a <a
v-if="showAdvanced" v-if="showAdvanced"
@@ -586,16 +511,6 @@ export default {
</div> </div>
</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 <CloudConfig
ref="yamlEditor" ref="yamlEditor"
:mode="mode" :mode="mode"
@@ -604,17 +519,76 @@ export default {
:network-script="networkScript" :network-script="networkScript"
@updateUserData="updateUserData" @updateUserData="updateUserData"
@updateNetworkData="updateNetworkData" @updateNetworkData="updateNetworkData"
> />
<template #after-user-data>
<Checkbox <div class="spacer"></div>
v-model:value="installAgent" <Checkbox
class="check mb-20" v-if="value.cpuPinningFeatureEnabled"
type="checkbox" v-model:value="cpuPinning"
label-key="harvester.virtualMachine.installAgent" class="check"
:mode="mode" type="checkbox"
/> tooltip-key="harvester.virtualMachine.cpuPinning.tooltip"
</template> label-key="harvester.virtualMachine.cpuPinning.label"
</CloudConfig> :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"
/>
</Tab> </Tab>
</Tabbed> </Tabbed>
</CruResource> </CruResource>
@@ -172,7 +172,6 @@ export default {
try { try {
await proxyResource.save(); await proxyResource.save();
proxyResource.notifyGeneratedName?.();
buttonCb(true); buttonCb(true);
this.$router.push({ this.$router.push({
+7 -47
View File
@@ -8,7 +8,6 @@ import LabeledSelect from '@shell/components/form/LabeledSelect';
import { LabeledInput } from '@components/Form/LabeledInput'; import { LabeledInput } from '@components/Form/LabeledInput';
import NameNsDescription from '@shell/components/form/NameNsDescription'; import NameNsDescription from '@shell/components/form/NameNsDescription';
import Conditions from '@shell/components/form/Conditions'; import Conditions from '@shell/components/form/Conditions';
import DiskPerformanceOptions from './kubevirt.io.virtualmachine/VirtualMachineVolume/DiskPerformanceOptions';
import { Banner } from '@components/Banner'; import { Banner } from '@components/Banner';
import { Checkbox } from '@components/Form/Checkbox'; import { Checkbox } from '@components/Form/Checkbox';
import jsyaml from 'js-yaml'; import jsyaml from 'js-yaml';
@@ -27,11 +26,9 @@ import { HCI, VOLUME_SNAPSHOT } from '../types';
import { LVM_DRIVER } from '../models/harvester/storage.k8s.io.storageclass'; import { LVM_DRIVER } from '../models/harvester/storage.k8s.io.storageclass';
import { DATA_ENGINE_V2 } from '../models/harvester/persistentvolumeclaim'; import { DATA_ENGINE_V2 } from '../models/harvester/persistentvolumeclaim';
import { GIBIBYTE } from '../utils/unit'; import { GIBIBYTE } from '../utils/unit';
import { VOLUME_MODE, ACCESS_MODE } from '@pkg/harvester/config/types'; import { VOLUME_MODE } from '@pkg/harvester/config/types';
import { isInternalStorageClass } from '../utils/storage-class'; import { isInternalStorageClass } from '../utils/storage-class';
const { READ_WRITE_MANY, READ_WRITE_ONCE, READ_ONLY_MANY } = ACCESS_MODE;
export default { export default {
name: 'HarvesterVolume', name: 'HarvesterVolume',
@@ -48,8 +45,7 @@ export default {
LabeledSelect, LabeledSelect,
LabeledInput, LabeledInput,
NameNsDescription, NameNsDescription,
Conditions, Conditions
DiskPerformanceOptions
}, },
mixins: [CreateEditView], mixins: [CreateEditView],
@@ -87,7 +83,7 @@ export default {
if (this.mode === _CREATE) { if (this.mode === _CREATE) {
// default volumeMode to Block // default volumeMode to Block
this.value.spec.volumeMode = VOLUME_MODE.BLOCK; this.value.spec.volumeMode = VOLUME_MODE.BLOCK;
this.value.spec.accessModes = [READ_WRITE_MANY]; this.value.spec.accessModes = ['ReadWriteMany'];
} }
const storage = this.value?.spec?.resources?.requests?.storage || null; const storage = this.value?.spec?.resources?.requests?.storage || null;
@@ -102,15 +98,7 @@ export default {
createWithDataVolume: false, createWithDataVolume: false,
snapshots: [], snapshots: [],
images: [], images: [],
GIBIBYTE, GIBIBYTE
// Default KubeVirt high-performance disk profile, stored as annotations and
// applied when this volume is later attached to a VM as a disk.
perf: {
cache: get(this.value, `metadata.annotations."${ HCI_ANNOTATIONS.DISK_CACHE_MODE }"`) || '',
io: get(this.value, `metadata.annotations."${ HCI_ANNOTATIONS.DISK_IO_MODE }"`) || '',
dedicatedIOThread: get(this.value, `metadata.annotations."${ HCI_ANNOTATIONS.DISK_DEDICATED_IOTHREAD }"`) === 'true',
volumeMode: this.value?.spec?.volumeMode,
},
}; };
}, },
@@ -172,7 +160,7 @@ export default {
}, },
accessModeOptions() { accessModeOptions() {
return [READ_WRITE_ONCE, READ_WRITE_MANY, READ_ONLY_MANY]; return ['ReadWriteOnce', 'ReadWriteMany', 'ReadOnlyMany'];
}, },
imageOption() { imageOption() {
@@ -342,7 +330,6 @@ export default {
} }
}, },
'value.spec.volumeMode'(neu) { 'value.spec.volumeMode'(neu) {
this.perf.volumeMode = neu;
if (neu === VOLUME_MODE.FILE_SYSTEM) { if (neu === VOLUME_MODE.FILE_SYSTEM) {
this.setVolumeForVmAnnotation(); this.setVolumeForVmAnnotation();
} else if (neu === VOLUME_MODE.BLOCK ) { } else if (neu === VOLUME_MODE.BLOCK ) {
@@ -368,7 +355,7 @@ export default {
getAccessMode() { getAccessMode() {
if (!this.longhornV2LVMSupport) { if (!this.longhornV2LVMSupport) {
return [READ_WRITE_MANY]; return ['ReadWriteMany'];
} }
if (this.value?.spec?.accessModes && this.value?.spec?.accessModes?.length > 0) { if (this.value?.spec?.accessModes && this.value?.spec?.accessModes?.length > 0) {
@@ -384,7 +371,7 @@ export default {
readWriteOnce = storageClass.provisioner === LVM_DRIVER || (!this.value.thirdPartyStorageFeatureEnabled && storageClass.parameters?.dataEngine === DATA_ENGINE_V2); readWriteOnce = storageClass.provisioner === LVM_DRIVER || (!this.value.thirdPartyStorageFeatureEnabled && storageClass.parameters?.dataEngine === DATA_ENGINE_V2);
} }
return readWriteOnce ? [READ_WRITE_ONCE] : [READ_WRITE_MANY]; return readWriteOnce ? ['ReadWriteOnce'] : ['ReadWriteMany'];
}, },
buildDataVolumeObj() { buildDataVolumeObj() {
const storage = { const storage = {
@@ -457,23 +444,6 @@ export default {
imageAnnotations = { ...this.value.metadata.annotations }; imageAnnotations = { ...this.value.metadata.annotations };
} }
// Persist the default high-performance disk profile as annotations.
if (this.perf.cache) {
imageAnnotations[HCI_ANNOTATIONS.DISK_CACHE_MODE] = this.perf.cache;
} else {
delete imageAnnotations[HCI_ANNOTATIONS.DISK_CACHE_MODE];
}
if (this.perf.io) {
imageAnnotations[HCI_ANNOTATIONS.DISK_IO_MODE] = this.perf.io;
} else {
delete imageAnnotations[HCI_ANNOTATIONS.DISK_IO_MODE];
}
if (this.perf.dedicatedIOThread) {
imageAnnotations[HCI_ANNOTATIONS.DISK_DEDICATED_IOTHREAD] = 'true';
} else {
delete imageAnnotations[HCI_ANNOTATIONS.DISK_DEDICATED_IOTHREAD];
}
const spec = { const spec = {
...this.value.spec, ...this.value.spec,
resources: { requests: { storage: this.storage } }, resources: { requests: { storage: this.storage } },
@@ -638,16 +608,6 @@ export default {
class="mb-20" class="mb-20"
@update:value="update" @update:value="update"
/> />
<Banner
color="info"
:label="t('harvester.volume.performance.pvcTip')"
/>
<DiskPerformanceOptions
:value="perf"
:mode="mode"
@update="update"
/>
</Tab> </Tab>
<Tab <Tab
v-if="!isCreate" v-if="!isCreate"
+1 -151
View File
@@ -5,17 +5,9 @@ import Tab from '@shell/components/Tabbed/Tab';
import Loading from '@shell/components/Loading'; import Loading from '@shell/components/Loading';
import CreateEditView from '@shell/mixins/create-edit-view'; import CreateEditView from '@shell/mixins/create-edit-view';
import ResourceTabs from '@shell/components/form/ResourceTabs/index'; import ResourceTabs from '@shell/components/form/ResourceTabs/index';
import { LabeledInput } from '@components/Form/LabeledInput';
import { RadioGroup } from '@components/Form/Radio';
import { Banner } from '@components/Banner';
import StaticRoutes from './StaticRoutes'; import StaticRoutes from './StaticRoutes';
import VpcPeerings from './VpcPeerings'; import VpcPeerings from './VpcPeerings';
import { set } from '@shell/utils/object'; import { set } from '@shell/utils/object';
import { allHash } from '@shell/utils/promise';
import { isValidIP } from '@shell/utils/validators/cidr';
import { HCI } from '../../types';
const splitIPs = (value) => `${ value || '' }`.split(',').map((ip) => ip.trim()).filter(Boolean);
export default { export default {
name: 'EditVPC', name: 'EditVPC',
@@ -23,11 +15,8 @@ export default {
emits: ['update:value'], emits: ['update:value'],
components: { components: {
Banner,
CruResource, CruResource,
LabeledInput,
NameNsDescription, NameNsDescription,
RadioGroup,
Tab, Tab,
StaticRoutes, StaticRoutes,
ResourceTabs, ResourceTabs,
@@ -39,106 +28,16 @@ export default {
inheritAttrs: false, inheritAttrs: false,
async fetch() {
const inStore = this.$store.getters['currentProduct'].inStore;
const hasEgressGateways = !!this.$store.getters[`${ inStore }/schemaFor`](HCI.VPC_EGRESS_GATEWAY);
await allHash({
subnets: this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.SUBNET }),
gateways: hasEgressGateways ? this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.VPC_EGRESS_GATEWAY }) : [],
});
},
data() { data() {
set(this.value, 'spec', this.value.spec || { set(this.value, 'spec', this.value.spec || {
staticRoutes: [], staticRoutes: [],
vpcPeerings: [], vpcPeerings: [],
}); });
const bfdPort = this.value.spec.bfdPort || {}; return { staticRoutes: [] };
return {
staticRoutes: [],
bfdPortEnabled: bfdPort.enabled === true,
bfdPortIP: bfdPort.ip || '',
};
},
computed: {
bfdPortErrors() {
return this.isView ? [] : this.validateBfdPort();
},
validationPassed() {
return !!this.value?.metadata?.name && this.bfdPortErrors.length === 0;
},
// Each field shows its own error once touched, so a disabled Save always has a visible reason
nameRules() {
return {
name: [(value) => (value ? undefined : this.t('validation.required', { key: this.t('generic.name') }, true))], namespace: [], description: []
};
},
bfdPortIPRules() {
return [(value) => this.bfdPortIPError(value)];
},
gatewaysNeedingBfdPort() {
return this.bfdPortEnabled ? [] : this.value.bfdEgressGateways || [];
},
}, },
methods: { methods: {
bfdPortIPError(value) {
if (!this.bfdPortEnabled) {
return undefined;
}
const ips = splitIPs(value);
const ipv6Count = ips.filter((ip) => ip.includes(':')).length;
if (!ips.length) {
return this.t('validation.required', { key: this.t('harvester.vpc.bfdPort.ip.label') }, true);
}
if (ips.length > 2 || ips.some((ip) => !isValidIP(ip)) || (ips.length === 2 && ipv6Count !== 1)) {
return this.t('harvester.vpc.bfdPort.validation.ip', null, true);
}
const subnet = (this.value.subnetResources || []).find((item) => ips.some((ip) => item.containsIP(ip)));
if (subnet) {
return this.t('harvester.vpc.bfdPort.validation.subnet', { subnet: subnet.id, cidr: subnet.spec?.cidrBlock }, true);
}
return undefined;
},
validateBfdPort() {
return [this.bfdPortIPError(this.bfdPortIP)].filter(Boolean);
},
applyBfdPort() {
const current = this.value.spec.bfdPort;
if (!this.bfdPortEnabled && !current) {
return;
}
const bfdPort = {
...(current || {}),
enabled: this.bfdPortEnabled,
ip: splitIPs(this.bfdPortIP).join(','),
};
if (!bfdPort.ip) {
delete bfdPort.ip;
}
this.value.spec.bfdPort = bfdPort;
},
async saveVpc(buttonCb) { async saveVpc(buttonCb) {
const errors = []; const errors = [];
@@ -149,15 +48,12 @@ export default {
errors.push(this.t('validation.required', { key: this.t('generic.name') }, true)); errors.push(this.t('validation.required', { key: this.t('generic.name') }, true));
} }
errors.push(...this.validateBfdPort());
if (errors.length > 0) { if (errors.length > 0) {
buttonCb(false); buttonCb(false);
this.errors = errors; this.errors = errors;
return false; return false;
} }
this.applyBfdPort();
await this.value.save(); await this.value.save();
buttonCb(true); buttonCb(true);
this.done(); this.done();
@@ -180,7 +76,6 @@ export default {
:mode="mode" :mode="mode"
:apply-hooks="applyHooks" :apply-hooks="applyHooks"
:errors="errors" :errors="errors"
:validation-passed="validationPassed"
@finish="saveVpc" @finish="saveVpc"
@error="e=>errors=e" @error="e=>errors=e"
> >
@@ -188,7 +83,6 @@ export default {
:value="value" :value="value"
:mode="mode" :mode="mode"
:namespaced="false" :namespaced="false"
:rules="nameRules"
@update:value="$emit('update:value', $event)" @update:value="$emit('update:value', $event)"
/> />
<ResourceTabs <ResourceTabs
@@ -221,50 +115,6 @@ export default {
:vpc="value" :vpc="value"
/> />
</Tab> </Tab>
<Tab
name="bfdPort"
:label="t('harvester.vpc.bfdPort.label')"
:weight="-3"
:error="bfdPortErrors.length > 0"
:error-icon-tooltip="bfdPortErrors.join(' ')"
>
<Banner
color="info"
:label="t('harvester.vpc.bfdPort.banner')"
/>
<RadioGroup
v-model:value="bfdPortEnabled"
name="bfdPort"
data-testid="vpc-bfd-port-enabled"
:options="[true, false]"
:labels="[t('generic.enabled'), t('generic.disabled')]"
:aria-label="t('harvester.vpc.bfdPort.label')"
:mode="mode"
/>
<Banner
v-if="gatewaysNeedingBfdPort.length"
color="warning"
data-testid="vpc-bfd-port-gateways"
:label="t('harvester.vpc.bfdPort.gatewaysNeedPort', { gateways: gatewaysNeedingBfdPort.map((gateway) => gateway.id).join(', ') }, true)"
/>
<div
v-if="bfdPortEnabled"
class="row mt-20"
>
<div class="col span-6">
<LabeledInput
v-model:value="bfdPortIP"
data-testid="vpc-bfd-port-ip"
required
:rules="bfdPortIPRules"
:mode="mode"
:label="t('harvester.vpc.bfdPort.ip.label')"
:placeholder="t('harvester.vpc.bfdPort.ip.placeholder')"
:tooltip="t('harvester.vpc.bfdPort.ip.tooltip')"
/>
</div>
</div>
</Tab>
</ResourceTabs> </ResourceTabs>
</CruResource> </CruResource>
</template> </template>
@@ -1,864 +0,0 @@
<script>
import CruResource from '@shell/components/CruResource';
import NameNsDescription from '@shell/components/form/NameNsDescription';
import ResourceTabs from '@shell/components/form/ResourceTabs';
import Tab from '@shell/components/Tabbed/Tab';
import ArrayList from '@shell/components/form/ArrayList';
import Loading from '@shell/components/Loading';
import MessageLink from '@shell/components/MessageLink';
import LabeledSelect from '@shell/components/form/LabeledSelect';
import UnitInput from '@shell/components/form/UnitInput';
import { LabeledInput } from '@components/Form/LabeledInput';
import { RadioGroup } from '@components/Form/Radio';
import { Banner } from '@components/Banner';
import CreateEditView from '@shell/mixins/create-edit-view';
import { _EDIT, MODE } from '@shell/config/query-params';
import { allHash } from '@shell/utils/promise';
import { isValidIP } from '@shell/utils/validators/cidr';
import { HCI } from '../types';
// Limits from the VpcEgressGateway CRD
const MAX_REPLICAS = 10;
const MAX_BFD_VALUE = 3600000;
const MAX_BANDWIDTH_MBPS = 9223372036854;
// A whole number in Mbps, or a quantity in bits per second such as 100M or 1Gi
const BANDWIDTH_PATTERN = /^([0-9]+|([0-9]+(\.[0-9]+)?|\.[0-9]+)(M|Mi|G|Gi))$/;
const IP_FIELDS = {
internalIPs: { labelKey: 'harvester.egressGateway.ips.internal.label', subnet: 'internalSubnetResource' },
externalIPs: { labelKey: 'harvester.egressGateway.ips.external.label', subnet: 'externalSubnetResource' },
};
const BFD_DEFAULTS = {
enabled: false, minRX: 1000, minTX: 1000, multiplier: 3
};
// PrimaryCNI sends traffic out through the pod's primary network, so it takes no external subnet, external IPs or bandwidth
const ATTACHMENT = 'Attachment';
const PRIMARY_CNI = 'PrimaryCNI';
const isBlank = (value) => value === null || value === undefined || `${ value }`.trim() === '';
const isWholeNumber = (value, min, max) => /^\d+$/.test(`${ value }`.trim()) && Number(value) >= min && Number(value) <= max;
const isValidBandwidth = (value) => BANDWIDTH_PATTERN.test(`${ value }`.trim()) && (!isWholeNumber(value, 0, Infinity) || Number(value) <= MAX_BANDWIDTH_MBPS);
const toBandwidth = (value) => (isWholeNumber(value, 0, Infinity) ? Number(value) : `${ value }`.trim());
const cleanList = (list) => (list || []).map((item) => `${ item || '' }`.trim()).filter(Boolean);
const isValidBfdValue = (value) => isWholeNumber(value, 1, MAX_BFD_VALUE);
const unique = (list) => [...new Set(list)];
// Kube-OVN puts the sources of every policy into two sets, with SNAT and without, and leaves a source out of
// SNAT when any policy has SNAT off for it. The form edits those two sets; IP blocks set outside it are kept.
const policyGroups = (policies = []) => {
const noSnatSubnets = unique(policies.filter((policy) => !policy.snat).flatMap((policy) => policy.subnets || []));
const snatSubnets = unique(policies.filter((policy) => policy.snat).flatMap((policy) => policy.subnets || []))
.filter((subnet) => !noSnatSubnets.includes(subnet));
const ipBlockPolicies = policies
.filter((policy) => policy.ipBlocks?.length)
.map((policy) => ({ snat: !!policy.snat, ipBlocks: [...policy.ipBlocks] }));
return {
snatSubnets, noSnatSubnets, ipBlockPolicies
};
};
export default {
name: 'EditVpcEgressGateway',
emits: ['update:value'],
components: {
ArrayList,
Banner,
CruResource,
LabeledInput,
LabeledSelect,
Loading,
MessageLink,
NameNsDescription,
RadioGroup,
ResourceTabs,
Tab,
UnitInput,
},
mixins: [CreateEditView],
inheritAttrs: false,
props: {
value: {
type: Object,
required: true,
}
},
async fetch() {
const inStore = this.$store.getters['currentProduct'].inStore;
const schema = this.$store.getters[`${ inStore }/schemaFor`](HCI.VPC_EGRESS_GATEWAY);
await allHash({
vpcs: this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.VPC }),
subnets: this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.SUBNET }),
fields: schema?.fetchResourceFields(),
});
// Kube-OVN v1.16 (Harvester v1.10.0-rc1 and older) has no externalNetworkMode and always needs an external subnet
this.supportsPrimaryCNI = !!schema && this.$store.getters[`${ inStore }/pathExistsInSchema`](HCI.VPC_EGRESS_GATEWAY, 'spec.externalNetworkMode');
},
data() {
const spec = this.value?.spec || {};
return {
...policyGroups(spec.policies),
vpc: spec.vpc || '',
replicas: spec.replicas ?? 1,
externalNetworkMode: spec.externalNetworkMode || ATTACHMENT,
supportsPrimaryCNI: false,
internalSubnet: spec.internalSubnet || '',
externalSubnet: spec.externalSubnet || '',
internalIPs: [...(spec.internalIPs || [])],
externalIPs: [...(spec.externalIPs || [])],
bfd: { ...BFD_DEFAULTS, ...spec.bfd },
bandwidthIngress: spec.bandwidth?.ingress ?? '',
bandwidthEgress: spec.bandwidth?.egress ?? '',
};
},
computed: {
allSubnets() {
const inStore = this.$store.getters['currentProduct'].inStore;
return this.$store.getters[`${ inStore }/all`](HCI.SUBNET) || [];
},
vpcOptions() {
const inStore = this.$store.getters['currentProduct'].inStore;
const vpcs = this.$store.getters[`${ inStore }/all`](HCI.VPC) || [];
return vpcs.map((vpc) => ({ label: vpc.id, value: vpc.id }));
},
vpcSubnets() {
return this.allSubnets.filter((subnet) => subnet.spec?.vpc === this.vpc);
},
vpcSubnetOptions() {
return this.vpcSubnets.map((subnet) => ({ label: subnet.id, value: subnet.id }));
},
internalSubnetOptions() {
return this.vpcSubnets
.filter((subnet) => subnet.isOverlayAttachment)
.map((subnet) => ({ label: subnet.id, value: subnet.id }));
},
externalSubnetOptions() {
return this.allSubnets
.filter((subnet) => subnet.networkAttachment)
.map((subnet) => ({ label: subnet.id, value: subnet.id }));
},
internalSubnetResource() {
return this.allSubnets.find((subnet) => subnet.id === this.internalSubnet);
},
externalSubnetResource() {
return this.allSubnets.find((subnet) => subnet.id === this.externalSubnet);
},
usesPrimaryCNI() {
return this.externalNetworkMode === PRIMARY_CNI;
},
showExternalNetworkMode() {
return this.supportsPrimaryCNI || this.usesPrimaryCNI;
},
externalNetworkModes() {
return [ATTACHMENT, PRIMARY_CNI];
},
externalNetworkModeLabels() {
return [this.t('harvester.egressGateway.externalNetworkMode.attachment'), this.t('harvester.egressGateway.externalNetworkMode.primaryCNI')];
},
selectedVpc() {
const inStore = this.$store.getters['currentProduct'].inStore;
return this.vpc ? this.$store.getters[`${ inStore }/byId`](HCI.VPC, this.vpc) : null;
},
// A subnet goes in one of the two groups only, and the gateway's external subnet in neither
snatSubnetOptions() {
return this.vpcSubnetOptions.filter((option) => option.value !== this.externalSubnet && !this.noSnatSubnets.includes(option.value));
},
noSnatSubnetOptions() {
return this.vpcSubnetOptions.filter((option) => option.value !== this.externalSubnet && !this.snatSubnets.includes(option.value));
},
ipBlocksWithSnat() {
return this.ipBlockPolicies.filter((policy) => policy.snat).flatMap((policy) => policy.ipBlocks);
},
ipBlocksWithoutSnat() {
return this.ipBlockPolicies.filter((policy) => !policy.snat).flatMap((policy) => policy.ipBlocks);
},
tabErrors() {
return this.isView ? {
basic: [], policies: [], ips: [], bfd: [], bandwidth: []
} : this.validateTabs();
},
validationPassed() {
return this.validate().length === 0;
},
// Each field shows its own error once touched, so a disabled Save always has a visible reason
nameRules() {
return {
name: [(value) => (value ? undefined : this.t('validation.required', { key: this.t('generic.name') }, true))], namespace: [], description: []
};
},
vpcRules() {
return [(value) => this.requiredError(value, 'harvester.egressGateway.vpc.label')];
},
internalSubnetRules() {
return [(value) => this.requiredError(value, 'harvester.egressGateway.internalSubnet.label')];
},
// The policy lists only offer subnets of the chosen VPC, so say why they're empty
policySubnetsPlaceholder() {
if (!this.vpc) {
return this.t('harvester.egressGateway.policies.noVpc');
}
return this.vpcSubnetOptions.length ? this.t('harvester.egressGateway.policies.placeholder') : this.t('harvester.egressGateway.policies.noSubnets', { vpc: this.vpc }, true);
},
internalSubnetPlaceholder() {
if (!this.vpc) {
return this.t('harvester.egressGateway.internalSubnet.noVpc');
}
return this.internalSubnetOptions.length ? this.t('harvester.egressGateway.internalSubnet.placeholder') : this.t('harvester.egressGateway.internalSubnet.none', { vpc: this.vpc }, true);
},
maxReplicas() {
return MAX_REPLICAS;
},
replicasRules() {
return [(value) => (isWholeNumber(value, 0, MAX_REPLICAS) ? undefined : this.t('harvester.egressGateway.validation.replicas', null, true))];
},
externalSubnetRules() {
return [(value) => this.requiredError(value, 'harvester.egressGateway.externalSubnet.label') || (value === this.internalSubnet ? this.t('harvester.egressGateway.validation.sameSubnet', null, true) : undefined)];
},
internalIPRules() {
return [(ip) => this.ipError('internalIPs', ip)];
},
externalIPRules() {
return [(ip) => this.ipError('externalIPs', ip)];
},
ipCountErrors() {
return Object.keys(IP_FIELDS).map((field) => this.ipCountError(field)).filter(Boolean);
},
bfdIntervalRules() {
return [(value) => (isValidBfdValue(value) ? undefined : this.t('harvester.egressGateway.validation.bfd', null, true))];
},
bfdMultiplierRules() {
return [(value) => (isValidBfdValue(value) ? undefined : this.t('harvester.egressGateway.validation.bfdMultiplier', null, true))];
},
bandwidthRules() {
return [(value) => (isBlank(value) || isValidBandwidth(value) ? undefined : this.t('harvester.egressGateway.validation.bandwidth', null, true))];
},
vpcBfdPortDisabled() {
return !!this.selectedVpc && !this.selectedVpc.bfdPortEnabled;
},
vpcEditLocation() {
const location = this.selectedVpc?.detailLocation;
return location ? {
...location, query: { [MODE]: _EDIT }, hash: '#bfdPort'
} : null;
},
},
watch: {
vpc(neu, old) {
if (!old || neu === old) {
return;
}
const vpcSubnets = this.vpcSubnetOptions.map((option) => option.value);
if (!this.internalSubnetOptions.some((option) => option.value === this.internalSubnet)) {
this.internalSubnet = '';
}
this.snatSubnets = this.snatSubnets.filter((subnet) => vpcSubnets.includes(subnet));
this.noSnatSubnets = this.noSnatSubnets.filter((subnet) => vpcSubnets.includes(subnet));
},
// The mode can only be chosen on create; PrimaryCNI rejects the external fields, so they're cleared
externalNetworkMode(neu) {
if (neu === PRIMARY_CNI) {
this.externalSubnet = '';
this.externalIPs = [];
this.bandwidthIngress = '';
this.bandwidthEgress = '';
}
},
},
methods: {
requiredError(value, labelKey) {
return value ? undefined : this.t('validation.required', { key: this.t(labelKey) }, true);
},
ipError(field, ip) {
const value = `${ ip || '' }`.trim();
const { labelKey, subnet: subnetField } = IP_FIELDS[field];
const key = this.t(labelKey);
const subnet = this[subnetField];
if (!value) {
return undefined;
}
if (!isValidIP(value)) {
return this.t('harvester.egressGateway.validation.ipList', { key }, true);
}
if (cleanList(this[field]).filter((other) => other === value).length > 1) {
return this.t('harvester.egressGateway.validation.ipDuplicate', { key }, true);
}
if (subnet && !subnet.canAssignIP(value)) {
return this.t('harvester.egressGateway.validation.ipSubnet', {
key, subnet: subnet.id, cidr: subnet.spec?.cidrBlock
}, true);
}
return undefined;
},
ipCountError(field) {
const ips = cleanList(this[field]);
const replicas = Number(this.replicas);
if (ips.length && ips.length < replicas) {
return this.t('harvester.egressGateway.validation.ipCount', { key: this.t(IP_FIELDS[field].labelKey), replicas }, true);
}
return undefined;
},
policyError() {
const hasSource = this.snatSubnets.length || this.noSnatSubnets.length || this.ipBlockPolicies.length;
if (!hasSource) {
return this.t('harvester.egressGateway.validation.policyRequired', null, true);
}
// Kube-OVN reroutes a policy's sources to the gateway, so its own external subnet would loop back into it
if (this.externalSubnet && [...this.snatSubnets, ...this.noSnatSubnets].includes(this.externalSubnet)) {
return this.t('harvester.egressGateway.validation.policyExternalSubnet', { subnet: this.externalSubnet }, true);
}
return undefined;
},
// One policy for each group that has subnets, then the IP block policies as they were
policiesSpec() {
return [
...(this.snatSubnets.length ? [{ snat: true, subnets: [...this.snatSubnets] }] : []),
...(this.noSnatSubnets.length ? [{ snat: false, subnets: [...this.noSnatSubnets] }] : []),
...this.ipBlockPolicies.map((policy) => ({ ...policy, ipBlocks: [...policy.ipBlocks] })),
];
},
// The errors of each tab, so each tab can be marked and Save stays disabled until there are none
validateTabs() {
const errors = {
basic: [], policies: [], ips: [], bfd: [], bandwidth: []
};
[
['vpc', 'harvester.egressGateway.vpc.label'],
['internalSubnet', 'harvester.egressGateway.internalSubnet.label'],
...(this.externalNetworkMode === PRIMARY_CNI ? [] : [['externalSubnet', 'harvester.egressGateway.externalSubnet.label']]),
].forEach(([field, labelKey]) => {
if (!this[field]) {
errors.basic.push(this.t('validation.required', { key: this.t(labelKey) }, true));
}
});
if (this.internalSubnet && this.internalSubnet === this.externalSubnet) {
errors.basic.push(this.t('harvester.egressGateway.validation.sameSubnet', null, true));
}
if (!isWholeNumber(this.replicas, 0, MAX_REPLICAS)) {
errors.basic.push(this.t('harvester.egressGateway.validation.replicas', null, true));
}
const policyError = this.policyError();
if (policyError) {
errors.policies.push(policyError);
}
Object.keys(IP_FIELDS).forEach((field) => {
const ipError = cleanList(this[field]).map((ip) => this.ipError(field, ip)).find(Boolean);
const error = ipError || this.ipCountError(field);
if (error) {
errors.ips.push(error);
}
});
if (this.bfd.enabled && ['minRX', 'minTX'].some((field) => !isValidBfdValue(this.bfd[field]))) {
errors.bfd.push(this.t('harvester.egressGateway.validation.bfd', null, true));
}
if (this.bfd.enabled && !isValidBfdValue(this.bfd.multiplier)) {
errors.bfd.push(this.t('harvester.egressGateway.validation.bfdMultiplier', null, true));
}
if ([this.bandwidthIngress, this.bandwidthEgress].some((value) => !isBlank(value) && !isValidBandwidth(value))) {
errors.bandwidth.push(this.t('harvester.egressGateway.validation.bandwidth', null, true));
}
return errors;
},
validate() {
const errors = this.value.metadata?.name ? [] : [this.t('validation.required', { key: this.t('generic.name') }, true)];
return [...errors, ...Object.values(this.validateTabs()).flat()];
},
// The intervals are hidden while BFD is off, so a value cleared there falls back to its default
bfdSpec() {
const bfd = { ...this.bfd };
['minRX', 'minTX', 'multiplier'].forEach((field) => {
bfd[field] = isValidBfdValue(bfd[field]) || this.bfd.enabled ? Number(bfd[field]) : BFD_DEFAULTS[field];
});
return bfd;
},
toSpec() {
const spec = {
...(this.value.spec || {}),
vpc: this.vpc,
replicas: Number(this.replicas),
internalSubnet: this.internalSubnet,
externalSubnet: this.externalSubnet,
internalIPs: cleanList(this.internalIPs),
externalIPs: cleanList(this.externalIPs),
policies: this.policiesSpec(),
bfd: this.bfdSpec(),
bandwidth: {
ingress: isBlank(this.bandwidthIngress) ? undefined : toBandwidth(this.bandwidthIngress),
egress: isBlank(this.bandwidthEgress) ? undefined : toBandwidth(this.bandwidthEgress),
},
};
['internalIPs', 'externalIPs', 'policies'].forEach((field) => {
if (!spec[field].length) {
delete spec[field];
}
});
Object.keys(spec.bandwidth).forEach((direction) => {
if (spec.bandwidth[direction] === undefined) {
delete spec.bandwidth[direction];
}
});
if (!Object.keys(spec.bandwidth).length) {
delete spec.bandwidth;
}
// Attachment is the CRD default, so a new gateway only names the mode when it's PrimaryCNI
if (this.externalNetworkMode === PRIMARY_CNI) {
spec.externalNetworkMode = PRIMARY_CNI;
delete spec.externalSubnet;
}
return spec;
},
async saveGateway(buttonCb) {
this.errors = this.validate();
if (this.errors.length) {
buttonCb(false);
return;
}
this.value.spec = this.toSpec();
await this.save(buttonCb);
},
},
};
</script>
<template>
<Loading v-if="$fetchState.pending" />
<CruResource
v-else
:done-route="doneRoute"
:resource="value"
:mode="mode"
:errors="errors"
:validation-passed="validationPassed"
:apply-hooks="applyHooks"
@finish="saveGateway"
@error="e=>errors=e"
>
<NameNsDescription
:value="value"
:mode="mode"
:rules="nameRules"
@update:value="$emit('update:value', $event)"
/>
<ResourceTabs
class="mt-15"
:need-conditions="false"
:need-related="false"
:need-events="false"
:side-tabs="true"
:mode="mode"
>
<Tab
name="basic"
:label="t('generic.basic')"
:weight="99"
:error="tabErrors.basic.length > 0"
:error-icon-tooltip="tabErrors.basic.join(' ')"
>
<div class="row mt-10">
<div class="col span-6">
<LabeledSelect
v-model:value="vpc"
data-testid="egress-gateway-vpc"
class="mb-20"
required
:rules="vpcRules"
:options="vpcOptions"
:mode="mode"
:label="t('harvester.egressGateway.vpc.label')"
:placeholder="t('harvester.egressGateway.vpc.placeholder')"
/>
</div>
<div class="col span-6">
<LabeledInput
v-model:value.number="replicas"
data-testid="egress-gateway-replicas"
class="mb-20"
type="number"
required
:min="0"
:max="maxReplicas"
:mode="mode"
:rules="replicasRules"
:label="t('harvester.egressGateway.replicas.label')"
:tooltip="t('harvester.egressGateway.replicas.tooltip')"
/>
</div>
</div>
<div
v-if="showExternalNetworkMode"
class="row mb-20"
>
<div class="col span-12">
<!-- The CRD makes the mode immutable -->
<RadioGroup
v-model:value="externalNetworkMode"
data-testid="egress-gateway-external-network-mode"
name="externalNetworkMode"
:options="externalNetworkModes"
:labels="externalNetworkModeLabels"
:label="t('harvester.egressGateway.externalNetworkMode.label')"
:tooltip="t('harvester.egressGateway.externalNetworkMode.tooltip')"
:disabled="!isCreate"
:mode="mode"
/>
</div>
</div>
<div class="row">
<div class="col span-6">
<LabeledSelect
v-model:value="internalSubnet"
data-testid="egress-gateway-internal-subnet"
class="mb-20"
required
:options="internalSubnetOptions"
:rules="internalSubnetRules"
:disabled="!vpc"
:mode="mode"
:label="t('harvester.egressGateway.internalSubnet.label')"
:placeholder="internalSubnetPlaceholder"
:tooltip="t('harvester.egressGateway.internalSubnet.tooltip')"
/>
</div>
<div
v-if="!usesPrimaryCNI"
class="col span-6"
>
<LabeledSelect
v-model:value="externalSubnet"
data-testid="egress-gateway-external-subnet"
class="mb-20"
required
:options="externalSubnetOptions"
:mode="mode"
:rules="externalSubnetRules"
:label="t('harvester.egressGateway.externalSubnet.label')"
:placeholder="t('harvester.egressGateway.externalSubnet.placeholder')"
:tooltip="t('harvester.egressGateway.externalSubnet.tooltip')"
/>
</div>
</div>
</Tab>
<Tab
name="policies"
:label="t('harvester.egressGateway.policies.label')"
:weight="98"
:error="tabErrors.policies.length > 0"
:error-icon-tooltip="tabErrors.policies.join(' ')"
>
<p
v-if="!isView"
class="text-muted mb-20"
>
{{ t('harvester.egressGateway.policies.description') }}
</p>
<!-- One subnet in either list is enough, so the rule is shown once for both lists -->
<Banner
v-if="vpc && tabErrors.policies.length"
color="error"
data-testid="egress-gateway-policy-error"
:label="tabErrors.policies[0]"
/>
<div class="row">
<div class="col span-6">
<LabeledSelect
v-model:value="snatSubnets"
data-testid="egress-gateway-snat-subnets"
:disabled="!vpc"
:append-to-body="false"
:multiple="true"
:options="snatSubnetOptions"
:mode="mode"
:label="t('harvester.egressGateway.policies.snatSubnets.label')"
:placeholder="policySubnetsPlaceholder"
:tooltip="t('harvester.egressGateway.policies.snatSubnets.tooltip')"
/>
</div>
<div class="col span-6">
<LabeledSelect
v-model:value="noSnatSubnets"
data-testid="egress-gateway-no-snat-subnets"
:disabled="!vpc"
:append-to-body="false"
:multiple="true"
:options="noSnatSubnetOptions"
:mode="mode"
:label="t('harvester.egressGateway.policies.noSnatSubnets.label')"
:placeholder="policySubnetsPlaceholder"
:tooltip="t('harvester.egressGateway.policies.noSnatSubnets.tooltip')"
/>
</div>
</div>
<div
v-if="ipBlocksWithSnat.length || ipBlocksWithoutSnat.length"
class="row mt-20"
>
<div class="col span-6">
<LabeledInput
v-if="ipBlocksWithSnat.length"
data-testid="egress-gateway-snat-ip-blocks"
:value="ipBlocksWithSnat.join(', ')"
mode="view"
:label="t('harvester.egressGateway.policies.ipBlocks.snat')"
:tooltip="t('harvester.egressGateway.policies.ipBlocks.tooltip')"
/>
</div>
<div class="col span-6">
<LabeledInput
v-if="ipBlocksWithoutSnat.length"
data-testid="egress-gateway-no-snat-ip-blocks"
:value="ipBlocksWithoutSnat.join(', ')"
mode="view"
:label="t('harvester.egressGateway.policies.ipBlocks.noSnat')"
:tooltip="t('harvester.egressGateway.policies.ipBlocks.tooltip')"
/>
</div>
</div>
</Tab>
<Tab
name="ips"
:label="t('harvester.egressGateway.ips.label')"
:weight="97"
:error="tabErrors.ips.length > 0"
:error-icon-tooltip="tabErrors.ips.join(' ')"
>
<Banner
v-if="!isView"
color="info"
:label="usesPrimaryCNI ? t('harvester.egressGateway.ips.bannerPrimaryCNI') : t('harvester.egressGateway.ips.banner')"
/>
<Banner
v-for="error in ipCountErrors"
:key="error"
color="error"
:label="error"
/>
<ArrayList
v-model:value="internalIPs"
class="mt-20"
:rules="internalIPRules"
:mode="mode"
:title="t('harvester.egressGateway.ips.internal.label')"
:add-label="t('harvester.egressGateway.ips.internal.add')"
:value-placeholder="t('harvester.egressGateway.ips.internal.placeholder')"
/>
<ArrayList
v-if="!usesPrimaryCNI"
v-model:value="externalIPs"
class="mt-20"
:rules="externalIPRules"
:mode="mode"
:title="t('harvester.egressGateway.ips.external.label')"
:add-label="t('harvester.egressGateway.ips.external.add')"
:value-placeholder="t('harvester.egressGateway.ips.external.placeholder')"
/>
</Tab>
<Tab
name="bfd"
:label="t('harvester.egressGateway.bfd.label')"
:weight="96"
:error="tabErrors.bfd.length > 0"
:error-icon-tooltip="tabErrors.bfd.join(' ')"
>
<RadioGroup
v-model:value="bfd.enabled"
name="bfd"
:options="[true, false]"
:labels="[t('generic.enabled'), t('generic.disabled')]"
:label="t('harvester.egressGateway.bfd.enabled')"
:tooltip="t('harvester.egressGateway.bfd.tooltip')"
:mode="mode"
/>
<template v-if="bfd.enabled">
<Banner
v-if="vpcBfdPortDisabled"
color="warning"
>
<MessageLink
:to="vpcEditLocation"
target="_blank"
:prefix="t('harvester.egressGateway.bfd.vpcBfdPort.prefix', { vpc }, true)"
:middle="t('harvester.egressGateway.bfd.vpcBfdPort.middle')"
:suffix="t('harvester.egressGateway.bfd.vpcBfdPort.suffix')"
/>
</Banner>
<div class="row mt-20">
<div class="col span-4">
<UnitInput
v-model:value="bfd.minRX"
:min="1"
:mode="mode"
required
:rules="bfdIntervalRules"
:label="t('harvester.egressGateway.bfd.minRX.label')"
:tooltip="t('harvester.egressGateway.bfd.minRX.tooltip')"
:suffix="t('harvester.egressGateway.bfd.milliseconds')"
/>
</div>
<div class="col span-4">
<UnitInput
v-model:value="bfd.minTX"
:min="1"
:mode="mode"
required
:rules="bfdIntervalRules"
:label="t('harvester.egressGateway.bfd.minTX.label')"
:tooltip="t('harvester.egressGateway.bfd.minTX.tooltip')"
:suffix="t('harvester.egressGateway.bfd.milliseconds')"
/>
</div>
<div class="col span-4">
<LabeledInput
v-model:value.number="bfd.multiplier"
type="number"
:min="1"
:mode="mode"
required
:rules="bfdMultiplierRules"
:label="t('harvester.egressGateway.bfd.multiplier.label')"
:tooltip="t('harvester.egressGateway.bfd.multiplier.tooltip')"
/>
</div>
</div>
</template>
</Tab>
<Tab
v-if="!usesPrimaryCNI"
name="bandwidth"
:label="t('harvester.egressGateway.bandwidth.label')"
:weight="95"
:error="tabErrors.bandwidth.length > 0"
:error-icon-tooltip="tabErrors.bandwidth.join(' ')"
>
<Banner
v-if="!isView"
color="info"
:label="t('harvester.egressGateway.bandwidth.banner')"
/>
<div class="row mt-20">
<div class="col span-6">
<LabeledInput
v-model:value="bandwidthIngress"
data-testid="egress-gateway-bandwidth-ingress"
:mode="mode"
:rules="bandwidthRules"
:label="t('harvester.egressGateway.bandwidth.ingress.label')"
:placeholder="t('harvester.egressGateway.bandwidth.placeholder')"
/>
</div>
<div class="col span-6">
<LabeledInput
v-model:value="bandwidthEgress"
data-testid="egress-gateway-bandwidth-egress"
:mode="mode"
:rules="bandwidthRules"
:label="t('harvester.egressGateway.bandwidth.egress.label')"
:placeholder="t('harvester.egressGateway.bandwidth.placeholder')"
/>
</div>
</div>
</Tab>
</ResourceTabs>
</CruResource>
</template>
@@ -157,7 +157,7 @@ $yaml-height: 200px;
flex: 1; flex: 1;
min-height: $yaml-height; min-height: $yaml-height;
& .code-mirror .cm-editor { & .code-mirror .CodeMirror {
min-height: $yaml-height; min-height: $yaml-height;
} }
} }
@@ -219,8 +219,6 @@ export default {
/> />
</div> </div>
<slot name="after-user-data" />
<div class="mb-20"> <div class="mb-20">
<DataTemplate <DataTemplate
ref="networkTemplate" ref="networkTemplate"
@@ -289,7 +287,7 @@ $yaml-height: 350px;
flex: 1; flex: 1;
min-height: $yaml-height; min-height: $yaml-height;
& .code-mirror .cm-editor { & .code-mirror .CodeMirror {
min-height: $yaml-height; min-height: $yaml-height;
} }
} }
@@ -2,7 +2,6 @@
import InputOrDisplay from '@shell/components/InputOrDisplay'; import InputOrDisplay from '@shell/components/InputOrDisplay';
import { LabeledInput } from '@components/Form/LabeledInput'; import { LabeledInput } from '@components/Form/LabeledInput';
import LabeledSelect from '@shell/components/form/LabeledSelect'; import LabeledSelect from '@shell/components/form/LabeledSelect';
import { Checkbox } from '@components/Form/Checkbox';
import { clone } from '@shell/utils/object'; import { clone } from '@shell/utils/object';
import { _CREATE, _VIEW } from '@shell/config/query-params'; import { _CREATE, _VIEW } from '@shell/config/query-params';
@@ -34,7 +33,7 @@ export default {
emits: ['update'], emits: ['update'],
components: { components: {
LabeledInput, LabeledSelect, InputOrDisplay, Checkbox LabeledInput, LabeledSelect, InputOrDisplay
}, },
props: { props: {
@@ -170,7 +169,6 @@ export default {
this.value.isPod = true; this.value.isPod = true;
this.value.macAddress = ''; this.value.macAddress = '';
this.value.staticIp = ''; this.value.staticIp = '';
this.value.networkBoot = false;
} else { } else {
this.value.isPod = false; this.value.isPod = false;
} }
@@ -287,22 +285,6 @@ export default {
</div> </div>
</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 v-if="!isMasquerade && isSingle">
<div class="row mb-20"> <div class="row mb-20">
<a <a
@@ -1,6 +1,5 @@
<script> <script>
import InfoBox from '@shell/components/InfoBox'; import InfoBox from '@shell/components/InfoBox';
import { RadioGroup } from '@components/Form/Radio';
import { NETWORK_ATTACHMENT } from '@shell/config/types'; import { NETWORK_ATTACHMENT } from '@shell/config/types';
import { sortBy } from '@shell/utils/sort'; import { sortBy } from '@shell/utils/sort';
import { clone } from '@shell/utils/object'; import { clone } from '@shell/utils/object';
@@ -11,11 +10,7 @@ import { HCI as HCI_ANNOTATIONS } from '../../../config/labels-annotations';
import Base from './base'; import Base from './base';
export default { export default {
components: { components: { InfoBox, Base },
InfoBox, Base, RadioGroup
},
emits: ['update:value', 'update:networkBootFirst'],
props: { props: {
vm: { vm: {
@@ -40,11 +35,6 @@ export default {
isSingle: { isSingle: {
type: Boolean, type: Boolean,
default: true default: true
},
networkBootFirst: {
type: Boolean,
default: true
} }
}, },
@@ -92,20 +82,6 @@ export default {
vmState() { vmState() {
return this.vm?.stateDisplay; 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
}];
} }
}, },
@@ -242,22 +218,6 @@ export default {
/> />
</InfoBox> </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 <button
v-if="!isView" v-if="!isView"
type="button" type="button"
@@ -1,301 +0,0 @@
<script>
import LabeledSelect from '@shell/components/form/LabeledSelect';
import { Checkbox } from '@components/Form/Checkbox';
import { Banner } from '@components/Banner';
import { DISK_CACHE_MODE, DISK_IO_MODE, DISK_PERFORMANCE_PROFILE } from '../../../config/harvester-map';
const { DEFAULT, HIGH, CUSTOM } = DISK_PERFORMANCE_PROFILE;
export default {
name: 'DiskPerformanceOptions',
components: {
LabeledSelect, Checkbox, Banner
},
emits: ['update'],
props: {
// The disk row. This component reads/writes value.cache, value.io,
// value.dedicatedIOThread and (for the "High Performance" preset) value.bus.
value: {
type: Object,
default: () => ({})
},
mode: {
type: String,
default: 'create'
},
},
data() {
return {
DISK_PERFORMANCE_PROFILE,
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: {
storagePerformanceEnabled() {
return this.$store.getters['harvester-common/getFeatureEnabled']('highPerformanceStorage');
},
isCdRom() {
return this.value.type === 'cd-rom';
},
isCustom() {
return this.profile === CUSTOM;
},
isNativeIo() {
return this.value.io === 'native';
},
profileOptions() {
return [DEFAULT, HIGH, CUSTOM].map((value) => ({
label: this.t(`harvester.virtualMachine.volume.performance.profile.${ value }`),
value,
}));
},
cacheOptions() {
return DISK_CACHE_MODE.map((value) => ({
label: this.cacheLabel(value),
value,
// Native AIO only works with an uncached (O_DIRECT) disk, so while it is
// selected the only valid cache option is "none" — disable everything
// else, including "Default", to prevent an invalid combination.
disabled: this.isNativeIo && value !== 'none',
}));
},
ioOptions() {
return DISK_IO_MODE.map((value) => ({
label: value === '' ? this.t('harvester.virtualMachine.volume.performance.ioMode.default') : this.t(`harvester.virtualMachine.volume.performance.ioMode.${ value }`),
value,
}));
},
showFilesystemCacheWarning() {
return this.value.cache === 'none' && this.value.volumeMode === 'Filesystem';
},
showBusTip() {
const hasPerf = !!(this.value.cache || this.value.io || this.value.dedicatedIOThread);
return hasPerf && this.value.bus && this.value.bus !== 'virtio';
},
},
watch: {
// Keep the profile selector in sync if the row is repopulated (e.g. editing an existing VM).
'value.cache'() {
this.syncProfile();
},
'value.io'() {
this.syncProfile();
},
'value.dedicatedIOThread'() {
this.syncProfile();
},
},
methods: {
detectProfile() {
const { cache, io, dedicatedIOThread } = this.value;
if (!cache && !io && !dedicatedIOThread) {
return DEFAULT;
}
if (cache === 'none' && io === 'native' && dedicatedIOThread) {
return HIGH;
}
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');
}
return this.t(`harvester.virtualMachine.volume.performance.cacheMode.${ value }`);
},
onProfileChange(profile) {
const previous = this.profile;
this.profile = profile;
this.userSelectedCustom = profile === CUSTOM;
if (profile === DEFAULT) {
this.value.cache = '';
this.value.io = '';
this.value.dedicatedIOThread = false;
// "Default" means no overrides, so also undo the virtio bus that the
// "High Performance" preset applied. Skip it if the user has since
// picked a different bus themselves — that choice is theirs to keep.
if (this.busBeforeHighProfile !== null) {
if (this.value.bus === 'virtio') {
this.value.bus = this.busBeforeHighProfile;
}
this.busBeforeHighProfile = null;
}
} else if (profile === HIGH) {
this.value.cache = 'none';
this.value.io = 'native';
this.value.dedicatedIOThread = true;
if (previous !== HIGH) {
this.busBeforeHighProfile = this.value.bus || '';
}
this.value.bus = 'virtio';
}
// CUSTOM keeps whatever is currently set, including the bus.
this.update();
},
onIoChange(io) {
this.value.io = io;
// Native AIO requires an uncached disk; force cache to "none" to keep the
// combo valid — including when cache is still on its "Default" ('') value,
// which libvirt would otherwise reject at domain start.
if (io === 'native' && this.value.cache !== 'none') {
this.value.cache = 'none';
}
this.update();
},
update() {
this.$emit('update');
},
},
};
</script>
<template>
<div
v-if="!isCdRom && storagePerformanceEnabled"
class="disk-performance"
>
<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-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"
>
<LabeledSelect
v-model:value="value.cache"
:label="t('harvester.virtualMachine.volume.performance.cacheMode.label')"
:tooltip="t('harvester.virtualMachine.volume.performance.cacheMode.tip')"
:options="cacheOptions"
:mode="mode"
@update:value="update"
/>
</div>
<div
class="col span-6"
data-testid="input-disk-io"
>
<LabeledSelect
:value="value.io"
:label="t('harvester.virtualMachine.volume.performance.ioMode.label')"
:tooltip="t('harvester.virtualMachine.volume.performance.ioMode.tip')"
:options="ioOptions"
:mode="mode"
@update:value="onIoChange"
/>
</div>
</div>
<div class="row mb-20">
<div
class="col span-12"
data-testid="input-disk-dedicated-iothread"
>
<Checkbox
v-model:value="value.dedicatedIOThread"
:label="t('harvester.virtualMachine.volume.performance.dedicatedIOThread.label')"
:tooltip="t('harvester.virtualMachine.volume.performance.dedicatedIOThread.tip')"
:mode="mode"
@update:value="update"
/>
</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-key="harvester.virtualMachine.volume.performance.ioMode.nativeRequiresNoCacheTip"
/>
</div>
</div>
</template>
@@ -1,150 +0,0 @@
<script>
import LabeledSelect from '@shell/components/form/LabeledSelect';
import { LabeledInput } from '@components/Form/LabeledInput';
import { Checkbox } from '@components/Form/Checkbox';
import { Banner } from '@components/Banner';
import { _VIEW } from '@shell/config/query-params';
import { IO_THREADS_POLICY } from '../../../config/harvester-map';
export default {
name: 'VMPerformanceOptions',
components: {
LabeledSelect, LabeledInput, Checkbox, Banner
},
emits: ['update:blockMultiQueue', 'update:ioThreadsPolicy', 'update:ioThreadCount'],
props: {
blockMultiQueue: {
type: Boolean,
default: false
},
ioThreadsPolicy: {
type: String,
default: ''
},
ioThreadCount: {
type: Number,
default: 2
},
mode: {
type: String,
default: 'create'
},
// Whether the current disk set contains a virtio disk (VM context only).
hasVirtioDisk: {
type: Boolean,
default: true
},
// Whether any disk requests a dedicated I/O thread (drives the auto-enable hint).
hasDedicatedIothread: {
type: Boolean,
default: false
},
},
computed: {
isView() {
return this.mode === _VIEW;
},
storagePerformanceEnabled() {
return this.$store.getters['harvester-common/getFeatureEnabled']('highPerformanceStorage');
},
ioThreadsPolicyOptions() {
return IO_THREADS_POLICY.map((value) => ({
label: value === '' ? this.t('harvester.virtualMachine.volume.diskPerformance.ioThreadsPolicy.default') : this.t(`harvester.virtualMachine.volume.diskPerformance.ioThreadsPolicy.${ value }`),
value,
}));
},
},
watch: {
// Block Multi-Queue only applies to virtio disks. If the last virtio disk is
// removed while it is enabled, clear it so the VM is not left with an invalid
// setting the disabled checkbox can no longer surface.
hasVirtioDisk(neu) {
if (!neu && this.blockMultiQueue) {
this.$emit('update:blockMultiQueue', false);
}
},
},
};
</script>
<template>
<div
v-if="storagePerformanceEnabled && (!isView || blockMultiQueue || !!ioThreadsPolicy)"
class="vm-perf"
>
<h3>
{{ t('harvester.virtualMachine.volume.diskPerformance.title') }}
</h3>
<p class="text-muted mb-10">
{{ t('harvester.virtualMachine.volume.diskPerformance.description') }}
</p>
<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-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>
<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>
@@ -1,286 +0,0 @@
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 } = {}) => ({
props: { value, mode: _EDIT },
global: {
mocks: {
$store: {
getters: {
'harvester-common/getFeatureEnabled': () => featureEnabled,
'i18n/t': (key) => key,
'i18n/exists': () => true,
}
},
t: (key) => key,
},
}
});
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 }));
expect(wrapper.find('.disk-performance').exists()).toBe(false);
});
it('renders for a hard disk when the feature is enabled', () => {
const wrapper = mount(DiskPerformanceOptions, mountOptions(hardDisk()));
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));
wrapper.vm.onProfileChange('highPerformance');
expect(value.cache).toBe('none');
expect(value.io).toBe('native');
expect(value.dedicatedIOThread).toBe(true);
expect(value.bus).toBe('virtio');
expect(wrapper.emitted('update')).toHaveLength(1);
});
it('clears all overrides when switching back to Default', () => {
const value = hardDisk({
cache: 'none', io: 'native', dedicatedIOThread: true
});
const wrapper = mount(DiskPerformanceOptions, mountOptions(value));
wrapper.vm.onProfileChange('default');
expect(value.cache).toBe('');
expect(value.io).toBe('');
expect(value.dedicatedIOThread).toBe(false);
expect(wrapper.emitted('update')).toHaveLength(1);
});
it('restores the original bus when leaving High Performance for Default', () => {
const value = hardDisk({ bus: 'sata' });
const wrapper = mount(DiskPerformanceOptions, mountOptions(value));
wrapper.vm.onProfileChange('highPerformance');
expect(value.bus).toBe('virtio');
wrapper.vm.onProfileChange('default');
expect(value.bus).toBe('sata');
});
it('keeps a bus the user picked themselves after High Performance', () => {
const value = hardDisk({ bus: 'sata' });
const wrapper = mount(DiskPerformanceOptions, mountOptions(value));
wrapper.vm.onProfileChange('highPerformance');
value.bus = 'scsi';
wrapper.vm.onProfileChange('default');
expect(value.bus).toBe('scsi');
});
it('leaves the bus alone for a disk that never used the High Performance preset', () => {
const value = hardDisk({
bus: 'sata', cache: 'writeback', io: 'threads'
});
const wrapper = mount(DiskPerformanceOptions, mountOptions(value));
wrapper.vm.onProfileChange('default');
expect(value.bus).toBe('sata');
});
it.each([
['a cached state', 'writeback'],
['the Default cache', ''],
])('forces cache to none when Native I/O is selected from %s', (_label, cache) => {
const value = hardDisk({ cache });
const wrapper = mount(DiskPerformanceOptions, mountOptions(value));
wrapper.vm.onIoChange('native');
expect(value.io).toBe('native');
expect(value.cache).toBe('none');
expect(wrapper.emitted('update')).toHaveLength(1);
});
it('disables every cache option except none while Native I/O is active', () => {
const wrapper = mount(DiskPerformanceOptions, mountOptions(hardDisk({ io: 'native' })));
const disabledByValue = wrapper.vm.cacheOptions.reduce((acc, opt) => {
acc[opt.value] = opt.disabled;
return acc;
}, {});
expect(disabledByValue['none']).toBe(false);
expect(disabledByValue['']).toBe(true);
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();
});
});
@@ -1,105 +0,0 @@
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,21 +7,19 @@ import UnitInput from '@shell/components/form/UnitInput';
import { LabeledInput } from '@components/Form/LabeledInput'; import { LabeledInput } from '@components/Form/LabeledInput';
import LabeledSelect from '@shell/components/form/LabeledSelect'; import LabeledSelect from '@shell/components/form/LabeledSelect';
import ModalWithCard from '@shell/components/ModalWithCard'; import ModalWithCard from '@shell/components/ModalWithCard';
import { VOLUME_HOTPLUG_ACTION, SOURCE_TYPE } from '../../../config/harvester-map';
import { PVC, STORAGE_CLASS } from '@shell/config/types'; import { PVC, STORAGE_CLASS } from '@shell/config/types';
import { clone } from '@shell/utils/object'; import { clone } from '@shell/utils/object';
import { ucFirst, randomStr } from '@shell/utils/string'; import { ucFirst, randomStr } from '@shell/utils/string';
import { removeObject } from '@shell/utils/array'; import { removeObject } from '@shell/utils/array';
import { _VIEW, _EDIT, _CREATE } from '@shell/config/query-params'; import { _VIEW, _EDIT, _CREATE } from '@shell/config/query-params';
import { PLUGIN_DEVELOPER, DEV } from '@shell/store/prefs'; import { PLUGIN_DEVELOPER, DEV } from '@shell/store/prefs';
import { VOLUME_HOTPLUG_ACTION, SOURCE_TYPE } from '../../../config/harvester-map';
import { PRODUCT_NAME as HARVESTER_PRODUCT } from '../../../config/harvester'; import { PRODUCT_NAME as HARVESTER_PRODUCT } from '../../../config/harvester';
import { HCI } from '../../../types'; import { HCI } from '../../../types';
import { VOLUME_MODE, ACCESS_MODE } from '@pkg/harvester/config/types'; import { VOLUME_MODE } from '@pkg/harvester/config/types';
import { OFF } from '../../../models/kubevirt.io.virtualmachine'; import { OFF } from '../../../models/kubevirt.io.virtualmachine';
import { EMPTY_IMAGE } from '../../../utils/vm'; import { EMPTY_IMAGE } from '../../../utils/vm';
const { READ_WRITE_MANY } = ACCESS_MODE;
export default { export default {
emits: ['update:value'], emits: ['update:value'],
@@ -71,7 +69,7 @@ export default {
customAccessMode: { customAccessMode: {
type: String, type: String,
default: READ_WRITE_MANY default: 'ReadWriteMany'
}, },
resourceType: { resourceType: {
@@ -2,23 +2,9 @@ import { mount } from '@vue/test-utils';
import { _EDIT } from '@shell/config/query-params'; import { _EDIT } from '@shell/config/query-params';
import HarvesterEditContainer from '../container.vue'; 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', () => { describe('component: HarvesterEditContainer', () => {
it('should display all the inputs', () => { it('should display all the inputs', () => {
const wrapper = mount(HarvesterEditContainer, mountOptions()); const wrapper = mount(HarvesterEditContainer, { propsData: { mode: _EDIT, value: {} } });
const inputWraps = wrapper.findAll('[data-testid^=input-hec-]'); const inputWraps = wrapper.findAll('[data-testid^=input-hec-]');
@@ -29,7 +15,7 @@ describe('component: HarvesterEditContainer', () => {
'name', 'name',
'container', 'container',
])('should emit an update on %p input', (field) => { ])('should emit an update on %p input', (field) => {
const wrapper = mount(HarvesterEditContainer, mountOptions()); const wrapper = mount(HarvesterEditContainer, { propsData: { mode: _EDIT, value: {} } });
const input = wrapper.find(`[data-testid="input-hec-${ field }"]`).find('input'); const input = wrapper.find(`[data-testid="input-hec-${ field }"]`).find('input');
const newValue = 123; const newValue = 123;
@@ -42,7 +28,7 @@ describe('component: HarvesterEditContainer', () => {
'type', 'type',
'bus', 'bus',
])('should emit an update on %p selection change', async(field) => { ])('should emit an update on %p selection change', async(field) => {
const wrapper = mount(HarvesterEditContainer, mountOptions()); const wrapper = mount(HarvesterEditContainer, { propsData: { mode: _EDIT, value: {} } });
const select = wrapper.find(`[data-testid="input-hec-${ field }"]`); const select = wrapper.find(`[data-testid="input-hec-${ field }"]`);
select.find('button').trigger('click'); select.find('button').trigger('click');
@@ -51,11 +37,4 @@ describe('component: HarvesterEditContainer', () => {
expect(wrapper.emitted('update')).toHaveLength(1); 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,17 +5,14 @@ import HarvesterEditExisting from '../existing.vue';
describe('component: HarvesterEditExisting', () => { describe('component: HarvesterEditExisting', () => {
it('should display all the inputs', () => { it('should display all the inputs', () => {
const wrapper = mount(HarvesterEditExisting, { const wrapper = mount(HarvesterEditExisting, {
props: { propsData: {
mode: _EDIT, value: {}, rows: [] mode: _EDIT, value: {}, rows: []
}, },
global: { mocks: {
mocks: { $store: {
$store: { getters: {
getters: { 'harvester/all': () => [],
'harvester-common/getFeatureEnabled': () => true, 'i18n/t': jest.fn()
'harvester/all': () => [],
'i18n/t': jest.fn()
}
} }
} }
} }
@@ -30,17 +27,14 @@ describe('component: HarvesterEditExisting', () => {
'name', 'name',
])('should emit an update on %p input', (field) => { ])('should emit an update on %p input', (field) => {
const wrapper = mount(HarvesterEditExisting, { const wrapper = mount(HarvesterEditExisting, {
props: { propsData: {
mode: _EDIT, value: {}, rows: [] mode: _EDIT, value: {}, rows: []
}, },
global: { mocks: {
mocks: { $store: {
$store: { getters: {
getters: { 'harvester/all': () => [],
'harvester-common/getFeatureEnabled': () => true, 'i18n/t': jest.fn()
'harvester/all': () => [],
'i18n/t': jest.fn()
}
} }
} }
} }
@@ -59,17 +53,14 @@ describe('component: HarvesterEditExisting', () => {
'size', 'size',
])('should emit an update on %p input and blur', (field) => { ])('should emit an update on %p input and blur', (field) => {
const wrapper = mount(HarvesterEditExisting, { const wrapper = mount(HarvesterEditExisting, {
props: { propsData: {
mode: _EDIT, value: {}, rows: [] mode: _EDIT, value: {}, rows: []
}, },
global: { mocks: {
mocks: { $store: {
$store: { getters: {
getters: { 'harvester/all': () => [],
'harvester-common/getFeatureEnabled': () => true, 'i18n/t': jest.fn()
'harvester/all': () => [],
'i18n/t': jest.fn()
}
} }
} }
} }
@@ -89,17 +80,14 @@ describe('component: HarvesterEditExisting', () => {
// 'bus', // disabled // 'bus', // disabled
])('should emit an update on %p selection change', async(field) => { ])('should emit an update on %p selection change', async(field) => {
const wrapper = mount(HarvesterEditExisting, { const wrapper = mount(HarvesterEditExisting, {
props: { propsData: {
mode: _EDIT, value: {}, rows: [] mode: _EDIT, value: {}, rows: []
}, },
global: { mocks: {
mocks: { $store: {
$store: { getters: {
getters: { 'harvester/all': () => [],
'harvester-common/getFeatureEnabled': () => true, 'i18n/t': jest.fn()
'harvester/all': () => [],
'i18n/t': jest.fn()
}
} }
} }
} }
@@ -2,29 +2,23 @@ import { mount } from '@vue/test-utils';
import { _CREATE } from '@shell/config/query-params'; import { _CREATE } from '@shell/config/query-params';
import HarvesterEditVMImage from '../vmImage.vue'; 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', () => { describe('component: HarvesterEditVMImage', () => {
it('should display all the inputs', () => { it('should display all the inputs', () => {
const wrapper = mount(HarvesterEditVMImage, { const wrapper = mount(HarvesterEditVMImage, {
props: { propsData: {
mode: _CREATE, mode: _CREATE,
isVirtualType: false, isVirtualType: false,
newCreateId: '123', newCreateId: '123',
validateRequired: true, validateRequired: true,
idx: 1 idx: 1
}, },
global: { mocks: {
mocks: { $store: {
$store: { getters: {
getters: { 'harvester/all': jest.fn(),
'harvester-common/getFeatureEnabled': () => true, 'i18n/t': jest.fn(),
'harvester/all': jest.fn(), }
'i18n/t': jest.fn(), },
}
},
}
} }
}); });
@@ -37,23 +31,20 @@ describe('component: HarvesterEditVMImage', () => {
'name', 'name',
])('should emit an update on %p input', (field) => { ])('should emit an update on %p input', (field) => {
const wrapper = mount(HarvesterEditVMImage, { const wrapper = mount(HarvesterEditVMImage, {
props: { propsData: {
mode: _CREATE, mode: _CREATE,
isVirtualType: false, isVirtualType: false,
newCreateId: '123', newCreateId: '123',
validateRequired: true, validateRequired: true,
idx: 1 idx: 1
}, },
global: { mocks: {
mocks: { $store: {
$store: { getters: {
getters: { 'harvester/all': jest.fn(),
'harvester-common/getFeatureEnabled': () => true, 'i18n/t': jest.fn(),
'harvester/all': jest.fn(), }
'i18n/t': jest.fn(), },
}
},
}
} }
}); });
const input = wrapper.find(`[data-testid="input-hevi-${ field }"]`).find('input'); const input = wrapper.find(`[data-testid="input-hevi-${ field }"]`).find('input');
@@ -66,38 +57,31 @@ describe('component: HarvesterEditVMImage', () => {
it.each([ it.each([
'size', 'size',
])('should emit an update on %p input blur', async(field) => { ])('should emit an update on %p input blur', (field) => {
const wrapper = mount(HarvesterEditVMImage, { const wrapper = mount(HarvesterEditVMImage, {
props: { propsData: {
mode: _CREATE, mode: _CREATE,
isVirtualType: false, isVirtualType: false,
newCreateId: '123', newCreateId: '123',
validateRequired: true, validateRequired: true,
idx: 1 idx: 1
}, },
global: { mocks: {
mocks: { $store: {
$store: { getters: {
getters: { 'harvester/all': jest.fn(),
'harvester-common/getFeatureEnabled': () => true, 'i18n/t': jest.fn(),
'harvester/all': jest.fn(), }
'i18n/t': jest.fn(), },
}
},
}
} }
}); });
const input = wrapper.find(`[data-testid="input-hevi-${ field }"]`).find('input'); const input = wrapper.find(`[data-testid="input-hevi-${ field }"]`).find('input');
const newValue = 123; const newValue = 123;
// setting the value already emits an update, so the blur has to add one on top of that input.setValue(newValue);
await input.setValue(newValue); input.trigger('blur');
const afterSetValue = updates(wrapper); expect(wrapper.emitted('update')).toHaveLength(1);
await input.trigger('blur');
expect(updates(wrapper)).toBeGreaterThan(afterSetValue);
}); });
it.each([ it.each([
@@ -106,23 +90,20 @@ describe('component: HarvesterEditVMImage', () => {
'bus', 'bus',
])('should emit an update on %p selection change', async(field) => { ])('should emit an update on %p selection change', async(field) => {
const wrapper = mount(HarvesterEditVMImage, { const wrapper = mount(HarvesterEditVMImage, {
props: { propsData: {
mode: _CREATE, mode: _CREATE,
isVirtualType: false, isVirtualType: false,
newCreateId: '123', newCreateId: '123',
validateRequired: true, validateRequired: true,
idx: 1 idx: 1
}, },
global: { mocks: {
mocks: { $store: {
$store: { getters: {
getters: { 'harvester/all': jest.fn(),
'harvester-common/getFeatureEnabled': () => true, 'i18n/t': jest.fn(),
'harvester/all': jest.fn(), }
'i18n/t': jest.fn(), },
}
},
}
} }
}); });
const select = wrapper.find(`[data-testid="input-hevi-${ field }"]`); const select = wrapper.find(`[data-testid="input-hevi-${ field }"]`);
@@ -133,30 +114,4 @@ describe('component: HarvesterEditVMImage', () => {
expect(wrapper.emitted('update')).toHaveLength(1); 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,24 +2,18 @@ import { mount } from '@vue/test-utils';
import { _EDIT } from '@shell/config/query-params'; import { _EDIT } from '@shell/config/query-params';
import HarvesterEditVolume from '../volume.vue'; 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', () => { describe('component: HarvesterEditVolume', () => {
it('should display all the inputs', () => { it('should display all the inputs', () => {
const wrapper = mount(HarvesterEditVolume, { const wrapper = mount(HarvesterEditVolume, {
props: { validateRequired: true }, propsData: { validateRequired: true },
global: { mocks: {
mocks: { $store: {
$store: { getters: {
getters: { 'harvester/all': jest.fn(),
'harvester-common/getFeatureEnabled': () => true, 'i18n/t': jest.fn(),
'harvester/all': jest.fn(), 'i18n/exists': jest.fn(),
'i18n/t': jest.fn(), }
'i18n/exists': jest.fn(), },
}
},
}
} }
}); });
@@ -28,56 +22,29 @@ describe('component: HarvesterEditVolume', () => {
expect(inputWraps).toHaveLength(4); expect(inputWraps).toHaveLength(4);
}); });
it('should emit an update on name input', async() => { it.each([
'name',
'size',
])('should emit an update on %p input blur', (field) => {
const wrapper = mount(HarvesterEditVolume, { const wrapper = mount(HarvesterEditVolume, {
props: { mode: _EDIT, validateRequired: true }, propsData: { mode: _EDIT, validateRequired: true },
global: { mocks: {
mocks: { $store: {
$store: { getters: {
getters: { 'harvester/all': jest.fn(),
'harvester-common/getFeatureEnabled': () => true, 'i18n/t': jest.fn(),
'harvester/all': jest.fn(), 'i18n/exists': jest.fn(),
'i18n/t': jest.fn(), }
'i18n/exists': jest.fn(), },
}
},
}
} }
}); });
const before = updates(wrapper); const input = wrapper.find(`[data-testid="input-hev-${ field }"]`).find('input');
const input = wrapper.find('[data-testid="input-hev-name"]').find('input'); const newValue = 123;
await input.setValue(123); input.setValue(newValue);
input.trigger('blur');
expect(updates(wrapper)).toBeGreaterThan(before); expect(wrapper.emitted('update')).toHaveLength(1);
});
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([ it.each([
@@ -85,27 +52,23 @@ describe('component: HarvesterEditVolume', () => {
'bus' 'bus'
])('should emit an update on %p selection change', async(field) => { ])('should emit an update on %p selection change', async(field) => {
const wrapper = mount(HarvesterEditVolume, { const wrapper = mount(HarvesterEditVolume, {
props: { mode: _EDIT, validateRequired: true }, propsData: { mode: _EDIT, validateRequired: true },
global: { mocks: {
mocks: { $store: {
$store: { getters: {
getters: { 'harvester/all': jest.fn(),
'harvester-common/getFeatureEnabled': () => true, 'i18n/t': jest.fn(),
'harvester/all': jest.fn(), 'i18n/exists': jest.fn(),
'i18n/t': jest.fn(), }
'i18n/exists': jest.fn(), },
}
},
}
} }
}); });
const before = updates(wrapper);
const select = wrapper.find(`[data-testid="input-hev-${ field }"]`); const select = wrapper.find(`[data-testid="input-hev-${ field }"]`);
select.find('button').trigger('click'); select.find('button').trigger('click');
await wrapper.trigger('keydown.down'); await wrapper.trigger('keydown.down');
await wrapper.trigger('keydown.enter'); await wrapper.trigger('keydown.enter');
expect(updates(wrapper)).toBeGreaterThan(before); expect(wrapper.emitted('update')).toHaveLength(1);
}); });
}); });
@@ -2,10 +2,8 @@
import { LabeledInput } from '@components/Form/LabeledInput'; import { LabeledInput } from '@components/Form/LabeledInput';
import LabeledSelect from '@shell/components/form/LabeledSelect'; import LabeledSelect from '@shell/components/form/LabeledSelect';
import InputOrDisplay from '@shell/components/InputOrDisplay'; import InputOrDisplay from '@shell/components/InputOrDisplay';
import LabelValue from '@shell/components/LabelValue';
import { VOLUME_TYPE, InterfaceOption } from '../../../../config/harvester-map'; import { VOLUME_TYPE, InterfaceOption } from '../../../../config/harvester-map';
import { Banner } from '@components/Banner'; import { Banner } from '@components/Banner';
import DiskPerformanceOptions from '../DiskPerformanceOptions';
export default { export default {
name: 'HarvesterEditContainer', name: 'HarvesterEditContainer',
@@ -13,7 +11,7 @@ export default {
emits: ['update'], emits: ['update'],
components: { components: {
LabeledInput, LabeledSelect, InputOrDisplay, LabelValue, Banner, DiskPerformanceOptions LabeledInput, LabeledSelect, InputOrDisplay, Banner
}, },
props: { props: {
@@ -132,11 +130,11 @@ export default {
</InputOrDisplay> </InputOrDisplay>
</div> </div>
</div> </div>
<div <div class="row mb-20">
v-if="value.volumeBackups" <div
class="row mb-20" v-if="value.volumeBackups"
> class="col span-6"
<div class="col span-6"> >
<InputOrDisplay <InputOrDisplay
:name="t('harvester.virtualMachine.volume.readyToUse')" :name="t('harvester.virtualMachine.volume.readyToUse')"
:value="value.volumeBackups.readyToUse" :value="value.volumeBackups.readyToUse"
@@ -155,11 +153,5 @@ export default {
class="mb-20" class="mb-20"
:label="value.volumeBackups.error.message" :label="value.volumeBackups.error.message"
/> />
<DiskPerformanceOptions
:value="value"
:mode="mode"
@update="update"
/>
</div> </div>
</template> </template>
@@ -14,7 +14,6 @@ import { VOLUME_MODE } from '@pkg/harvester/config/types';
import { HCI } from '../../../../types'; import { HCI } from '../../../../types';
import { VOLUME_TYPE, InterfaceOption } from '../../../../config/harvester-map'; import { VOLUME_TYPE, InterfaceOption } from '../../../../config/harvester-map';
import { GIBIBYTE } from '../../../../utils/unit'; import { GIBIBYTE } from '../../../../utils/unit';
import DiskPerformanceOptions from '../DiskPerformanceOptions';
export default { export default {
name: 'HarvesterEditExisting', name: 'HarvesterEditExisting',
@@ -22,7 +21,7 @@ export default {
emits: ['update'], emits: ['update'],
components: { components: {
UnitInput, LabeledInput, LabeledSelect, InputOrDisplay, LabelValue, Banner, Checkbox, DiskPerformanceOptions UnitInput, LabeledInput, LabeledSelect, InputOrDisplay, LabelValue, Banner, Checkbox
}, },
props: { props: {
@@ -173,14 +172,6 @@ export default {
this.value.storageClassName = pvcResource.spec.storageClassName; this.value.storageClassName = pvcResource.spec.storageClassName;
this.value.volumeMode = pvcResource.spec.volumeMode; this.value.volumeMode = pvcResource.spec.volumeMode;
this.value.shareable = false; this.value.shareable = false;
// Adopt the volume's default high-performance profile (if any) as a starting point.
const ann = pvcResource.metadata?.annotations || {};
this.value.cache = ann[HCI_ANNOTATIONS.DISK_CACHE_MODE] || '';
this.value.io = ann[HCI_ANNOTATIONS.DISK_IO_MODE] || '';
this.value.dedicatedIOThread = ann[HCI_ANNOTATIONS.DISK_DEDICATED_IOTHREAD] === 'true';
this.update(); this.update();
}, },
@@ -388,11 +379,5 @@ export default {
class="mb-20" class="mb-20"
:label="value.volumeBackups.error.message" :label="value.volumeBackups.error.message"
/> />
<DiskPerformanceOptions
:value="value"
:mode="mode"
@update="update"
/>
</div> </div>
</template> </template>
Loaded 100 of 175 files, more files were not shown because too many files have changed in this diff. Show more