Compare commits

...
Author SHA1 Message Date
renovate[bot] 80aea57fe2 deps: update dependency node-forge to v1.4.3 [security] 2026-11-15 16:42:30 +00:00
Marcelo Fukumoto f3ca9e4c44 feat: redesign the VNC console (#1233)
* chore: bump @rancher/shell to 3.0.15-rc.1 for the Rc components

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

* feat: rebuild the VNC console toolbar with Rc components

Name and namespace, a connection status pill with its own menu, Rc tertiary buttons with the design's icons, and the keyboard hint under the screen. noVNC's grey backdrop is gone and the screen keeps a thin frame that turns into the keyboard-focus ring.

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

* feat: move VNC shortcut keys into one Rc dropdown menu

Saved shortcuts, Ctrl and Alt toggles that apply to the next key, Print Screen, F1 to F12 and the way into custom shortcuts now share the Shortcut keys menu, replacing the cascading popover and the separate custom keys menu. Saved shortcuts can carry a name; the old list format still reads. Focus goes back to the screen after a key is sent.

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

* feat: replace the VNC settings popover with the View options panel

Automatic or Manual scaling on the shell ButtonGroup, a zoom slider with step buttons, JPEG quality and compression with their trade-off spelled out, and Reset to defaults. The screen now scales to fit by default, inside its focus ring. View only is gone with the old panel.

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

* feat: confirm Ctrl+Alt+Del and Soft reboot in an RcModal

Small RcModal with the VM's name in the title and a destructive primary button, coloured the way the shell's own dialogs do it. Esc and the background now close it too, and the keyboard goes back to the screen afterwards.

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

* feat: rebuild VNC custom shortcuts as an RcModal with a key recorder

Record a combination by pressing it, name it, and see the saved ones as RcTags with a delete button each. Every change is saved straight away. Keys keep the format older versions read; names live in their own preference so those versions keep working.

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

* feat: show VNC connecting and connection failures as console overlays

A spinner with the VM's name while connecting (and the attempt count while retrying), and a card with an icon badge, title, explanation and Rc buttons when the console cannot be used: in use, unavailable, connection lost or failed. Take over confirms in an RcModal.

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

* feat: float a compact VNC bar over the screen in full screen

Name, connection status and Exit full screen in a floating bar instead of the toolbar, with the keyboard on the screen. Take over leaves full screen first, since its modal opens outside the console.

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

* fix: VNC console review fixes

Show a not-running state instead of connecting forever when the VM has no instance, and find the VM by its uid so the name shows. Keep a failed shortcut save from looking saved. Offer Take over only when another session holds the console, and Reconnect now while retrying. Wrap the toolbar on narrow windows, keep the screen black so overlays read in the light theme, keep the destructive button red on focus, announce only the status label, let Esc and Tab leave the key recorder, release held modifiers when the menu closes, and let Ctrl+T and Ctrl+N through in full screen.

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

* feat: use the redrawn VNC console icons

Power, maximize, minimize and wifi-off on the design's 24px grid, the 20px connecting spinner, and a status card badge that stays dark on the black screen. The screen is only black while there is no live picture.

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

* feat: run standalone Harvester Prime with the SUSE brand

Standalone Harvester reports ui-brand=harvester, which has no stylesheet, so Prime only got a green primary on top of the default palette: 33 of the 36 SUSE theme tokens differed from Rancher Prime (blue tertiary buttons, another green, dark text on primary buttons, no SUSE font). On the Prime flavor the brand is now switched to suse in this browser, and all 36 match Rancher Prime in light and dark.

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

* fix: name recorded VNC shortcut letters after the key pressed

macOS Option turns letters into symbols (Option+G gives ©), so a recorded Alt+Cmd+G was labelled and sent as ©. Letter keys now take their name from the key code when recording, labelling and sending, which also fixes shortcuts saved before.

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

* fix: give the VNC shortcut menu chips the secondary button colours

The key chips, held modifiers and the manage item used the link colour, so they stayed blue under the SUSE brand. They now take RcButton's secondary, active and tertiary tokens and follow the brand like the toolbar buttons.

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

* fix: VNC console review fixes, round three

Wait for the instance to run before connecting and retry refusals right after a start, keep Reconnect now counting retries, stop key sending once the VM is down, only rename option-mangled letters (Alt without Ctrl, dead keys) so other layouts keep their keys, give the keyboard back to View when its panel closes, add a shortcut with Enter, keep long shortcut names to two lines, only replace Harvester's own brand and refresh the favicon, and stop relying on stylesheet order for the spinner and danger button.

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

* feat: change the VNC menu keys with the held modifiers

The keys under Hold modifiers follow what is held, so the menu sends what the old cascading menu did: Ctrl+N/T/W/Y with Ctrl, Ctrl+Alt+Del with Ctrl and Alt (through the same confirmation as its button), and Print Screen and F1-F12 alone or with Alt. Ctrl+Alt+F1-F12 stays for switching Linux consoles. The recorder points to the menu for browser-reserved combinations.

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

* feat: bring View only back to the VNC View menu

The View menu has a View only switch again, as the old settings panel did: the screen stays live but no mouse or keyboard input reaches the VM, the status reads Connected (view only), the key menus are disabled and the hint says how to turn it off. The design does not have it yet.

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

* feat: move View only into the VNC connection menu

View only is how this session uses the connection, so it sits in the Connected menu (also in full screen) as a checkbox item, and the View menu is only about how the screen is shown.

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

* feat: keep the VNC console's controls usable around the connection

Full screen goes over the whole page and its bar gets Shortcut keys and Ctrl+Alt+Del, so menus and the confirmation show there too and Take over no longer has to leave full screen. Soft reboot works whatever the console's state, since it does not go through it. The Shortcut keys menu always opens: while keys cannot be sent it says why and disables only the keys, so custom shortcuts can still be managed. The focus ring now sits 2px off the screen so it shows against a dark framebuffer edge in the light theme.

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

* feat: disable the VNC console's input controls while View only is on

View only sends nothing to the VM, so Shortcut keys (managing shortcuts included), Ctrl+Alt+Del and Soft reboot are disabled instead of the menu opening to explain why. The menu still opens while disconnected, as there are shortcuts to manage. The hint under the screen takes the new wording, read raw since t() would escape its quotes.

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

* feat: fill the window with the VNC console in full screen

The screen takes the whole window, with no padding, ring or inset, and black around a picture of another shape. It always fits in full screen, whatever View mode is saved, which comes back on leaving. The bar floats over the screen, slightly transparent until it is hovered, holds the keyboard focus or has a menu open, and no longer has Ctrl+Alt+Del, which stays in the Shortcut keys menu.

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

* feat: show the mouse over the VNC console

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, so it can be seen in the window and in full screen. A guest that sends an image keeps it.

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

* fix: close the VNC console's menus on a click on the screen in Firefox

Firefox delivers the click to the canvas, where noVNC stops it, so an open menu never saw a click outside it. Full screen makes this matter, with little else left to click. noVNC does nothing else with a click, so let it through.

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

* feat: make View only a toggle in the VNC console toolbar

View only moves from the Connected menu to the shared ToggleSwitch between the connection status and Shortcut keys, in the toolbar and in the full screen bar, so its state is always in view and the status no longer has to repeat it. Turning it off hands the keyboard back to the console. The full screen bar no longer gets only half the window from its left: 50%, which would have squeezed its buttons with the wider content; it wraps when it really does not fit.

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

* feat: leave View only out of the VNC console's full screen bar

View only is set from the toolbar. A session that enters full screen with it on stays that way, with Shortcut keys disabled, and changes it after leaving.

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

* feat: make View only a checkbox in the VNC console toolbar

It takes the shared Checkbox instead of ToggleSwitch, in the same place between the connection status and Shortcut keys. Clicking its label now turns it off as well as on.

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

* fix: save the VNC view settings only when the user changes them

The previous console wrote its defaults to localStorage the first time it
opened, so Manual zoom at 100% looked like a choice and the new Automatic
default never reached anyone who had used the console. Settings now live
under a new key and are saved only when the user changes them.

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

* fix: keep View only on when the VNC View panel resets its settings

View only moved to the toolbar, but Reset to defaults in the View panel
still set it back to off, so the screen started sending the mouse and
keyboard to the VM again. The reset now leaves View only as it is.

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

* fix: give the VNC quality and compression sliders their full height

The slider rule's flex: 1 is meant for the zoom row. In the quality and
compression sections, which are columns, it set the height instead and
left those two sliders 4px tall, so a click on the visible thumb missed.

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

* fix: reach the VNC shortcut keys from the keyboard after holding a modifier

RcDropdown collects its items when the menu opens, and holding Ctrl or
Alt swaps the keys below the toggles while it is open, so the arrow keys
stopped at Alt. The menu now collects its items again on each key press,
as RcDropdown does for its submenus.

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

* fix: show a failed custom shortcut save inside the dialog

The dialog only reported a failed save with a growl, and the console
page's layout has no growls, so a delete or an add that could not be
saved changed nothing and said nothing. The error now shows as an alert
in the dialog until the next change or until it closes.

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

* fix: keep the focus in the custom shortcuts dialog after adding or deleting

The delete buttons and Add shortcut were disabled while a change saved,
and disabling the button that was just pressed dropped the keyboard's
focus to the page. They now stay enabled, and a change made while one saves is
ignored. After a delete the next row's button takes the focus, or the last
one's, and after an add, or once the list is empty, the recorder does.

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

* fix: record a modifier pressed on its own as a custom VNC shortcut

The recorder held every modifier for the key that ends the combination,
so the Windows key on its own could not be saved any more, while the old
dialog could. Modifiers released before any other key are now the
combination, once the last of them is released.

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

* fix: stop the custom shortcut form saying a new shortcut is already saved

The list shows a new shortcut while it saves, and the form kept it until
the save came back, so every add showed "This key combination is already
saved." as an alert for as long as the save took. The form now empties
as soon as Add shortcut is pressed, and the shortcut goes back in it if
the save fails, unless the next one was started meanwhile.

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

* fix: make the VNC Reconnect button an RcButton

The plain button took the global 40px button height inside the 32px
Disconnected pill, so its focus ring stuck out above and below the pill.
As a small ghost RcButton it is 24px tall and its ring stays inside.

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

* fix: carry View only over from the previous VNC console

The new storage key dropped a View only that someone turned on in the
previous console, so their mouse and keyboard reached the VM again
after the upgrade. View only was off unless the user turned it on, so
it is read from the previous key until this console saves its own
settings; the display settings still start fresh.

The comment on the key now says the settings are written once the user
changes one, rather than only the ones changed.

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

* fix: warn that a VNC soft reboot loses unsaved work

The soft reboot confirmation said the console disconnects while the VM
restarts and reconnects when it is back, which it does not: a soft
reboot restarts the guest in the same VM instance and pod, so the
console stays connected. It also dropped the previous dialog's warning
that unsaved work is lost, which is back.

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

---------

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>
2026-11-13 04:43:04 +01:00
Marcelo Fukumoto 08e483e3c8 chore(deps): align resolutions and yarn.lock with @rancher/shell 3.0.14 (#1239)
* chore(deps): align resolutions and yarn.lock with @rancher/shell 3.0.14

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

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

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

* chore(deps): keep the cronstrue pin

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

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

---------

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

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

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

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

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

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

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

* refactor: get the side navigation counts from the server

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

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

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

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

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

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

* fix: make the side navigation count requests more robust

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

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

* fix: count only the settings the Settings page shows

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

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

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

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

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

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

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

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

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

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

---------

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

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

* fix: validate Windows CloudInit YAML on save

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

* feat: use health API group for component health resources

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

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

* feat: add component health ignore controls

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

* feat: gate component health behind the componentHealth feature flag

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

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

* fix: address component health review comments

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

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

* refactor: split component health into dedicated components

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

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

* fix: sort component health by severity rank

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

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

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

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

* refactor: fetch component health resources in their own components

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

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

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

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

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

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

* refactor: use RcButton for the component health buttons

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

* fix: bring back deleting saved VNC console shortcut keys

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

Related: harvester/harvester#11550

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

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

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

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

Related: harvester/harvester#11550

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

* test: cover the label-key hints of VMPerformanceOptions

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

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

---------

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

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

* test: cover the VM delete prompt checkboxes

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

---------

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

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

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

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

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

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

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

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

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

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

* fix: point the network policy banner to the documentation

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

* feat: use the SUSE theme in standalone Prime

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

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

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

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

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

---------

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

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

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

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

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

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

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

* fix: keep the YAML editor heights with CodeMirror 6

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

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

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

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

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

* fix: keep the look of the file selector buttons

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* fix: reject zero-padded octets in IP ranges

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

---------

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

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

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

Only the placement changes; behaviour and validation are untouched.

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

* feat: follow the review on the VM Basics layout

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

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

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

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

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

Review follow-ups on both forms:

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

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

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

---------

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

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

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

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

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

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

* fix: expose VNC quality and compression settings

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

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

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

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

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

* feat: show whether the VNC console has keyboard focus

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

Related: harvester/harvester#3325

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

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

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

Ref: harvester/harvester#11550

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

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

Resolves the Copilot review comments on #1133:

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

Ref: harvester/harvester#11550

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

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

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

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

Ref: harvester/harvester#11550

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

---------

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

    Related issue: harvester/harvester#11731

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

    Related issue: harvester/harvester#11047

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

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

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

* feat: expose server-flavor setting

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

* refactor: copilot review

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

---------

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

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

* feat: add rancher-k3k addon UI

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

* refactor: copilot review

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

* refactor: copilot review

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

* refactor: remove k3k edit page

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

* refactor: k3k addon description

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

---------

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

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

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

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

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

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

* fix: align PCI passthrough action buttons height

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

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

---------

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

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

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

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

* refactor: AI review

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

---------

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

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

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

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

* refactor: PR comment

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

---------

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

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

* fix: move filter labels/schedule buttons position

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

* feat: improve serial console

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

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

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

* refactor: clear searach result after close

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

* refactor: fine tune serial console

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

---------

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

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

* fix: guard onQuotasInput against undefined payload

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

---------

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

    Related issue: harvester/harvester#9650

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

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

* feat: add access/ volume mode model

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

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

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

* fix: bugs in VM selection table

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

* refactor: copilot review

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

---------

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

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

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

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

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

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

Fixes point 2 of harvester/harvester#11124.

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

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

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

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

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

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

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

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

---------

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

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

* ci: simplify CI_BRANCH expression comment

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

---------

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

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

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

* refactor: copilot review

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

---------

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

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

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

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

---------

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

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

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

* refactor: customize empty table rows message

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

* refactor: fixed the table column

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

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

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

* style: remove unneeded overflow css

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

---------

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

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

* refactor: wordings

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

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

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

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

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

---------

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

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

* refactor: destructure ACCESS_MODE variables in CDISettings.vue accessModeOptions

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

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

---------

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

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

Related issue: harvester/harvester#10417

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

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

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

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

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

---------

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

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

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

* refactor: add noopener noreferrer rel

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

---------

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

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

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

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

* refactor: modify duration column width

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

* refactor: copilot review comment

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

---------

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

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

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

Fixes harvester/harvester#11174

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

* refactor: copilot review

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

* refactor: remove console

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

---------

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

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

* refactor: review comment

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

---------

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

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

* refactor: not pre-select target namespace

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

* refactor: ignore option

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

* refactor: copilot review

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

---------

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

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

* refactor: copilot review

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

---------

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

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

* feat: allow duration column to be sorted

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

---------

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

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

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

* refactor: copilot review

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

* refactor: copilot review

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

---------

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

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

* refactor: copilot review

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

---------

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

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

* fix: rename advanced to configurations

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

* fix: fixed column width

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

* refactor: review comment

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

* revert: power on background color

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

---------

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

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

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

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

* feat(forklift): UI based on the FIGMA

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

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

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

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

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

* feat(forklift): Add the succeded state

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

* Merge the new APIs

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

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

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

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

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

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

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

* feat(forklift): Added pagination UI

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

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

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

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

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

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

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

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

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

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

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

* feat(forklift): Remove test flags

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

* feat(forklift): Changed based on review

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

* feat(forklift): fixed title and button

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

* feat(forklift): Design changes

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

* feat(forklift): Changed to Wizard

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

* feat(forklift): added the provider wizard

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

* feat(forklift): Fixed some UI changes

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

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

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

* feat(forklift): update size

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

* feat(forklift): small fixes

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

* feat(forklift): small fixes after Copilot

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

* feat(forklift): small fixes after Copilot

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

* feat(forklift): reverted settings.json changes

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

* feat(forklift): small fixes after Copilot

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

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

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

* feat(forklift): Fixed the type for VMware

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

* feat(forklift): small changes before rebase

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

* feat: Added new API for the vms

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

* feat: Fix some labels

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

* feat: Added some final fixes to structure

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

* feat: added loading to provider steps

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

* feat: added comments from copilot review

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

---------

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

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

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

* feat: Allow user to customize snapshot/backup deadline

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

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

---------

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

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

* feat: add feature flag

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

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-07-09 13:17:19 +08:00
Andy Lee 59f260eab8 fix: vpc topology should consume NAD labels (#975)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-07-08 13:47:25 +08:00
Volker Theile 495e80267d feat: Unattend.xml support for Windows (#954)
Documentation: https://kubevirt.io/user-guide/user_workloads/startup_scripts/#sysprep
Related to: https://github.com/harvester/harvester/issues/1836

Signed-off-by: Volker Theile <vtheile@suse.com>
2026-07-06 08:45:33 +02:00
Alexandre Alves 479c298f4a feat: security update (#967) 2026-07-06 11:19:32 +08:00
renovate[bot] 3fdde25d17 deps: update dependency qs to v6.15.3 (#968)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-07-06 11:09:50 +08:00
Andy Lee 5090d8ecad ci: disable digest update (#966)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-07-01 16:54:30 +08:00
Andy Lee b9334bafb7 feat: add overlay networks and underlay networks resources page (#938)
* feat: allow user to select kube-system ns

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

* feat: add NICs tab when creating overlay network

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

* refactor: only show NIC tab if ns is kube-system

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

* feat: add NAT & Internet tabs

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

* feat: add provider networks / vlan edit pages

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

* feat: add edit pages

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

* refactor: review comments

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

* refactor: copilot review

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

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-07-01 16:33:20 +08:00
Andy Lee 9a675da756 docs: add release block in README.md (#964)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-07-01 12:18:28 +08:00
renovate[bot] 8c0c36e022 deps: update patch dependencies (#945)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-07-01 11:22:07 +08:00
Siva Kanakala 140a85f6a8 fix: Fix VM Template UserData editor remaining editable in view-mode (#951)
Signed-off-by: Siva Kanakala <siva.kanakala@suse.com>
2026-07-01 11:21:26 +08:00
Volker Theile e62ae7e1d8 fix: Fix the title of the CloudConfig DataTemplate dialog (#953)
Signed-off-by: Volker Theile <vtheile@suse.com>
2026-07-01 11:21:07 +08:00
Tim Serong d03cff645b feat: add Longhorn V2 hugepage settings (#942)
This exposes the longhorn-v2-data-engine-hugepage-enabled and
longhorn-v2-data-engine-memory-size settings in the Harvester GUI, on
Harvester v1.9.0 and later.

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

Signed-off-by: Tim Serong <tserong@suse.com>
2026-06-25 14:39:23 +10:00
Volker Theile 34dfe4027e fix: 'No Media' image selection removes 'harvesterhci.io/os' label from VM CR (#941)
When editing a Virtual Machine's volumes, if the user selects 'No media' for the Image, the 'harvesterhci.io/os' label is incorrectly removed from the VM's metadata.

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

Signed-off-by: Volker Theile <vtheile@suse.com>
2026-06-24 15:36:31 +02:00
Siva Kanakala 135d520b8d fix: Fix CloudConfigTemplate UserData editor remaining editable in view-mode (#939)
Signed-off-by: Siva Kanakala <siva.kanakala@suse.com>
2026-06-24 11:33:19 +08:00
Andy Lee 62a19ee3fb feat: add namespace filtering when updating namespaces (#940)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-06-23 21:44:39 +08:00
renovate[bot] 64f0f5fb87 deps: update patch dependencies (#932)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-06-22 14:36:19 +08:00
Andy Lee 93a692ff0c feat: add NICs tab when creating overlay network (#931)
* feat: allow user to select kube-system ns

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

* feat: add NICs tab when creating overlay network

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

* refactor: only show NIC tab if ns is kube-system

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

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-06-22 14:32:26 +08:00
Andy Lee 5e3f12de35 feat: clear selected VM after doing bulk action (#929)
* feat: clear selected VM rows after click bulk action

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

* refactor: await altStopVM action

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

* refactor: multiple VM start actions

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

* refactor: modify altRestartVM()

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

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-06-17 13:55:01 +08:00
Po Han Huang f115261889 feat: improve clone status (#928)
* feat: improve clone status

Signed-off-by: pohanhuang <pohan.huang@suse.com>

* fix: pr comments

Signed-off-by: pohanhuang <pohan.huang@suse.com>

---------

Signed-off-by: pohanhuang <pohan.huang@suse.com>
2026-06-17 11:10:43 +08:00
Andy Lee 5985913f5e feat: add Host Networks tab list and edit pages (#920)
* feat: add Host Network tab

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

* feat: add Host Network edit page

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

* feat: add node selector tab

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

* refactor: copilot review

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

* fix: lint

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

* fix: copilot review

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

* refactor: add warning message if addon is not enabled or already hasone

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

* refactor: some wordings in en-us.yaml

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

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-06-16 10:57:15 +08:00
renovate[bot] 661ab995f6 deps: update patch dependencies (#921)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-06-15 14:01:50 +08:00
Andy Lee d3f63df883 refactor: disable and hide filesystem warning banner in edit / view mode (#919)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-06-09 14:49:39 +08:00
Renuka Devi Rajendran 44ef9195eb feat: add exclusive VLAN field to storage network settings (#914)
Signed-off-by: Renuka Devi Rajendran <renuka.rajendran@suse.com>
2026-06-08 08:44:24 -07:00
Andy Lee b18aebbbd4 fix: snapshot/backup/volume attach VM name (#918)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-06-08 16:49:09 +08:00
renovate[bot] d2db23d69a deps: update minor dependencies to v7.29.7 (#915)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-06-08 15:40:18 +08:00
Andy Lee 55918232a6 feat: add volume expansion checkbox in storage class configuration (#911)
* feat: add support for volume expansion in storage configuration

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

* refactor: update volume expansion wording

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

* refactor: hide checkbox if feature flag is not enabled

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

* refactor: revert unneeded change

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

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-06-05 14:54:10 +08:00
Andy Lee ce2adbdc3b feat: support adding VM display name in creation page (#912)
* feat: add VM display name annotation support in edit and list views

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

* refactor: add display name checkbox and input field

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

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-06-05 12:11:07 +08:00
Jack Yu ae65037083 feat: add disable resource pooling checkbox on pcidevice page (#902)
Signed-off-by: Jack Yu <jack.yu@suse.com>
2026-06-05 11:18:14 +08:00
Jack Yu b4ea7c8f98 feat: remove old format pci device name checking (#889)
when implementing the first version pci device passthrough,
we didn't have our own device plugin, then resource name was changed
after upgrade.

Right now, we already have our own device plugin, which we can control
resource name by our ourselves. So, we can remove old mechanism.

Signed-off-by: Jack Yu <jack.yu@suse.com>
2026-06-05 11:18:04 +08:00
Andy Lee 836b04f222 feat: support filesystem volume in create VM page (#910)
* feat: add filesystem tab

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

* feat: add filesystem tab in create VM page

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

* refactor: update some wordings

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

* feat: add support for filesystem feature flag and enable filesystem tab

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

* refactor: remove unneeded wordings

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

* feat: add support for filesystem feature flag and update icon button positioning

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

* refactor: based on copilot review

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

* refactor: remove wrong feature flag

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

* fix: vm template

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

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-06-02 13:34:09 +08:00
Andy Lee 0908c7fc6b Revert "feat: support filesystem disk for VM (#898)" (#909)
This reverts commit b34d618c7c.

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-06-02 11:21:40 +08:00
Andy Lee b34d618c7c feat: support filesystem disk for VM (#898)
* feat: add filesystem tab

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

* feat: add filesystem tab in create VM page

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

* refactor: update some wordings

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

* feat: add support for filesystem feature flag and enable filesystem tab

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

* refactor: remove unneeded wordings

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

* feat: add support for filesystem feature flag and update icon button positioning

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

* refactor: based on copilot review

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

* refactor: tab name

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

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-06-02 10:33:04 +08:00
renovate[bot] 8945b9f158 deps: update dependency @types/node to v25.9.1 (#894)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-06-01 16:49:08 +08:00
renovate[bot] c5af2b576b deps: update dependency semver to v7.8.1 (#893)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-06-01 16:34:06 +08:00
Andy Lee 45872cef3b feat: add autoattachPodInterface in edit VM mode if no network interface configured (#888)
* feat: add autoattachPodInterface in edit VM mode if no network interface configured

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

* refactor: remove unneeded code

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

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-05-31 15:51:51 +08:00
khushalchandak17 3e5ee422ce fix(console): defer window.open to prevent dropdown staying open in Firefox (#890)
Signed-off-by: khushalchandak17 <khushal.chandak@suse.com>
2026-05-29 17:09:13 +08:00
Andy Lee 75202a9e55 chore: bump shell to 3.0.12-rc3 (#892)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-05-29 15:49:49 +08:00
Andy Lee 5f5ce291fb ci: disable body-max-line-length eslint rule (#887)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-05-27 17:17:14 +08:00
Jack Yu a27e38fc81 feat: display message from MIG status and change the state to match the case (#879)
Signed-off-by: Jack Yu <jack.yu@suse.com>
2026-05-26 13:44:27 +08:00
Andy Lee 89e1484884 feat: add natOutgoing option for custom subnet with corresponding tooltip (#878)
* feat: add external connectivity option for subnets with corresponding tooltip

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

* fix: remove gatewayType from subnet spec when not needed

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

* refactor: update external connectivity feature to use NAT outgoing and improve tooltip descriptions

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

* fix: update subnet creation to correctly handle natOutgoing and improve comment clarity

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

* refactor: improve tooltip clarity for external connectivity NAT option

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

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-05-26 12:13:59 +08:00
renovate[bot] eacca055c7 deps: update minor dependencies (#884)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-05-25 18:02:44 +08:00
renovate[bot] 56c1738055 deps: update dependency roarr to v7.21.5 (#883)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-05-25 14:29:21 +08:00
renovate[bot] 8f4b335cae deps: update dependency qs to v6.15.2 [security] (#880)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-05-25 14:24:22 +08:00
Andy Lee 91232beffc fix: vGPU and USB enable/disable actions needs to be hidden for read only users (#877)
* fix: vGPU / USB enable/disable actions needs to be hidden for read only users

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

* style: add scoped styles for group actions in DeviceList component

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

* style: remove width property from group actions in DeviceList components

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

* fix: update logging type in init function and improve SideNav visibility handling

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

* fix: ensure canManageGroup only returns true for non-empty rows with updatable permissions

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

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-05-22 11:56:44 +08:00
Andy Lee 09e8946cc3 fix: missing VMIM in host detail VM tab (#876)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-05-18 14:55:02 +08:00
Volker Theile e70c684382 feat: Prevent VM start after restore from backup or snapshot (#865)
* feat: Prevent VM start after restore from backup or snapshot

Related to: https://github.com/harvester/harvester/issues/10422
Related to: https://github.com/harvester/harvester/pull/10480

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

* feat: Prevent VM start after restore from backup or snapshot

Related to: https://github.com/harvester/harvester/issues/10422
Related to: https://github.com/harvester/harvester/pull/10480

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

---------

Signed-off-by: Volker Theile <vtheile@suse.com>
2026-05-18 08:10:36 +02:00
Andy Lee 1446aac168 refactor: enable add volume button regardless of rows length (#869)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-05-18 12:34:32 +08:00
renovate[bot] 8e65274b0c deps: update dependency @types/node to v25.6.2 (#870)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-05-18 12:04:13 +08:00
renovate[bot] e5432210b9 deps: update dependency semver to v7.8.0 (#871)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-05-18 12:00:49 +08:00
Andy Lee af52df0ba0 fix: add alternative action for VM restart and soft reboot (#868)
* fix: add alternative action for VM restart and soft reboot

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

* refactor: fix alignment

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

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-05-15 12:03:20 +08:00
Andy Lee e5a1929ac5 refactor: remove unused pluralization for persistent volume claim in localization file (#867)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-05-15 12:02:51 +08:00
Andy Lee 9de065a5c9 feat: allow migrate mutliple VMs functionality and localization (#863)
* feat: enhance VM migration functionality and localization

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

* refactor: add allVmsOnTargetNode method and update migration titles in localization

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

* feat: enhance migration error handling and update localization for migration dialog

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

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-05-13 15:59:13 +08:00
renovate[bot] cd933bdbf8 deps: update dependency eslint-plugin-promise to v7.3.0 (#858)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-05-12 16:19:04 +08:00
Andy Lee 5fe642a42d feat: add tooltip for route connectivity in network attachment definition (#864) 2026-05-12 16:14:11 +08:00
renovate[bot] 18c66083ab deps: update dependency yaml to v2.8.4 (#857)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-05-12 15:59:13 +08:00
Andy Lee d291a35754 feat: add PodSecurityStandard setting (#842)
* feat: add PodSecurity Standard setting

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

* refactor: unneeded change

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

* refactor: filter by isSystem namespace

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

* refactor: add fallback logic

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

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-05-07 13:15:47 +08:00
Andy Lee 5cc8b4c301 fix: some actions should be hidden for read-only user (#855)
* fix: some actions limited for virt-viewer

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

* refactor: based on schema collectionMethods

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

* fix: conditionally add migrate action to available actions

* fix: update collectionMethods check to use find for case-insensitive matching

* fix: update canEditClusterMembers method to use schema for collectionMethods

* fix: update canCreateImage check to use case-insensitive matching

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-05-07 10:21:26 +08:00
Andy Lee 032700293c perf: improve vm list page performance (#835)
* fix: remove unneeded persistentvolumeclaim type label translation key

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

* refactor: improve lockIconTooltipMessage call twice

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

* refactor: avoid watch allVMs

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

* perf: improve the some functions with pre-created map

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

* perf: improve the vm list page

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

* refactor: AI comment

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

* refactor: based on feedback

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

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-05-04 16:33:59 +08:00
Jack Yu 8cb793e7ad feat: add class type colume for usb device (#839)
Signed-off-by: Jack Yu <jack.yu@suse.com>
2026-05-04 15:17:01 +08:00
Andy Lee 2c45b71d1f ci: remove brackets in PR Management (#852)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-05-04 14:30:02 +08:00
Andy Lee 5a301dcf55 fix: workflow not trigger (#849)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-05-04 13:50:24 +08:00
Andy Lee 1a92265d03 ci: replace pull_request_target with two-step workflows (#841)
* ci: update PR auto assign workflows

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

* ci: update backport label workflow

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

* ci: update backport PR via mergify workflow

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

* ci: update add PR label workflow

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

* refactor: file name

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

* refactor: limit auto-assign-check for target branches

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

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-05-03 23:11:55 +08:00
Andy Lee 8f65915bad refactor: enable edit as yaml in VM image page (#843)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-05-03 23:05:36 +08:00
Andy Lee 67bb6dfbd5 docs: add AGENTS.md for AI agent guidance (#837)
* feat: add AGENNTS.md

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

* refactor: update based on copilot feedback

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

* refactor: update AGENTS.md

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

* refactor: update based on AI suggestion

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

* refactor: based on comments

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

* refactor: some files

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

* refactor: boundaries.md

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

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-04-29 16:05:51 +08:00
renovate[bot] e74428d951 deps: update dependency @types/node to v25.6.0 (#830)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-04-27 11:44:54 +08:00
renovate[bot] 629f7df6b9 deps: update patch dependencies (#829)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-04-26 22:38:51 +08:00
Tim Liou b7119d5c4c chore: bump sha for upstream action pinning (#827)
Signed-off-by: Tim Liou <tim.liou@suse.com>
2026-04-24 16:36:43 +08:00
Andy Lee 6fdd1e3954 fix: change auth/V3user to auth/user (#824)
* fix: change auth/V3user to auth/user

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

* refactor: extract to utils/auth.js

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

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-04-22 15:39:24 +08:00
Andy Lee 7d0f33f31d feat: show generic error message for API response 40x error (#816)
* feat: add generic error for API response 40X

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

* refactor: fallback error msg

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

* refactor: update error msg

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

* refactor: based on comment

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

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-04-21 17:55:30 +08:00
Andy Lee 9ce95daf76 ci: disable digest update in renovate.json (#823)
* ci: disable digest update in renovate.json

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

* refactor: keep but disable digest update auto merge

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

* refactor: add schedule for digest update

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

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-04-21 16:49:01 +08:00
Andy Lee ce72232bc3 fix: failed build-extension-charts CI (#822)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-04-20 16:51:45 +08:00
Andy Lee afc0e0f531 chore: bump @rancher/shell to 3.0.12-rc.1 (#810)
* chore: bump @rancher/shell to 3.0.12-rc.1

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

* ci: update node version to 24

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

* ci: update build catalog yaml

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

* fix: nav items order

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

* refactor: remove unneeded weightType

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

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-04-20 16:29:57 +08:00
renovate[bot] e941cc9a90 deps: update dependency node-forge to v1.4.0 [security] (#780)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-04-20 12:14:47 +08:00
renovate[bot] 9961523d08 deps: update dependency follow-redirects to v1.16.0 [security] (#813)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-04-20 11:11:06 +08:00
Andy LeeandCopilot c4d1018388 fix: provisioner not update when deleting disk (#791)
* fix: provisioner not update when deleting disk

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

* refactor: update pkg/harvester/edit/harvesterhci.io.host/HarvesterDisk.vue

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

* refactor: based on feedback

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

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-04-20 10:56:42 +08:00
Andy Lee be64329776 feat: pop up dialog when enabling nvidia driver addon (#811)
* feat: add nvidia driver toolkit dialog

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

* refactor: add disable button guard

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

* refactor: based on feedback

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

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-04-17 11:00:10 +08:00
Andy Lee 35411ed87a Revert "deps: update patch digest dependencies (#804)" (#808)
This reverts commit 15eb0f07f7.
2026-04-13 14:42:16 +08:00
renovate[bot] 15eb0f07f7 deps: update patch digest dependencies (#804)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-04-13 14:17:27 +08:00
Andy Lee fb78f24fdd chore: add v1.8.1 v1.9.0 feature flags (#792)
* chore: add v1.8.1 and v1.9.0 feature flags

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

* chore: bump to v1.9.0-dev

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

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-04-13 14:08:44 +08:00
renovate[bot] 81ad827829 deps: update fossas/fossa-action action to v1.9.0 (#794)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-04-07 16:10:40 +08:00
Andy Lee 6dd9b33336 ci: add add_minrelaseday to delay dep update (#798)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-04-07 15:22:11 +08:00
Tim Liou 1f9e9b336b chore: bump version to 1.8.0-rc5 (#789)
Signed-off-by: Tim Liou <tim.liou@suse.com>
2026-04-01 09:07:56 +08:00
Andy Lee c5b4f6cd1e refactor: add banner in PCI Devices page (#785)
* refactor: add banner in PCI Devices page

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

* refactor: based on copilot review

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

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-03-31 17:45:06 +08:00
Andy Lee 4ce35ce075 fix: the rancher-eio/read-vault-secret sha (#786)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-03-31 14:02:41 +08:00
Andy Lee 27c26bd782 ci: remove unused EMBED_PKG variable (#783)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-03-31 13:48:43 +08:00
Tim Liou 9d698b1230 chore: bump version to 1.8.0-rc4 (#778)
Signed-off-by: Tim Liou <tim.liou@suse.com>
2026-03-27 16:38:29 +08:00
freezeandAndy Lee 566e79eda5 feat: support advance option and creation from DataVolume (#776)
* feat: support advance option and creation from DataVolume

    - advance option would let user change the accessMode/volumeMode
    - creation from DataVolume could supports various scenario with
      3rd-party storage

Signed-off-by: Vicente Cheng <freeze.bilsted@gmail.com>

* feat: add data migration action on volume page

Signed-off-by: Vicente Cheng <freeze.bilsted@gmail.com>

* refactor: use show advanced options link instead of checkbox

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

* feat: add feature flag

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

* feat: add feature flag for dataMigration action

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

---------

Signed-off-by: Vicente Cheng <freeze.bilsted@gmail.com>
Signed-off-by: Andy Lee <andy.lee@suse.com>
Co-authored-by: Andy Lee <andy.lee@suse.com>
2026-03-26 17:29:14 +08:00
Andy Lee 42ddcfc1fe chore: bump version to 1.8.0-rc3 (#774)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-03-25 17:27:39 +08:00
Andy Lee ad3decf71f fix: use default value got undefined value in payload (#772)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-03-25 17:08:32 +08:00
Andy Lee 8083a41df0 ci: remove the single quota for use commit hash (#767)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-03-25 14:08:59 +08:00
Andy Lee 46b860260a ci: add CODEOWNERS file (#768)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-03-25 13:37:15 +08:00
freeze 62801b3b13 chore: pin GH Actions to commit sha (#765) 2026-03-25 10:12:25 +08:00
renovate[bot] 161e3bbd97 deps: update dependency yaml to v2.8.3 (#755)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-03-23 00:05:52 +08:00
Andy Lee 97e93dba0b docs: update install instruction doc link (#753)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-03-20 16:36:09 +08:00
Andy Lee 9a8a709e56 refactor: change rwxNetwork setting to kind json (#751)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-03-20 13:28:30 +08:00
Andy Lee d1949641a7 feat: introduce rwxNetwork setting (#746)
* feat: add rwxNetwork setting

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

* fix: network payload

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

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-03-19 15:55:55 +08:00
freeze 9c9f59c939 feat: add storage migration operation (#724)
- add storage migration
    - add cancel storage migration

Signed-off-by: Vicente Cheng <freeze.bilsted@gmail.com>
2026-03-19 11:45:54 +08:00
Andy Lee ccc14c7fb9 chore: bump to v1.8.0-rc2 (#747)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-03-19 11:28:06 +08:00
Andy Lee 2ba471907e feat: introduce instance-manager-resources setting (#744)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-03-18 17:16:12 +08:00
Andy Lee 5aea476f64 refactor: remove using resourceName to determine is vGPU device (#741) 2026-03-18 10:35:47 +08:00
Andy Lee 519c7d9f1f fix: typo (#740)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-03-17 16:26:59 +08:00
Tim Liou a9c392c13f fix: reword the error message to focus on bootable volume (#736)
Signed-off-by: Tim Liou <tim.liou@suse.com>
2026-03-12 17:43:07 +08:00
Tim Liou 888ec7a50f fix: container disks don't need volumeClaimTemplates but volumes (#735)
Signed-off-by: Tim Liou <tim.liou@suse.com>
2026-03-12 17:42:21 +08:00
Po Han Huang a2486a7d38 feat: ensure the state is pending when perform cloning the efi (#730)
* feat: ensure the state is pending when perform cloning the efi

Signed-off-by: pohanhuang <pohan.huang@suse.com>

* feat: define harvesterhci.io/clone-backend-storage-status in labels-annotations.js

Signed-off-by: pohanhuang <pohan.huang@suse.com>

---------

Signed-off-by: pohanhuang <pohan.huang@suse.com>
2026-03-11 15:30:33 +08:00
Andy Lee df3d249923 chore: bump to v1.8.0-rc1 (#731)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-03-11 15:29:27 +08:00
Andy Lee 23344e0c07 feat: add vGPU filter button and hide the enable/disable passthrough in PCIDevice page (#729)
* feat: add another filter button

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

* feat: add feature falg to hide vGPU enable/disable actions in PCIDevices page

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

* refactor: update with conditionally rendering

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

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-03-11 15:29:14 +08:00
Andy Lee 62b80b3cec feat: add Insecure Skip TLS Verify checkbox in cluster-registration-url setting (#716)
* feat: add Insecure Skip TLS Verify checkbox

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

* refactor: set insecureSkipTLSVerify default to false

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

* fix: conflict

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

* refactor: remove unneeded change

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

* fix: get the feature flag in data()

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

* refactor: make data logic simpler

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

* refactor: put tip in info banner

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

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-03-09 10:51:20 +08:00
renovate[bot] 1cf94ee550 deps: update dependency @types/node to v20.19.37 (#726)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-03-08 14:15:49 +08:00
renovate[bot] dfaa9fbe33 deps: update dependency elkjs to ^0.11.0 (#727)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-03-08 14:15:01 +08:00
Andy Lee 94b1c24479 chore: bump @rancher/shell to v3.0.9-rc.6 (#712)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-03-08 14:13:46 +08:00
Jack Yu e0b2b9ec57 feat: add support-bundle-file-name setting (#725)
* feat: support customizing support bundle file name

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

* feat: add supportBundleFileNameSetting feature flag

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

---------

Signed-off-by: Jack Yu <jack.yu@suse.com>
2026-03-06 15:51:20 +08:00
Andy Lee 06b38a0f99 fix: import sources page header (#723)
* fix: the import sources page header

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

* refactor: update VMware term

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

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-03-05 16:36:15 +08:00
Yiya Chen 4be3634c82 feat: add VPC network topology in detail page (#721)
* feat: add topology

Signed-off-by: Yi-Ya Chen <yiya.chen@suse.com>

* feat: add provider info

Signed-off-by: Yi-Ya Chen <yiya.chen@suse.com>

* refactor: remove comments

Signed-off-by: Yi-Ya Chen <yiya.chen@suse.com>

* fix: exclude default network

Signed-off-by: Yi-Ya Chen <yiya.chen@suse.com>

* feat: add VPC peering

Signed-off-by: Yi-Ya Chen <yiya.chen@suse.com>

* refactor: remove regex

Signed-off-by: Yi-Ya Chen <yiya.chen@suse.com>

* refactor: adjust row height

Signed-off-by: Yi-Ya Chen <yiya.chen@suse.com>

* feat: introduce auto layout

Signed-off-by: Yi-Ya Chen <yiya.chen@suse.com>

---------

Signed-off-by: Yi-Ya Chen <yiya.chen@suse.com>
2026-03-04 11:47:00 +08:00
Andy Lee de103ff91e fix: missing Download Logs button in Rancher integration mode (#715)
* fix: missing Download Logs button in Rancher integration mode

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

* refactor: add comment

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

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-03-02 16:47:20 +08:00
Andy Lee 37a91601c9 feat: add vmMigrationTimeout in vm-force-reset-policy setting (#718)
Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-03-02 11:10:52 +08:00
renovate[bot] 9794671ccd deps: update patch digest dependencies (#719)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-03-02 11:10:22 +08:00
Volker Theile 337f9186f1 fix(vmimport): Rename list pages according to their URL path (#717)
See https://github.com/harvester/harvester-ui-extension/pull/697#issuecomment-3957918146

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

Signed-off-by: Volker Theile <vtheile@suse.com>
2026-02-26 16:32:40 +08:00
Volker Theile 7c187e894d fix(vmimport): Add missing list page for ovasource (#714)
... and several small improvements.

Signed-off-by: Volker Theile <vtheile@suse.com>
2026-02-25 16:47:15 +08:00
Gaurav Mehta c2df13ad73 fix: changed logic to use power status from underlying inventory (#707)
Signed-off-by: Gaurav Mehta <gaurav.mehta@suse.com>
2026-02-23 20:08:54 +11:00
Tim Liou 93f027a57c fix: shall update hotpluggable when change to a non-iso image (#713)
Signed-off-by: Tim Liou <tim.liou@suse.com>
2026-02-23 17:08:33 +08:00
renovate[bot] da83f04b6c deps: update dependency qs to v6.15.0 (#710)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-02-23 11:50:05 +08:00
renovate[bot] a97cb08e3f deps: update patch digest dependencies (#705)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-02-14 14:22:19 +08:00
Tim Liou 3fdc9f03a3 feat: add cdrom hotplug volume (#703)
Signed-off-by: Tim Liou <tim.liou@suse.com>
2026-02-13 16:33:50 +08:00
Jack Yu c8a613874a feat: add cpu model selection (#702)
Signed-off-by: Jack Yu <jack.yu@suse.com>
2026-02-13 15:40:07 +08:00
Andy Lee 2db7ee7397 feat: show notification if there is VM pending restart (#700)
* feat: show notification if there is VM pending restart

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

* refactor: update based on comments

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

* refactor: calculate count from vm names

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

---------

Signed-off-by: Andy Lee <andy.lee@suse.com>
2026-02-03 16:21:20 +08:00
294 changed files with 34248 additions and 7993 deletions
+2 -1
View File
@@ -4,7 +4,8 @@ description: Setup node and install dependencies
runs:
using: 'composite'
steps:
- uses: actions/setup-node@v4
- name: Setup Nodejs with yarn caching
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version-file: '.nvmrc'
cache: 'yarn'
+12
View File
@@ -0,0 +1,12 @@
name: Run Unit Tests
description: Run Unit Tests
runs:
using: 'composite'
steps:
- name: Setup env
uses: ./.github/actions/setup
- name: Run unit tests
shell: bash
run: yarn test:ci
-6
View File
@@ -1,6 +0,0 @@
addAssignees: author
addReviewers: true
numberOfReviewers: 0
reviewers:
- a110605
- houhoucoop
+15 -6
View File
@@ -1,14 +1,23 @@
<!-- This template is for Devs to give QA details before moving the issue To-Test -->
### Summary
<!-- Give the fix root cause or feature requirement, at least list what this PR changes -->
### PR Checklists
### PR Checklist
<!-- Check Yes if there is backend PR related to this UI PR, tag the backend owner's Github account -->
- Are backend engineers aware of UI changes ?
- [ ] Yes, the backend owner is:
- [ ] Yes, the backend owner is @
- [ ] No, frontend-only.
### Related Issue #
<!-- Define findings related to the feature or bug issue. -->
### Related Issue
<!-- Link the issue as harvester/harvester#<issue_number> -->
harvester/harvester#<issue_number>
### Test Steps
<!-- Provide the test steps for reviewer to verify the issue -->
1. Go to ... page
### Test screenshot or video
<!-- Attach screenshot or video of the changes and eventual comparison if you find it necessary -->
<!-- Attach screenshot or video of the changes and eventual comparison -->
+14 -4
View File
@@ -14,10 +14,17 @@
"semanticCommits": "enabled",
"semanticCommitType": "deps",
"prHourlyLimit": 12,
"digest": {
"enabled": false
},
"timezone": "Asia/Taipei",
"schedule": ["after 10am on sunday"],
"postUpdateOptions": ["yarnDedupeFewer"],
"packageRules": [
{
"matchUpdateTypes": ["digest"],
"enabled": false
},
{
"matchUpdateTypes": ["major"],
"enabled": false
@@ -34,14 +41,17 @@
{
"matchUpdateTypes": ["minor"],
"groupName": "minor dependencies",
"minimumReleaseAge": "7 days",
"labels": ["minor-update"],
"reviewers": ["a110605", "houhoucoop"]
},
{
"matchUpdateTypes": ["patch", "digest"],
"automerge": true,
"groupName": "patch digest dependencies",
"labels": ["patch-update", "automerge"]
"matchUpdateTypes": ["patch"],
"automerge": false,
"minimumReleaseAge": "7 days",
"groupName": "patch dependencies",
"labels": ["patch-update"],
"reviewers": ["a110605", "houhoucoop"]
}
]
}
+39
View File
@@ -0,0 +1,39 @@
name: "PR Management Add PR Label Collect Data"
on:
pull_request:
types: [opened, reopened, edited]
branches:
- main
- 'release-harvester-v*'
jobs:
collect:
if: github.event.pull_request.draft == false
runs-on: ubuntu-latest
permissions:
contents: read
actions: write
steps:
- name: Checkout repository
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with:
ref: ${{ github.base_ref }}
- name: Setup Nodejs and yarn install
uses: ./.github/actions/setup
- name: Extract PR label
run: |
PR_LABEL=$(node ./scripts/extract-release-label.mjs "${{ github.event.pull_request.title }}")
echo "PR_LABEL=$PR_LABEL"
{
echo "PR_NUMBER=${{ github.event.pull_request.number }}"
echo "PR_LABEL=$PR_LABEL"
} > pr-add-label-data.env
- name: Upload PR data artifact
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: pr-add-label-data
path: pr-add-label-data.env
+33
View File
@@ -0,0 +1,33 @@
name: "PR Management Add PR Label"
on:
workflow_run:
workflows:
- "PR Management Add PR Label Collect Data"
types: [completed]
jobs:
auto-assign-pr-label:
runs-on: ubuntu-latest
if: ${{ github.event.workflow_run.conclusion == 'success' }}
permissions:
actions: read
pull-requests: write
steps:
- name: Download PR data artifact
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
with:
name: pr-add-label-data
run-id: ${{ github.event.workflow_run.id }}
github-token: ${{ github.token }}
- name: Load PR data
run: |
cat pr-add-label-data.env >> $GITHUB_ENV
- name: Set PR label
env:
GH_TOKEN: ${{ github.token }}
run: |
echo "PR_LABEL = $PR_LABEL"
gh pr edit "$PR_NUMBER" --repo "${{ github.repository }}" --add-label "$PR_LABEL"
+28
View File
@@ -0,0 +1,28 @@
name: "PR Management Auto Assign Collect Data"
on:
pull_request:
types: [opened, ready_for_review]
branches:
- main
- 'release-harvester-v*'
jobs:
collect:
runs-on: ubuntu-latest
permissions:
contents: read
actions: write
steps:
- name: Save PR data to artifact
run: |
{
echo "PR_NUMBER=${{ github.event.pull_request.number }}"
echo "PR_AUTHOR=${{ github.event.pull_request.user.login }}"
} > pr-auto-assign-data.env
- name: Upload PR data artifact
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: pr-auto-assign-data
path: pr-auto-assign-data.env
@@ -1,17 +0,0 @@
name: "[PR Management] Auto Assign Reviewer & Assignee"
on:
pull_request_target:
types: [opened, ready_for_review]
permissions:
pull-requests: write
jobs:
auto-assign:
if: github.event.pull_request.draft == false
runs-on: ubuntu-latest
steps:
- uses: rancher/gh-issue-mgr/auto-assign-action@main
with:
configuration-path: .github/auto-assign-config.yaml
+35
View File
@@ -0,0 +1,35 @@
name: "PR Management Auto Assign"
on:
workflow_run:
workflows:
- "PR Management Auto Assign Collect Data"
types: [completed]
jobs:
auto-assign:
runs-on: ubuntu-latest
if: ${{ github.event.workflow_run.conclusion == 'success' }}
env:
REVIEWERS: "a110605,houhoucoop"
permissions:
actions: read
pull-requests: write
steps:
- name: Download PR data artifact
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
with:
name: pr-auto-assign-data
run-id: ${{ github.event.workflow_run.id }}
github-token: ${{ github.token }}
- name: Load PR data
run: |
cat pr-auto-assign-data.env >> $GITHUB_ENV
- name: Auto assign PR author
env:
GH_TOKEN: ${{ github.token }}
run: |
echo "Assigning PR author: $PR_AUTHOR"
gh pr edit "$PR_NUMBER" --repo "${{ github.repository }}" --add-assignee "$PR_AUTHOR" --add-reviewer "$REVIEWERS"
@@ -0,0 +1,30 @@
name: "PR Management Add Labels Collect Data"
on:
pull_request:
types: [opened, reopened]
branches:
- main
- 'release-harvester-v*'
jobs:
collect:
if: github.event.pull_request.draft == false
runs-on: ubuntu-latest
permissions:
contents: read
actions: write
steps:
- name: Save PR data to artifact
run: |
{
echo "PR_NUMBER=${{ github.event.pull_request.number }}"
echo "PR_BASE_REF=${{ github.event.pull_request.base.ref }}"
echo "PR_USER_LOGIN=${{ github.event.pull_request.user.login }}"
} > pr-backport-label-data.env
- name: Upload PR data artifact
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: pr-backport-label-data
path: pr-backport-label-data.env
+44 -55
View File
@@ -1,40 +1,44 @@
name: "[PR Management] Add Labels"
name: "PR Management Add Backport Labels"
on:
pull_request_target:
types: [opened, reopened]
branches:
- main
- 'release-harvester-v*'
permissions:
pull-requests: write
workflow_run:
workflows:
- "PR Management Add Labels Collect Data"
types: [completed]
jobs:
add-require-backport-label:
if: github.event.pull_request.draft == false &&
github.event.pull_request.base.ref == 'main'
runs-on: ubuntu-latest
if: ${{ github.event.workflow_run.conclusion == 'success' }}
permissions:
actions: read
pull-requests: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Download PR data artifact
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
with:
ref: ${{ github.base_ref }}
name: pr-backport-label-data
run-id: ${{ github.event.workflow_run.id }}
github-token: ${{ github.token }}
- name: Fetch release branches and PR labels
id: fetch_info
- name: Load PR data
run: |
cat pr-backport-label-data.env >> $GITHUB_ENV
- name: Add require-backport label (main branch PRs)
if: env.PR_BASE_REF == 'main'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
repo="${{ github.repository }}"
pr_number=${{ github.event.pull_request.number }}
pr_number="$PR_NUMBER"
release_branches=$(gh api "repos/${repo}/branches" --paginate --jq '.[].name' | grep -E '^release-harvester-v[0-9]+\.[0-9]+$' || true)
if [[ -z "$release_branches" ]]; then
echo "should_label=false" >> "$GITHUB_OUTPUT"
echo "No release branches found, skipping."
exit 0
fi
@@ -44,51 +48,36 @@ jobs:
tags=$(gh api "repos/${repo}/releases" --paginate --jq '.[].tag_name')
if echo "$tags" | grep -Fxq "$release_tag"; then
echo "should_label=false" >> "$GITHUB_OUTPUT"
echo "Release $release_tag already published, skipping."
exit 0
fi
label="require backport/v${version}"
echo "should_label=true" >> "$GITHUB_OUTPUT"
echo "backport_label=$label" >> "$GITHUB_OUTPUT"
pr_labels=$(gh pr view "$pr_number" --repo "$repo" --json labels --jq '.labels[].name' || echo "")
pr_labels_csv=$(echo "$pr_labels" | tr '\n' ',' | sed 's/,$//')
echo "pr_labels=$pr_labels_csv" >> "$GITHUB_OUTPUT"
- name: Add label if needed
if: steps.fetch_info.outputs.should_label == 'true' && !contains(steps.fetch_info.outputs.pr_labels, steps.fetch_info.outputs.backport_label)
if echo "$pr_labels" | grep -Fxq "$label"; then
echo "Label '$label' already present, skipping."
exit 0
fi
echo "Adding label: $label"
gh pr edit "$pr_number" --repo "$repo" --add-label "$label"
- name: Add backport label (release branch PRs opened by Mergify)
if: startsWith(env.PR_BASE_REF, 'release-harvester-v')
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_TOKEN: ${{ github.token }}
run: |
echo "Adding label: ${{ steps.fetch_info.outputs.backport_label }}"
gh pr edit ${{ github.event.pull_request.number }} \
--repo ${{ github.repository }} \
--add-label "${{ steps.fetch_info.outputs.backport_label }}"
set -euo pipefail
add-backport-label:
if: github.event.pull_request.draft == false &&
startsWith(github.event.pull_request.base.ref, 'release-harvester-v')
runs-on: ubuntu-latest
steps:
- name: Check conditions for backport label
id: check
run: |
IS_MERGIFY=$(echo '${{ github.event.pull_request.user.login }}' | grep -iq 'mergify' && echo true || echo false)
TARGET_BRANCH=${{ github.event.pull_request.base.ref }}
IS_MERGIFY=$(echo "$PR_USER_LOGIN" | grep -iq 'mergify' && echo true || echo false)
echo "IS_MERGIFY=$IS_MERGIFY" >> $GITHUB_OUTPUT
echo "TARGET_BRANCH=$TARGET_BRANCH" >> $GITHUB_OUTPUT
if [[ "$IS_MERGIFY" != "true" ]]; then
echo "PR author is not Mergify, skipping."
exit 0
fi
- name: Add label if needed
if: steps.check.outputs.IS_MERGIFY == 'true' && startsWith(steps.check.outputs.TARGET_BRANCH, 'release-harvester-v')
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
TARGET_BRANCH="${{ steps.check.outputs.TARGET_BRANCH }}"
version="${TARGET_BRANCH#release-harvester-v}"
version="${PR_BASE_REF#release-harvester-v}"
label="backport/v${version}"
echo "Adding label $label"
gh pr edit ${{ github.event.pull_request.number }} \
--repo ${{ github.repository }} \
--add-label "$label"
echo "Adding label: $label"
gh pr edit "$PR_NUMBER" --repo "${{ github.repository }}" --add-label "$label"
@@ -0,0 +1,28 @@
name: "PR Management Request Backport via Mergify Collect Data"
on:
pull_request:
types: [closed]
branches: [main]
jobs:
collect:
if: github.event.pull_request.merged == true
runs-on: ubuntu-latest
permissions:
contents: read
actions: write
steps:
- name: Save PR data to artifact
run: |
labels_json='${{ toJson(github.event.pull_request.labels.*.name) }}'
{
echo "PR_NUMBER=${{ github.event.pull_request.number }}"
echo "PR_LABELS=$(echo "$labels_json" | jq -r '[.[]] | join(",")')"
} > pr-backport-request-data.env
- name: Upload PR data artifact
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: pr-backport-request-data
path: pr-backport-request-data.env
+22 -16
View File
@@ -1,41 +1,47 @@
name: "[PR Management] Request Backport via Mergify"
name: "PR Management Request Backport via Mergify"
on:
pull_request_target:
types: [closed]
branches: [main]
permissions:
pull-requests: write
workflow_run:
workflows:
- "PR Management Request Backport via Mergify Collect Data"
types: [completed]
jobs:
comment-backport:
if: github.event.pull_request.merged == true
runs-on: ubuntu-latest
if: ${{ github.event.workflow_run.conclusion == 'success' }}
permissions:
actions: read
pull-requests: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Download PR data artifact
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
with:
ref: ${{ github.base_ref }}
name: pr-backport-request-data
run-id: ${{ github.event.workflow_run.id }}
github-token: ${{ github.token }}
- name: Load PR data
run: |
cat pr-backport-request-data.env >> $GITHUB_ENV
- name: Post Mergify backport command
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
pr_number=${{ github.event.pull_request.number }}
pr_number="$PR_NUMBER"
repo="${{ github.repository }}"
labels_json='${{ toJson(github.event.pull_request.labels.*.name) }}'
labels=$(echo "$labels_json" | jq -r '.[] // empty')
labels=$(echo "$PR_LABELS" | tr ',' '\n')
echo "Labels on PR: $labels"
matches=$(echo "$labels" | grep -oE '^require backport/v[0-9]+\.[0-9]+$' || true)
if [[ -z "$matches" ]]; then
echo "No back‑port labels found — skipping."
echo "No back-port labels found — skipping."
exit 0
fi
@@ -15,7 +15,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- name: Check package version
env:
@@ -25,12 +25,12 @@ jobs:
name: Build & Upload Hosted
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3
with:
fetch-depth: 1
# Note - Cannot use the setup action here as it uses a different yarn install arg
- uses: actions/setup-node@v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version-file: '.nvmrc'
cache: 'yarn'
@@ -45,19 +45,20 @@ jobs:
run: ./scripts/build-upload-gate
- name: Get gcs auth
uses: rancher-eio/read-vault-secrets@main
uses: rancher-eio/read-vault-secrets@d266f55186f80a893839f6e15662e67388e443e6 # v3
with:
secrets: |
secret/data/github/repo/${{ github.repository }}/google-auth/harvester/credentials token | GOOGLE_AUTH ;
- name: Apply gcs auth
# https://github.com/google-github-actions/auth
uses: 'google-github-actions/auth@v2'
uses: google-github-actions/auth@c200f3691d83b41bf9bbd8638997a462592937ed # v2
with:
credentials_json: "${{ env.GOOGLE_AUTH }}"
- name: Upload build
uses: 'google-github-actions/upload-cloud-storage@v2'
uses: google-github-actions/upload-cloud-storage@c0f6160ff80057923ff50e5e567695cea181ec23 # v2
# https://github.com/google-github-actions/upload-cloud-storage
with:
path: ${{steps.build-hosted.outputs.BUILD_HOSTED_DIR}}
@@ -71,12 +72,12 @@ jobs:
name: Build & Upload Embedded
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3
with:
fetch-depth: 1
# Note - Cannot use the setup action here as it uses a different yarn install arg
- uses: actions/setup-node@v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version-file: '.nvmrc'
cache: 'yarn'
@@ -89,19 +90,19 @@ jobs:
DISABLED_EMBED_PKG: https://releases.rancher.com/harvester-ui/plugin/harvester-1.0.3.tar.gz
- name: Get gcs auth
uses: rancher-eio/read-vault-secrets@main
uses: rancher-eio/read-vault-secrets@d266f55186f80a893839f6e15662e67388e443e6 # v3
with:
secrets: |
secret/data/github/repo/${{ github.repository }}/google-auth/harvester/credentials token | GOOGLE_AUTH ;
- name: Apply gcs auth
# https://github.com/google-github-actions/auth
uses: 'google-github-actions/auth@v2'
uses: google-github-actions/auth@c200f3691d83b41bf9bbd8638997a462592937ed # v2
with:
credentials_json: "${{ env.GOOGLE_AUTH }}"
- name: Upload tar
uses: 'google-github-actions/upload-cloud-storage@v2'
uses: google-github-actions/upload-cloud-storage@c0f6160ff80057923ff50e5e567695cea181ec23 # v2
with:
path: ${{steps.build-embedded.outputs.BUILD_EMBEDED_TGZ}}
destination: releases.rancher.com/harvester-ui/dashboard
@@ -114,16 +115,23 @@ jobs:
name: Build & Upload Plugin
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3
with:
fetch-depth: 1
# Note - Cannot use the setup action here as it uses a different yarn install arg
- uses: actions/setup-node@v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version-file: '.nvmrc'
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
name: Build pkg
run: ./scripts/ci-build-pkg.sh harvester
@@ -133,19 +141,19 @@ jobs:
run: ./scripts/build-upload-gate
- name: Get gcs auth
uses: rancher-eio/read-vault-secrets@main
uses: rancher-eio/read-vault-secrets@d266f55186f80a893839f6e15662e67388e443e6 # v3
with:
secrets: |
secret/data/github/repo/${{ github.repository }}/google-auth/harvester/credentials token | GOOGLE_AUTH ;
- name: Apply gcs auth
# https://github.com/google-github-actions/auth
uses: 'google-github-actions/auth@v2'
uses: google-github-actions/auth@c200f3691d83b41bf9bbd8638997a462592937ed # v2
with:
credentials_json: "${{ env.GOOGLE_AUTH }}"
- name: Upload plugin tar
uses: 'google-github-actions/upload-cloud-storage@v2'
uses: google-github-actions/upload-cloud-storage@c0f6160ff80057923ff50e5e567695cea181ec23 # v2
with:
path: dist-pkg/${{steps.ci-build-pkg.outputs.PKG_TARBALL}}
destination: releases.rancher.com/harvester-ui/plugin
@@ -155,7 +163,7 @@ jobs:
process_gcloudignore: false
- name: Upload plugin directory
uses: 'google-github-actions/upload-cloud-storage@v2'
uses: google-github-actions/upload-cloud-storage@c0f6160ff80057923ff50e5e567695cea181ec23 # v2
with:
path: dist-pkg/${{steps.ci-build-pkg.outputs.PKG_NAME}}
destination: releases.rancher.com/harvester-ui/plugin/${{steps.ci-build-pkg.outputs.PKG_NAME}}
+12 -12
View File
@@ -27,14 +27,14 @@ jobs:
build-status: ${{ job.status }}
steps:
- name: Read Secrets
uses: rancher-eio/read-vault-secrets@main
uses: rancher-eio/read-vault-secrets@d266f55186f80a893839f6e15662e67388e443e6 # v3
with:
secrets: |
secret/data/github/repo/${{ github.repository }}/dockerhub/rancher/credentials username | DOCKER_USERNAME ;
secret/data/github/repo/${{ github.repository }}/dockerhub/rancher/credentials password | DOCKER_PASSWORD ;
- name: Checkout repository (normal flow)
uses: actions/checkout@v4
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- name: Enable Corepack
run: corepack enable
@@ -45,26 +45,26 @@ jobs:
git config user.email 'github-actions[bot]@users.noreply.github.com'
- name: Login to Docker Hub
uses: docker/login-action@v3
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
with:
username: ${{ env.DOCKER_USERNAME }}
password: ${{ env.DOCKER_PASSWORD }}
- name: Setup Helm
uses: azure/setup-helm@v3
uses: azure/setup-helm@5119fcb9089d432beecbf79bb2c7915207344b78 # v3
with:
version: v3.8.0
- name: Setup Nodejs with yarn caching
uses: actions/setup-node@v4
with:
node-version: '20'
cache: yarn
- name: Setup Nodejs with yarn install
uses: ./.github/actions/setup
- name: Install dependencies
run: yarn
# 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
run: |
publish="yarn publish-pkgs -cp -r ${{ inputs.registry_target }} -o ${{ inputs.registry_user }}"
$publish
$publish
+15 -9
View File
@@ -13,7 +13,7 @@ jobs:
target_branch: ${{ steps.get-version.outputs.target_branch }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- name: Determine target branch
id: get-version
@@ -44,7 +44,7 @@ jobs:
version: ${{ steps.get_version.outputs.version }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- name: Extract version from package.json
id: get_version
@@ -62,7 +62,13 @@ jobs:
contents: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- name: Setup Node from .nvmrc
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version-file: '.nvmrc'
cache: 'yarn'
- name: Setup environment
run: |
@@ -70,7 +76,7 @@ jobs:
yarn install --frozen-lockfile
- name: Setup Helm
uses: azure/setup-helm@v3
uses: azure/setup-helm@5119fcb9089d432beecbf79bb2c7915207344b78 # v3
with:
version: v3.8.0
@@ -79,7 +85,7 @@ jobs:
yarn publish-pkgs -s ${{ github.repository }} -b ${{ needs.setup-target-branch.outputs.target_branch }} -t harvester-${{ needs.extract-version.outputs.version }}
- name: Upload charts artifact
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: charts
path: tmp
@@ -94,7 +100,7 @@ jobs:
contents: write
steps:
- name: Checkout release branch
uses: actions/checkout@v4
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with:
ref: '${{ github.ref_name }}'
@@ -105,7 +111,7 @@ jobs:
echo "LAST_COMMIT=${LAST_COMMIT}" >> $GITHUB_ENV
- name: Checkout target branch
uses: actions/checkout@v4
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with:
ref: '${{ needs.setup-target-branch.outputs.target_branch }}'
@@ -121,7 +127,7 @@ jobs:
git config user.email 'github-actions[bot]@users.noreply.github.com'
- name: Download build artifacts
uses: actions/download-artifact@v4
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
with:
name: charts
@@ -132,7 +138,7 @@ jobs:
git push origin ${{ needs.setup-target-branch.outputs.target_branch }}
- name: Run Helm chart releaser
uses: helm/chart-releaser-action@v1.7.0
uses: helm/chart-releaser-action@cae68fefc6b5f367a0275617c9f83181ba54714f # v1.7.0
with:
charts_dir: ./charts
env:
@@ -17,7 +17,7 @@ jobs:
release_tag: ${{ steps.determine_tag.outputs.release_tag }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- name: Determine release tag
id: determine_tag
@@ -33,7 +33,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- name: Check package version
env:
TAG_VERSION: ${{ github.event.release.tag_name }}
@@ -43,12 +43,10 @@ jobs:
needs:
- setup-release-tag
- check-version
uses: rancher/dashboard/.github/workflows/build-extension-charts.yml@master
uses: rancher/dashboard/.github/workflows/build-extension-charts.yml@9bf23dff6650116673346447bcf0b088e0edb27f # creators-pkg-v3.0.12
permissions:
actions: write
contents: write
deployments: write
pages: write
pull-requests: write
with:
target_branch: gh-pages
tagged_release: '${{ needs.setup-release-tag.outputs.release_tag }}'
@@ -1,6 +1,7 @@
name: Build Standalone on PR Merge
on:
workflow_dispatch: # manually trigger on Github Actions only support PR branch pushed to harvester/harvester-ui-extension
push:
branches:
- main
@@ -29,3 +30,35 @@ jobs:
id-token: write
with:
CI_BRANCH: ${{github.ref_name}}
comment-on-pr:
name: Comment build result on PR
# Only for manual runs so the existing push / pull_request flows are untouched.
if: github.event_name == 'workflow_dispatch'
needs:
- build
runs-on: ubuntu-latest
permissions:
pull-requests: write
steps:
- name: Add build artifact comment to the PR opened from this branch
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
BRANCH: ${{ github.ref_name }}
run: |
set -euo pipefail
# Match scripts/version: sanitize the branch and map main -> latest.
if [ "$BRANCH" = "main" ]; then
DIR="latest"
else
DIR=$(printf '%s' "$BRANCH" | sed -E 's/[^a-zA-Z0-9.-]+/-/g')
fi
URL="https://releases.rancher.com/harvester-ui/dashboard/${DIR}/index.html"
PR=$(gh pr list --repo "$GITHUB_REPOSITORY" --state open --base main --head "$BRANCH" --json number --jq '.[0].number // empty')
if [ -z "$PR" ]; then
echo "No open PR found for branch $BRANCH, skipping comment."
exit 0
fi
BODY=$(printf '🚀 **UI Artifact Build Status:** `SUCCESS` ✅\n> ui-index: %s\n> ui-source: external' "$URL")
gh pr comment "$PR" --repo "$GITHUB_REPOSITORY" --body "$BODY"
@@ -9,7 +9,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- name: Check package version
env:
TAG_VERSION: ${{github.ref_name}}
+3 -3
View File
@@ -15,18 +15,18 @@ jobs:
timeout-minutes: 30
steps:
- name: Checkout
uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
# The FOSSA token is shared between all repos in Harvester's GH org. It can
# be used directly and there is no need to request specific access to EIO.
- name: Read FOSSA token
uses: rancher-eio/read-vault-secrets@main
uses: rancher-eio/read-vault-secrets@d266f55186f80a893839f6e15662e67388e443e6 # v3
with:
secrets: |
secret/data/github/org/harvester/fossa/credentials token | FOSSA_API_KEY_PUSH_ONLY
- name: FOSSA scan
uses: fossas/fossa-action@main
uses: fossas/fossa-action@ff70fe9fe17cbd2040648f1c45e8ec4e4884dcf3 # v1.9.0
with:
api-key: ${{ env.FOSSA_API_KEY_PUSH_ONLY }}
# Only runs the scan and do not provide/returns any results back to the
-30
View File
@@ -1,30 +0,0 @@
name: "[PR Management] Add PR Label"
on:
pull_request_target:
types: [opened, reopened, edited]
branches:
- main
- 'release-harvester-v*'
permissions:
pull-requests: write
jobs:
auto-assign-pr-label:
if: github.event.pull_request.draft == false
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
ref: ${{ github.base_ref }}
- name: Setup Nodejs and yarn install
uses: ./.github/actions/setup
- name: Set PR label
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
PR_LABEL=$(node ./scripts/extract-release-label.mjs "${{ github.event.pull_request.title }}")
echo "PR_LABEL = $PR_LABEL"
gh pr edit ${{ github.event.pull_request.number }} --repo ${{ github.repository }} --add-label "$PR_LABEL"
+10 -2
View File
@@ -1,7 +1,7 @@
name: Tests
on:
workflow_call: # This tells GH that the workflow is reusable
workflow_call: # This tells GH that the workflow is reusable
push:
branches:
- main
@@ -16,7 +16,7 @@ jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with:
fetch-depth: 0 # Need full history for commit-lint
@@ -71,3 +71,11 @@ jobs:
GITHUB_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
GITHUB_BEFORE: ${{ github.event.before }}
GITHUB_AFTER: ${{ github.event.after }}
unit-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- name: Run unit tests
uses: ./.github/actions/test
+1 -1
View File
@@ -1 +1 @@
20
24
+286
View File
@@ -0,0 +1,286 @@
> This `./AGENTS.md` file is generated by running `yarn agents:generate`. `CLAUDE.md` and `GEMINI.md` are symlinks to this file so Claude Code, GitHub Copilot and Gemini all read the same content.
# Project Overview
The Harvester UI Extension is a Rancher extension that provides the user interface for Harvester within the Rancher Dashboard.
```
Note: This extension is available starting from Rancher 2.10.0. Ensure your Rancher version is 2.10.0 or later to access Harvester integration.
```
# Personas
## Software Developer
You are an expert Senior Software Engineer specializing in Vue.js and TypeScript. You have deep knowledge of Kubernetes and the Rancher ecosystem.
- **Focus**: Writing clean, maintainable, and performant code.
- **Priorities**: Adhering to the project's code style, ensuring type safety, and following best practices for component design.
# Agents
## Boundaries
- ✅ **Always:**
- Write to `.github`, `docs/`, `pkg/harvester`, `scripts/`.
- Make commits in a new branch (for a PR).
- Run `yarn lint:fix` before commits.
- Use conventional commit format:
```
<type>: <description>
```
- Follow existing naming conventions (PascalCase for components, camelCase for functions).
- After changing a Vue, JS, or TS file, make sure it's automatically formatted with ESLint.
- After updating files in `docs/agents.md/`, run `yarn agents:generate` to update root `AGENTS.md`.
- ⚠️ **Ask first:**
- Adding dependencies
- Upgrading dependencies
- 🚫 **Never:**
- Commit or log secrets, `.env`, `kubeconfig` or any API keys.
- Edit `node_modules/`.
- Commit directly to `main` (use PRs).
- Skip git hooks with `--no-verify` flag.
## Tools
### Prerequisites
- **Node.js**: `>= 24.0.0` (see `.nvmrc` for the pinned version: `24`)
- **Package manager**: `yarn` (v1 classic)
### Common Commands
| Command | Description |
|---------|-------------|
| `yarn install --frozen-lockfile` | Install dependencies (CI-safe, no lockfile changes) |
| `RANCHER_ENV=harvester API=https://<harvester-ip> yarn dev` | Start development server at `https://127.0.0.1:8005` |
| `yarn build-pkg harvester` | Build the Harvester extension package |
| `yarn serve-pkgs` | Serve the locally built extension for testing |
| `yarn lint` | Run ESLint (zero warnings allowed) |
| `yarn lint:fix` | Run ESLint with auto-fix |
| `yarn test` | Run the unit tests (Jest) in watch mode |
| `yarn test:ci` | Run the unit tests once, as CI does (silent) |
| `yarn clean` | Clean build artifacts |
| `yarn agents:generate` | Regenerate `AGENTS.md` from `docs/agents.md/` sources |
### Development
- **Start dev server**:
```bash
RANCHER_ENV=harvester API=https://your-harvester-ip yarn dev
```
- `API` should point to a running Harvester cluster (e.g., `https://x.x.x.x`).
- The dashboard will be available at `https://127.0.0.1:8005`.
### Building
- **Build extension package**:
```bash
yarn build-pkg harvester
```
- **Serve locally built extension** (for integration testing with a Rancher instance):
```bash
yarn serve-pkgs
```
### Linting
- **Check** (must pass with zero warnings):
```bash
yarn lint
```
- **Auto-fix**:
```bash
yarn lint:fix
```
- ESLint covers `.js`, `.ts`, and `.vue` files.
- Always run `yarn lint:fix` before committing.
### Unit Tests
- **Run**:
```bash
yarn test
```
- `yarn test` starts Jest in watch mode (like in the Rancher dashboard) and only runs the tests related to changed files. It does not exit, so use `yarn test:ci` for a single run of all tests, e.g. in scripts.
- CI runs `yarn test:ci` on every pull request.
- See the Unit Tests section of the Contributors Guide for how the tests are set up.
### Commit Conventions
- Commits are validated by [commitlint](https://commitlint.js.org/) via a Husky `commit-msg` hook.
- Follow [Conventional Commits](https://www.conventionalcommits.org/) format (configured in `commitlint.config.js`).
### Agent Documentation
- Source files live in `docs/agents.md/` (agents, contributors, personas subdirectories).
- After editing any source file, regenerate the root `AGENTS.md`:
```bash
yarn agents:generate
```
# Contributors Guide
## Getting Started
Please see the [Harvester UI Extension README](https://github.com/harvester/harvester-ui-extension).
To get started, follow the `Development Setup` section.
## Project Information
- **Tech Stack:**
- `Vue.js`: Framework
- `Linting`: ESLint
- `CSS`: SCSS should be used
- `TypeScript`: Primary language for logic.
- **Code Style and Standards:**
- `Language`: TypeScript is preferred for new code.
- `Vue.js`:
- Composition API components are preferred over Options API.
- Large pages with lots of code and styles should be avoided by breaking the page up into smaller Vue components.
- Order the Single File Component blocks as `<script>`, then `<template>`, then `<style>`.
- The `<style>` tag should include `lang="scss" scoped`.
- `Linting`: Follow the ESLint configuration in the root.
- **File Structure:**
- `.github/`: CI/CD workflows and Renovate config.
- `docs/`: Documentation source for `AGENTS.md` generation.
- `scripts/`: Bash scripts for build, CI and doc generation.
- `pkg/harvester/`: Main extension source. Files are named after K8s resource types (e.g., `kubevirt.io.virtualmachine`, `harvesterhci.io.volume`).
- `index.ts`: Plugin entry point — registers the product and auto-imports models/detail/edit views.
- `types.ts`: `HCI` constant mapping 60+ K8s resource types to string identifiers.
- `components/`: Reusable Vue components (VNC/serial console, settings panels, upgrade banners, filters).
- `config/`: Constants — settings keys, table column definitions, feature flags, type mappings, doc links.
- `detail/`: Read-only detail views per resource type. Complex resources use subdirectories with tabs.
- `dialog/`: Modal dialogs for operations (VM clone/migrate/restart, backup/restore, device passthrough, etc.).
- `edit/`: Create/edit forms. Complex resources (e.g., VM) split into subcomponents (CpuMemory, Network, Volume, CloudConfig, etc.).
- `formatters/`: Table cell formatters — state badges, usage bars, resource references.
- `l10n/`: Localization (`en-us.yaml`).
- `list/`: List (table) views per resource type, mirroring `detail/` and `edit/` naming.
- `mixins/`: Shared Vue mixins — VM helpers (`harvester-vm/`) and disk helpers (`harvester-disk.js`).
- `models/`: Model classes extending `SteveModel` with computed properties and actions. Base class: `harvester.js`.
- `pages/`: Route-level pages — dashboard, support, console, members, brand, alertmanager.
- `promptRemove/`: Custom delete-confirmation dialogs (VM, backup).
- `routing/`: Vue Router config — all product routes (CRUD, console, support, upgrade, etc.).
- `store/`: Vuex modules — `harvester-common.js` for shared state; `harvester-store/` for VM/resource creation actions with Steve integration.
- `styles/`: Global SCSS files.
- `utils/`: Helpers — VM volume templates, CPU/memory calc, cron parsing, regex validators, feature flags.
- `validators/`: Form validation functions per resource type, pushing i18n error messages.
## Harvester UI Extension Development Guide
### Backward Compatibility
The Harvester UI Extension supports earlier cluster versions (e.g., UI Ext v1.8.0 works with clusters v1.7.0 and v1.6.0). It uses Feature Flags defined in `pkg/harvester/config/` to ensure the UI matches the cluster's specific version.
### Implementation Steps for New Features
To add a feature in a new release, follow these steps:
1. **Register**: Add a unique `[Feature Name]` to the corresponding release array in the configuration.
2. **Check**: Use the following getter to verify if the feature is enabled for the current version:
```js
computed: {
newFeatureEnabled() {
return this.$store.getters['harvester-common/getFeatureEnabled']('[Feature Name]');
},
},
```
3. **Render**: Use the result of the check to conditionally render the UI components.
## E2E Tests (Cypress)
See https://github.com/harvester/harvester-ui-tests
## Unit Tests (Jest)
Unit and component tests run with [Jest](https://jestjs.io/). The setup follows the Rancher dashboard and the Rancher extension template ([rancher/ui-plugin-examples](https://github.com/rancher/ui-plugin-examples)), so both stay aligned.
- Run the tests in watch mode with `yarn test`, all tests once with `yarn test:ci`, a single file with `yarn test <path>`. CI runs `yarn test:ci` on every pull request.
- Test files live next to the code in `__tests__` folders and are named `<name>.test.js` or `<name>.test.ts`.
- Configuration:
- `jest.config.js`: environment, module aliases (`@shell`, `@components`, `@pkg`) and transforms.
- `jest.setup.js`: global mocks (`t`, `$store`, common directives) and browser APIs that jsdom does not provide.
- `vue3JestRegisterTs.js`: makes TypeScript available to the Vue compiler, otherwise `.vue` files with typed props fail to compile.
- Components are tested with the Vue Test Utils 2 API: use `props` and `global.mocks`, not the Vue 2 options `propsData` and `mocks`.
- Models and utils can be tested without mounting anything, see `pkg/harvester/models/__tests__` for examples.
## Node Dependencies
Dependencies are managed via `package.json` and `yarn`
- To install dependencies use `yarn install`. This will fail if dependencies and versions listed in `package.json` are out of step with the `yarn.lock` file
- To add a dependency use `yarn run add:no-lock ...` instead of `yarn add`
- To upgrade a dependency use `yarn run upgrade:no-lock ...` instead of `yarn upgrade`
Renovate automatically updates dependencies and opens upgrade PRs after 10:00 AM on Sundays (`Asia/Taipei`).
For the Renovate config, see `.github/renovate.json`.
## Milestone guidance
- All issues must first be resolved in the `main` branch
- If backports are needed they can be made via the backport bot
- pull requests
- comment `@Mergifyio backport <target branch>` e.g. `@Mergifyio backport release-harvester-v1.8`
- All backported pull requests must link to a backported issue
## Creating a branch
### To resolve an issue
- Checkout the branch matching the milestone of the issue `git checkout ${targetMilestoneBranch}`. Replace `${targetMilestoneBranch}` with the target milestone of the issue. For example
- `main` for the latest unreleased minor version
- `release-harvester-v.X` for release minor versions
- `release-harvester-v1.6`
- `release-harvester-v1.7`
- `release-harvester-v1.8`
- Ensure you have the latest of that branch `git pull --rebase`
- Checkout the branch to commit the changes to `git checkout issue-${issueNumber}`. Replace `${issueNumber}` with the issue number.
## Creating a commit
- This project uses commit-lint with [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) to ensure consistent and meaningful commit messages.
### Commit Message Format
All commit messages must follow the conventional commit format:
```
<type>: <description>
[optional body]
[optional footer(s)]
```
### Supported Types
- feat: New features
- fix: Bug fixes
- docs: Documentation changes
- style: Code style changes (formatting, missing semicolons, etc.)
- refactor: Code refactoring
- perf: Performance improvements
- test: Adding or updating tests
- build: Build system or external dependencies
- ci: CI/CD changes
- chore: Other changes that don't modify src or test files
- revert: Reverts a previous commit
- wip: Work in progress
- deps: Dependency updates
- security: Security fixes
## Creating a Pull Request
- Pull requests must come from forks
- Description should always have commit supported type prefix. E.g `fix: XXX`, `feat: OOO`
- A Pull Request will only be merged once
- ALL CI gates have passed
- At least one harvester/harvester-ui-extension code owners reviews and approves the PR
Symlink
+1
View File
@@ -0,0 +1 @@
./AGENTS.md
+2
View File
@@ -0,0 +1,2 @@
@a110605
@houhoucoop
Symlink
+1
View File
@@ -0,0 +1 @@
./AGENTS.md
+22 -2
View File
@@ -5,14 +5,27 @@ The Harvester UI Extension is a Rancher extension that provides the user interfa
> **Note:**
> This extension is available starting from **Rancher 2.10.0**. Ensure your Rancher version is **2.10.0 or later** to access Harvester integration.
## Table of Contents
- [Installation](#installation)
- [Development Setup](#development-setup)
- [Commit Message Guidelines](#commit-message-guidelines)
- [Branch Structure](#branch-structure)
- [Testing Guidelines](#testing-guidelines)
- [Release](#release)
- [Contributing](#contributing)
- [License](#license)
## Installation
For detailed installation instructions, please refer to the [official Harvester documentation](https://docs.harvesterhci.io/v1.5/rancher/harvester-ui-extension#installation-on-rancher-210).
For Harvester UI extension installation instructions, please refer to the page **Rancher Integration** -> **Harvester UI Extension** in [official Harvester documentation](https://docs.harvesterhci.io).
## Development Setup
Ensure **Node.js v20 or later** is installed for development and debugging.
Ensure **Node.js v24 or later** is installed for development and debugging.
### Standalone Mode
@@ -157,6 +170,13 @@ To test the standalone UI, configure Harvester to load the UI from an external s
2. Set **ui-source** to `External`
3. Set **ui-index** to the desired URL
## Release
The Harvester UI Extension follows the [Harvester](https://github.com/harvester/harvester) release cycle. After RC1 is cut for a new Harvester version, we usually create and work from the corresponding release branch (for example, `release-harvester-v1.8`). The remaining RC builds and the final official release are published from that branch.
After Harvester releases a new version, update the Harvester entry in rancher/ui-plugin-charts [manifest.json](https://github.com/rancher/ui-plugin-charts/blob/aafd215debbc6cb3100e7ba4b0a542c932397acd/manifest.json#L133-L151). This ensures air-gapped users can pull the new Harvester UI Extension image.
## Contributing
If you want to contribute, start by reading this document, then visit our [Getting Started guide](https://extensions.rancher.io/extensions/next/extensions-getting-started) to learn how to develop and submit changes.
+3 -2
View File
@@ -32,10 +32,11 @@ module.exports = {
'subject-empty': [2, 'never'],
'subject-full-stop': [2, 'never', '.'],
'subject-max-length': [0, 'never'],
'header-max-length': [0, 'always', 100],
'body-leading-blank': [2, 'always'],
'body-max-line-length': [2, 'always', 100],
'body-max-line-length': [0, 'always', 100],
'footer-leading-blank': [2, 'always'],
'footer-max-line-length': [2, 'always', 100],
'footer-max-line-length': [0, 'always', 100],
},
// Ignore merge commits and revert commits
ignores: [
+63
View File
@@ -0,0 +1,63 @@
# Agents.md
This folder contains files used to construct a single root `AGENTS.md`
We do this because
- The single commonality between almost all AI tools is that they look for a root `AGENTS.md`
- Having the information in a single place for all AI tools is better than duplicating and maintaining the information in multiple files for each AI tool
## Process
1. Add files to or update files in `./docs/agents.md/agents`, `./docs/agents.md/personas`, `./docs/agents.md/contributors`.
2. Each file must
- Start markdown headers at the `##` level
- End in a new line
- Order contents in AGENTS.md by giving an optional number prefix
3. Run `yarn agents:generate`.
- Take the contents of `./docs/agents.md/template_agents.md`
- Insert the contents of the agents, personas and contributors files
- Output to `./AGENTS.md`
4. Commit all changes, including root `./AGENTS.md` and any files that link to it
## Guidance
### Examples
When referencing code or configuration it's good to include an example
## Future Tasks
- Add real world examples when referencing code
- Create a GH workflow to monitor `agents.md` folder files in a PR, if changed run generate script and add new AGENTS.md to PR
- Discuss
- Three multi AI tool related questions
- Questions
- how AI specific patterns, like co-pilot instructions, can be expressed in a way to be adopted by or reduce duplication with the root agents.md
- how AI tool specific metadata code can be included
- multiple agents vs personas approach works
- Proposal
- Generic information applicable to all AI tools is added to the root `agents.md`
- Agent, instruction or other AI specific files or patterns can be used in files specific to that AI tool. They must not contain duplicate information to the root `agents.md`
- The root `agents.md` continues to be AI tool agnostic
- How can folder specific agents be used
- Proposal
- `agents.md` are added to folders as long as most LLMs can make use of them and they do not duplicate information in the root `agents.md`
## Test Prompts
To validate LLMs are picking up information consider running the following prompts.
### Information
Can they provide correct information?
- `what's this project about?`
- `can you tell me the process for fixing a github issue in this repo?`
- `what makes a good software developer?`
- `what should never be done in this project?`
- `what are the folders in this project for?`
- `what are the env vars i could use when running e2e tests?`
### Actions
Can they use the information in their actions?
Pending
+21
View File
@@ -0,0 +1,21 @@
## Boundaries
- ✅ **Always:**
- Write to `.github`, `docs/`, `pkg/harvester`, `scripts/`.
- Make commits in a new branch (for a PR).
- Run `yarn lint:fix` before commits.
- Use conventional commit format:
```
<type>: <description>
```
- Follow existing naming conventions (PascalCase for components, camelCase for functions).
- After changing a Vue, JS, or TS file, make sure it's automatically formatted with ESLint.
- After updating files in `docs/agents.md/`, run `yarn agents:generate` to update root `AGENTS.md`.
- ⚠️ **Ask first:**
- Adding dependencies
- Upgrading dependencies
- 🚫 **Never:**
- Commit or log secrets, `.env`, `kubeconfig` or any API keys.
- Edit `node_modules/`.
- Commit directly to `main` (use PRs).
- Skip git hooks with `--no-verify` flag.
+77
View File
@@ -0,0 +1,77 @@
## Tools
### Prerequisites
- **Node.js**: `>= 24.0.0` (see `.nvmrc` for the pinned version: `24`)
- **Package manager**: `yarn` (v1 classic)
### Common Commands
| Command | Description |
|---------|-------------|
| `yarn install --frozen-lockfile` | Install dependencies (CI-safe, no lockfile changes) |
| `RANCHER_ENV=harvester API=https://<harvester-ip> yarn dev` | Start development server at `https://127.0.0.1:8005` |
| `yarn build-pkg harvester` | Build the Harvester extension package |
| `yarn serve-pkgs` | Serve the locally built extension for testing |
| `yarn lint` | Run ESLint (zero warnings allowed) |
| `yarn lint:fix` | Run ESLint with auto-fix |
| `yarn test` | Run the unit tests (Jest) in watch mode |
| `yarn test:ci` | Run the unit tests once, as CI does (silent) |
| `yarn clean` | Clean build artifacts |
| `yarn agents:generate` | Regenerate `AGENTS.md` from `docs/agents.md/` sources |
### Development
- **Start dev server**:
```bash
RANCHER_ENV=harvester API=https://your-harvester-ip yarn dev
```
- `API` should point to a running Harvester cluster (e.g., `https://x.x.x.x`).
- The dashboard will be available at `https://127.0.0.1:8005`.
### Building
- **Build extension package**:
```bash
yarn build-pkg harvester
```
- **Serve locally built extension** (for integration testing with a Rancher instance):
```bash
yarn serve-pkgs
```
### Linting
- **Check** (must pass with zero warnings):
```bash
yarn lint
```
- **Auto-fix**:
```bash
yarn lint:fix
```
- ESLint covers `.js`, `.ts`, and `.vue` files.
- Always run `yarn lint:fix` before committing.
### Unit Tests
- **Run**:
```bash
yarn test
```
- `yarn test` starts Jest in watch mode (like in the Rancher dashboard) and only runs the tests related to changed files. It does not exit, so use `yarn test:ci` for a single run of all tests, e.g. in scripts.
- CI runs `yarn test:ci` on every pull request.
- See the Unit Tests section of the Contributors Guide for how the tests are set up.
### Commit Conventions
- Commits are validated by [commitlint](https://commitlint.js.org/) via a Husky `commit-msg` hook.
- Follow [Conventional Commits](https://www.conventionalcommits.org/) format (configured in `commitlint.config.js`).
### Agent Documentation
- Source files live in `docs/agents.md/` (agents, contributors, personas subdirectories).
- After editing any source file, regenerate the root `AGENTS.md`:
```bash
yarn agents:generate
```
@@ -0,0 +1,72 @@
## Getting Started
Please see the [Harvester UI Extension README](https://github.com/harvester/harvester-ui-extension).
To get started, follow the `Development Setup` section.
## Project Information
- **Tech Stack:**
- `Vue.js`: Framework
- `Linting`: ESLint
- `CSS`: SCSS should be used
- `TypeScript`: Primary language for logic.
- **Code Style and Standards:**
- `Language`: TypeScript is preferred for new code.
- `Vue.js`:
- Composition API components are preferred over Options API.
- Large pages with lots of code and styles should be avoided by breaking the page up into smaller Vue components.
- Order the Single File Component blocks as `<script>`, then `<template>`, then `<style>`.
- The `<style>` tag should include `lang="scss" scoped`.
- `Linting`: Follow the ESLint configuration in the root.
- **File Structure:**
- `.github/`: CI/CD workflows and Renovate config.
- `docs/`: Documentation source for `AGENTS.md` generation.
- `scripts/`: Bash scripts for build, CI and doc generation.
- `pkg/harvester/`: Main extension source. Files are named after K8s resource types (e.g., `kubevirt.io.virtualmachine`, `harvesterhci.io.volume`).
- `index.ts`: Plugin entry point — registers the product and auto-imports models/detail/edit views.
- `types.ts`: `HCI` constant mapping 60+ K8s resource types to string identifiers.
- `components/`: Reusable Vue components (VNC/serial console, settings panels, upgrade banners, filters).
- `config/`: Constants — settings keys, table column definitions, feature flags, type mappings, doc links.
- `detail/`: Read-only detail views per resource type. Complex resources use subdirectories with tabs.
- `dialog/`: Modal dialogs for operations (VM clone/migrate/restart, backup/restore, device passthrough, etc.).
- `edit/`: Create/edit forms. Complex resources (e.g., VM) split into subcomponents (CpuMemory, Network, Volume, CloudConfig, etc.).
- `formatters/`: Table cell formatters — state badges, usage bars, resource references.
- `l10n/`: Localization (`en-us.yaml`).
- `list/`: List (table) views per resource type, mirroring `detail/` and `edit/` naming.
- `mixins/`: Shared Vue mixins — VM helpers (`harvester-vm/`) and disk helpers (`harvester-disk.js`).
- `models/`: Model classes extending `SteveModel` with computed properties and actions. Base class: `harvester.js`.
- `pages/`: Route-level pages — dashboard, support, console, members, brand, alertmanager.
- `promptRemove/`: Custom delete-confirmation dialogs (VM, backup).
- `routing/`: Vue Router config — all product routes (CRUD, console, support, upgrade, etc.).
- `store/`: Vuex modules — `harvester-common.js` for shared state; `harvester-store/` for VM/resource creation actions with Steve integration.
- `styles/`: Global SCSS files.
- `utils/`: Helpers — VM volume templates, CPU/memory calc, cron parsing, regex validators, feature flags.
- `validators/`: Form validation functions per resource type, pushing i18n error messages.
## Harvester UI Extension Development Guide
### Backward Compatibility
The Harvester UI Extension supports earlier cluster versions (e.g., UI Ext v1.8.0 works with clusters v1.7.0 and v1.6.0). It uses Feature Flags defined in `pkg/harvester/config/` to ensure the UI matches the cluster's specific version.
### Implementation Steps for New Features
To add a feature in a new release, follow these steps:
1. **Register**: Add a unique `[Feature Name]` to the corresponding release array in the configuration.
2. **Check**: Use the following getter to verify if the feature is enabled for the current version:
```js
computed: {
newFeatureEnabled() {
return this.$store.getters['harvester-common/getFeatureEnabled']('[Feature Name]');
},
},
```
3. **Render**: Use the result of the check to conditionally render the UI components.
@@ -0,0 +1,3 @@
## E2E Tests (Cypress)
See https://github.com/harvester/harvester-ui-tests
@@ -0,0 +1,12 @@
## Unit Tests (Jest)
Unit and component tests run with [Jest](https://jestjs.io/). The setup follows the Rancher dashboard and the Rancher extension template ([rancher/ui-plugin-examples](https://github.com/rancher/ui-plugin-examples)), so both stay aligned.
- Run the tests in watch mode with `yarn test`, all tests once with `yarn test:ci`, a single file with `yarn test <path>`. CI runs `yarn test:ci` on every pull request.
- Test files live next to the code in `__tests__` folders and are named `<name>.test.js` or `<name>.test.ts`.
- Configuration:
- `jest.config.js`: environment, module aliases (`@shell`, `@components`, `@pkg`) and transforms.
- `jest.setup.js`: global mocks (`t`, `$store`, common directives) and browser APIs that jsdom does not provide.
- `vue3JestRegisterTs.js`: makes TypeScript available to the Vue compiler, otherwise `.vue` files with typed props fail to compile.
- Components are tested with the Vue Test Utils 2 API: use `props` and `global.mocks`, not the Vue 2 options `propsData` and `mocks`.
- Models and utils can be tested without mounting anything, see `pkg/harvester/models/__tests__` for examples.
@@ -0,0 +1,12 @@
## Node Dependencies
Dependencies are managed via `package.json` and `yarn`
- To install dependencies use `yarn install`. This will fail if dependencies and versions listed in `package.json` are out of step with the `yarn.lock` file
- To add a dependency use `yarn run add:no-lock ...` instead of `yarn add`
- To upgrade a dependency use `yarn run upgrade:no-lock ...` instead of `yarn upgrade`
Renovate automatically updates dependencies and opens upgrade PRs after 10:00 AM on Sundays (`Asia/Taipei`).
For the Renovate config, see `.github/renovate.json`.
@@ -0,0 +1,58 @@
## Milestone guidance
- All issues must first be resolved in the `main` branch
- If backports are needed they can be made via the backport bot
- pull requests
- comment `@Mergifyio backport <target branch>` e.g. `@Mergifyio backport release-harvester-v1.8`
- All backported pull requests must link to a backported issue
## Creating a branch
### To resolve an issue
- Checkout the branch matching the milestone of the issue `git checkout ${targetMilestoneBranch}`. Replace `${targetMilestoneBranch}` with the target milestone of the issue. For example
- `main` for the latest unreleased minor version
- `release-harvester-v.X` for release minor versions
- `release-harvester-v1.6`
- `release-harvester-v1.7`
- `release-harvester-v1.8`
- Ensure you have the latest of that branch `git pull --rebase`
- Checkout the branch to commit the changes to `git checkout issue-${issueNumber}`. Replace `${issueNumber}` with the issue number.
## Creating a commit
- This project uses commit-lint with [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) to ensure consistent and meaningful commit messages.
### Commit Message Format
All commit messages must follow the conventional commit format:
```
<type>: <description>
[optional body]
[optional footer(s)]
```
### Supported Types
- feat: New features
- fix: Bug fixes
- docs: Documentation changes
- style: Code style changes (formatting, missing semicolons, etc.)
- refactor: Code refactoring
- perf: Performance improvements
- test: Adding or updating tests
- build: Build system or external dependencies
- ci: CI/CD changes
- chore: Other changes that don't modify src or test files
- revert: Reverts a previous commit
- wip: Work in progress
- deps: Dependency updates
- security: Security fixes
## Creating a Pull Request
- Pull requests must come from forks
- Description should always have commit supported type prefix. E.g `fix: XXX`, `feat: OOO`
- A Pull Request will only be merged once
- ALL CI gates have passed
- At least one harvester/harvester-ui-extension code owners reviews and approves the PR
@@ -0,0 +1,5 @@
## Software Developer
You are an expert Senior Software Engineer specializing in Vue.js and TypeScript. You have deep knowledge of Kubernetes and the Rancher ecosystem.
- **Focus**: Writing clean, maintainable, and performant code.
- **Priorities**: Adhering to the project's code style, ensuring type safety, and following best practices for component design.
+22
View File
@@ -0,0 +1,22 @@
> This `./AGENTS.md` file is generated by running `yarn agents:generate`. `CLAUDE.md` and `GEMINI.md` are symlinks to this file so Claude Code, GitHub Copilot and Gemini all read the same content.
# Project Overview
The Harvester UI Extension is a Rancher extension that provides the user interface for Harvester within the Rancher Dashboard.
```
Note: This extension is available starting from Rancher 2.10.0. Ensure your Rancher version is 2.10.0 or later to access Harvester integration.
```
# Personas
`<personas>`
# Agents
`<agents>`
# Contributors Guide
`<contributors>`
+46
View File
@@ -0,0 +1,46 @@
// Same settings in every environment, otherwise tests that format dates depend on the machine
process.env.TZ = 'UTC';
// The setup follows the one of the Rancher dashboard and of the Rancher extension template (rancher/ui-plugin-examples)
module.exports = {
roots: ['<rootDir>/pkg'],
testEnvironment: 'jsdom',
// Jest 28+ (jest-environment-jsdom) defaults package resolution to the "browser" export condition, which makes
// packages like @vue/test-utils resolve their browser (global-Vue) build and throw "Vue is not defined".
testEnvironmentOptions: { customExportConditions: ['node', 'node-addons'] },
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
watchman: false,
moduleFileExtensions: ['js', 'mjs', 'json', 'vue', 'ts'],
modulePaths: ['<rootDir>'],
moduleNameMapper: {
'^~/(.*)$': '<rootDir>/$1',
'^@/(.*)$': '<rootDir>/$1',
'^@shell/(.*)$': '<rootDir>/node_modules/@rancher/shell/$1',
'^@components/(.*)$': '<rootDir>/node_modules/@rancher/shell/rancher-components/$1',
// At build time @pkg/<path> is resolved to the package that imports it (see vue.config.js of @rancher/shell)
'^@pkg/harvester/(.*)$': '<rootDir>/pkg/harvester/$1',
'^@pkg/(.*)$': '<rootDir>/pkg/harvester/$1',
// clipboard-polyfill's package `exports` only declares an `import` condition, so map it to its ESM build
// (transpiled via transformIgnorePatterns below)
'^clipboard-polyfill$': '<rootDir>/node_modules/clipboard-polyfill/dist/es6/clipboard-polyfill.es6.js',
'\\.(jpe?g|png|gif|webp|svg|mp4|webm|ogg|mp3|wav|flac|aac|woff2?|eot|ttf|otf)$': '<rootDir>/svgTransform.js',
},
modulePathIgnorePatterns: ['<rootDir>/pkg/harvester/node_modules'],
testPathIgnorePatterns: ['<rootDir>/node_modules/', '<rootDir>(/.*)*/__tests__/utils/'],
transform: {
// vue3-jest, but with TypeScript registered for the Vue compiler first, see vue3JestRegisterTs.js
'^.+\\.vue$': '<rootDir>/vue3JestRegisterTs.js',
// isolatedModules: transpile only, the types are not checked while testing
'^.+\\.tsx?$': ['ts-jest', { tsconfig: { sourceMap: true, isolatedModules: true } }],
// Use the project babel config (babel.config.js, which extends the one of @rancher/shell)
'^.+\\.js$': '<rootDir>/node_modules/babel-jest',
// process mjs (e.g. vee-validate ESM) with babel-jest
'^.+\\.mjs$': '<rootDir>/node_modules/babel-jest',
'^.+\\.svg$': '<rootDir>/svgTransform.js',
},
transformIgnorePatterns: [
// @rancher/shell is shipped untranspiled, the other packages are ESM-only. @replit/codemirror-vim-core is
// required by the CommonJS build of @replit/codemirror-vim, which the shell's YamlEditor imports
'/node_modules/(?!(@rancher/shell|color|color-string|color-convert|color-name|vee-validate|@vee-validate|clipboard-polyfill|intl-messageformat|@formatjs|@replit/codemirror-vim-core)/)',
],
};
+106
View File
@@ -0,0 +1,106 @@
/* eslint-env jest */
import { createApp } from 'vue';
import { config } from '@vue/test-utils';
import i18n from '@shell/plugins/i18n';
import FloatingVue from 'floating-vue';
import { floatingVueOptions } from '@shell/plugins/floating-vue';
import vSelect from 'vue-select';
import cleanTooltipDirective from '@shell/directives/clean-tooltip';
import cleanHtmlDirective from '@shell/directives/clean-html';
import htmlStrippedAriaLabelDirective from '@shell/directives/strip-html-aria-label';
import '@shell/plugins/replaceall';
import { TextEncoder, TextDecoder } from 'util';
const vueApp = createApp({});
global.TextEncoder = TextEncoder;
global.TextDecoder = TextDecoder;
// vueApp.config.productionTip = false;
vueApp.use(i18n, { store: { dispatch() {} } });
vueApp.use(FloatingVue, floatingVueOptions);
vueApp.directive('clean-html', cleanHtmlDirective);
vueApp.directive('clean-tooltip', cleanTooltipDirective);
vueApp.component('v-select', vSelect);
config.global.components['v-select'] = vSelect;
config.global.plugins = [FloatingVue];
config.global.mocks['t'] = (key) => `%${ key }%`;
config.global.mocks['$store'] = {
getters: {},
dispatch: jest.fn(),
commit: jest.fn(),
};
config.global.directives = {
...config.global.directives,
t: {
mounted(el, binding) {
el.textContent = `%${ binding.value }%`;
},
updated(el, binding) {
el.textContent = `%${ binding.value }%`;
}
},
'clean-tooltip': cleanTooltipDirective,
'clean-html': cleanHtmlDirective,
'stripped-aria-label': htmlStrippedAriaLabelDirective,
};
config.global.stubs['t'] = { template: '<span><slot /></span>' };
/**
* Global configuration for Jest tests
*/
beforeAll(() => {
// matchMedia and getContext methods aren't included in jest's version of jsdom for us to mock
// implemented as per jest documentation: https://jestjs.io/docs/manual-mocks#mocking-methods-which-are-not-implemented-in-jsdom
Object.defineProperty(window, 'matchMedia', {
value: jest.fn().mockImplementation(() => ({
addListener: jest.fn(),
removeListener: jest.fn(),
addEventListener: jest.fn(),
removeEventListener: jest.fn()
}))
});
Object.defineProperty(HTMLCanvasElement.prototype, 'getContext', {
value: jest.fn().mockImplementation(() => ({
createLinearGradient: jest.fn(),
fillRect: jest.fn(),
getImageData: jest.fn(() => ({ data: [] }))
}))
});
Object.defineProperty(window, 'IntersectionObserver', {
writable: true,
value: jest.fn().mockImplementation(() => ({
observe: jest.fn(),
unobserve: jest.fn(),
disconnect: jest.fn(),
})),
});
});
jest.mock('@shell/composables/useI18n', () => {
return {
useI18n() {
return { t: (key, options) => `${ key }${ options ? `-${ JSON.stringify(options) }` : '' }` };
}
};
});
// eslint-disable-next-line no-console
jest.spyOn(console, 'warn').mockImplementation((warning) => warning.includes('[Vue warn]') ? null : console.log(warning));
/**
* Common initialization for each test, required for resetting states
*/
beforeEach(() => {
// jest.resetModules(); // Use this function inside your test if you need to remove any cache stored
// jest.clearAllMocks(); // Use this function inside your test if you need to reset mocks
jest.restoreAllMocks(); // Use this function inside your test if you need to reset mocks and restore existing functionality
// Mock the $extension object
// config.mocks['$extension'] = { getDynamic: () => undefined };
config.global.mocks['$store'] = { getters: { 'i18n/t': jest.fn() } };
// Overrides some components
// config.stubs['my-component'] = { template: "<div></div> "};
});
+51 -14
View File
@@ -1,49 +1,78 @@
{
"name": "harvester-ui-extension",
"version": "1.8.0-dev",
"version": "1.10.0-dev",
"private": false,
"engines": {
"node": ">=20.0.0"
"node": ">=24.0.0"
},
"dependencies": {
"@babel/plugin-transform-class-static-block": "7.28.6",
"@rancher/shell": "3.0.9-rc.1",
"@babel/plugin-transform-class-static-block": "7.29.7",
"@novnc/novnc": "1.7.0",
"@rancher/shell": "3.0.14",
"@vue-flow/background": "^1.3.0",
"@vue-flow/controls": "^1.1.1",
"@vue-flow/core": "^1.33.5",
"@vue-flow/minimap": "^1.4.0",
"cache-loader": "^4.1.0",
"color": "4.2.3",
"ip": "2.0.1",
"@xterm/xterm": "6.0.0",
"@xterm/addon-fit": "0.11.0",
"@xterm/addon-search": "0.16.0",
"@xterm/addon-web-links": "0.12.0",
"@xterm/addon-webgl": "0.19.0",
"@xterm/addon-canvas": "0.7.0",
"node-polyfill-webpack-plugin": "^3.0.0",
"elkjs": "^0.11.0",
"vue-draggable-next": "^2.2.1",
"yaml": "^2.5.1"
},
"resolutions": {
"@types/node": "~20.19.0",
"@novnc/novnc": "1.7.0",
"@tootallnate/once": "^2.0.1",
"@types/lodash": "4.17.25",
"@types/node": "25.3.3",
"cookie": "0.7.2",
"cronstrue": "2.59.0",
"d3-color": "3.1.0",
"**/diff2html/diff": "5.2.2",
"ejs": "3.1.10",
"follow-redirects": "1.15.11",
"follow-redirects": "1.16.0",
"glob": "7.2.3",
"glob-parent": "6.0.2",
"json5": "2.2.3",
"@types/lodash": "4.17.23",
"markdown-it": "14.3.1",
"merge": "2.1.1",
"node-forge": "1.3.3",
"node-forge": "1.4.3",
"nth-check": "2.1.1",
"qs": "6.14.1",
"roarr": "7.21.4",
"semver": "7.7.3",
"postcss": "8.5.26",
"postcss-selector-parser": "7.1.6",
"qs": "6.16.0",
"roarr": "7.21.7",
"semver": "7.5.4",
"serialize-javascript": "7.0.5",
"uuid": "11.1.1",
"webpack-dev-server": "5.2.6",
"ws": "8.21.0",
"@vue/cli-service/html-webpack-plugin": "^5.0.0"
},
"scripts": {
"dev": "NODE_ENV=dev ./node_modules/.bin/vue-cli-service serve",
"build": "./node_modules/.bin/vue-cli-service build",
"clean": "./node_modules/@rancher/shell/scripts/clean",
"lint": "./node_modules/.bin/eslint --max-warnings 0 --ext .js,.ts,.vue .",
"lint": "./node_modules/@rancher/shell/scripts/lint --max-warnings 0 --ext .js,.ts,.vue .",
"lint:fix": "./node_modules/@rancher/shell/scripts/lint --fix --max-warnings 0 --ext .js,.ts,.vue .",
"test": "jest --watch",
"test:ci": "NODE_OPTIONS=--max_old_space_size=8192 jest --silent",
"build-pkg": "./node_modules/@rancher/shell/scripts/build-pkg.sh",
"serve-pkgs": "./node_modules/@rancher/shell/scripts/serve-pkgs",
"publish-pkgs": "./node_modules/@rancher/shell/scripts/extension/publish",
"parse-tag-name": "./node_modules/@rancher/shell/scripts/extension/parse-tag-name",
"commitlint": "commitlint --edit",
"prepare": "husky"
"prepare": "husky",
"agents:generate": "./scripts/generate-agent-and-persona-mds.sh",
"prelint": "npm --prefix node_modules/@rancher/shell/eslint-legacy install eslint-plugin-jest@^24 --no-save --no-audit --no-fund --legacy-peer-deps --loglevel=error",
"prelint:fix": "npm --prefix node_modules/@rancher/shell/eslint-legacy install eslint-plugin-jest@^24 --no-save --no-audit --no-fund --legacy-peer-deps --loglevel=error"
},
"devDependencies": {
"@commitlint/load": "^19.8.1",
@@ -51,6 +80,14 @@
"@commitlint/config-conventional": "^19.8.1",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^7.1.0",
"husky": "^9.1.7"
"husky": "^9.1.7",
"@types/jest": "29.5.12",
"@vue/test-utils": "2.4.6",
"@vue/vue3-jest": "29.2.6",
"babel-jest": "29.7.0",
"babel-plugin-transform-require-context": "0.1.1",
"jest": "29.7.0",
"jest-environment-jsdom": "29.7.0",
"ts-jest": "29.4.12"
}
}
+1 -2
View File
@@ -7,8 +7,7 @@ The Harvester UI Extension is a Rancher extension that provides the user interfa
## Installation
For detailed installation instructions, please refer to the [official Harvester documentation](https://docs.harvesterhci.io/v1.5/rancher/harvester-ui-extension#installation-on-rancher-210).
For Harvester UI extension installation instructions, please refer to the page **Rancher Integration** -> **Harvester UI Extension** in [official Harvester documentation](https://docs.harvesterhci.io).
## Development Setup
File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 5.8 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 5.8 KiB

+5
View File
@@ -271,4 +271,9 @@ export default {
.filter-label .v-popper__arrow-container {
display: none;
}
.fixed-header-actions .middle .filter + .btn-group {
display: inline-flex;
vertical-align: middle;
}
</style>
@@ -116,6 +116,11 @@ export default {
.vm-schedule-dropdown .v-popper__arrow-container {
display: none;
}
.fixed-header-actions .middle .vm-schedule-filter + .btn-group {
display: inline-flex;
vertical-align: middle;
}
</style>
<style lang="scss" scoped>
@@ -0,0 +1,186 @@
<script>
import { Banner } from '@components/Banner';
import MatchExpressions from '@shell/components/form/MatchExpressions';
import ResourceTable from '@shell/components/ResourceTable';
import { _EDIT } from '@shell/config/query-params';
import { convert, simplify, matching as selectorMatching } from '@shell/utils/selector';
import throttle from 'lodash/throttle';
import { NODE } from '@shell/config/types';
import { NAME, AGE } from '@shell/config/table-headers';
export default {
name: 'HarvesterNodeSelector',
components: {
Banner,
MatchExpressions,
ResourceTable,
},
props: {
mode: {
type: String,
default: _EDIT,
},
value: {
type: Object,
required: true,
},
},
async fetch() {
this.updateMatchingResources();
},
data() {
const inStore = this.$store.getters['currentProduct'].inStore;
return {
matchingResources: {
matched: 0,
matches: [],
none: true,
sample: null,
total: 0,
},
tableHeaders: [
NAME,
{
name: 'host-ip',
labelKey: 'tableHeaders.hostIp',
search: ['internalIp'],
value: 'internalIp',
sort: ['internalIp'],
align: 'center',
},
{
name: 'cpuManager',
labelKey: 'harvester.tableHeaders.cpuManager',
value: 'id',
formatter: 'HarvesterCPUPinning',
width: 150,
align: 'center',
},
{
name: 'diskState',
labelKey: 'tableHeaders.diskState',
value: 'diskState',
formatter: 'HarvesterDiskState',
width: 130,
},
AGE,
],
inStore,
};
},
watch: {
value: {
handler: 'updateMatchingResources',
deep: true,
},
allResourcesInScope() {
this.updateMatchingResources();
},
},
computed: {
schema() {
return this.$store.getters[`${ this.inStore }/schemaFor`](NODE);
},
selectorExpressions: {
get() {
return convert(
this.value.matchLabels || {},
this.value.matchExpressions || []
);
},
set(selectorExpressions) {
const { matchLabels, matchExpressions } = simplify(selectorExpressions);
this.value['matchLabels'] = matchLabels;
this.value['matchExpressions'] = matchExpressions;
this.updateMatchingResources();
},
},
allNodes() {
return this.$store.getters[`${ this.inStore }/all`](NODE) || [];
},
allResourcesInScope() {
return this.allNodes.length;
},
},
methods: {
updateMatchingResources: throttle(function() {
const expressions = this.selectorExpressions;
const allNodes = this.allNodes;
// Empty expressions with no key = no match
const hasValidExpression = expressions.length > 0 && expressions.every((e) => !!e.key);
if (!hasValidExpression) {
this.matchingResources = {
matched: 0,
matches: [],
none: true,
sample: null,
total: allNodes.length,
};
return;
}
const matches = selectorMatching(allNodes, expressions, 'metadata.labels');
this.matchingResources = {
matched: matches.length,
matches,
none: matches.length === 0,
sample: matches[0]?.nameDisplay || null,
total: allNodes.length,
};
}, 100, { trailing: true })
},
};
</script>
<template>
<div>
<div class="row">
<div class="col span-12">
<MatchExpressions
v-model:value="selectorExpressions"
:mode="mode"
:show-remove="false"
:type="'node'"
:target-resources="allResourcesInScope"
/>
</div>
</div>
<div class="row">
<div class="col span-12">
<Banner :color="(matchingResources.none ? 'warning' : 'success')">
<span v-clean-html="t('generic.selectors.matchingResources.matchesSome', matchingResources)" />
</Banner>
</div>
</div>
<div class="row">
<div class="col span-12">
<ResourceTable
:rows="matchingResources.matches"
:headers="tableHeaders"
key-field="id"
:table-actions="false"
:row-actions="false"
:schema="schema"
:groupable="false"
:search="false"
/>
</div>
</div>
</div>
</template>
+34 -8
View File
@@ -55,8 +55,12 @@ export default {
!this.latestUpgrade.isUpgradeFailed;
},
canUpgrade() {
return this.versionOptions.length > 0 && !this.isUpgradeInProgress;
},
versionOptions() {
const versions = this.$store.getters['harvester/all'](HCI.VERSION);
const versions = this.$store.getters['harvester/all'](HCI.VERSION) || [];
return versions.map((V) => V.metadata.name);
},
@@ -124,6 +128,7 @@ export default {
try {
await proxyResource.save();
proxyResource.notifyGeneratedName?.();
this.cancel();
} catch (err) {
@@ -154,14 +159,23 @@ export default {
:cluster="currentCluster.nameDisplay"
/>
</h1>
<button
v-if="versionOptions.length && !isUpgradeInProgress"
type="button"
class="btn bg-warning btn-sm"
@click="open"
<span
v-clean-tooltip="{
content: canUpgrade ? t('harvester.upgradePage.upgradeAvailable') : t('harvester.upgradePage.upgradeUnavailable'),
triggers: ['hover', 'focus', 'touch'],
}"
class="upgrade-btn-wrap"
:tabindex="canUpgrade ? -1 : 0"
>
<t k="harvester.upgradePage.upgrade" />
</button>
<button
:disabled="!canUpgrade"
type="button"
class="btn bg-warning btn-sm"
@click="open"
>
<t k="harvester.upgradePage.upgrade" />
</button>
</span>
</header>
<ModalWithCard
@@ -296,6 +310,18 @@ export default {
line-height: 23px;
}
.upgrade-btn-wrap {
display: inline-flex;
button {
color: #000 !important;
}
button:hover {
color: #000 !important;
}
}
.currentVersion {
margin-top: 10px;
display: flex;
+59
View File
@@ -0,0 +1,59 @@
<script setup>
defineProps({
networkEntries: {
type: Array,
default: () => [],
},
storageEntries: {
type: Array,
default: () => [],
},
});
</script>
<template>
<div class="mappings-cell">
<div
v-for="(entry, idx) in networkEntries"
:key="'net-' + idx"
class="mapping-entry"
>
<i
class="icon icon-network"
aria-hidden="true"
/>
<span>{{ entry }}</span>
</div>
<div
v-for="(entry, idx) in storageEntries"
:key="'stor-' + idx"
class="mapping-entry"
>
<i
class="icon icon-datastore"
aria-hidden="true"
/>
<span>{{ entry }}</span>
</div>
</div>
</template>
<style lang="scss" scoped>
.mappings-cell {
display: flex;
flex-direction: column;
gap: 8px;
}
.mapping-entry {
display: flex;
align-items: center;
gap: 6px;
font-size: 13px;
color: var(--muted);
.icon {
font-size: 16px;
}
}
</style>
+1 -1
View File
@@ -122,7 +122,7 @@ export default {
return this.$store.getters['currentCluster'].isLocal;
},
canEditClusterMembers() {
return this.normanClusterRTBSchema?.collectionMethods.find((x) => x.toLowerCase() === 'post');
return this.schema?.collectionMethods.find((x) => x.toLowerCase() === 'post');
},
},
};
+442 -63
View File
@@ -1,7 +1,6 @@
<script>
import { allHash } from '@shell/utils/promise';
import debounce from 'lodash/debounce';
import Socket, {
EVENT_CONNECTED,
EVENT_CONNECTING,
@@ -22,74 +21,98 @@ export default {
data() {
return {
socket: null,
terminal: null,
fitAddon: null,
searchAddon: null,
webglAddon: null,
isOpen: false,
isOpening: false,
backlog: [],
firstTime: true,
queue: []
socket: null,
terminal: null,
textDecoder: null,
fitAddon: null,
searchAddon: null,
webglAddon: null,
onResize: null,
isOpen: false,
isOpening: false,
backlog: [],
firstTime: true,
queue: [],
isDraining: false,
drainScheduled: false,
drainTimer: null,
showSearch: false,
searchQuery: '',
searchOptions: {
caseSensitive: false,
regex: false,
wholeWord: false,
incremental: true,
decorations: {
matchBackground: '#B45309',
matchBorder: '#FDBA74',
matchOverviewRuler: '#FDBA74',
activeMatchBackground: '#EA580C',
activeMatchBorder: '#FED7AA',
activeMatchColorOverviewRuler: '#FED7AA',
},
},
};
},
computed: {
serialConsoleUrl() {
return this.value?.getSerialConsolePath || '';
},
xtermConfig() {
return {
allowProposedApi: true,
cursorBlink: true,
cursorStyle: 'bar',
cursorWidth: 2,
scrollback: 5000,
useStyle: true,
fontSize: 12,
fontFamily: 'JetBrains Mono, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',
fontSize: 16,
lineHeight: 1.3,
};
},
},
watch: {
queue: {
handler: debounce(async function(neu) {
if (neu.length === 0) {
return;
}
const msg = await Promise.all(neu);
(msg || []).forEach((m) => {
this.terminal.write(m);
});
this.queue = [];
}, 10),
deep: true
}
},
beforeUnmount() {
this.close();
},
watch: {
serialConsoleUrl() {
if (this.terminal) {
this.connect();
}
},
},
async mounted() {
this.textDecoder = new TextDecoder('utf-8');
await this.setupTerminal();
await this.connect();
this.onResize = debounce(() => this.fit(), 100);
window.addEventListener('resize', this.onResize);
this.scheduleFit();
},
methods: {
async setupTerminal() {
const docStyle = getComputedStyle(document.querySelector('body'));
const xterm = await import(/* webpackChunkName: "xterm" */ 'xterm');
const xterm = await import(/* webpackChunkName: "xterm" */ '@xterm/xterm');
const addons = await allHash({
fit: import(/* webpackChunkName: "xterm" */ 'xterm-addon-fit'),
webgl: import(/* webpackChunkName: "xterm" */ 'xterm-addon-webgl'),
weblinks: import(/* webpackChunkName: "xterm" */ 'xterm-addon-web-links'),
search: import(/* webpackChunkName: "xterm" */ 'xterm-addon-search'),
fit: import(/* webpackChunkName: "xterm" */ '@xterm/addon-fit'),
webgl: import(/* webpackChunkName: "xterm" */ '@xterm/addon-webgl'),
weblinks: import(/* webpackChunkName: "xterm" */ '@xterm/addon-web-links'),
search: import(/* webpackChunkName: "xterm" */ '@xterm/addon-search'),
canvas: import(/* webpackChunkName: "xterm" */ '@xterm/addon-canvas'),
});
const terminal = new xterm.Terminal({
theme: {
background: docStyle.getPropertyValue('--terminal-bg').trim(),
cursor: docStyle.getPropertyValue('--terminal-cursor').trim(),
cursor: docStyle.getPropertyValue('--terminal-text').trim(),
foreground: docStyle.getPropertyValue('--terminal-text').trim()
},
...this.xtermConfig,
@@ -97,25 +120,48 @@ export default {
this.fitAddon = new addons.fit.FitAddon();
this.searchAddon = new addons.search.SearchAddon();
try {
this.webglAddon = new addons.webgl.WebGlAddon();
} catch (e) {
// Some browsers (Safari) don't support the webgl renderer, so don't use it.
this.webglAddon = null;
}
terminal.loadAddon(this.fitAddon);
terminal.loadAddon(this.searchAddon);
terminal.loadAddon(new addons.weblinks.WebLinksAddon());
terminal.open(this.$refs.xterm);
if ( this.webglAddon ) {
// The webgl renderer can fail without throwing: the context may be lost
// mid-session, or it can attach but silently never paint, leaving the
// terminal's helper textarea at 0x0. Detect both cases and fall back to the
// canvas renderer so the terminal stays interactive.
try {
this.webglAddon = new addons.webgl.WebglAddon();
this.webglAddon.onContextLoss(() => {
if (!this.isUnmounted && this.terminal) {
this.fallbackToCanvas(terminal, addons);
}
});
terminal.loadAddon(this.webglAddon);
// Detect the silent "attaches but never paints" failure after a render frame.
requestAnimationFrame(() => {
if (this.isUnmounted || !this.terminal) {
return;
}
const textarea = this.$refs.xterm?.querySelector('.xterm-helper-textarea');
const hasPainted = textarea && textarea.getBoundingClientRect().height > 0;
if (this.webglAddon && !hasPainted) {
this.fallbackToCanvas(terminal, addons);
this.fit();
}
});
} catch (e) {
// Some browsers (e.g. Safari) don't support the webgl renderer, so don't use it.
this.fallbackToCanvas(terminal, addons);
}
this.fit();
this.flush();
this.scheduleDrainQueue();
terminal.onData((input) => {
const msg = this.str2ab(input);
@@ -123,9 +169,132 @@ export default {
this.write(msg);
});
terminal.attachCustomKeyEventHandler((event) => {
const key = event.key?.toLowerCase();
if ((event.ctrlKey || event.metaKey) && key === 'f') {
event.preventDefault();
this.openSearch();
return false;
}
if (key === 'escape' && this.showSearch) {
event.preventDefault();
this.closeSearch();
return false;
}
return true;
});
this.terminal = terminal;
},
openSearch() {
this.showSearch = true;
this.$nextTick(() => {
const input = this.$refs.searchInput;
if (input) {
input.focus();
input.select();
}
});
},
closeSearch() {
this.showSearch = false;
this.searchQuery = '';
this.clearSearchHighlights();
this.terminal?.focus();
},
clearSearchHighlights() {
this.searchAddon?.clearActiveDecoration();
this.searchAddon?.clearDecorations();
this.terminal?.clearSelection();
// Disposing the search decorations doesn't repaint the webgl/canvas
// layer, so force a refresh to remove the lingering highlight.
if (this.terminal) {
this.terminal.refresh(0, this.terminal.rows - 1);
}
},
findNext() {
if (!this.searchAddon || !this.searchQuery) {
return;
}
this.searchAddon.findNext(this.searchQuery, this.searchOptions);
},
findPrevious() {
if (!this.searchAddon || !this.searchQuery) {
return;
}
this.searchAddon.findPrevious(this.searchQuery, this.searchOptions);
},
onSearchInput() {
if (!this.searchQuery) {
this.clearSearchHighlights();
return;
}
this.findNext();
},
onSearchKeydown(event) {
if (event.key === 'Enter') {
event.preventDefault();
if (event.shiftKey) {
this.findPrevious();
} else {
this.findNext();
}
}
if (event.key === 'Escape') {
event.preventDefault();
this.closeSearch();
}
},
scheduleFit() {
this.$nextTick(() => {
requestAnimationFrame(() => {
this.fit();
// Re-fit after layout settles to avoid undersized rows on first paint.
setTimeout(() => this.fit(), 120);
});
});
},
// Dispose the webgl renderer (if any) and switch to the canvas renderer.
// Used when webgl fails to construct, loses its context, or silently never paints.
fallbackToCanvas(terminal, addons) {
if (this.isUnmounted) {
return;
}
this.webglAddon?.dispose();
this.webglAddon = null;
if (!this.canvasAddon) {
this.canvasAddon = new addons.canvas.CanvasAddon();
terminal.loadAddon(this.canvasAddon);
}
this.fit();
},
str2ab(str) {
const enc = new TextEncoder();
@@ -140,12 +309,131 @@ export default {
}
},
enqueueMessage(messagePromise) {
this.queue.push(messagePromise);
this.scheduleDrainQueue();
},
scheduleDrainQueue() {
if (this.drainScheduled || this.isDraining || !this.terminal) {
return;
}
this.drainScheduled = true;
const shouldDrainImmediately = this.queue.length <= 3;
const runDrain = () => {
this.drainScheduled = false;
this.drainTimer = null;
this.drainQueue();
};
if (shouldDrainImmediately) {
runDrain();
return;
}
this.drainTimer = requestAnimationFrame(runDrain);
},
async decodeMessageData(data) {
if (typeof data === 'string') {
return data;
}
if (!this.textDecoder) {
this.textDecoder = new TextDecoder('utf-8');
}
if (data instanceof Blob) {
const buffer = await data.arrayBuffer();
return this.textDecoder.decode(new Uint8Array(buffer), { stream: true });
}
if (data instanceof ArrayBuffer) {
return this.textDecoder.decode(new Uint8Array(data), { stream: true });
}
if (ArrayBuffer.isView(data)) {
const view = data;
const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
return this.textDecoder.decode(bytes, { stream: true });
}
return String(data || '');
},
async drainQueue() {
if (this.isDraining || !this.terminal) {
return;
}
this.isDraining = true;
try {
while (this.queue.length > 0) {
const pendingMessages = this.queue.splice(0, this.queue.length);
const settledMessages = await Promise.allSettled(pendingMessages);
const messages = settledMessages
.filter((result) => result.status === 'fulfilled')
.map((result) => result.value);
const output = messages.filter(Boolean).join('');
if (output) {
await this.writeOutputInChunks(output);
}
if (this.queue.length > 0) {
await this.nextFrame();
}
}
} finally {
this.isDraining = false;
// If data arrived between the last while-check and releasing the lock,
// immediately schedule another drain so output never gets stuck.
if (this.queue.length > 0 && this.terminal) {
this.scheduleDrainQueue();
}
}
},
async writeOutputInChunks(output) {
if (!output) {
return;
}
const chunkSize = output.length > 20000 ? 16000 : output.length > 8000 ? 8000 : output.length;
if (chunkSize === output.length) {
this.terminal.write(output);
return;
}
for (let index = 0; index < output.length; index += chunkSize) {
this.terminal.write(output.slice(index, index + chunkSize));
if (index + chunkSize < output.length) {
await this.nextFrame();
}
}
},
nextFrame() {
return new Promise((resolve) => requestAnimationFrame(resolve));
},
clear() {
this.terminal.clear();
},
getSocketUrl() {
return `${ this.value?.getSerialConsolePath }`;
return this.serialConsoleUrl;
},
async connect() {
@@ -181,6 +469,7 @@ export default {
this.fit();
this.flush();
}
this.scheduleFit();
if (this.firstTime) {
this.socket.send(this.str2ab('\n'));
@@ -195,7 +484,7 @@ export default {
});
this.socket.addEventListener(EVENT_MESSAGE, (e) => {
this.queue.push(e.detail.data.text());
this.enqueueMessage(this.decodeMessageData(e.detail.data));
});
this.socket.connect();
@@ -218,22 +507,19 @@ export default {
}
this.fitAddon.fit();
const { rows, cols } = this.fitAddon.proposeDimensions();
if ( !this.isOpen ) {
return;
}
const message = JSON.stringify({
Width: cols,
Height: rows
});
this.socket.send(this.str2ab(message));
},
close() {
if (this.onResize) {
window.removeEventListener('resize', this.onResize);
this.onResize = null;
}
if (this.drainTimer) {
cancelAnimationFrame(this.drainTimer);
this.drainTimer = null;
}
if ( this.socket ) {
this.socket.disconnect();
}
@@ -248,6 +534,44 @@ export default {
<template>
<div class="harvester-shell-container">
<div
v-if="showSearch"
class="shell-search"
>
<input
ref="searchInput"
v-model="searchQuery"
type="text"
class="shell-search-input"
placeholder="Search in terminal"
@input="onSearchInput"
@keydown="onSearchKeydown"
>
<button
class="btn role-secondary btn-sm shell-search-btn"
type="button"
title="Shift+Enter"
@click="findPrevious"
>
Prev
</button>
<button
class="btn role-secondary btn-sm shell-search-btn"
type="button"
title="Enter"
@click="findNext"
>
Next
</button>
<button
class="btn role-secondary btn-sm shell-search-btn"
type="button"
title="Esc"
@click="closeSearch"
>
Close
</button>
</div>
<div
ref="xterm"
class="shell-body"
@@ -257,18 +581,73 @@ export default {
</template>
<style lang="scss">
@import '../../../../node_modules/xterm/css/xterm.css';
@import '../../../../node_modules/@xterm/xterm/css/xterm.css';
body, #__nuxt, #__layout, MAIN {
height: 100%;
}
.harvester-shell-container {
display: flex;
flex-direction: column;
position: relative;
height: 100%;
min-height: 0;
overflow: hidden;
.shell-body, .terminal.xterm {
.resize-observer {
display: none;
}
.shell-search {
display: flex;
align-items: center;
gap: 8px;
justify-content: flex-end;
position: absolute;
top: 8px;
right: 10px;
z-index: 5;
padding: 8px;
border-radius: 6px;
border: 1px solid var(--border);
background: color-mix(in srgb, var(--body-bg) 88%, transparent);
}
.shell-search-input {
min-width: 220px;
max-width: 420px;
flex: 0 1 320px;
border: 1px solid var(--border);
border-radius: 4px;
background: var(--body-bg);
color: var(--body-text);
padding: 6px 8px;
}
.shell-search-btn {
min-width: 64px;
}
.shell-body {
flex: 1 1 auto;
height: 100%;
width: 100%;
min-height: 0;
padding: 0 10px;
box-sizing: border-box;
}
.terminal.xterm,
.terminal.xterm .xterm-viewport,
.terminal.xterm .xterm-screen,
.terminal.xterm .xterm-scrollable-element {
width: 100%;
height: 100%;
}
.terminal.xterm .xterm-scrollable-element {
min-height: 100%;
}
}
</style>
+21 -22
View File
@@ -10,6 +10,7 @@ import { docLink } from '../utils/feature-flags';
const CATEGORY = {
ui: [
'branding',
HCI_SETTING.SERVER_FLAVOR,
'ui-source',
'ui-index',
]
@@ -53,7 +54,7 @@ export default {
};
},
computed: { ...mapGetters({ t: 'i18n/t' }) },
computed: { ...mapGetters({ t: 'i18n/t', isHarvesterPrime: 'harvester-common/isHarvesterPrime' }) },
watch: {
settings: {
@@ -140,10 +141,6 @@ export default {
filterCategorySettings() {
return this.settings.filter((s) => {
if (!this.getFeatureEnabled(s.featureFlag)) {
return false;
}
if (this.category !== 'advanced') {
return (CATEGORY[this.category] || []).find((item) => item === s.id);
} else if (this.category === 'advanced') {
@@ -154,10 +151,6 @@ export default {
}) || [];
},
getFeatureEnabled(id) {
return id ? this.$store.getters['harvester-common/getFeatureEnabled'](id) : true;
},
getSettingOption(id) {
return HCI_ALLOWED_SETTINGS.find((setting) => setting.id === id);
},
@@ -231,14 +224,21 @@ export default {
v-if="setting.customized"
class="modified"
>
Modified
{{ t('advancedSettings.tags.modified.label') }}
</span>
<span
v-if="setting.experimental"
v-clean-tooltip="t('advancedSettings.experimental')"
v-clean-tooltip="t('advancedSettings.tags.experimental.description')"
class="experimental"
>
Experimental
{{ t('advancedSettings.tags.experimental.label') }}
</span>
<span
v-if="setting.preview"
v-clean-tooltip="t('advancedSettings.tags.preview.description')"
class="preview"
>
{{ t('advancedSettings.tags.preview.label') }}
</span>
</h1>
<h2 v-clean-html="t(setting.description, getDocLinkParams(setting) || {}, true)">
@@ -262,7 +262,8 @@ export default {
v-if="!setting.hide"
class="settings-value"
>
<pre v-if="setting.kind === 'json'">{{ setting.json }}</pre>
<pre v-if="setting.id === 'branding' && isHarvesterPrime">{{ $store.getters['harvester-common/privateLabel'] }}</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 === 'enum'">{{ t(setting.enum) }}</pre>
<pre v-else-if="setting.kind === 'custom' && setting.custom">{{ setting.custom }}</pre>
@@ -352,21 +353,19 @@ export default {
flex: 1;
}
.modified {
.modified,
.experimental,
.preview {
margin-left: 10px;
border: 1px solid var(--primary);
border: 1px solid;
border-radius: 5px;
padding: 2px 10px;
font-size: 12px;
}
.experimental {
margin-left: 10px;
border: 1px solid var(--error);
border-radius: 5px;
padding: 2px 10px;
font-size: 12px;
}
.modified { border-color: var(--primary); }
.experimental { border-color: var(--error); }
.preview { border-color: var(--warning); }
.no-search-match {
text-align: center;
+12 -5
View File
@@ -55,14 +55,21 @@ export default {
const host = window.location.host;
const prefix = window.location.pathname.replace(this.$route.path, '');
const params = this.$route?.params;
const popupWidth = Math.max(800, screen.width - 200);
const popupHeight = Math.max(600, screen.height - 200);
const popupLeft = Math.max(0, window.screenX + Math.floor((window.outerWidth - popupWidth) / 2));
const popupTop = Math.max(0, window.screenY + Math.floor((window.outerHeight - popupHeight) / 2));
const url = `https://${ host }${ prefix }/${ PRODUCT_NAME }/c/${ params.cluster }/console/${ uid }/${ type }`;
window.open(
url,
'_blank',
`toolbars=0,width=${ screen.width - 200 },height=${ screen.height - 200 },left=0,top=0,noreferrer`
);
// Defer so v-select can finish closing the dropdown before the popup steals focus
this.$nextTick(() => {
window.open(
url,
'_blank',
`toolbars=0,width=${ popupWidth },height=${ popupHeight },left=${ popupLeft },top=${ popupTop },noreferrer`
);
});
},
isEmpty(o) {
@@ -0,0 +1,336 @@
<script setup>
import { computed, ref, watch } from 'vue';
import { useStore } from 'vuex';
import SortableTable from '@shell/components/SortableTable';
import { BadgeState } from '@components/BadgeState';
import { RcCounterBadge, RcTag } from '@components/Pill';
import { RcButton } from '@components/RcButton';
import { useI18n } from '@shell/composables/useI18n';
import { _CREATE, _EDIT, _VIEW } from '@shell/config/query-params';
import { HCI } from '../../types';
import {
AFFECTED_RESOURCES_TRUNCATE_COUNT, MESSAGE_TRUNCATE_LENGTH, activeAffectedResourceNames, affectedResourceLabel,
allAffectedResourceNames, ignoreRuleName, ignoredResourceCount, resourceIgnoredBy, severityColor
} from '../../utils/component-health';
const props = defineProps({
rows: {
type: Array,
required: true,
},
ignoreRules: {
type: Array,
default: () => [],
},
showIgnored: {
type: Boolean,
default: false,
},
// what is typed in the filter box of the table this one sits in
filterText: {
type: String,
default: '',
},
// the checks could not be loaded, so having none does not mean there are no issues
loadFailed: {
type: Boolean,
default: false,
},
});
const emit = defineEmits(['open-rule']);
const store = useStore();
const { t } = useI18n(store);
const headers = [
{
name: 'severity',
labelKey: 'harvester.dashboard.sections.componentHealth.severity',
value: 'severityRank',
sort: 'severityRank',
search: false,
width: 110,
},
{
name: 'checkName',
labelKey: 'harvester.dashboard.sections.componentHealth.check',
value: 'checkName',
sort: 'checkName',
// all that a row shows, so the filter also finds a resource hidden behind "more"
search: 'filterText',
},
{
name: 'message',
labelKey: 'harvester.dashboard.sections.componentHealth.message',
value: 'message',
search: false,
canBeVariable: true,
},
{
name: 'affectedCount',
labelKey: 'harvester.dashboard.sections.componentHealth.affectedCount',
value: 'affectedCount',
sort: 'affectedCount',
search: false,
width: 340,
canBeVariable: true,
},
];
const table = ref(null);
// this table has no filter box of its own, but it filters its rows the same way
watch([table, () => props.filterText], ([checksTable, text]) => {
if (checksTable) {
checksTable.searchQuery = text;
}
});
const canCreateRule = computed(() => {
const schema = store.getters['harvester/schemaFor'](HCI.HEALTH_IGNORE_RULE);
return !!schema?.collectionMethods?.find((method) => method.toLowerCase() === 'post');
});
// only the rule the UI made for the check, others on it are left as they are
function actionsOf(row) {
const name = ignoreRuleName(row.componentHealthName, row.checkName);
const rule = props.ignoreRules.find(({ metadata }) => metadata?.name === name);
const action = (key, icon, invoke) => ({
action: key,
label: t(`harvester.dashboard.sections.componentHealth.ignore.${ key }`),
icon: `icon ${ icon }`,
enabled: true,
invoke,
});
const open = (mode) => () => emit('open-rule', {
row, rule, mode
});
if (!rule) {
return canCreateRule.value ? [action(_CREATE, 'icon-plus', open(_CREATE))] : [];
}
const actions = [action(_VIEW, 'icon-document', open(_VIEW))];
if (rule.canUpdate) {
actions.push(action(_EDIT, 'icon-edit', open(_EDIT)));
}
if (rule.canDelete) {
actions.push({ divider: true }, action('delete', 'icon-trash', () => rule.promptRemove()));
}
return actions;
}
// the table's action menu reads them from the row, as it does on a resource
const rowsWithActions = computed(() => props.rows.map((row) => ({ ...row, availableActions: actionsOf(row) })));
// a menu that could only say there is nothing to do is left out
const hasActions = computed(() => rowsWithActions.value.some((row) => row.availableActions.length));
const expandedMessageIds = ref([]);
const expandedResourceIds = ref([]);
function affectedResourceNames(row) {
return props.showIgnored ? allAffectedResourceNames(row) : activeAffectedResourceNames(row);
}
// called from the template, where the refs are unwrapped, so the array is changed in place
function toggleId(list, id) {
const index = list.indexOf(id);
if (index === -1) {
list.push(id);
} else {
list.splice(index, 1);
}
}
function isMessageTruncated(message) {
return !!message && message.length > MESSAGE_TRUNCATE_LENGTH;
}
function displayedMessage(row, message) {
return expandedMessageIds.value.includes(row.id) || !isMessageTruncated(message) ? message : message.slice(0, MESSAGE_TRUNCATE_LENGTH);
}
function visibleAffectedResourceNames(row) {
const names = affectedResourceNames(row);
return expandedResourceIds.value.includes(row.id) ? names : names.slice(0, AFFECTED_RESOURCES_TRUNCATE_COUNT);
}
function remainingAffectedResourcesCount(row) {
return Math.max(affectedResourceNames(row).length - AFFECTED_RESOURCES_TRUNCATE_COUNT, 0);
}
function isResourceIgnored(row, name) {
return row.ignored || !!resourceIgnoredBy(row, name);
}
// the ignored resources that are left out of the list
function hiddenIgnoredCount(row) {
return props.showIgnored ? 0 : ignoredResourceCount(row);
}
</script>
<template>
<div
v-if="!rows.length"
class="text-muted"
>
{{ t(`harvester.dashboard.sections.componentHealth.${ loadFailed ? 'checksNotLoaded' : 'noIssues' }`) }}
</div>
<SortableTable
v-else
ref="table"
:rows="rowsWithActions"
:headers="headers"
key-field="id"
:search="false"
:table-actions="false"
:row-actions="hasActions"
:paging="true"
:rows-per-page="10"
default-sort-by="severity"
>
<template #cell:severity="{row}">
<BadgeState
:color="severityColor(row.severity)"
:label="row.severity"
/>
</template>
<template #cell:checkName="{row, value}">
<span :class="{ 'text-muted': row.ignored }">
{{ value }}
<template v-if="row.ignored">
({{ t('harvester.dashboard.sections.componentHealth.ignore.ignored') }})
</template>
</span>
</template>
<template #cell:message="{row, value}">
<span :class="{ 'text-muted': row.ignored }">
{{ displayedMessage(row, value) }}
<RcButton
v-if="isMessageTruncated(value)"
variant="link"
size="small"
class="compact-link"
:aria-expanded="expandedMessageIds.includes(row.id)"
@click="toggleId(expandedMessageIds, row.id)"
>
{{ expandedMessageIds.includes(row.id) ? t('generic.showLess') : t('generic.showMore') }}
</RcButton>
</span>
</template>
<template #cell:affectedCount="{row, value}">
<div
v-if="affectedResourceNames(row).length"
class="affected-resources"
>
<div class="affected-title">
<span class="text-label">{{ affectedResourceLabel(row, store) }}</span>
<RcCounterBadge
:count="value || allAffectedResourceNames(row).length"
type="inactive"
/>
<span class="api-version text-muted">{{ row.affectedResources.apiVersion }}</span>
</div>
<div class="affected-names">
<RcTag
v-for="name in visibleAffectedResourceNames(row)"
:key="name"
class="affected-name"
:class="{ ignored: isResourceIgnored(row, name) }"
type="inactive"
:disabled="isResourceIgnored(row, name)"
>
<span class="name">{{ name }}</span>
<!-- when all of the check is ignored its name says so -->
<span v-if="!row.ignored && isResourceIgnored(row, name)">
({{ t('harvester.dashboard.sections.componentHealth.ignore.ignored') }})
</span>
</RcTag>
</div>
<RcButton
v-if="remainingAffectedResourcesCount(row)"
variant="link"
size="small"
class="compact-link"
:aria-expanded="expandedResourceIds.includes(row.id)"
@click="toggleId(expandedResourceIds, row.id)"
>
{{ expandedResourceIds.includes(row.id) ? t('generic.showLess') : t('generic.plusMore', { n: remainingAffectedResourcesCount(row) }) }}
</RcButton>
<span
v-if="hiddenIgnoredCount(row)"
class="hidden-ignored text-muted"
>
{{ t('harvester.dashboard.sections.componentHealth.ignore.plusIgnored', { n: hiddenIgnoredCount(row) }) }}
</span>
</div>
<span v-else>
{{ t('harvester.dashboard.sections.componentHealth.noAffectedResources') }}
</span>
</template>
</SortableTable>
</template>
<style lang="scss" scoped>
// these sit next to text, so they line up with it
.compact-link {
--rc-button-padding: 0;
}
.affected-resources {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 4px;
padding: 4px 0;
}
.affected-title {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px 8px;
margin-bottom: 4px;
}
.api-version {
font-size: 12px;
}
// the same size as the "+ N more" link above it
.hidden-ignored {
font-size: 12px;
}
.affected-names {
display: flex;
flex-wrap: wrap;
gap: 4px;
}
.affected-name {
max-width: 100%;
font-size: 12px;
// a long name wraps, so none is ever cut off
.name {
min-width: 0;
overflow-wrap: anywhere;
}
// the ones that count are filled, the ignored ones are only outlined
&.rc-tag.ignored {
background: transparent;
border-style: dashed;
border-color: var(--rc-disabled-text-color);
}
}
</style>
@@ -0,0 +1,342 @@
<script setup>
import { computed, onMounted, ref } from 'vue';
import { HCI } from '../../types';
import { useStore } from 'vuex';
import { useI18n } from '@shell/composables/useI18n';
import SortableTable from '@shell/components/SortableTable';
import { exceptionToErrorsArray } from '@shell/utils/error';
import Banner from '@components/Banner/Banner.vue';
import { BadgeState } from '@components/BadgeState';
import { Checkbox } from '@components/Form/Checkbox';
import { RcButton } from '@components/RcButton';
import { useModal } from '@components/RcModal';
import ComponentChecksTable from './ComponentChecksTable.vue';
import IgnoreRuleModal from './IgnoreRuleModal.vue';
import {
COMPONENT_HEALTH_SEVERITIES, HEALTH_SUMMARY_SEVERITY_RANK, activeAffectedResourceNames, affectedResourceKind,
affectedResourceLabel, allAffectedResourceNames, componentOf, healthSummarySeverity, ignoredCounts, severityColor
} from '../../utils/component-health';
const store = useStore();
const { t } = useI18n(store);
const table = ref(null);
const loading = ref(true);
const lists = {
healthSummaries: ref([]),
componentHealths: ref([]),
ignoreRules: ref([]),
};
const { healthSummaries, componentHealths, ignoreRules } = lists;
// the lists that could not be loaded, with why
const loadErrors = ref({});
const headers = [
{
name: 'severity',
labelKey: 'harvester.dashboard.sections.healthSummary.severity',
value: 'severityRank',
sort: 'severityRank',
search: 'severity',
width: 110,
},
{
name: 'component',
labelKey: 'harvester.dashboard.sections.healthSummary.component',
value: 'component',
sort: 'component',
// the table's filter only looks at its own rows, the checks are in the sub-rows
search: ['component', 'checksFilterText'],
},
{
align: 'right',
name: 'errorCount',
labelKey: 'harvester.dashboard.sections.healthSummary.errorCount',
value: 'errorCount',
sort: 'errorCount',
search: false,
width: 120,
},
{
align: 'right',
name: 'warningCount',
labelKey: 'harvester.dashboard.sections.healthSummary.warningCount',
value: 'warningCount',
sort: 'warningCount',
search: false,
width: 120,
},
];
const {
open: openRuleModal, isOpen: ruleModalOpen, payload: ruleToOpen, modal: ruleModal
} = useModal();
const showIgnored = ref(false);
const filterText = computed(() => table.value?.searchQuery || '');
const checks = computed(() => {
const result = [];
(componentHealths.value || []).forEach((componentHealth) => {
const component = componentOf(componentHealth);
const statusChecks = componentHealth?.status?.checks || {};
Object.entries(statusChecks).forEach(([checkName, check]) => {
result.push({
id: `${ componentHealth.id }/${ checkName }`,
component,
componentHealthName: componentHealth.metadata?.name,
checkName,
ignored: !!check.ignored,
severity: check.severity,
// the table sorts on a row property, the severities are not in alphabetical order
severityRank: COMPONENT_HEALTH_SEVERITIES.indexOf(check.severity),
message: check.message,
affectedCount: check.affectedCount,
affectedResources: check.affectedResources,
});
});
});
return result;
});
const shownChecks = computed(() => checks.value.filter((check) => showIgnored.value || !check.ignored).map((check) => ({
...check,
filterText: [
check.component,
check.severity,
check.checkName,
check.message,
check.affectedResources?.apiVersion,
affectedResourceKind(check),
affectedResourceLabel(check, store),
...(showIgnored.value ? allAffectedResourceNames(check) : activeAffectedResourceNames(check)),
].join(' ').toLowerCase(),
})));
const ignored = computed(() => ignoredCounts(checks.value));
const hasIgnored = computed(() => ignored.value.checks + ignored.value.resources > 0);
// says what turning it on brings back, the same whether it is on or off
const showIgnoredLabel = computed(() => {
const counts = [
ignored.value.checks && t('harvester.dashboard.sections.componentHealth.ignoredChecks', { count: ignored.value.checks }),
ignored.value.resources && t('harvester.dashboard.sections.componentHealth.ignoredResources', { count: ignored.value.resources }),
].filter(Boolean).join(', ');
return t('harvester.dashboard.sections.componentHealth.showIgnored', { counts });
});
const rows = computed(() => {
const result = [];
(healthSummaries.value || []).forEach((healthSummary) => {
const components = healthSummary?.status?.components || {};
Object.entries(components).forEach(([component, counts]) => {
const componentChecks = shownChecks.value.filter((check) => check.component === component);
const row = {
id: `${ healthSummary.id }/${ component }`,
component,
errorCount: counts?.errorCount || 0,
warningCount: counts?.warningCount || 0,
checksFilterText: componentChecks.map((check) => check.filterText).join(' '),
checks: componentChecks,
};
row.severity = healthSummarySeverity(row);
// the table sorts on a row property, so the severity has to be on the row
row.severityRank = HEALTH_SUMMARY_SEVERITY_RANK[row.severity];
result.push(row);
});
});
return result;
});
onMounted(async() => {
const types = {
healthSummaries: HCI.HEALTH_SUMMARY,
componentHealths: HCI.COMPONENT_HEALTH,
};
if (store.getters['harvester/schemaFor'](HCI.HEALTH_IGNORE_RULE)) {
types.ignoreRules = HCI.HEALTH_IGNORE_RULE;
}
// a list that fails does not stop the others from showing
await Promise.all(Object.entries(types).map(async([key, type]) => {
try {
lists[key].value = await store.dispatch('harvester/findAll', { type });
} catch (err) {
loadErrors.value[key] = exceptionToErrorsArray(err).join(', ');
}
}));
loading.value = false;
});
// the table has these from shell 3.0.15, in the props of its #header-right slot, so they can go with that bump
function expandAll() {
table.value.expanded = Object.fromEntries(rows.value.map((row) => [row.id, true]));
}
function collapseAll() {
table.value.expanded = {};
}
</script>
<template>
<Banner
v-for="(error, key) in loadErrors"
:key="key"
color="error"
:label="t(`harvester.dashboard.sections.componentHealth.loadFailed.${ key }`, { error })"
/>
<SortableTable
ref="table"
:rows="rows"
:headers="headers"
:loading="loading"
key-field="id"
:table-actions="false"
:row-actions="false"
:paging="true"
:rows-per-page="10"
:sub-rows="true"
:sub-expandable="true"
:sub-expand-column="true"
default-sort-by="severity"
>
<template #header-left>
<div
v-if="hasIgnored"
class="show-ignored"
>
<Checkbox
v-model:value="showIgnored"
type="checkbox"
:label="showIgnoredLabel"
/>
</div>
</template>
<template #header-right>
<div
v-if="rows.length"
class="expand-actions"
>
<RcButton
variant="link"
size="small"
@click="expandAll"
>
{{ t('harvester.dashboard.sections.healthSummary.expandAll') }}
</RcButton>
<RcButton
variant="link"
size="small"
@click="collapseAll"
>
{{ t('harvester.dashboard.sections.healthSummary.collapseAll') }}
</RcButton>
</div>
</template>
<template #cell:severity="{row}">
<BadgeState
:color="severityColor(row.severity)"
:label="row.severity"
/>
</template>
<!-- the table's chevron can't take the keyboard focus, this opens the row from the keyboard -->
<template #cell:component="{row}">
<RcButton
variant="link"
class="component-name"
:aria-expanded="!!table?.isExpanded(row)"
@click="table.toggleExpand(row)"
>
{{ row.component }}
</RcButton>
</template>
<template #sub-row="{row, fullColspan}">
<tr class="sub-row">
<td :colspan="fullColspan">
<ComponentChecksTable
class="sub-table"
:rows="row.checks"
:ignore-rules="ignoreRules"
:show-ignored="showIgnored"
:filter-text="filterText"
:load-failed="!!loadErrors.componentHealths"
@open-rule="openRuleModal"
/>
</td>
</tr>
</template>
</SortableTable>
<!-- mounted each time it opens, so the form always starts over -->
<IgnoreRuleModal
v-if="ruleModalOpen"
v-bind="ruleToOpen"
:modal="ruleModal"
/>
</template>
<style lang="scss" scoped>
// the filter box in the same row is taller, this lines up with it
.show-ignored {
display: flex;
align-items: center;
height: 100%;
}
.expand-actions {
display: flex;
align-items: center;
gap: 8px;
}
// a button is taller than the table's rows
.component-name {
--rc-button-padding: 0;
&.rc-button.btn-medium:not(.btn-sm) {
min-height: 0;
line-height: inherit;
}
}
// the shell has this look for a table in a sub-row from 3.0.15, this can go with that bump
.sub-row {
background-color: var(--body-bg) !important;
> td:first-child {
padding-left: 0;
padding-right: 0;
}
.sub-table {
padding: 16px 32px;
}
:deep(.sortable-table) {
border: 0;
border-radius: 0;
outline: 0;
}
:deep(thead tr:hover) {
background-color: var(--body-bg);
}
:deep(thead th) {
font-weight: 600;
}
:deep(tbody tr) {
border-bottom: 0;
}
}
</style>
@@ -0,0 +1,320 @@
<script setup>
import { computed, ref } from 'vue';
import { useStore } from 'vuex';
import dayjs from 'dayjs';
import isEqual from 'lodash/isEqual';
import Banner from '@components/Banner/Banner.vue';
import { LabeledInput } from '@components/Form/LabeledInput';
import { RadioGroup } from '@components/Form/Radio';
import { RcButton } from '@components/RcButton';
import { RcHeading } from '@components/RcHeading';
import { RcModal } from '@components/RcModal';
import LabelValue from '@shell/components/LabelValue';
import LabeledSelect from '@shell/components/form/LabeledSelect';
import { useI18n } from '@shell/composables/useI18n';
import { _CREATE, _VIEW } from '@shell/config/query-params';
import { exceptionToErrorsArray } from '@shell/utils/error';
import { dateTimeFormat } from '@shell/utils/time';
import { HCI } from '../../types';
import { IGNORE_DURATION_DAYS, IGNORE_RULE_SOURCE_LABEL, allAffectedResourceNames, ignoreRuleName } from '../../utils/component-health';
const props = defineProps({
row: {
type: Object,
required: true,
},
// empty when the rule is created
rule: {
type: Object,
default: null,
},
mode: {
type: String,
default: _CREATE,
},
// `show` and the `close` handler, from whoever owns this modal's visibility
modal: {
type: Object,
required: true,
},
});
const store = useStore();
const { t } = useI18n(store);
const isView = computed(() => props.mode === _VIEW);
const ruleResources = props.rule?.spec?.resources || [];
const expiresAt = props.rule?.spec?.expiresAt;
const hasExpired = !!expiresAt && !dayjs(expiresAt).isAfter(dayjs());
// a rule can still list resources that are no longer affected
const resourceOptions = computed(() => [...new Set([...allAffectedResourceNames(props.row), ...ruleResources])]);
// a rule that lists no resource ignores the entire check
const chosenScope = ref(props.rule && !ruleResources.length ? 'check' : null);
const scope = computed({
get: () => chosenScope.value || (resourceOptions.value.length ? 'resources' : 'check'),
set: (value) => {
chosenScope.value = value;
},
});
// null selects every resource, the ones that are not selected are kept visible
const selected = ref(ruleResources.length ? ruleResources : null);
// a rule keeps the expiry it has until another duration is chosen
const duration = ref(props.rule ? null : 'days7');
const reason = ref(props.rule?.spec?.reason || '');
const errors = ref([]);
const saving = ref(false);
const selectedResources = computed(() => {
return selected.value === null ? resourceOptions.value : resourceOptions.value.filter((name) => selected.value.includes(name));
});
const scopeOptions = computed(() => [
{ label: t('harvester.dashboard.sections.componentHealth.ignore.scopeCheck'), value: 'check' },
{ label: t('harvester.dashboard.sections.componentHealth.ignore.scopeResources'), value: 'resources' },
]);
const durationOptions = computed(() => Object.keys(IGNORE_DURATION_DAYS).map((key) => ({
label: t(`harvester.dashboard.sections.componentHealth.ignore.${ key }`),
value: key,
})));
// worked out once for each choice, so the date shown is the date saved
const newExpiresAt = computed(() => {
const days = IGNORE_DURATION_DAYS[duration.value];
return days ? dayjs().add(days, 'day').toISOString() : undefined;
});
const spec = computed(() => {
const out = {
componentHealth: props.row.componentHealthName,
checkKey: props.row.checkName,
};
// the rule only lists the selected resources, so it does not swallow the ones coming later
if (scope.value === 'resources') {
out.resources = selectedResources.value;
}
const expiry = duration.value ? newExpiresAt.value : expiresAt;
if (expiry) {
out.expiresAt = expiry;
}
if (reason.value) {
out.reason = reason.value;
}
return out;
});
// what the form changes, in an order that does not depend on the options
const editable = (ruleSpec) => ({
resources: [...(ruleSpec?.resources || [])].sort(),
expiresAt: ruleSpec?.expiresAt || '',
reason: ruleSpec?.reason || '',
});
const hasChanges = computed(() => !props.rule || !isEqual(editable(spec.value), editable(props.rule.spec)));
// a rule that lists no resource would ignore the entire check
const canSave = computed(() => (scope.value === 'check' || selectedResources.value.length > 0) && hasChanges.value);
// saving something else on an expired rule leaves it expired
const staysExpired = computed(() => hasExpired && !duration.value && hasChanges.value);
const currentExpiry = computed(() => {
if (!expiresAt) {
return t('harvester.dashboard.sections.componentHealth.ignore.neverExpires');
}
return t(`harvester.dashboard.sections.componentHealth.ignore.${ hasExpired ? 'expiredOn' : 'expiresOn' }`, { date: dateTimeFormat(expiresAt, store) });
});
const newExpiry = computed(() => {
if (!newExpiresAt.value) {
return t('harvester.dashboard.sections.componentHealth.ignore.willNeverExpire');
}
return t('harvester.dashboard.sections.componentHealth.ignore.willExpireOn', { date: dateTimeFormat(newExpiresAt.value, store) });
});
function close() {
// stays open while the rule is saved, so a failure can still be shown
if (!saving.value) {
props.modal.onClose();
}
}
async function save() {
errors.value = [];
saving.value = true;
try {
const rule = props.rule ? await store.dispatch('harvester/clone', { resource: props.rule }) : await store.dispatch('harvester/create', {
type: HCI.HEALTH_IGNORE_RULE,
metadata: {
name: ignoreRuleName(props.row.componentHealthName, props.row.checkName),
labels: { [IGNORE_RULE_SOURCE_LABEL]: 'user' },
},
});
rule.spec = spec.value;
await rule.save();
store.dispatch('growl/success', {
title: t('generic.notification.title.succeed'),
message: t(`harvester.dashboard.sections.componentHealth.ignore.${ props.rule ? 'updated' : 'created' }`, { name: props.row.checkName }),
}, { root: true });
saving.value = false;
close();
} catch (err) {
errors.value = exceptionToErrorsArray(err?.data || err);
saving.value = false;
}
}
</script>
<template>
<!-- Not v-bind="modal": closing goes through close(), which refuses while the rule is saved -->
<RcModal
:show="modal.show"
:title="t(`harvester.dashboard.sections.componentHealth.ignore.${ mode }`)"
data-testid="component-health-ignore-modal"
@close="close"
@primary-action="save"
>
<div class="row">
<div class="col span-6">
<LabelValue
:name="t('harvester.dashboard.sections.componentHealth.component')"
:value="row.component"
/>
</div>
<div class="col span-6">
<LabelValue
:name="t('harvester.dashboard.sections.componentHealth.check')"
:value="row.checkName"
/>
</div>
</div>
<div v-if="resourceOptions.length">
<RcHeading :size="4">
{{ t('harvester.dashboard.sections.componentHealth.ignore.scope') }}
</RcHeading>
<RadioGroup
v-model:value="scope"
name="ignore-scope"
:aria-label="t('harvester.dashboard.sections.componentHealth.ignore.scope')"
:mode="mode"
:options="scopeOptions"
/>
<div
v-if="scope === 'resources'"
class="ignore-resources"
>
<LabeledSelect
:value="selectedResources"
:label="t('harvester.dashboard.sections.componentHealth.ignore.resources')"
:mode="mode"
:options="resourceOptions"
:multiple="true"
:close-on-select="false"
:clearable="false"
:required="!isView"
@update:value="selected = $event"
/>
</div>
</div>
<div>
<RcHeading :size="4">
{{ t('harvester.dashboard.sections.componentHealth.ignore.duration') }}
</RcHeading>
<p
v-if="rule"
class="current-expiry mb-10"
data-testid="component-health-ignore-current-expiry"
>
{{ currentExpiry }}
</p>
<template v-if="!isView">
<RadioGroup
v-model:value="duration"
name="ignore-duration"
:aria-label="t('harvester.dashboard.sections.componentHealth.ignore.duration')"
:mode="mode"
:options="durationOptions"
:row="true"
/>
<p
v-if="duration"
class="new-expiry text-muted"
data-testid="component-health-ignore-new-expiry"
>
{{ newExpiry }}
</p>
</template>
</div>
<LabeledInput
v-model:value="reason"
:label="t('harvester.dashboard.sections.componentHealth.ignore.reason')"
:placeholder="isView ? '' : t('harvester.dashboard.sections.componentHealth.ignore.reasonPlaceholder')"
:mode="mode"
/>
<Banner
v-for="(err, i) in errors"
:key="i"
class="m-0"
color="error"
:label="err"
/>
<Banner
v-if="staysExpired"
class="m-0"
color="warning"
data-testid="component-health-ignore-stays-expired"
:label="t('harvester.dashboard.sections.componentHealth.ignore.staysExpired', { date: dateTimeFormat(expiresAt, store) })"
/>
<template
v-if="isView"
#actions="{ close: closeModal }"
>
<RcButton
variant="primary"
size="large"
data-testid="component-health-ignore-close"
@click="closeModal"
>
{{ t('generic.close') }}
</RcButton>
</template>
<template
v-else
#primary-action="{ primaryAction }"
>
<RcButton
variant="primary"
size="large"
:disabled="!canSave || saving"
:aria-busy="saving"
data-testid="component-health-ignore-confirm"
@click="primaryAction"
>
{{ t(rule ? 'generic.save' : 'generic.create') }}
</RcButton>
</template>
</RcModal>
</template>
<style lang="scss" scoped>
// lines the field up with the radio's label
.ignore-resources {
margin: 10px 0 0 19px;
}
</style>
@@ -0,0 +1,912 @@
import { mount as vtuMount, flushPromises } from '@vue/test-utils';
import { createStore } from 'vuex';
import Banner from '@components/Banner/Banner.vue';
import { BadgeState } from '@components/BadgeState';
import { Checkbox } from '@components/Form/Checkbox';
import { LabeledInput } from '@components/Form/LabeledInput';
import { RadioGroup } from '@components/Form/Radio';
import { RcCounterBadge, RcTag } from '@components/Pill';
import { RcModal } from '@components/RcModal';
import LabeledSelect from '@shell/components/form/LabeledSelect';
import { HCI } from '../../../types';
import { affectedResourceLabel, ignoreRuleName, ignoredCounts, totalErrorCount } from '../../../utils/component-health';
import HealthSummaryTable from '../HealthSummaryTable.vue';
import ComponentChecksTable from '../ComponentChecksTable.vue';
import IgnoreRuleModal from '../IgnoreRuleModal.vue';
jest.mock('focus-trap', () => ({
createFocusTrap: jest.fn(() => ({
activate: jest.fn(),
deactivate: jest.fn(),
})),
}));
const TYPES = {
healthSummaries: HCI.HEALTH_SUMMARY,
componentHealths: HCI.COMPONENT_HEALTH,
ignoreRules: HCI.HEALTH_IGNORE_RULE,
};
const saveRule = jest.fn();
const newRule = { save: saveRule };
const editedRule = { save: saveRule };
const createRule = jest.fn(() => newRule);
const cloneRule = jest.fn(() => editedRule);
let store;
// resources are fetched by the components themselves, so serve them from a mocked store
const opts = (props = {}) => {
store = createStore({
getters: {
'i18n/t': () => (k) => k,
'i18n/exists': () => () => true,
'prefs/get': () => () => false,
currentProduct: () => ({ inStore: 'harvester' }),
'harvester/schemaFor': () => (type) => (props.noSchemaFor === type ? null : { collectionMethods: props.collectionMethods || ['GET', 'POST'] }),
'type-map/labelFor': () => (schema, count) => `label of ${ count }`,
},
actions: {
'growl/success': jest.fn(),
'harvester/findAll': (_, { type }) => {
const key = Object.keys(TYPES).find((k) => TYPES[k] === type);
props.onFindAll?.(type);
return props.failing === key ? Promise.reject(new Error('failed')) : props[key] || [];
},
'harvester/create': createRule,
'harvester/clone': cloneRule,
}
});
return { global: { plugins: [store], stubs: { teleport: true } } };
};
const toggleExpand = jest.fn();
// renders the summary rows with every sub-row open, and the checks of each sub-row
const summaryTable = {
props: ['rows', 'headers'],
data() {
return { searchQuery: '', expanded: {} };
},
methods: { toggleExpand, isExpanded: () => false },
template: `<div>
<slot name="header-left" />
<slot name="header-right" />
<div class="summary">{{ rows.map(r => r.id + ":" + r.severityRank).join(",") }}</div>
<div v-for="row in rows" :key="row.id" class="name"><slot name="cell:component" :row="row" /></div>
<div v-for="row in rows" :key="row.id" :class="'sub-' + row.component"><slot name="sub-row" :row="row" :fullColspan="1" /></div>
</div>`,
};
const checksTable = {
props: ['rows', 'headers', 'rowActions'],
data() {
return { searchQuery: '' };
},
template: '<div class="checks">{{ rows.map(r => r.id + ":" + r.severityRank).join(",") }}</div>',
};
const mountSummary = async(props) => {
const base = opts(props);
const w = vtuMount(HealthSummaryTable, { ...base, global: { ...base.global, stubs: { ...base.global.stubs, SortableTable: summaryTable } } });
await flushPromises();
return w;
};
const mountChecks = (props, stubs = {}, storeProps = {}) => {
const base = opts(storeProps);
return vtuMount(ComponentChecksTable, {
...base,
props,
global: {
...base.global,
stubs: {
...base.global.stubs, SortableTable: checksTable, ...stubs
}
},
});
};
const summaryOf = (components) => ({ id: 's', status: { components } });
const healthOf = (id, component, checks) => ({
id, metadata: { name: id, labels: { 'health.harvesterhci.io/component': component } }, status: { checks }
});
const CHECK = {
id: 'h/a',
component: 'x',
componentHealthName: 'h',
checkName: 'a',
affectedResources: { kind: 'VirtualMachine', names: { one: {}, two: {} } },
};
const IN_A_WEEK = new Date(Date.now() + (7 * 24 * 3600 * 1000)).toISOString();
const LAST_WEEK = new Date(Date.now() - (7 * 24 * 3600 * 1000)).toISOString();
// named the way the UI names the rule of a check, unless `extra` says otherwise
const ruleOf = (spec = {}, extra = {}) => {
const fullSpec = {
componentHealth: 'h', checkKey: 'a', ...spec
};
return {
metadata: { name: ignoreRuleName(fullSpec.componentHealth, fullSpec.checkKey) },
spec: fullSpec,
canUpdate: true,
canDelete: true,
promptRemove: jest.fn(),
...extra,
};
};
const actionsOf = (props = {}, storeProps = {}) => {
const w = mountChecks({ rows: [CHECK], ...props }, {}, storeProps);
const actions = w.findComponent(checksTable).props('rows')[0].availableActions;
return {
w,
actions,
keys: actions.map((action) => (action.divider ? '-' : action.action)),
invoke: (key) => actions.find((action) => action.action === key).invoke(),
};
};
const mountRuleModal = ({
rule, mode, save = () => {}, row = CHECK
} = {}) => {
createRule.mockClear();
cloneRule.mockClear();
saveRule.mockReset().mockImplementation(save);
delete newRule.spec;
delete editedRule.spec;
const onClose = jest.fn();
const w = vtuMount(IgnoreRuleModal, {
...opts(),
props: {
row, rule, mode, modal: { show: true, onClose }
},
});
return {
w,
onClose,
confirm: () => w.find('[data-testid="component-health-ignore-confirm"]'),
duration: () => w.findAllComponents(RadioGroup).find((group) => group.props('name') === 'ignore-duration'),
currentExpiry: () => w.find('[data-testid="component-health-ignore-current-expiry"]'),
newExpiry: () => w.find('[data-testid="component-health-ignore-new-expiry"]'),
warning: () => w.findAllComponents(Banner).find((banner) => banner.props('color') === 'warning'),
};
};
describe('health components', () => {
it('ranks the health summary rows by severity', async() => {
const w = await mountSummary({
healthSummaries: [{
id: 'a',
status: {
components: {
x: { errorCount: 1 }, y: {}, z: { warningCount: 2 }
}
}
}]
});
expect(w.find('.summary').text()).toBe('a/x:0,a/y:2,a/z:1');
});
it('opens a row from the component name, which takes the keyboard focus', async() => {
toggleExpand.mockClear();
const w = await mountSummary({ healthSummaries: [summaryOf({ x: {} })] });
const name = w.find('.name button');
expect(name.text()).toBe('x');
expect(name.attributes('aria-expanded')).toBe('false');
await name.trigger('click');
expect(toggleExpand.mock.calls.map(([row]) => row.component)).toStrictEqual(['x']);
});
it('shows the checks of a component in its sub-row', async() => {
const w = await mountSummary({
healthSummaries: [summaryOf({ x: { errorCount: 1 }, y: { warningCount: 1 } })],
componentHealths: [
healthOf('h1', 'x', { a: { severity: 'Error' } }),
healthOf('h2', 'y', { b: { severity: 'Warning' } }),
healthOf('h3', 'x', { c: { severity: 'Error' } }),
],
});
const rowsOf = (component) => w.findAllComponents(ComponentChecksTable).find((c) => c.element.closest(`.sub-${ component }`)).props('rows').map((r) => r.id);
expect(rowsOf('x')).toStrictEqual(['h1/a', 'h3/c']);
expect(rowsOf('y')).toStrictEqual(['h2/b']);
});
it('ranks the checks Error, Warning, Info', async() => {
const w = await mountSummary({
healthSummaries: [summaryOf({ x: { errorCount: 1 } })],
componentHealths: [healthOf('h', 'x', {
a: { severity: 'Info' }, b: { severity: 'Error' }, c: { severity: 'Warning' }
})],
});
expect(w.findComponent(ComponentChecksTable).props('rows').map((r) => `${ r.id }:${ r.severityRank }`)).toStrictEqual(['h/a:2', 'h/b:0', 'h/c:1']);
});
it('gives what was typed in the outer table to the table of checks', async() => {
const w = await mountSummary({
healthSummaries: [summaryOf({ x: { errorCount: 1 } })],
componentHealths: [healthOf('h', 'x', { a: { severity: 'Error' } })],
});
await w.findComponent(summaryTable).setData({ searchQuery: 'warn' });
expect(w.findComponent(ComponentChecksTable).props('filterText')).toBe('warn');
});
it('lets the table of checks filter its own rows', async() => {
const w = mountChecks({ rows: [CHECK], filterText: 'warn' });
const table = w.findComponent(checksTable);
await flushPromises();
expect(table.vm.searchQuery).toBe('warn');
await w.setProps({ filterText: 'error' });
expect(table.vm.searchQuery).toBe('error');
expect(table.props('headers').filter((header) => header.search !== false).map((header) => header.search)).toStrictEqual(['filterText']);
});
it('calls a row with errors Error, and only its errors match that word', async() => {
const w = await mountSummary({
healthSummaries: [summaryOf({ x: { errorCount: 1 } })],
componentHealths: [healthOf('h', 'x', { a: { severity: 'Error' }, b: { severity: 'Warning' } })],
});
const checks = w.findComponent(ComponentChecksTable).props('rows');
expect(w.findComponent(summaryTable).props('rows')[0].severity).toBe('Error');
expect(checks.map((r) => r.filterText.includes('error'))).toStrictEqual([true, false]);
});
it('does not search the count columns', async() => {
const w = await mountSummary({ healthSummaries: [summaryOf({ x: {} })] });
const { headers } = w.findComponent(summaryTable).props();
expect(headers.filter((header) => header.search !== false).map((header) => header.name)).toStrictEqual(['severity', 'component']);
});
it('gives the table filter what a sub-row shows', async() => {
const w = await mountSummary({
healthSummaries: [summaryOf({ x: { warningCount: 1 } })],
componentHealths: [healthOf('h', 'x', {
a: {
severity: 'Warning',
message: 'Some Message',
affectedResources: {
apiVersion: 'kubevirt.io/v1', kind: 'VirtualMachine', names: { 'vm-shown': {}, 'vm-hidden': { ignored: true } }
},
}
})],
});
const filterText = () => w.findComponent(summaryTable).props('rows')[0].checksFilterText;
['x', 'warning', 'a', 'some message', 'kubevirt.io/v1', 'virtualmachine', 'label of', 'vm-shown'].forEach((text) => expect(filterText()).toContain(text));
expect(filterText()).not.toContain('vm-hidden');
await w.findComponent(Checkbox).vm.$emit('update:value', true);
expect(filterText()).toContain('vm-hidden');
});
it('leaves the rows as they are when filtering', async() => {
toggleExpand.mockClear();
const w = await mountSummary({
healthSummaries: [summaryOf({ x: { errorCount: 1 }, y: { warningCount: 1 } })],
componentHealths: [healthOf('h1', 'x', { a: { severity: 'Error' } }), healthOf('h2', 'y', { b: { severity: 'Warning' } })],
});
const table = w.findComponent(summaryTable);
await table.setData({ searchQuery: 'warning' });
await table.setData({ searchQuery: '' });
expect(toggleExpand).not.toHaveBeenCalled();
expect(table.vm.expanded).toStrictEqual({});
});
it('expands and collapses all the rows', async() => {
const w = await mountSummary({ healthSummaries: [summaryOf({ x: {}, y: {} })] });
const table = w.findComponent(summaryTable);
const [expand, collapse] = w.findAll('.expand-actions button');
await expand.trigger('click');
expect(table.vm.expanded).toStrictEqual({ 's/x': true, 's/y': true });
await collapse.trigger('click');
expect(table.vm.expanded).toStrictEqual({});
});
it('only offers to expand and collapse when there are rows', async() => {
const w = await mountSummary({});
expect(w.find('.expand-actions').exists()).toBe(false);
});
it('only offers the ignored checks when there are some', async() => {
const w = await mountSummary({
healthSummaries: [summaryOf({ x: { warningCount: 1 } })],
componentHealths: [healthOf('h', 'x', { a: { severity: 'Error', ignored: true }, b: { severity: 'Warning' } })],
});
const shownRows = () => w.findComponent(ComponentChecksTable).props('rows').map((r) => r.id);
expect(shownRows()).toStrictEqual(['h/b']);
expect(w.text()).toContain('showIgnored');
await w.findComponent(Checkbox).vm.$emit('update:value', true);
expect(shownRows()).toStrictEqual(['h/a', 'h/b']);
const clean = await mountSummary({
healthSummaries: [summaryOf({ x: { warningCount: 1 } })],
componentHealths: [healthOf('h', 'x', { b: { severity: 'Warning' } })],
});
expect(clean.text()).not.toContain('showIgnored');
});
it('expands a long message', async() => {
const message = 'x'.repeat(150);
const table = { props: ['rows'], template: '<div><slot name="cell:message" :row="rows[0]" :value="rows[0].message" /></div>' };
const w = mountChecks({ rows: [{ ...CHECK, message }] }, { SortableTable: table });
expect(w.text()).not.toContain(message);
expect(w.text()).toContain('generic.showMore');
await w.find('button.variant-link').trigger('click');
expect(w.text()).toContain(message);
expect(w.text()).toContain('generic.showLess');
});
it('shows the resources as chips, under what the UI calls them and their full count', () => {
const table = { props: ['rows'], template: '<div><slot name="cell:affectedCount" :row="rows[0]" :value="rows[0].affectedCount" /></div>' };
const row = {
...CHECK,
affectedCount: 7,
affectedResources: {
apiVersion: 'longhorn.io/v1beta2', kind: 'Volume', names: { one: { ignored: true, ignoredBy: 'r' }, two: {} }
}
};
const w = mountChecks({ rows: [row] }, { SortableTable: table });
expect(w.find('.affected-title .text-label').text()).toBe('label of 7');
expect(w.find('.affected-title .api-version').text()).toBe('longhorn.io/v1beta2');
expect(w.findComponent(RcCounterBadge).props('count')).toBe(7);
expect(w.findAllComponents(RcTag).map((tag) => tag.text())).toStrictEqual(['two']);
});
it('keeps the full count and says how many ignored resources it leaves out', () => {
const table = { props: ['rows'], template: '<div><slot name="cell:affectedCount" :row="rows[0]" :value="rows[0].affectedCount" /></div>' };
const row = {
...CHECK, affectedCount: 2, affectedResources: { kind: 'Volume', names: { one: { ignored: true, ignoredBy: 'r' }, two: {} } }
};
const hidden = mountChecks({ rows: [row] }, { SortableTable: table });
const shown = mountChecks({ rows: [row], showIgnored: true }, { SortableTable: table });
expect(hidden.findComponent(RcCounterBadge).props('count')).toBe(2);
expect(hidden.find('.hidden-ignored').text()).toContain('ignore.plusIgnored');
expect(shown.findComponent(RcCounterBadge).props('count')).toBe(2);
expect(shown.find('.hidden-ignored').exists()).toBe(false);
});
it('counts what "Show ignored" brings back, each thing once', () => {
const check = (ignored, names) => ({ ignored, affectedResources: { names } });
expect(ignoredCounts([
check(true, { a: { ignored: true }, b: { ignored: true } }),
check(false, { c: { ignored: true }, d: {} }),
check(false, {
e: { ignored: true }, f: { ignored: true }, g: {}
}),
check(false, { h: {} }),
])).toStrictEqual({ checks: 1, resources: 3 });
expect(ignoredCounts(undefined)).toStrictEqual({ checks: 0, resources: 0 });
});
it('names the rule of a check after it', () => {
expect(ignoreRuleName('harvester-controller-vmimage', 'ImageRetryLimitExceeded')).toBe('harvester-controller-vmimage.imageretrylimitexceeded');
});
it('turns what a name can not have in a check into hyphens', () => {
expect(ignoreRuleName('harvester-controller-schedulevmbackup', 'Proactive Schedule Suspend')).toBe('harvester-controller-schedulevmbackup.proactive-schedule-suspend');
expect(ignoreRuleName('h', ' Reach_Max Failure! ')).toBe('h.reach-max-failure');
});
it('tells the ignored resources apart, and all of them when the check is ignored', () => {
const table = { props: ['rows'], template: '<div><slot name="cell:severity" :row="rows[0]" /><slot name="cell:affectedCount" :row="rows[0]" :value="2" /></div>' };
const row = {
...CHECK, severity: 'Error', affectedResources: { kind: 'Volume', names: { one: { ignored: true, ignoredBy: 'r' }, two: {} } }
};
const wholeRow = {
...row, ignored: true, affectedResources: { kind: 'Volume', names: { one: {}, two: {} } }
};
const tags = (w) => w.findAllComponents(RcTag).map((tag) => ({
ignored: tag.classes().includes('ignored'), disabled: tag.props('disabled'), says: tag.text().includes('ignore.ignored')
}));
const partly = mountChecks({ rows: [row], showIgnored: true }, { SortableTable: table });
const whole = mountChecks({ rows: [wholeRow], showIgnored: true }, { SortableTable: table });
expect(tags(partly)).toStrictEqual([
{
ignored: true, disabled: true, says: true
},
{
ignored: false, disabled: false, says: false
},
]);
expect(partly.findComponent(BadgeState).props('color')).toBe('bg-error');
expect(tags(whole)).toStrictEqual([
{
ignored: true, disabled: true, says: false
},
{
ignored: true, disabled: true, says: false
},
]);
expect(whole.findComponent(BadgeState).props('color')).toBe('bg-error');
});
it('keeps the resources past the first ones behind a link', async() => {
const table = { props: ['rows'], template: '<div><slot name="cell:affectedCount" :row="rows[0]" :value="rows[0].affectedCount" /></div>' };
const names = Object.fromEntries(['a', 'b', 'c', 'd', 'e', 'f', 'g'].map((name) => [name, {}]));
const row = {
...CHECK, affectedCount: 7, affectedResources: { kind: 'VirtualMachine', names }
};
const w = mountChecks({ rows: [row] }, { SortableTable: table });
expect(w.findAllComponents(RcTag)).toHaveLength(3);
expect(w.find('button.variant-link').text()).toContain('generic.plusMore');
await w.find('button.variant-link').trigger('click');
expect(w.findAllComponents(RcTag)).toHaveLength(7);
expect(w.find('button.variant-link').text()).toContain('generic.showLess');
});
it('adds up the errors of all the components, for the alert on the tab', () => {
const components = {
x: { errorCount: 2, warningCount: 5 }, y: { errorCount: 1 }, z: {}
};
expect(totalErrorCount([summaryOf(components)])).toBe(3);
expect(totalErrorCount([summaryOf({ x: { warningCount: 5 } })])).toBe(0);
expect(totalErrorCount([{ id: 'empty' }])).toBe(0);
expect(totalErrorCount(undefined)).toBe(0);
});
it('names the resources by their schema, or by their kind without one', () => {
const store = {
getters: {
'harvester/schemaFor': (id) => (['longhorn.io.volume', 'node'].includes(id) ? { id } : null),
'type-map/labelFor': (schema, count) => `${ schema.id } ${ count }`,
}
};
const label = (apiVersion, kind) => affectedResourceLabel({ affectedCount: 6, affectedResources: { apiVersion, kind } }, store);
expect(label('longhorn.io/v1beta2', 'Volume')).toBe('longhorn.io.volume 6');
expect(label('v1', 'Node')).toBe('node 6');
expect(label('harvesterhci.io/v1beta1', 'Upgrade')).toBe('Upgrade');
});
it('tells when a component has no checks, unless they could not be loaded', () => {
expect(mountChecks({ rows: [] }).text()).toContain('noIssues');
expect(mountChecks({ rows: [], loadFailed: true }).text()).toContain('checksNotLoaded');
});
it('still shows the checks when the rules can not be loaded, and says so', async() => {
const w = await mountSummary({
healthSummaries: [summaryOf({ x: { errorCount: 1 } })],
componentHealths: [healthOf('h', 'x', { a: { severity: 'Error' } })],
failing: 'ignoreRules',
});
const checks = w.findComponent(ComponentChecksTable);
expect(checks.props('rows').map((r) => r.id)).toStrictEqual(['h/a']);
expect(checks.props('loadFailed')).toBe(false);
expect(w.findAllComponents(Banner).map((banner) => banner.props('label'))).toStrictEqual(['%harvester.dashboard.sections.componentHealth.loadFailed.ignoreRules%']);
});
it('does not call a component without issues when its checks can not be loaded', async() => {
const w = await mountSummary({
healthSummaries: [summaryOf({ x: { errorCount: 1 } })],
failing: 'componentHealths',
});
expect(w.findComponent(ComponentChecksTable).props('loadFailed')).toBe(true);
expect(w.findAllComponents(Banner).map((banner) => banner.props('label'))).toStrictEqual(['%harvester.dashboard.sections.componentHealth.loadFailed.componentHealths%']);
});
it('does not ask for the rules without their schema', async() => {
const onFindAll = jest.fn();
await mountSummary({ noSchemaFor: HCI.HEALTH_IGNORE_RULE, onFindAll });
expect(onFindAll.mock.calls.map(([type]) => type)).toStrictEqual([HCI.HEALTH_SUMMARY, HCI.COMPONENT_HEALTH]);
});
it('marks a check and the resources that are ignored', () => {
const table = {
props: ['rows'],
template: '<div><slot name="cell:checkName" :row="rows[0]" :value="rows[0].checkName" /><slot name="cell:affectedCount" :row="rows[0]" :value="2" /></div>',
};
const row = { ...CHECK, affectedResources: { kind: 'VirtualMachine', names: { one: { ignored: true, ignoredBy: 'r' }, two: {} } } };
const textOf = (props) => mountChecks({ showIgnored: true, ...props }, { SortableTable: table }).text().replace(/\s+/g, ' ');
expect(textOf({ rows: [row] })).toMatch(/one ?\(%harvester\.dashboard\.sections\.componentHealth\.ignore\.ignored%\) ?two/);
expect(textOf({ rows: [row] })).not.toContain('a (%harvester');
expect(textOf({ rows: [{ ...row, ignored: true }] })).toContain('a (%harvester.dashboard.sections.componentHealth.ignore.ignored%)');
});
describe('the actions of a check', () => {
it('offers to create a rule when the check has none from the UI', () => {
const elsewhere = ruleOf({}, { metadata: { name: 'ignore-x7k2p' } });
const { w, keys, invoke } = actionsOf({ ignoreRules: [ruleOf({ checkKey: 'b' }), ruleOf({ componentHealth: 'other' }), elsewhere] });
expect(keys).toStrictEqual(['create']);
invoke('create');
expect(w.emitted('open-rule')).toStrictEqual([[{
row: CHECK, rule: undefined, mode: 'create'
}]]);
});
it('offers to view, edit and delete the rule of the check, and only that one', () => {
const rule = ruleOf();
const elsewhere = ruleOf({}, { metadata: { name: 'ignore-x7k2p' } });
const { w, keys, invoke } = actionsOf({ ignoreRules: [elsewhere, ruleOf({ checkKey: 'b' }), rule] });
expect(keys).toStrictEqual(['view', 'edit', '-', 'delete']);
invoke('view');
invoke('edit');
invoke('delete');
expect(w.emitted('open-rule')).toStrictEqual([
[{
row: CHECK, rule, mode: 'view'
}],
[{
row: CHECK, rule, mode: 'edit'
}],
]);
expect(rule.promptRemove).toHaveBeenCalledTimes(1);
expect(elsewhere.promptRemove).not.toHaveBeenCalled();
});
it('only offers what the user is allowed to do', () => {
const keysFor = (extra) => actionsOf({ ignoreRules: [ruleOf({}, extra)] }).keys;
expect(keysFor({ canDelete: false })).toStrictEqual(['view', 'edit']);
expect(keysFor({ canUpdate: false })).toStrictEqual(['view', '-', 'delete']);
expect(keysFor({ canUpdate: false, canDelete: false })).toStrictEqual(['view']);
expect(actionsOf({}, { collectionMethods: ['GET'] }).keys).toStrictEqual([]);
expect(actionsOf({}, { noSchemaFor: HCI.HEALTH_IGNORE_RULE }).keys).toStrictEqual([]);
});
it('leaves out the menu when no check has anything in it', () => {
const rowActions = (props, storeProps) => actionsOf(props, storeProps).w.findComponent(checksTable).props('rowActions');
expect(rowActions({}, { collectionMethods: ['GET'] })).toBe(false);
expect(rowActions({ ignoreRules: [ruleOf()] }, { collectionMethods: ['GET'] })).toBe(true);
expect(rowActions({})).toBe(true);
});
});
describe('creating a rule', () => {
it('starts the modal over each time it opens', async() => {
const w = await mountSummary({
healthSummaries: [summaryOf({ x: { errorCount: 1 } })],
componentHealths: [healthOf('h', 'x', { a: { severity: 'Error' } })],
});
const open = async() => {
await w.findComponent(ComponentChecksTable).vm.$emit('open-rule', { row: CHECK, mode: 'create' });
await flushPromises();
};
expect(w.findComponent(RcModal).exists()).toBe(false);
await open();
await w.findComponent(LabeledInput).vm.$emit('update:value', 'known issue');
await flushPromises();
expect(w.findComponent(LabeledInput).props('value')).toBe('known issue');
await w.findComponent(RcModal).vm.$emit('close');
await flushPromises();
expect(w.findComponent(RcModal).exists()).toBe(false);
await open();
expect(w.findComponent(LabeledInput).props('value')).toBe('');
});
it('ignores the selected resources for the chosen time', async() => {
const { w, onClose, confirm } = mountRuleModal();
await w.findComponent(LabeledSelect).vm.$emit('update:value', ['two']);
await w.findComponent(LabeledInput).vm.$emit('update:value', 'known issue');
await flushPromises();
await confirm().trigger('click');
await flushPromises();
expect(cloneRule).not.toHaveBeenCalled();
expect(newRule.spec).toStrictEqual({
componentHealth: 'h',
checkKey: 'a',
resources: ['two'],
expiresAt: expect.any(String),
reason: 'known issue',
});
expect(saveRule).toHaveBeenCalledTimes(1);
expect(onClose).toHaveBeenCalledTimes(1);
});
it('names the rule after its check, so a second one for it is refused', async() => {
const { confirm } = mountRuleModal();
await confirm().trigger('click');
await flushPromises();
expect(createRule.mock.calls[0][1].metadata).toStrictEqual({ name: 'h.a', labels: { 'health.harvesterhci.io/source': 'user' } });
});
it('gives a check with spaces a valid name, and keeps the check as it is', async() => {
const { confirm } = mountRuleModal({ row: { ...CHECK, checkName: 'Proactive Schedule Suspend' } });
await confirm().trigger('click');
await flushPromises();
expect(createRule.mock.calls[0][1].metadata.name).toBe('h.proactive-schedule-suspend');
expect(newRule.spec.checkKey).toBe('Proactive Schedule Suspend');
});
it('says when the rule will expire, from 7 days on', async() => {
const {
confirm, duration, currentExpiry, newExpiry
} = mountRuleModal();
expect(currentExpiry().exists()).toBe(false);
expect(duration().props('value')).toBe('days7');
expect(newExpiry().text()).toContain('ignore.willExpireOn');
await duration().vm.$emit('update:value', 'forever');
await flushPromises();
expect(newExpiry().text()).toContain('ignore.willNeverExpire');
expect(confirm().attributes('disabled')).toBeUndefined();
});
it('ignores the entire check forever without listing its resources', async() => {
const { w, confirm } = mountRuleModal();
const [scope, duration] = w.findAllComponents(RadioGroup);
await scope.vm.$emit('update:value', 'check');
await duration.vm.$emit('update:value', 'forever');
await flushPromises();
await confirm().trigger('click');
await flushPromises();
expect(newRule.spec).toStrictEqual({ componentHealth: 'h', checkKey: 'a' });
});
it('only offers the entire check when the check lists no resources', () => {
const w = vtuMount(IgnoreRuleModal, {
...opts(),
props: { row: { ...CHECK, affectedResources: undefined }, modal: { show: true, onClose: jest.fn() } },
});
expect(w.findAllComponents(RadioGroup)).toHaveLength(1);
expect(w.findComponent(LabeledSelect).exists()).toBe(false);
});
it('can not ignore without a resource selected', async() => {
const { w, confirm } = mountRuleModal();
expect(confirm().attributes('disabled')).toBeUndefined();
await w.findComponent(LabeledSelect).vm.$emit('update:value', []);
await flushPromises();
expect(confirm().attributes('disabled')).toBeDefined();
});
it('stays open and shows the error when saving fails', async() => {
const { w, onClose, confirm } = mountRuleModal({ save: () => Promise.reject(new Error('forbidden')) });
await confirm().trigger('click');
await flushPromises();
expect(w.text()).toContain('forbidden');
expect(onClose).not.toHaveBeenCalled();
expect(confirm().attributes('disabled')).toBeUndefined();
});
it('does not close while the rule is saved', async() => {
let finishSaving;
const { w, onClose, confirm } = mountRuleModal({
save: () => new Promise((resolve) => {
finishSaving = resolve;
})
});
await confirm().trigger('click');
await flushPromises();
expect(confirm().attributes('disabled')).toBeDefined();
await w.findComponent(RcModal).vm.$emit('close');
expect(onClose).not.toHaveBeenCalled();
finishSaving();
await flushPromises();
expect(onClose).toHaveBeenCalledTimes(1);
});
});
describe('editing a rule', () => {
it('starts from what the rule has, with no new duration chosen', () => {
const rule = ruleOf({
resources: ['two'], expiresAt: IN_A_WEEK, reason: 'known issue'
});
const {
w, duration, currentExpiry, newExpiry
} = mountRuleModal({ rule, mode: 'edit' });
const [scope] = w.findAllComponents(RadioGroup);
expect(scope.props('value')).toBe('resources');
expect(w.findComponent(LabeledSelect).props('value')).toStrictEqual(['two']);
expect(currentExpiry().text()).toContain('ignore.expiresOn');
expect(duration().props('value')).toBeNull();
expect(duration().props('options').map((option) => option.value)).toStrictEqual(['days7', 'days30', 'forever']);
expect(newExpiry().exists()).toBe(false);
expect(w.findComponent(LabeledInput).props('value')).toBe('known issue');
});
it('can not save until something changes', async() => {
const { w, confirm, duration } = mountRuleModal({ rule: ruleOf(), mode: 'edit' });
const reason = (value) => w.findComponent(LabeledInput).vm.$emit('update:value', value);
expect(confirm().attributes('disabled')).toBeDefined();
await reason('known issue');
await flushPromises();
expect(confirm().attributes('disabled')).toBeUndefined();
await reason('');
await duration().vm.$emit('update:value', 'forever');
await flushPromises();
expect(confirm().attributes('disabled')).toBeDefined();
await duration().vm.$emit('update:value', 'days7');
await flushPromises();
expect(confirm().attributes('disabled')).toBeUndefined();
});
it('saves on a copy of the rule, with the expiry it has', async() => {
const rule = ruleOf({
resources: ['two'], expiresAt: IN_A_WEEK, reason: 'known issue'
});
const { w, onClose, confirm } = mountRuleModal({ rule, mode: 'edit' });
await w.findComponent(LabeledInput).vm.$emit('update:value', 'still known');
await flushPromises();
await confirm().trigger('click');
await flushPromises();
expect(createRule).not.toHaveBeenCalled();
expect(cloneRule.mock.calls[0][1]).toStrictEqual({ resource: rule });
expect(editedRule.spec).toStrictEqual({ ...rule.spec, reason: 'still known' });
expect(saveRule).toHaveBeenCalledTimes(1);
expect(onClose).toHaveBeenCalledTimes(1);
});
it('takes the resources, the expiry and the reason off the rule', async() => {
const { w, confirm, duration } = mountRuleModal({
rule: ruleOf({
resources: ['two'], expiresAt: IN_A_WEEK, reason: 'known issue'
}),
mode: 'edit'
});
const [scope] = w.findAllComponents(RadioGroup);
await scope.vm.$emit('update:value', 'check');
await duration().vm.$emit('update:value', 'forever');
await w.findComponent(LabeledInput).vm.$emit('update:value', '');
await flushPromises();
await confirm().trigger('click');
await flushPromises();
expect(editedRule.spec).toStrictEqual({ componentHealth: 'h', checkKey: 'a' });
});
it('renews an expired rule with the duration chosen', async() => {
const {
confirm, duration, currentExpiry, newExpiry
} = mountRuleModal({ rule: ruleOf({ expiresAt: LAST_WEEK }), mode: 'edit' });
expect(currentExpiry().text()).toContain('ignore.expiredOn');
await duration().vm.$emit('update:value', 'days30');
await flushPromises();
expect(newExpiry().text()).toContain('ignore.willExpireOn');
await confirm().trigger('click');
await flushPromises();
expect(new Date(editedRule.spec.expiresAt).getTime()).toBeGreaterThan(new Date(IN_A_WEEK).getTime());
});
it('warns that an expired rule stays expired when only something else changes', async() => {
const { w, duration, warning } = mountRuleModal({ rule: ruleOf({ expiresAt: LAST_WEEK }), mode: 'edit' });
expect(warning()).toBeUndefined();
await w.findComponent(LabeledInput).vm.$emit('update:value', 'known issue');
await flushPromises();
expect(warning().props('label')).toContain('ignore.staysExpired');
await duration().vm.$emit('update:value', 'days7');
await flushPromises();
expect(warning()).toBeUndefined();
});
it('does not warn about a rule that has not expired', async() => {
const { w, warning } = mountRuleModal({ rule: ruleOf({ expiresAt: IN_A_WEEK }), mode: 'edit' });
await w.findComponent(LabeledInput).vm.$emit('update:value', 'known issue');
await flushPromises();
expect(warning()).toBeUndefined();
});
it('opens a rule without resources on the entire check, and selects them all when asked', async() => {
const {
w, confirm, duration, currentExpiry
} = mountRuleModal({ rule: ruleOf(), mode: 'edit' });
const [scope] = w.findAllComponents(RadioGroup);
expect(scope.props('value')).toBe('check');
expect(currentExpiry().text()).toContain('ignore.neverExpires');
expect(duration().props('value')).toBeNull();
expect(w.findComponent(LabeledSelect).exists()).toBe(false);
await scope.vm.$emit('update:value', 'resources');
await flushPromises();
expect(w.findComponent(LabeledSelect).props('value')).toStrictEqual(['one', 'two']);
await confirm().trigger('click');
await flushPromises();
expect(editedRule.spec.resources).toStrictEqual(['one', 'two']);
});
it('keeps a resource of the rule that is no longer affected', async() => {
const { w, confirm } = mountRuleModal({ rule: ruleOf({ resources: ['gone', 'two'] }), mode: 'edit' });
const select = w.findComponent(LabeledSelect);
expect(select.props('options')).toStrictEqual(['one', 'two', 'gone']);
expect(select.props('value')).toStrictEqual(['two', 'gone']);
await w.findComponent(LabeledInput).vm.$emit('update:value', 'known issue');
await flushPromises();
await confirm().trigger('click');
await flushPromises();
expect(editedRule.spec.resources).toStrictEqual(['two', 'gone']);
});
});
describe('viewing a rule', () => {
it('shows what the rule has without letting it change', async() => {
const {
w, onClose, confirm, duration, currentExpiry
} = mountRuleModal({
rule: ruleOf({
resources: ['two'], expiresAt: IN_A_WEEK, reason: 'known issue'
}),
mode: 'view'
});
[...w.findAllComponents(RadioGroup), w.findComponent(LabeledSelect), w.findComponent(LabeledInput)].forEach((field) => {
expect(field.props('mode')).toBe('view');
});
expect(currentExpiry().text()).toContain('ignore.expiresOn');
expect(duration()).toBeUndefined();
expect(w.findComponent(LabeledInput).props('value')).toBe('known issue');
expect(confirm().exists()).toBe(false);
expect(w.find('[data-testid="rc-modal-cancel"]').exists()).toBe(false);
await w.find('[data-testid="component-health-ignore-close"]').trigger('click');
expect(onClose).toHaveBeenCalledTimes(1);
expect(cloneRule).not.toHaveBeenCalled();
expect(saveRule).not.toHaveBeenCalled();
});
});
});
@@ -0,0 +1,224 @@
<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>
+536 -83
View File
@@ -1,153 +1,606 @@
<template>
<div>
<div v-if="connected && disconnected">
<main class="main-layout error">
<div class="text-center">
<BrandImage
file-name="error-desert-landscape.svg"
width="900"
height="300"
/>
<h1>
{{ t('generic.notification.title.warning') }}
</h1>
<h2 class="text-secondary mt-20">
{{ t('vncConsole.error.message') }}
</h2>
</div>
</main>
</div>
<div v-if="reconnecting">
<main class="main-layout">
<div class="text-center">
<h2 class="text-secondary mt-20">
{{ t('vncConsole.reconnecting.message') }}:{{ retryTimes }} of {{ maximumRetryTimes }}
</h2>
</div>
</main>
</div>
<div
ref="view"
/>
</div>
</template>
<script>
import RFB from '@novnc/novnc/core/rfb';
import BrandImage from '@shell/components/BrandImage';
import { RcButton } from '@components/RcButton';
import { RcIcon } from '@components/RcIcon';
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 {
name: 'NovncConsole',
components: {
RcButton, RcIcon, RcModal, NovncStatusCard
},
props: {
url: {
type: String,
default: ''
}
},
settings: {
type: Object,
default: () => ({})
},
// KubeVirt honours preserveSession from v1.6.3. Older versions ignore it, so every
// connection takes the console over and automatic retries would kick the other user.
preserveSession: {
type: Boolean,
default: true
},
vmRunning: {
type: Boolean,
default: true
},
vmName: {
type: String,
default: ''
},
// When the VM was seen starting to run on this page (ms), or 0.
startedAt: {
type: Number,
default: 0
},
},
components: { BrandImage },
emits: ['status-changed', 'capabilities'],
data() {
return {
rfb: null,
connected: false,
disconnected: false,
reconnectDelay: 3000,
reconnecting: false,
maximumRetryTimes: 10,
status: CONSOLE_STATUS.CONNECTING,
statusDetail: '',
desktopName: '',
retryTimes: 0,
setTimeout: null,
maximumRetryTimes: MAXIMUM_RETRY_TIMES,
reconnectTimer: null,
isClosed: false,
failure: '',
showTakeOverModal: false,
focused: false,
};
},
computed: {
statusInfo() {
return {
status: this.status,
detail: this.statusDetail,
desktopName: this.desktopName,
retryTimes: this.retryTimes,
maximumRetryTimes: this.maximumRetryTimes,
};
},
showError() {
return this.status === CONSOLE_STATUS.FAILED || (this.status === CONSOLE_STATUS.DISCONNECTED && this.failure === CONSOLE_FAILURE.DROPPED);
},
// 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() {
// noVNC hides the canvas focus outline, so track focus to show where typing goes.
this.$refs.view.addEventListener('focusin', this.onFocusIn);
this.$refs.view.addEventListener('focusout', this.onFocusOut);
this.$nextTick(() => {
this.connect();
});
},
beforeUnmount() {
this.clearTimeout();
this.$refs.view?.removeEventListener('focusin', this.onFocusIn);
this.$refs.view?.removeEventListener('focusout', this.onFocusOut);
this.isClosed = true;
this.clearReconnectTimer();
this.teardown();
},
methods: {
connect() {
const rfb = new RFB(this.$refs.view, this.url);
connect(takeOver = false) {
if (!this.url || this.isClosed) {
return;
}
rfb.addEventListener('connect', () => {
this.clearTimeout();
this.teardown();
this.connected = true;
this.retryTimes = 0;
this.reconnecting = false;
});
this.failure = '';
this.status = this.retryTimes > 0 ? CONSOLE_STATUS.RECONNECTING : CONSOLE_STATUS.CONNECTING;
rfb.addEventListener('disconnect', (e) => {
this.clearTimeout();
let rfb;
this.disconnected = true;
this.rfb = null;
this.reconnect();
});
try {
const url = new URL(this.url);
if (this.preserveSession) {
url.searchParams.set('preserveSession', takeOver === true ? 'false' : 'true');
}
rfb = new ZoomableRFB(this.$refs.view, url.href, { shared: true });
} catch (err) {
this.statusDetail = err?.message || `${ err }`;
this.status = CONSOLE_STATUS.FAILED;
return;
}
// 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.applySettings();
},
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) {
this.reconnecting = false;
this.connected = true;
this.disconnected = true;
this.fail(this.vmRunning ? CONSOLE_FAILURE.IN_USE : CONSOLE_FAILURE.UNAVAILABLE);
return;
}
this.retryTimes += 1;
this.reconnecting = true;
this.connected = false;
this.disconnected = false;
this.status = CONSOLE_STATUS.RECONNECTING;
this.setTimeout = setTimeout(() => {
const delay = Math.min(BASE_RECONNECT_DELAY * (2 ** (this.retryTimes - 1)), MAXIMUM_RECONNECT_DELAY);
this.reconnectTimer = setTimeout(() => {
this.reconnectTimer = null;
this.connect();
}, this.reconnectDelay);
}, delay);
},
clearTimeout() {
if (this.setTimeout) {
clearTimeout(this.setTimeout);
clearReconnectTimer() {
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
},
disconnect() {
this.rfb.disconnect();
teardown(disconnect = true) {
const rfb = this.rfb;
if (!rfb) {
return;
}
this.rfb = null;
rfb.removeEventListener('connect', this.onConnect);
rfb.removeEventListener('disconnect', this.onDisconnect);
rfb.removeEventListener('securityfailure', this.onSecurityFailure);
rfb.removeEventListener('credentialsrequired', this.onCredentialsRequired);
rfb.removeEventListener('desktopname', this.onDesktopName);
rfb.removeEventListener('capabilities', this.onCapabilities);
if (!disconnect) {
return;
}
try {
rfb.disconnect();
} catch (err) {
// The socket may already be gone, nothing left to clean up.
}
},
applySettings() {
const rfb = this.rfb;
if (!rfb) {
return;
}
const settings = this.settings || {};
// 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() {
this.rfb.sendCtrlAltDel();
this.rfb?.sendCtrlAltDel();
},
sendKey(keysym, code, down) {
this.rfb.sendKey(keysym, code, down);
}
this.rfb?.sendKey(keysym, code, down);
},
}
};
</script>
<template>
<div
class="novnc-console"
: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>
.error {
// Without a live picture the screen is black like a monitor, so the overlays read the same in
// 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;
background: #000;
.row {
&.is-live {
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;
gap: 16px;
max-width: 480px;
padding: 0 20px;
}
h1 {
font-size: 5rem;
// RcIcon has no 20px size, the one the design uses here, so it inherits it.
&__spinner {
display: flex;
font-size: 20px;
}
.desert-landscape {
img {
max-width: 100%;
}
&__connecting-label {
margin: 0;
font-size: 16px;
line-height: 21px;
}
}
</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,264 +1,355 @@
<script>
import { STEVE } from '@shell/config/types';
import { stringify } from '@shell/utils/error';
import Banner from '@components/Banner/Banner.vue';
import AsyncButton from '@shell/components/AsyncButton';
import ModalWithCard from '@shell/components/ModalWithCard';
const PREFERED_SHORTCUT_KEYS = 'prefered-shortcut-keys';
import { RcButton } from '@components/RcButton';
import { RcIcon } from '@components/RcIcon';
import { RcModal } from '@components/RcModal';
import RcTag from '@components/Pill/RcTag';
import { LabeledInput } from '@components/Form/LabeledInput';
import NovncKeyRecorder from './NovncKeyRecorder';
import { readShortcuts, shortcutId, shortcutLabels, writeShortcuts } from './shortcuts';
export default {
name: 'NovncConsoleCustomKeys',
emits: ['close'],
components: {
ModalWithCard, Banner, AsyncButton
Banner, RcButton, RcIcon, RcModal, RcTag, LabeledInput, NovncKeyRecorder
},
props: {
show: {
type: Boolean,
default: false,
},
},
emits: ['close'],
data() {
return {
keysRecord: [],
addedShortcutKeys: [],
preferredShortcutKeys: [],
isRecording: false,
keys: [],
name: '',
saving: false,
error: '',
};
},
computed: {
savedShortcutKeys() {
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;
preference() {
return this.$store.getters['management/all'](STEVE.PREFERENCE)?.[0];
},
displayedKeys() {
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;
shortcuts() {
return readShortcuts(this.preference).map((shortcut) => ({ ...shortcut, labels: shortcutLabels(shortcut) }));
},
recordButton() {
if (this.isRecording) {
return 'harvester.virtualMachine.detail.console.record.stop';
}
isDuplicate() {
const id = shortcutId({ keys: this.keys });
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(',') }`;
return !!this.keys.length && this.shortcuts.some((shortcut) => shortcutId(shortcut) === id);
},
canAdd() {
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;
return !!this.keys.length && !this.isDuplicate;
},
},
watch: {
savedShortcutKeys: {
handler() {
this.preferredShortcutKeys = [].concat(this.savedShortcutKeys) || [];
},
immediate: true
show(show) {
if (!show) {
this.error = '';
}
},
},
methods: {
closeRecordingModal() {
window.removeEventListener('keydown', this.handleShortcut);
this.$emit('close');
clear() {
this.keys = [];
this.name = '';
},
toggleRecording() {
this.isRecording = !this.isRecording;
// The buttons stay enabled while a change saves: disabling the one that was pressed would drop the
// keyboard's focus to the page.
async add() {
if (!this.canAdd || this.saving) {
return;
}
if (this.isRecording) {
this.keysRecord = [];
window.addEventListener('keydown', this.handleShortcut);
} else {
window.removeEventListener('keydown', this.handleShortcut);
const { name, keys } = this;
const shortcuts = [...this.shortcuts, { name: name.trim(), keys }];
// The list shows the new shortcut while it saves, and a form still holding it would say it is already
// saved, so the form empties now. Add shortcut turns disabled with it, so the recorder takes the focus.
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;
}
},
handleShortcut(event) {
event.preventDefault();
async remove(index) {
if (this.saving) {
return;
}
const {
key, keyCode, code, location, charCode
} = event;
const removed = await this.save(this.shortcuts.filter((_, i) => i !== index));
this.keysRecord.push({
key, keyCode, code, location, charCode
});
// The row may be gone with the button that had the focus: the delete button now in its place, or
// the last one, takes it, and the recorder once the list is empty.
if (removed) {
this.$nextTick(() => {
const buttons = this.$refs.list?.querySelectorAll('button') || [];
(buttons[index] || buttons[buttons.length - 1] || this.$refs.recorder?.$el)?.focus();
});
}
},
addShortcutKey() {
this.addedShortcutKeys.push([].concat(this.keysRecord));
},
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];
// Every change is saved straight away, so closing the modal can never lose one.
async save(shortcuts) {
this.saving = true;
this.error = '';
try {
preference.data[PREFERED_SHORTCUT_KEYS] = JSON.stringify(out);
await preference.save();
this.closeRecordingModal();
buttonCb(true);
await writeShortcuts(this.preference, shortcuts.map(({ name, keys }) => ({ name, keys })));
return true;
} catch (err) {
buttonCb(false);
// The console page has no growls, so the dialog says it itself.
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>
<template>
<ModalWithCard
name="recordShortcutKeys"
:width="550"
<RcModal
:show="show"
size="medium"
:title="t('harvester.virtualMachine.detail.console.customKeys.title')"
data-testid="vnc-custom-keys-modal"
@close="$emit('close')"
>
<template #title>
<t k="harvester.virtualMachine.detail.console.customShortcutKeys" />
</template>
<Banner
v-if="error"
color="error"
role="alert"
data-testid="vnc-custom-keys-error"
>
{{ error }}
</Banner>
<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>
<p class="custom-keys__intro">
{{ t('harvester.virtualMachine.detail.console.customKeys.description') }}
</p>
<hr>
<section class="custom-keys__new">
<h3 class="custom-keys__heading">
{{ t('harvester.virtualMachine.detail.console.customKeys.new') }}
</h3>
<div class="displayed-keys mt-20">
<h4
v-clean-html="t('harvester.virtualMachine.detail.console.record.preferredKeys')"
class="text-default-text"
<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"
/>
<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"
<p
v-if="isDuplicate"
class="custom-keys__error"
role="alert"
>
<t k="generic.close" />
</button>
<AsyncButton
mode="done"
@click="saveKeys"
/>
{{ 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>
</ModalWithCard>
</RcModal>
</template>
<style lang="scss" scoped>
.displayed-keys {
.banner {
.custom-keys {
&__intro {
margin: 0;
}
}
.displayed-banners {
max-height: 155px;
overflow: auto;
}
&__new {
display: flex;
flex-direction: column;
gap: 16px;
padding: 16px 20px 20px;
border: 1px solid var(--border);
border-radius: 8px;
}
.actions {
width: 100%;
display: flex;
justify-content: flex-end;
&__heading {
margin: 0 0 12px;
font-size: 14px;
font-weight: 700;
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>
@@ -1,108 +0,0 @@
<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,15 +1,41 @@
<script>
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 { allHash } from '@shell/utils/promise';
import KeyTable from '@novnc/novnc/core/input/keysym';
import * as KeyboardUtil from '@novnc/novnc/core/input/util';
import { HCI } from '../../types';
import NovncConsole from './NovncConsole';
import NovncConsoleItem from './NovncConsoleItem';
import NovncConsole, { CONSOLE_STATUS } from './NovncConsole';
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';
const PREFERED_SHORTCUT_KEYS = 'prefered-shortcut-keys';
// The previous console saved its defaults under its key the first time it opened, so they can't tell a
// 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 = {
ControlLeft: {
@@ -106,15 +132,29 @@ const F_KEYS = {
export default {
name: 'NovncConsoleWrapper',
components: {
NovncConsole, NovncConsoleItem, NovncConsoleCustomKeys
RcButton, RcModal, Checkbox, NovncConsole, NovncConsoleCustomKeys, NovncConnectionStatus, NovncIcon, NovncShortcutKeysMenu, NovncStatusCard, NovncViewOptions
},
// A VM that is not running has no instance, so find it by the uid in the route instead.
async fetch() {
const _hash = { vmResource: this.$store.dispatch('harvester/find', { type: HCI.VM, id: this.value.id }) };
if (this.value?.id) {
const hash = await allHash({ vmResource: this.$store.dispatch('harvester/find', { type: HCI.VM, id: this.value.id }) });
const hash = await allHash(_hash);
this.vmResource = hash.vmResource;
this.vmResource = hash.vmResource;
return;
}
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: {
@@ -129,45 +169,89 @@ export default {
data() {
return {
keysRecord: [],
vmResource: {},
renderKeysModal: false,
currentUser: null,
hideCustomKeysBar: false,
settings: { ...DEFAULT_SETTINGS },
capabilities: {},
isFullscreen: false,
confirmAction: null,
startedAt: 0,
consoleStatus: {
status: 'connecting',
retryTimes: 0,
maximumRetryTimes: 0,
desktopName: '',
},
};
},
computed: {
savedShortcutKeys() {
const preference = this.$store.getters['management/all'](STEVE.PREFERENCE);
const preferedShortcutKeys = preference?.[0]?.data?.[PREFERED_SHORTCUT_KEYS];
let out = [];
if (!preference?.[0]?.data) {
// eslint-disable-next-line vue/no-side-effects-in-computed-properties
this.hideCustomKeysBar = true;
return out;
}
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;
preference() {
return this.$store.getters['management/all'](STEVE.PREFERENCE)?.[0];
},
// Custom keys are stored in the user preference, which is not available everywhere.
hideCustomKeysBar() {
return !this.preference?.data;
},
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() {
return this.isEmpty(this.value);
return this.isEmpty(this.value) || !this.vmRunning;
},
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() {
@@ -185,37 +269,65 @@ 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() {
return !!this.vmResource?.actions?.softreboot;
},
preferredShortcutKeys() {
return (this.savedShortcutKeys || []).map((item) => {
return {
label: item.map((K) => K.key.charAt(0).toUpperCase() + K.key.slice(1)).join('+'),
value: item
};
});
rfbSettings() {
return {
viewOnly: !!this.settings.viewOnly,
// Full screen always fills the window; the saved mode is back on leaving it.
scaleViewport: this.isFullscreen || this.settings.viewMode === VIEW_MODE.SCALE,
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: {
@@ -224,45 +336,65 @@ export default {
},
close() {
this.$refs.novncConsole.disconnect();
this.$refs.novncConsole?.disconnect();
},
update({ key, pos }) {
this.keysRecord.splice(pos, this.keysRecord.length - pos, key);
},
// Press the keys in order, then release them in reverse, e.g. Ctrl+Alt+F2.
sendKeys(keys) {
if (!this.canSendKeys || !this.$refs.novncConsole) {
return;
}
// Send function key, e.g. ALT + F
sendKeys() {
this.keysRecord.forEach((key) => {
keys.forEach((key) => {
this.$refs.novncConsole.sendKey(this.allKeys[key].value, key, true);
});
this.keysRecord.reverse().forEach((key) => {
[...keys].reverse().forEach((key) => {
this.$refs.novncConsole.sendKey(this.allKeys[key].value, key, false);
});
this.$refs.popover.isOpen = false;
this.keysRecord = [];
this.focusConsole();
},
sendCustomKeys(keys) {
const keyList = [].concat(keys);
if (!this.canSendKeys || !this.$refs.novncConsole) {
return;
}
const combination = [].concat(keys);
const keyList = combination.map((K) => baseKey(K, combination));
keyList.forEach((K) => {
this.$refs.novncConsole.sendKey(KeyboardUtil.getKeysym(K), KeyboardUtil.getKeycode(K), true);
});
keyList.reverse().forEach((K) => {
[...keyList].reverse().forEach((K) => {
this.$refs.novncConsole.sendKey(KeyboardUtil.getKeysym(K), KeyboardUtil.getKeycode(K), false);
});
this.focusConsole();
},
reconnect() {
this.$refs.novncConsole.reconnect();
// The shortcut menu hands focus back to its trigger as it closes, so take it on the next tick.
focusConsole() {
this.$nextTick(() => this.$refs.novncConsole?.focus());
},
softReboot() {
this.vmResource.doSoftReboot();
// RcModal's focus trap returns focus to the opener in a timeout once the modal unmounts,
// so queue ours behind it.
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() {
@@ -271,116 +403,516 @@ export default {
hideKeysModal() {
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>
<template>
<div id="app">
<div class="vm-console">
<div class="combination-keys">
<v-dropdown
ref="popover"
placement="top"
trigger="click"
:container="false"
@auto-hide="keysRecord = []"
>
<button class="btn btn-sm bg-primary">
{{ t("harvester.virtualMachine.detail.console.shortcutKeys") }}
</button>
<template #popper>
<novnc-console-item
:items="keymap"
:path="keysRecord"
:pos="0"
@update="update"
@send-keys="sendKeys"
/>
</template>
</v-dropdown>
<button
v-if="hasSoftRebootAction"
class="btn btn-sm bg-primary"
@click="softReboot"
>
{{ t("harvester.action.softreboot") }}
</button>
<button
class="btn btn-sm bg-primary"
@click="reconnect"
>
{{ t("harvester.action.reconnect") }}
</button>
<v-dropdown
v-if="!hideCustomKeysBar"
ref="customKeyPopover"
placement="top"
trigger="click"
:container="false"
>
<button class="btn btn-sm bg-primary">
{{ t("harvester.virtualMachine.detail.console.customShortcutKeys") }}
</button>
<template #popper>
<div>
<button
class="btn btn-sm bg-primary"
@click="showKeysModal"
>
{{ t("harvester.virtualMachine.detail.console.management") }}
</button>
</div>
<hr>
<div
v-for="(keys, index) in preferredShortcutKeys"
:key="index"
>
<button
class="btn btn-sm bg-primary"
@click="sendCustomKeys(keys.value)"
>
{{ keys.label }}
</button>
</div>
</template>
</v-dropdown>
<NovncConsoleCustomKeys
v-if="renderKeysModal"
:current-user="currentUser"
@close="hideKeysModal"
<div
ref="consoleContainer"
class="vm-console"
:class="{ 'vm-console--fullscreen': isFullscreen }"
>
<div
v-if="isFullscreen"
class="fullscreen-bar"
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>
<NovncIcon type="minimize" />
</template>
{{ t('harvester.virtualMachine.detail.console.fullscreen.exit') }}
</RcButton>
</div>
<NovncConsole
v-if="url && !isDown"
ref="novncConsole"
:url="url"
<header
v-else
class="console-toolbar"
>
<div class="console-toolbar__identity">
<div class="console-toolbar__vm">
<span
class="console-toolbar__vm-name"
data-testid="vnc-vm-name"
>{{ vmName }}</span>
<span class="console-toolbar__vm-namespace">{{ vmNamespace }}</span>
</div>
<NovncConnectionStatus
:status="connectionStatus"
:label="statusLabel"
:vm-name="vmName"
@reconnect="reconnect"
/>
<Checkbox
class="console-toolbar__view-only"
:value="!!settings.viewOnly"
:label="t('harvester.virtualMachine.detail.console.viewOnly')"
use-body-text-color
data-testid="vnc-view-only"
@update:value="setViewOnly"
/>
</div>
<div class="console-toolbar__group">
<NovncShortcutKeysMenu
v-bind="shortcutMenuProps"
@send-keys="sendKeys"
@send-shortcut="sendCustomKeys"
@manage="showKeysModal"
@ctrl-alt-del="ctrlAltDelete"
/>
</div>
<span
class="console-toolbar__divider"
aria-hidden="true"
/>
<div class="console-toolbar__group">
<RcButton
variant="tertiary"
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") }}
</RcButton>
<template #popper>
<NovncViewOptions
:settings="settings"
@update="updateSettings"
@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>
<RcModal
:show="!!confirmAction"
size="small"
: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>
</template>
<style lang="scss" scoped>
.vm-console {
height: 100%;
height: 100vh;
height: 100dvh;
display: grid;
grid-template-rows: 30px auto;
grid-template-columns: minmax(0, 1fr);
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;
}
}
}
.combination-keys {
background: rgb(40, 40, 40);
.fullscreen-bar {
// vnc.vue stretches the console's child divs to full height; the bar keeps its own.
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>
@@ -0,0 +1,73 @@
<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>
@@ -0,0 +1,232 @@
<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>
@@ -0,0 +1,404 @@
<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>
@@ -0,0 +1,104 @@
<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>
@@ -0,0 +1,302 @@
<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>
@@ -0,0 +1,73 @@
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';
}
}
}
@@ -0,0 +1,19 @@
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);
});
});
@@ -0,0 +1,241 @@
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);
});
});
@@ -0,0 +1,161 @@
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([]);
});
});
@@ -0,0 +1,321 @@
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;
});
});
});
@@ -0,0 +1,91 @@
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']);
});
});
@@ -0,0 +1,158 @@
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([]);
});
});
@@ -0,0 +1,36 @@
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);
});
});
@@ -0,0 +1,109 @@
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
@@ -0,0 +1,118 @@
// 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;
});
}
@@ -19,7 +19,8 @@ export default {
<div class="row mb-20">
<div class="col span-12">
<FileSelector
class="btn btn-sm bg-primary mb-10"
variant="primary"
class="mb-10"
:label="t('generic.readFromFile')"
@selected="onKeySelected"
/>
@@ -0,0 +1,196 @@
<script>
import { RadioGroup } from '@components/Form/Radio';
import LabeledSelect from '@shell/components/form/LabeledSelect';
import { NAMESPACE } from '@shell/config/types';
import CreateEditView from '@shell/mixins/create-edit-view';
export default {
name: 'HarvesterClusterPodSecurityStandard',
components: {
RadioGroup,
LabeledSelect,
},
mixins: [CreateEditView],
props: {
value: {
type: Object,
default: () => ({}),
},
},
async fetch() {
const inStore = this.$store.getters['currentProduct'].inStore;
await this.$store.dispatch(`${ inStore }/findAll`, { type: NAMESPACE });
},
data() {
let enabled = false;
let whitelistedNamespaces = [];
let privilegedNamespaces = [];
let restrictedNamespaces = [];
try {
const parsed = JSON.parse(this.value.value || this.value.default || '{}');
enabled = !!parsed.enabled;
whitelistedNamespaces = parsed.whitelistedNamespacesList ? parsed.whitelistedNamespacesList.split(',') : [];
privilegedNamespaces = parsed.privilegedNamespacesList ? parsed.privilegedNamespacesList.split(',') : [];
restrictedNamespaces = parsed.restrictedNamespacesList ? parsed.restrictedNamespacesList.split(',') : [];
} catch (e) {
enabled = false;
whitelistedNamespaces = [];
privilegedNamespaces = [];
restrictedNamespaces = [];
}
return {
enabled,
whitelistedNamespaces,
privilegedNamespaces,
restrictedNamespaces,
};
},
computed: {
enabledOptions() {
return [
{ label: this.t('generic.enabled'), value: true },
{ label: this.t('generic.disabled'), value: false },
];
},
allNamespaces() {
const inStore = this.$store.getters['currentProduct'].inStore;
return this.$store.getters[`${ inStore }/all`](NAMESPACE).filter((ns) => !ns.isSystem).map((ns) => ns.id);
},
whitelistedOptions() {
const excluded = new Set([...this.privilegedNamespaces, ...this.restrictedNamespaces]);
return this.allNamespaces.filter((ns) => !excluded.has(ns));
},
privilegedOptions() {
const excluded = new Set([...this.whitelistedNamespaces, ...this.restrictedNamespaces]);
return this.allNamespaces.filter((ns) => !excluded.has(ns));
},
restrictedOptions() {
const excluded = new Set([...this.whitelistedNamespaces, ...this.privilegedNamespaces]);
return this.allNamespaces.filter((ns) => !excluded.has(ns));
},
},
methods: {
useDefault() {
try {
const parsed = JSON.parse(this.value.default || '{}');
this.enabled = !!parsed.enabled;
this.whitelistedNamespaces = parsed.whitelistedNamespacesList ? parsed.whitelistedNamespacesList.split(',') : [];
this.privilegedNamespaces = parsed.privilegedNamespacesList ? parsed.privilegedNamespacesList.split(',') : [];
this.restrictedNamespaces = parsed.restrictedNamespacesList ? parsed.restrictedNamespacesList.split(',') : [];
} catch (e) {
this.enabled = false;
this.whitelistedNamespaces = [];
this.privilegedNamespaces = [];
this.restrictedNamespaces = [];
}
this.save();
},
onUpdateEnabled() {
if (!this.enabled) {
this.whitelistedNamespaces = [];
this.privilegedNamespaces = [];
this.restrictedNamespaces = [];
}
this.save();
},
updateWhitelisted(selected) {
this.whitelistedNamespaces = selected;
this.save();
},
updatePrivileged(selected) {
this.privilegedNamespaces = selected;
this.save();
},
updateRestricted(selected) {
this.restrictedNamespaces = selected;
this.save();
},
save() {
this.value.value = JSON.stringify({
enabled: this.enabled,
whitelistedNamespacesList: this.whitelistedNamespaces.join(','),
privilegedNamespacesList: this.privilegedNamespaces.join(','),
restrictedNamespacesList: this.restrictedNamespaces.join(','),
});
},
},
};
</script>
<template>
<div>
<div class="row mb-20">
<div class="col span-6">
<RadioGroup
v-model:value="enabled"
name="enabled"
:options="enabledOptions"
@update:value="onUpdateEnabled"
/>
</div>
</div>
<template v-if="enabled">
<div class="row mb-20">
<div class="col span-12">
<LabeledSelect
v-model:value="whitelistedNamespaces"
:label="t('harvester.setting.clusterPodSecurityStandard.whitelistedNamespaces.label')"
:options="whitelistedOptions"
:multiple="true"
:mode="mode"
@update:value="updateWhitelisted"
/>
</div>
</div>
<div class="row mb-20">
<div class="col span-12">
<LabeledSelect
v-model:value="privilegedNamespaces"
:label="t('harvester.setting.clusterPodSecurityStandard.privilegedNamespaces.label')"
:options="privilegedOptions"
:multiple="true"
:mode="mode"
@update:value="updatePrivileged"
/>
</div>
</div>
<div class="row mb-20">
<div class="col span-12">
<LabeledSelect
v-model:value="restrictedNamespaces"
:label="t('harvester.setting.clusterPodSecurityStandard.restrictedNamespaces.label')"
:options="restrictedOptions"
:multiple="true"
:mode="mode"
@update:value="updateRestricted"
/>
</div>
</div>
</template>
</div>
</template>
@@ -0,0 +1,123 @@
<script>
import MessageLink from '@shell/components/MessageLink';
import CreateEditView from '@shell/mixins/create-edit-view';
import { LabeledInput } from '@components/Form/LabeledInput';
import { HCI_SETTING } from '../../config/settings';
import { Checkbox } from '@components/Form/Checkbox';
import { Banner } from '@components/Banner';
export default {
name: 'HarvesterEditClusterRegistrationURL',
components: {
LabeledInput, MessageLink, Checkbox, Banner
},
mixins: [CreateEditView],
data() {
let parseDefaultValue = {};
try {
parseDefaultValue = JSON.parse(this.value.value);
} catch (error) {
parseDefaultValue.url = this.value.value;
parseDefaultValue.insecureSkipTLSVerify = true;
}
return {
parseDefaultValue,
errors: []
};
},
computed: {
toCA() {
return `${ HCI_SETTING.ADDITIONAL_CA }?mode=edit`;
},
clusterRegistrationTLSVerifyEnabled() {
return this.$store.getters['harvester-common/getFeatureEnabled']('clusterRegistrationTLSVerify');
},
registrationURL: {
get() {
return this.clusterRegistrationTLSVerifyEnabled ? this.parseDefaultValue.url : this.parseDefaultValue;
},
set(value) {
if (this.clusterRegistrationTLSVerifyEnabled) {
this.parseDefaultValue.url = value;
} else {
this.parseDefaultValue = value;
}
}
}
},
methods: {
getDefaultValue() {
if (this.clusterRegistrationTLSVerifyEnabled) {
return { url: '', insecureSkipTLSVerify: false };
} else {
return '';
}
},
updateUrl() {
this.update();
},
update() {
if (this.clusterRegistrationTLSVerifyEnabled) {
this.value['value'] = JSON.stringify(this.parseDefaultValue);
} else {
this.value['value'] = this.parseDefaultValue;
}
},
useDefault() {
this.parseDefaultValue = this.getDefaultValue();
},
updateInsecureSkipTLSVerify(newValue) {
const { url = '' } = this.parseDefaultValue;
this.parseDefaultValue = { url, insecureSkipTLSVerify: newValue };
this.update();
},
}
};
</script>
<template>
<div
class="row"
>
<div class="col span-12">
<Banner color="info">
<MessageLink
:to="toCA"
target="_blank"
prefix-label="harvester.setting.clusterRegistrationUrl.tip.prefix"
middle-label="harvester.setting.clusterRegistrationUrl.tip.middle"
suffix-label="harvester.setting.clusterRegistrationUrl.tip.suffix"
/>
</Banner>
<LabeledInput
v-model:value="registrationURL"
class="mb-20"
:mode="mode"
:label="t('harvester.setting.clusterRegistrationUrl.url')"
@update:value="updateUrl"
/>
<div v-if="clusterRegistrationTLSVerifyEnabled">
<Checkbox
v-model:value="parseDefaultValue.insecureSkipTLSVerify"
class="check mb-5"
type="checkbox"
:label="t('harvester.setting.clusterRegistrationUrl.insecureSkipTLSVerify')"
@update:value="updateInsecureSkipTLSVerify"
/>
</div>
</div>
</div>
</template>
@@ -0,0 +1,104 @@
<script>
import UnitInput from '@shell/components/form/UnitInput';
import { Banner } from '@components/Banner';
export default {
name: 'HarvesterInstanceManagerResources',
components: {
UnitInput,
Banner,
},
props: {
value: {
type: Object,
default: () => ({
value: '',
default: '{}'
})
},
},
data() {
const resources = this.parseJSON(this.value?.value) || this.parseJSON(this.value?.default) || {};
return {
resources,
parseError: null,
};
},
methods: {
parseJSON(string) {
try {
return JSON.parse(string);
} catch (e) {
this.parseError = this.t('harvester.setting.instanceManagerResources.parseError', { error: e.message });
return null;
}
},
update() {
if (!this.value) return;
const cpu = { ...this.resources?.cpu };
if (cpu.v1 !== null && cpu.v1 !== undefined) cpu.v1 = String(cpu.v1);
if (cpu.v2 !== null && cpu.v2 !== undefined) cpu.v2 = String(cpu.v2);
this.value.value = JSON.stringify({ ...this.resources, cpu });
},
useDefault() {
if (this.value?.default) {
this.resources = this.parseJSON(this.value.default) || {};
this.update();
}
},
},
};
</script>
<template>
<div>
<Banner
v-if="parseError"
color="error"
>
{{ parseError }}
</Banner>
<div class="row">
<div class="col span-12">
<UnitInput
v-model:value="resources.cpu.v1"
:label="t('harvester.setting.instanceManagerResources.v1')"
suffix="%"
:delay="0"
type="number"
min="0"
max="100"
required
:mode="mode"
class="mb-20"
@update:value="update"
/>
<UnitInput
v-model:value="resources.cpu.v2"
:label="t('harvester.setting.instanceManagerResources.v2')"
suffix="%"
:delay="0"
type="number"
min="0"
max="100"
required
:mode="mode"
class="mb-20"
@update:value="update"
/>
</div>
</div>
</div>
</template>
@@ -191,7 +191,8 @@ export default {
>
<div class="col span-12">
<FileSelector
class="btn btn-sm bg-primary mb-10"
variant="primary"
class="mb-10"
:label="t('generic.readFromFile')"
@selected="onKeySelected"
/>
@@ -213,9 +214,7 @@ $yaml-height: 540px;
:deep() .yaml-editor{
flex: 1;
min-height: $yaml-height;
& .code-mirror .CodeMirror {
position: initial;
height: auto;
& .code-mirror .cm-editor {
min-height: $yaml-height;
}
}
@@ -0,0 +1,371 @@
<script>
import { LabeledInput } from '@components/Form/LabeledInput';
import LabeledSelect from '@shell/components/form/LabeledSelect.vue';
import { RadioGroup } from '@components/Form/Radio';
import ArrayList from '@shell/components/form/ArrayList';
import { isValidCIDR } from '@pkg/harvester/utils/regular';
import { _EDIT } from '@shell/config/query-params';
import { Banner } from '@components/Banner';
import { allHash } from '@shell/utils/promise';
import { HCI } from '../../types';
import { NETWORK_TYPE } from '../../config/types';
const { L2VLAN, UNTAGGED } = NETWORK_TYPE;
const SHARE_STORAGE_NETWORK = 'share-storage-network';
const NETWORK = 'network';
const DEFAULT_DEDICATED_NETWORK = {
vlan: '',
clusterNetwork: '',
range: '',
exclude: [],
};
export default {
name: 'RwxNetworkSetting',
components: {
RadioGroup,
Banner,
ArrayList,
LabeledInput,
LabeledSelect,
},
props: {
registerBeforeHook: {
type: Function,
required: true,
},
mode: {
type: String,
default: _EDIT,
},
value: {
type: Object,
default: () => {
return {};
},
},
},
async fetch() {
const inStore = this.$store.getters['currentProduct'].inStore;
await allHash({
clusterNetworks: this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.CLUSTER_NETWORK }),
vlanStatus: this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.VLAN_STATUS }),
});
},
data() {
let enabled = false; // enabled / disabled options
let shareStorageNetwork = false; // shareStorageNetwork / dedicatedRwxNetwork options
let dedicatedNetwork = { ...DEFAULT_DEDICATED_NETWORK };
let networkType = L2VLAN;
let exclude = [];
try {
const parsedValue = JSON.parse(this.value.value || this.value.default || '{}');
const parsedNetwork = parsedValue?.[NETWORK] || parsedValue || {};
if (parsedValue && typeof parsedValue === 'object') {
shareStorageNetwork = !!parsedValue[SHARE_STORAGE_NETWORK];
networkType = 'vlan' in parsedNetwork ? L2VLAN : UNTAGGED;
dedicatedNetwork = {
vlan: parsedNetwork.vlan || '',
clusterNetwork: parsedNetwork.clusterNetwork || '',
range: parsedNetwork.range || '',
};
exclude = parsedNetwork?.exclude?.toString().split(',') || [];
enabled = shareStorageNetwork || !!(parsedNetwork.vlan || parsedNetwork.clusterNetwork || parsedNetwork.range);
}
} catch (error) {
enabled = false;
shareStorageNetwork = false;
dedicatedNetwork = { ...DEFAULT_DEDICATED_NETWORK };
}
return {
enabled,
shareStorageNetwork,
dedicatedNetwork,
networkType,
exclude,
defaultAddValue: '',
};
},
created() {
if (this.registerBeforeHook) {
this.registerBeforeHook(this.willSave, 'willSave');
}
},
computed: {
showDedicatedNetworkConfig() {
return this.enabled && !this.shareStorageNetwork;
},
showVlan() {
return this.networkType === L2VLAN;
},
networkTypes() {
return [L2VLAN, UNTAGGED];
},
clusterNetworkOptions() {
const inStore = this.$store.getters['currentProduct'].inStore;
const clusterNetworks = this.$store.getters[`${ inStore }/all`](HCI.CLUSTER_NETWORK) || [];
const clusterNetworksOptions = this.networkType === UNTAGGED ? clusterNetworks.filter((network) => network.id !== 'mgmt') : clusterNetworks;
return clusterNetworksOptions.map((network) => {
const disabled = !network.isReadyForStorageNetwork;
return {
label: disabled ? `${ network.id } (${ this.t('generic.notReady') })` : network.id,
value: network.id,
disabled,
};
});
},
},
methods: {
onUpdateEnabled() {
if (!this.enabled) {
this.shareStorageNetwork = false;
this.dedicatedNetwork = { ...DEFAULT_DEDICATED_NETWORK };
}
this.update();
},
onUpdateNetworkType() {
if (this.shareStorageNetwork) {
this.dedicatedNetwork = { ...DEFAULT_DEDICATED_NETWORK };
}
this.update();
},
onUpdateDedicatedType(neu) {
this.dedicatedNetwork.clusterNetwork = '';
if (neu === L2VLAN) {
this.dedicatedNetwork.vlan = '';
} else {
delete this.dedicatedNetwork.vlan;
}
this.update();
},
inputVlan(neu) {
if (neu === '') {
this.dedicatedNetwork.vlan = '';
this.update();
return;
}
const newValue = Number(neu);
if (newValue > 4094) {
this.dedicatedNetwork.vlan = 4094;
} else if (newValue < 1) {
this.dedicatedNetwork.vlan = 1;
} else {
this.dedicatedNetwork.vlan = newValue;
}
this.update();
},
useDefault() {
this.enabled = false;
this.shareStorageNetwork = false;
this.dedicatedNetwork = { ...DEFAULT_DEDICATED_NETWORK };
this.update();
},
update() {
const value = { [SHARE_STORAGE_NETWORK]: false };
if (this.enabled && this.shareStorageNetwork) {
value[SHARE_STORAGE_NETWORK] = true;
}
if (this.showDedicatedNetworkConfig) {
value[NETWORK] = {};
if (this.showVlan) {
value[NETWORK].vlan = this.dedicatedNetwork.vlan;
}
value[NETWORK].clusterNetwork = this.dedicatedNetwork.clusterNetwork;
value[NETWORK].range = this.dedicatedNetwork.range;
const excludeList = this.exclude.filter((ip) => ip);
if (Array.isArray(excludeList) && excludeList.length > 0) {
value[NETWORK].exclude = excludeList;
}
}
this.value.value = JSON.stringify(value);
},
willSave() {
this.update();
if (!this.showDedicatedNetworkConfig) {
return Promise.resolve();
}
const errors = [];
if (this.showVlan && !this.dedicatedNetwork.vlan) {
errors.push(this.t('validation.required', { key: this.t('harvester.setting.storageNetwork.vlan') }, true));
}
if (!this.dedicatedNetwork.clusterNetwork) {
errors.push(this.t('validation.required', { key: this.t('harvester.setting.storageNetwork.clusterNetwork') }, true));
}
if (!this.dedicatedNetwork.range) {
errors.push(this.t('validation.required', { key: this.t('harvester.setting.storageNetwork.range.label') }, true));
} else if (!isValidCIDR(this.dedicatedNetwork.range)) {
errors.push(this.t('harvester.setting.storageNetwork.range.invalid', null, true));
}
if (this.exclude) {
const hasInvalidCIDR = this.exclude.find((cidr) => {
return cidr && !isValidCIDR(cidr);
});
if (hasInvalidCIDR) {
errors.push(this.t('harvester.setting.storageNetwork.exclude.invalid', null, true));
}
}
if (errors.length > 0) {
return Promise.reject(errors);
}
return Promise.resolve();
},
},
};
</script>
<template>
<div :class="mode">
<Banner color="warning">
<t
k="harvester.setting.rwxNetwork.warning"
:raw="true"
/>
</Banner>
<RadioGroup
v-model:value="enabled"
class="mb-20"
name="rwx-network-enable"
:options="[true,false]"
:labels="[t('generic.enabled'), t('generic.disabled')]"
@update:value="onUpdateEnabled"
/>
<RadioGroup
v-if="enabled"
v-model:value="shareStorageNetwork"
class="mb-20"
name="rwx-network-type"
:options="[true,false]"
:labels="[t('harvester.setting.rwxNetwork.shareStorageNetwork'), t('harvester.setting.rwxNetwork.dedicatedRwxNetwork')]"
@update:value="onUpdateNetworkType"
/>
<Banner
v-if="shareStorageNetwork"
class="mb-20"
color="warning"
>
<t
k="harvester.setting.rwxNetwork.shareStorageNetworkWarning"
:raw="true"
/>
</Banner>
<template v-if="showDedicatedNetworkConfig">
<LabeledSelect
v-model:value="networkType"
class="mb-20"
:options="networkTypes"
:mode="mode"
:label="t('harvester.fields.type')"
required
@update:value="onUpdateDedicatedType"
/>
<LabeledInput
v-if="showVlan"
v-model:value.number="dedicatedNetwork.vlan"
type="number"
class="mb-20"
:mode="mode"
required
placeholder="e.g. 1 - 4094"
label-key="harvester.setting.storageNetwork.vlan"
@update:value="inputVlan"
/>
<LabeledSelect
v-model:value="dedicatedNetwork.clusterNetwork"
label-key="harvester.setting.storageNetwork.clusterNetwork"
class="mb-20"
required
:options="clusterNetworkOptions"
@update:value="update"
/>
<LabeledInput
v-model:value="dedicatedNetwork.range"
class="mb-5"
:mode="mode"
required
:placeholder="t('harvester.setting.storageNetwork.range.placeholder')"
label-key="harvester.setting.storageNetwork.range.label"
@update:value="update"
/>
<ArrayList
v-model:value="exclude"
:show-header="true"
:default-add-value="defaultAddValue"
:mode="mode"
:add-label="t('harvester.setting.storageNetwork.exclude.addIp')"
class="mt-20"
@update:value="update"
>
<template #column-headers>
<div class="box mb-10">
<div class="key">
{{ t('harvester.setting.storageNetwork.exclude.label') }}
</div>
</div>
</template>
<template #columns="scope">
<div class="key">
<input
v-model="scope.row.value"
:placeholder="t('harvester.setting.storageNetwork.exclude.placeholder')"
@update:value="update"
/>
</div>
</template>
</ArrayList>
</template>
</div>
</template>
@@ -62,7 +62,8 @@ export default {
<div class="chooseFile">
<FileSelector
:include-file-name="true"
class="btn btn-sm bg-primary mr-20"
variant="primary"
class="mr-20"
label="Choose File"
@selected="onKeySelectedCa('publicCertificate', $event)"
/>
@@ -80,7 +81,8 @@ export default {
<div class="chooseFile">
<FileSelector
:include-file-name="true"
class="btn btn-sm bg-primary mr-20"
variant="primary"
class="mr-20"
label="Choose File"
@selected="onKeySelectedCa('privateKey', $event)"
/>
@@ -98,7 +100,8 @@ export default {
<div class="chooseFile">
<FileSelector
:include-file-name="true"
class="btn btn-sm bg-primary mr-20"
variant="primary"
class="mr-20"
label="Choose File"
@selected="onKeySelectedCa('ca', $event)"
/>
@@ -3,7 +3,7 @@ import { LabeledInput } from '@components/Form/LabeledInput';
import LabeledSelect from '@shell/components/form/LabeledSelect.vue';
import { RadioGroup } from '@components/Form/Radio';
import ArrayList from '@shell/components/form/ArrayList';
import { isValidCIDR } from '@shell/utils/validators/cidr';
import { isValidCIDR } from '@pkg/harvester/utils/regular';
import { _EDIT } from '@shell/config/query-params';
import { Banner } from '@components/Banner';
import Tip from '@shell/components/Tip';
@@ -64,6 +64,9 @@ export default {
try {
parsedDefaultValue = JSON.parse(this.value.value);
if (typeof parsedDefaultValue.exclusiveVlan !== 'boolean') {
parsedDefaultValue.exclusiveVlan = false;
}
networkType = 'vlan' in parsedDefaultValue ? L2VLAN : UNTAGGED; // backend doesn't provide networkType, so we check if vlan is provided instead
openVlan = true;
} catch (error) {
@@ -72,7 +75,8 @@ export default {
vlan: '',
clusterNetwork: '',
range: '',
exclude: []
exclude: [],
exclusiveVlan: false
};
}
const exclude = parsedDefaultValue?.exclude?.toString().split(',') || [];
@@ -94,6 +98,10 @@ export default {
},
computed: {
showExclusiveVlan() {
return this.networkType === L2VLAN &&
Number(this.parsedDefaultValue.vlan) !== 1;
},
showVlan() {
return this.networkType === L2VLAN;
},
@@ -132,6 +140,18 @@ export default {
};
});
},
exclusiveVlanOptions() {
return [
{
label: this.t('generic.enabled'),
value: true
},
{
label: this.t('generic.disabled'),
value: false
}
];
},
},
watch: {
@@ -174,7 +194,8 @@ export default {
vlan: '',
clusterNetwork: '',
range: '',
exclude: []
exclude: [],
exclusiveVlan: false
};
},
@@ -280,7 +301,15 @@ export default {
label-key="harvester.setting.storageNetwork.vlan"
@update:value="inputVlan"
/>
<LabeledSelect
v-if="showExclusiveVlan"
v-model:value="parsedDefaultValue.exclusiveVlan"
class="mb-20"
:options="exclusiveVlanOptions"
:mode="mode"
label-key="harvester.setting.storageNetwork.exclusiveVlan"
@update:value="update"
/>
<LabeledSelect
v-model:value="parsedDefaultValue.clusterNetwork"
label-key="harvester.setting.storageNetwork.clusterNetwork"
@@ -69,6 +69,15 @@ export default {
:mode="mode"
label-key="harvester.setting.vmForceDeletionPolicy.period"
/>
<LabeledInput
v-if="parseDefaultValue.enable"
v-model:value.number="parseDefaultValue.vmMigrationTimeout"
class="mb-20"
type="number"
:mode="mode"
label-key="harvester.setting.vmForceDeletionPolicy.vmMigrationTimeout"
/>
</div>
</div>
</template>
@@ -5,7 +5,7 @@ import { RadioGroup } from '@components/Form/Radio';
import { Banner } from '@components/Banner';
import ArrayList from '@shell/components/form/ArrayList';
import { allHash } from '@shell/utils/promise';
import { isValidCIDR } from '@shell/utils/validators/cidr';
import { isValidCIDR } from '@pkg/harvester/utils/regular';
import { NODE } from '@shell/config/types';
import { _EDIT } from '@shell/config/query-params';
import { HCI } from '../../types';
@@ -0,0 +1,649 @@
<script setup>
import { ref, computed, watch, toRefs } from 'vue';
import { useStore } from 'vuex';
import Loading from '@shell/components/Loading';
import { Banner } from '@components/Banner';
import { STORAGE_CLASS, NETWORK_ATTACHMENT } from '@shell/config/types';
import { useI18n } from '@shell/composables/useI18n';
import { randomStr } from '@shell/utils/string';
import { HCI } from '../../types';
import { VOLUME_MODE, ACCESS_MODE } from '../../config/types';
import { FORKLIFT_NAMESPACE } from '../../config/harvester-map';
import { buildNetworkMapEntries, buildStorageMapEntries } from '../../utils/forklift';
import { isInternalStorageClass } from '../../utils/storage-class';
import MappingColumn from './MappingColumn.vue';
import StorageDefaultsModal from './StorageDefaultsModal.vue';
const DEFAULT_VOLUME_MODE = VOLUME_MODE.FILE_SYSTEM;
const DEFAULT_ACCESS_MODE = ACCESS_MODE?.READ_WRITE_MANY ?? 'ReadWriteMany';
const props = defineProps({
providerName: { type: String, default: '' },
provider: { type: Object, default: null },
selectedVms: { type: Array, default: () => [] },
stepData: { type: Object, required: true },
useAllProviderData: { type: Boolean, default: false },
existingNetworkMap: { type: Object, default: null },
existingStorageMap: { type: Object, default: null },
});
const emit = defineEmits(['ready']);
const store = useStore();
const { t } = useI18n(store);
const vms = ref([]);
const harvesterNetworks = ref([]);
const storageClasses = ref([]);
const allNetworkMaps = ref([]);
const allStorageMaps = ref([]);
const errors = ref([]);
const loading = ref(true);
// Storage defaults edit modal state.
const showStorageDefaultsModal = ref(false);
const editingStorageEntry = ref(null);
const { networkEntries, storageEntries } = toRefs(props.stepData);
const NAMESPACE = FORKLIFT_NAMESPACE;
const harvesterNetworkOptions = computed(() => {
const options = [
{ label: t('harvester.addons.vmMigration.configureMappings.networkMapping.options.podNetworking'), value: 'pod' },
{ label: t('harvester.addons.vmMigration.configureMappings.networkMapping.options.ignored'), value: 'ignored' },
];
harvesterNetworks.value.forEach((net) => {
const ns = net.metadata?.namespace || '';
const name = net.metadata?.name || net.id;
const fullName = ns ? `${ ns }/${ name }` : name;
options.push({ label: fullName, value: fullName });
});
return options;
});
const storageClassOptions = computed(() => {
const options = storageClasses.value.filter((s) => !s.parameters?.backingImage).map((sc) => {
const value = sc.name;
let label = sc.isDefault ? `${ value } (${ t('generic.default') })` : value;
let disabled = false;
if (isInternalStorageClass(value)) {
label += ` (${ t('harvester.storage.internal.label') })`;
disabled = true;
}
return {
label,
value,
disabled,
};
});
if (!options.find((o) => o.value === 'harvester-longhorn')) {
options.unshift({ label: 'harvester-longhorn', value: 'harvester-longhorn' });
}
return options;
});
const applyNetworkMapTargets = (mapSpec) => {
if (!mapSpec) {
return;
}
networkEntries.value.forEach((entry) => {
const match = mapSpec.find(
(m) => m.source?.id === entry.id || m.source?.name === entry.name
);
if (match?.destination) {
const dest = match.destination;
if (dest.type === 'pod') {
entry.target = 'pod';
} else if (dest.type === 'ignored') {
entry.target = 'ignored';
} else if (dest.type === 'multus' && dest.name) {
entry.target = dest.namespace ? `${ dest.namespace }/${ dest.name }` : dest.name;
}
}
});
};
const applyStorageMapTargets = (mapSpec, { markOverridden = false, captureInherited = false } = {}) => {
if (!mapSpec) {
return;
}
storageEntries.value.forEach((entry) => {
const match = mapSpec.find(
(m) => m.source?.id === entry.id || m.source?.name === entry.name
);
if (match?.destination?.storageClass) {
entry.target = match.destination.storageClass;
if (captureInherited) {
entry.inheritedFromProvider = true;
}
if (match.destination.volumeMode) {
entry.volumeMode = match.destination.volumeMode;
if (captureInherited) {
entry.inheritedVolumeMode = match.destination.volumeMode;
}
}
if (match.destination.accessMode) {
entry.accessModes = [match.destination.accessMode];
if (captureInherited) {
entry.inheritedAccessModes = [match.destination.accessMode];
}
}
if (markOverridden) {
entry.overridden = true;
}
}
});
};
const applyDefaultNetworkMap = () => {
const defaultMap = allNetworkMaps.value.find(
(nm) => nm.metadata.name === `${ props.providerName }-network-map-default`
);
applyNetworkMapTargets(defaultMap?.spec?.map);
};
const applyDefaultStorageMap = () => {
const defaultMap = allStorageMaps.value.find(
(sm) => sm.metadata.name === `${ props.providerName }-storage-map-default`
);
applyStorageMapTargets(defaultMap?.spec?.map, { captureInherited: true });
};
const allNetworksMapped = computed(() => networkEntries.value.length > 0 && networkEntries.value.every((e) => !!e.target));
const allStorageMapped = computed(() => storageEntries.value.length > 0 && storageEntries.value.every((e) => !!e.target));
// The "Inherited from provider" hint only appears in the migration plan wizard
// (where mappings inherit from the provider default), not on the provider creation page.
const inheritedProviderName = computed(() => (props.useAllProviderData ? '' : props.providerName));
const openStorageDefaults = (entry) => {
editingStorageEntry.value = entry;
showStorageDefaultsModal.value = true;
};
const closeStorageDefaults = () => {
showStorageDefaultsModal.value = false;
editingStorageEntry.value = null;
};
const applyStorageDefaults = ({ volumeMode, accessModes }) => {
if (editingStorageEntry.value) {
editingStorageEntry.value.volumeMode = volumeMode;
editingStorageEntry.value.accessModes = accessModes;
const inheritedVolumeMode = editingStorageEntry.value.inheritedVolumeMode;
const inheritedAccessMode = editingStorageEntry.value.inheritedAccessModes?.[0];
const selectedAccessMode = accessModes?.[0];
editingStorageEntry.value.overridden = volumeMode !== inheritedVolumeMode || selectedAccessMode !== inheritedAccessMode;
}
};
const canSave = computed(() => {
if (props.useAllProviderData) {
return true;
}
return networkEntries.value.length > 0 && storageEntries.value.length > 0 &&
allNetworksMapped.value && allStorageMapped.value;
});
watch(canSave, (val) => {
emit('ready', val);
});
// After restore, check if ready
if (canSave.value) {
emit('ready', true);
}
const buildNetworkEntries = () => {
const networkMap = {};
vms.value.forEach((vm) => {
const vmName = vm.name || vm.id;
if (vm.networks && vm.networks.length > 0) {
vm.networks.forEach((net) => {
const netKey = net.id || net.name || 'default';
if (!networkMap[netKey]) {
networkMap[netKey] = {
name: net.name || t('harvester.addons.vmMigration.generic.unknown'),
id: net.id || '',
vlanId: net.vlanId || '',
target: '',
usedBy: [],
_key: `net-${ netKey }`,
};
}
if (!networkMap[netKey].usedBy.includes(vmName)) {
networkMap[netKey].usedBy.push(vmName);
}
});
}
});
networkEntries.value = Object.values(networkMap);
};
const buildStorageEntries = () => {
const datastoreMap = {};
vms.value.forEach((vm) => {
const vmName = vm.name || vm.id;
if (vm.disks && vm.disks.length > 0) {
vm.disks.forEach((disk) => {
const ds = disk.datastore;
if (ds && ds.id) {
if (!datastoreMap[ds.id]) {
datastoreMap[ds.id] = {
name: ds.name || t('harvester.addons.vmMigration.generic.unknown'),
id: ds.id,
type: ds.type || '',
capacity: 0,
target: '',
volumeMode: DEFAULT_VOLUME_MODE,
accessModes: [DEFAULT_ACCESS_MODE],
inheritedVolumeMode: DEFAULT_VOLUME_MODE,
inheritedAccessModes: [DEFAULT_ACCESS_MODE],
inheritedFromProvider: false,
overridden: false,
usedBy: [],
_key: `stor-${ ds.id }`,
};
}
datastoreMap[ds.id].capacity += disk.capacity || 0;
if (!datastoreMap[ds.id].usedBy.includes(vmName)) {
datastoreMap[ds.id].usedBy.push(vmName);
}
}
});
}
});
storageEntries.value = Object.values(datastoreMap);
};
const buildNetworkEntriesFromProvider = (networksData) => {
networkEntries.value = (Array.isArray(networksData) ? networksData : []).map((net) => ({
name: net.name || net.id,
id: net.id || '',
vlanId: net.vlanId || '',
target: '',
usedBy: [],
_key: `net-${ net.id || net.name }`,
}));
};
const buildStorageEntriesFromProvider = (datastoresData) => {
storageEntries.value = (Array.isArray(datastoresData) ? datastoresData : []).map((ds) => ({
name: ds.name || ds.id,
id: ds.id || '',
type: ds.type || '',
capacity: ds.capacity || 0,
target: '',
volumeMode: DEFAULT_VOLUME_MODE,
accessModes: [DEFAULT_ACCESS_MODE],
inheritedVolumeMode: DEFAULT_VOLUME_MODE,
inheritedAccessModes: [DEFAULT_ACCESS_MODE],
inheritedFromProvider: false,
overridden: false,
usedBy: [],
_key: `stor-${ ds.id || ds.name }`,
}));
};
const formatStorageDetail = (entry) => {
const parts = [];
if (entry.type) {
parts.push(entry.type);
}
if (entry.capacity) {
const gb = entry.capacity / (1024 * 1024 * 1024);
if (gb >= 1024) {
parts.push(t('harvester.addons.vmMigration.generic.memoryTb', { value: (gb / 1024).toFixed(1) }));
} else {
parts.push(t('harvester.addons.vmMigration.generic.memoryGb', { value: Math.round(gb) }));
}
}
return parts.join(' • ');
};
const buildNetworkMapSpec = (providerRef) => ({
map: buildNetworkMapEntries(networkEntries.value, NAMESPACE),
provider: providerRef,
});
const buildStorageMapSpec = (providerRef) => ({
map: buildStorageMapEntries(storageEntries.value),
provider: providerRef,
});
const saveAndReturn = async() => {
const inStore = store.getters['currentProduct'].inStore;
const providerRef = {
source: {
apiVersion: 'forklift.konveyor.io/v1beta1',
kind: 'Provider',
name: props.providerName,
namespace: NAMESPACE,
},
destination: {
apiVersion: 'forklift.konveyor.io/v1beta1',
kind: 'Provider',
name: 'host',
namespace: NAMESPACE,
},
};
// Update existing maps in place (edit mode)
if (props.existingNetworkMap && props.existingStorageMap) {
props.existingNetworkMap.spec = buildNetworkMapSpec(providerRef);
await props.existingNetworkMap.save();
props.existingStorageMap.spec = buildStorageMapSpec(providerRef);
await props.existingStorageMap.save();
return {
networkMapName: props.existingNetworkMap.metadata.name,
storageMapName: props.existingStorageMap.metadata.name,
};
}
const providerOwnerRef = props.provider ? [{
apiVersion: 'forklift.konveyor.io/v1beta1',
kind: 'Provider',
name: props.provider.metadata.name,
uid: props.provider.metadata.uid,
blockOwnerDeletion: true,
}] : [];
const networkMap = await store.dispatch(`${ inStore }/create`, {
type: HCI.FORKLIFT_NETWORK_MAP,
metadata: {
name: `${ props.providerName }-network-map-${ props.useAllProviderData ? 'default' : randomStr(5).toLowerCase() }`,
namespace: NAMESPACE,
ownerReferences: providerOwnerRef,
},
spec: buildNetworkMapSpec(providerRef),
});
await networkMap.save();
const storageMap = await store.dispatch(`${ inStore }/create`, {
type: HCI.FORKLIFT_STORAGE_MAP,
metadata: {
name: `${ props.providerName }-storage-map-${ props.useAllProviderData ? 'default' : randomStr(5).toLowerCase() }`,
namespace: NAMESPACE,
ownerReferences: providerOwnerRef,
},
spec: buildStorageMapSpec(providerRef),
});
await storageMap.save();
return { networkMapName: networkMap.metadata.name, storageMapName: storageMap.metadata.name };
};
defineExpose({ saveMappings: saveAndReturn });
const init = async() => {
const inStore = store.getters['currentProduct'].inStore;
try {
harvesterNetworks.value = await store.dispatch(`${ inStore }/findAll`, { type: NETWORK_ATTACHMENT });
} catch (e) {
harvesterNetworks.value = [];
}
try {
storageClasses.value = await store.dispatch(`${ inStore }/findAll`, { type: STORAGE_CLASS });
} catch (e) {
storageClasses.value = [];
}
try {
allNetworkMaps.value = await store.dispatch(`${ inStore }/findAll`, { type: HCI.FORKLIFT_NETWORK_MAP });
} catch (e) {
allNetworkMaps.value = [];
}
try {
allStorageMaps.value = await store.dispatch(`${ inStore }/findAll`, { type: HCI.FORKLIFT_STORAGE_MAP });
} catch (e) {
allStorageMaps.value = [];
}
if (networkEntries.value.length === 0 || storageEntries.value.length === 0) {
try {
const providerUid = props.provider?.metadata?.uid;
const providerType = props.provider?.spec?.type || 'vsphere';
const baseUrl = store.getters['harvester-common/getHarvesterClusterUrl'](
`v1/harvester/providers/${ providerType }/${ providerUid }`
);
const [networksData, datastoresData] = await Promise.all([
store.dispatch(`${ inStore }/request`, { url: `${ baseUrl }/networks` }).catch(() => []),
store.dispatch(`${ inStore }/request`, { url: `${ baseUrl }/datastores?detail=1` }).catch(() => []),
]);
if (props.useAllProviderData) {
if (networkEntries.value.length === 0) {
buildNetworkEntriesFromProvider(networksData);
}
if (storageEntries.value.length === 0) {
buildStorageEntriesFromProvider(datastoresData);
}
} else {
vms.value = props.selectedVms;
const networkNameMap = (Array.isArray(networksData) ? networksData : []).reduce((map, n) => {
map[n.id] = n.name;
return map;
}, {});
const datastoreInfoMap = (Array.isArray(datastoresData) ? datastoresData : []).reduce((map, d) => {
map[d.id] = { name: d.name, type: d.type || '' };
return map;
}, {});
vms.value = vms.value.map((vm) => {
const resolved = { ...vm };
if (resolved.networks) {
resolved.networks = resolved.networks.map((n) => ({
...n,
name: n.name || networkNameMap[n.id] || n.id,
}));
}
if (resolved.disks) {
resolved.disks = resolved.disks.map((d) => {
const dsInfo = d.datastore ? datastoreInfoMap[d.datastore.id] : null;
return {
...d,
datastore: d.datastore ? {
...d.datastore,
name: d.datastore.name || dsInfo?.name || d.datastore.id,
type: dsInfo?.type || '',
} : d.datastore,
};
});
}
return resolved;
});
if (networkEntries.value.length === 0) {
buildNetworkEntries();
}
if (storageEntries.value.length === 0) {
buildStorageEntries();
}
}
} catch (e) {
errors.value = [e?.message || t('harvester.addons.vmMigration.errors.failedResolveDetails')];
}
}
const hasExistingNetworkTargets = networkEntries.value.some((e) => !!e.target);
const hasExistingStorageTargets = storageEntries.value.some((e) => !!e.target);
if (!hasExistingNetworkTargets) {
if (props.existingNetworkMap?.spec?.map) {
applyNetworkMapTargets(props.existingNetworkMap.spec.map);
} else {
applyDefaultNetworkMap();
}
}
if (!hasExistingStorageTargets) {
if (props.existingStorageMap?.spec?.map) {
applyStorageMapTargets(props.existingStorageMap.spec.map, { markOverridden: true });
} else {
applyDefaultStorageMap();
}
}
loading.value = false;
};
init();
</script>
<template>
<Loading v-if="loading" />
<div
v-else
class="configure-mappings"
>
<Banner
v-for="(err, i) in errors"
:key="i"
color="error"
:label="err"
/>
<p class="text-deemphasized line-height-20">
{{ t('harvester.addons.vmMigration.configureMappings.description') }}
</p>
<div class="mappings-columns">
<MappingColumn
:title="t('harvester.addons.vmMigration.configureMappings.networkMapping.title')"
:description="t('harvester.addons.vmMigration.configureMappings.networkMapping.description')"
:entries="networkEntries"
:options="harvesterNetworkOptions"
:placeholder="t('harvester.addons.vmMigration.configureMappings.networkMapping.placeholder')"
:show-used-by="!useAllProviderData"
:clearable="useAllProviderData"
>
<template #source-detail="{ entry }">
<span class="source-detail text-deemphasized">{{ t('harvester.addons.vmMigration.generic.vlan', { id: entry.vlanId || '0' }) }}</span>
</template>
</MappingColumn>
<MappingColumn
:title="t('harvester.addons.vmMigration.configureMappings.storageMapping.title')"
:description="t('harvester.addons.vmMigration.configureMappings.storageMapping.description')"
:entries="storageEntries"
:options="storageClassOptions"
:placeholder="t('harvester.addons.vmMigration.configureMappings.storageMapping.placeholder')"
:show-used-by="!useAllProviderData"
:clearable="useAllProviderData"
:show-volume-settings="true"
:inherited-provider-name="inheritedProviderName"
@edit-defaults="openStorageDefaults"
>
<template #source-detail="{ entry }">
<span
v-if="entry.type || entry.capacity"
class="source-detail text-deemphasized"
>{{ formatStorageDetail(entry) }}</span>
</template>
</MappingColumn>
</div>
<StorageDefaultsModal
v-if="showStorageDefaultsModal && editingStorageEntry"
:storage-class-name="editingStorageEntry.target"
:provider-name="providerName"
:show-inherited="!!inheritedProviderName"
:volume-mode="editingStorageEntry.volumeMode"
:access-modes="editingStorageEntry.accessModes"
:inherited-volume-mode="editingStorageEntry.inheritedVolumeMode"
:inherited-access-modes="editingStorageEntry.inheritedAccessModes"
@apply="applyStorageDefaults"
@close="closeStorageDefaults"
/>
</div>
</template>
<style lang="scss" scoped>
.mappings-columns {
display: flex;
flex-direction: column;
gap: 32px;
@media only screen and (min-width: map-get($breakpoints, '--viewport-7')) {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
}
@media only screen and (min-width: map-get($breakpoints, '--viewport-9')) {
gap: 48px;
}
@media only screen and (min-width: map-get($breakpoints, '--viewport-12')) {
gap: 64px;
}
}
.configure-mappings {
display: flex;
flex-direction: column;
gap: 24px;
.line-height-20 {
line-height: 20px;
}
}
.source-detail {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
</style>
@@ -0,0 +1,573 @@
<script setup>
import { ref, computed, watch, toRefs } from 'vue';
import { useStore } from 'vuex';
import { LabeledInput } from '@components/Form/LabeledInput';
import { Checkbox } from '@components/Form/Checkbox';
import { Banner } from '@components/Banner';
import Loading from '@shell/components/Loading';
import AsyncButton from '@shell/components/AsyncButton';
import LabeledSelect from '@shell/components/form/LabeledSelect';
import { SECRET } from '@shell/config/types';
import { randomStr } from '@shell/utils/string';
import { useI18n } from '@shell/composables/useI18n';
import { HCI } from '../../types';
import { FORKLIFT_NAMESPACE } from '../../config/harvester-map';
import { decodeSecretValue } from '../../utils/forklift';
const CREATE_NEW = '__create_new__';
const props = defineProps({
stepData: { type: Object, required: true },
createOnly: { type: Boolean, default: false },
editMode: { type: Boolean, default: false },
});
const emit = defineEmits(['complete', 'ready', 'form-valid', 'testing']);
const store = useStore();
const { t } = useI18n(store);
const allProviders = ref([]);
const allSecrets = ref([]);
const errors = ref([]);
const testBtnRef = ref(null);
const loading = ref(true);
const testing = ref(false);
const {
selectedProvider,
providerName,
url,
username,
password,
skipTlsVerify,
vddkInitImage,
testPassed,
testResult,
testError,
createdProvider,
createdSecret,
} = toRefs(props.stepData);
const isExistingProvider = computed(() => selectedProvider.value !== CREATE_NEW);
const isFormValid = computed(() => !!providerName.value && !!url.value && !!username.value && !!password.value);
const providerOptions = computed(() => {
const options = [
{ label: t('harvester.addons.vmMigration.configureProvider.createNew'), value: CREATE_NEW }
];
allProviders.value.forEach((p) => {
if (!p.spec?.url) {
return;
}
const secretRef = p.spec?.secret;
if (secretRef) {
const secret = allSecrets.value.find(
(s) => s.metadata.name === secretRef.name && s.metadata.namespace === secretRef.namespace
);
if (!secret?.data?.user || !secret?.data?.password) {
return;
}
} else {
return;
}
options.push({
label: p.metadata.name,
value: p.metadata.name,
});
});
return options;
});
// When the provider selection changes, populate or clear the fields
watch(selectedProvider, (val) => {
testPassed.value = false;
testResult.value = null;
testError.value = null;
if (val === CREATE_NEW) {
providerName.value = '';
url.value = '';
username.value = '';
password.value = '';
skipTlsVerify.value = false;
vddkInitImage.value = '';
createdProvider.value = null;
createdSecret.value = null;
} else {
const provider = allProviders.value.find(
(p) => p.metadata.name === val && p.metadata.namespace === FORKLIFT_NAMESPACE
);
if (provider) {
providerName.value = provider.metadata.name;
url.value = provider.spec?.url || '';
vddkInitImage.value = provider.spec?.settings?.vddkInitImage || '';
const secretRef = provider.spec?.secret;
if (secretRef) {
const secret = allSecrets.value.find(
(s) => s.metadata.name === secretRef.name && s.metadata.namespace === secretRef.namespace
);
if (secret?.data) {
username.value = decodeSecretValue(secret.data.user);
password.value = decodeSecretValue(secret.data.password);
skipTlsVerify.value = decodeSecretValue(secret.data.insecureSkipVerify) === 'true';
}
}
createdProvider.value = provider;
}
}
});
// Reset test state when any field changes (only for create new)
watch([providerName, url, username, password], () => {
if (!isExistingProvider.value) {
testPassed.value = false;
testResult.value = null;
}
});
// Emit ready/complete when testPassed changes
watch(testPassed, (val) => {
emit('ready', val);
if (val) {
emit('complete', { providerName: providerName.value, provider: createdProvider.value });
}
}, { immediate: true });
// Emit form-valid when form validity changes
watch(isFormValid, (val) => {
emit('form-valid', val);
}, { immediate: true });
watch(testing, (val) => {
emit('testing', val);
}, { immediate: true });
const pollProviderReady = async(name) => {
const inStore = store.getters['currentProduct'].inStore;
const namespace = FORKLIFT_NAMESPACE;
const maxAttempts = 15;
let attempts = 0;
while (attempts < maxAttempts) {
await new Promise((resolve) => setTimeout(resolve, 2000));
attempts++;
const refreshed = await store.dispatch(`${ inStore }/find`, {
type: HCI.FORKLIFT_PROVIDER,
id: `${ namespace }/${ name }`,
opt: { force: true }
});
const conditions = refreshed?.status?.conditions || [];
const connectionCondition = conditions.find((c) => c.type === 'ConnectionTestSucceeded');
const readyCondition = conditions.find((c) => c.type === 'Ready');
if (connectionCondition) {
if (connectionCondition.status === 'True') {
return { connected: true };
}
return { connected: false, errorMsg: connectionCondition.message || t('harvester.addons.vmMigration.errors.connectionFailed') };
}
if (readyCondition) {
if (readyCondition.status === 'True') {
return { connected: true };
} else if (readyCondition.status === 'False') {
return { connected: false, errorMsg: readyCondition.message || t('harvester.addons.vmMigration.errors.providerNotReady') };
}
}
}
return { connected: false, errorMsg: '' };
};
const handlePollResult = ({ connected, errorMsg }, buttonCb) => {
if (connected) {
testPassed.value = true;
testResult.value = t('harvester.addons.vmMigration.configureProvider.testSuccess');
testing.value = false;
buttonCb(true);
} else {
testError.value = errorMsg || t('harvester.addons.vmMigration.configureProvider.testTimeout');
testing.value = false;
buttonCb(false);
}
};
const cleanupCreatedResources = async() => {
if (createdProvider.value) {
try {
await createdProvider.value.remove();
} catch (e) {}
createdProvider.value = null;
createdSecret.value = null;
} else if (createdSecret.value) {
try {
await createdSecret.value.remove();
} catch (e) {}
createdSecret.value = null;
}
};
const testConnection = async(buttonCb) => {
testResult.value = null;
testError.value = null;
testing.value = true;
if (!providerName.value || !url.value || !username.value || !password.value) {
testError.value = t('harvester.addons.vmMigration.configureProvider.testMissingFields');
testing.value = false;
buttonCb(false);
return;
}
const inStore = store.getters['currentProduct'].inStore;
// Edit mode: update existing provider URL + secret, then poll
if (props.editMode && createdProvider.value) {
try {
createdProvider.value.spec.url = url.value;
const vddkImage = vddkInitImage.value?.trim();
if (vddkImage) {
createdProvider.value.spec.settings = {
...(createdProvider.value.spec.settings || {}),
vddkInitImage: vddkImage,
};
} else if (createdProvider.value.spec.settings) {
delete createdProvider.value.spec.settings.vddkInitImage;
}
await createdProvider.value.save();
const secretRef = createdProvider.value.spec?.secret;
if (secretRef && createdSecret.value) {
createdSecret.value.data = {
user: btoa(username.value),
password: btoa(password.value),
insecureSkipVerify: btoa(String(skipTlsVerify.value)),
url: btoa(url.value),
};
await createdSecret.value.save();
}
handlePollResult(await pollProviderReady(providerName.value), buttonCb);
} catch (err) {
testError.value = err.message || t('harvester.addons.vmMigration.configureProvider.testFailed');
testing.value = false;
buttonCb(false);
}
return;
}
// For existing providers, just poll for Ready/ConnectionTestSucceeded status
if (isExistingProvider.value) {
try {
handlePollResult(await pollProviderReady(providerName.value), buttonCb);
} catch (err) {
testError.value = err.message || t('harvester.addons.vmMigration.configureProvider.testFailed');
testing.value = false;
buttonCb(false);
}
return;
}
// For new providers, create provider + secret then poll
try {
await cleanupCreatedResources();
const namespace = FORKLIFT_NAMESPACE;
const secretName = `${ providerName.value }-creds-${ randomStr(4).toLowerCase() }`;
const spec = {
type: 'vsphere',
url: url.value,
secret: {
name: secretName,
namespace,
},
};
const vddkImage = vddkInitImage.value?.trim();
if (vddkImage) {
spec.settings = { vddkInitImage: vddkImage };
}
const provider = await store.dispatch(`${ inStore }/create`, {
type: HCI.FORKLIFT_PROVIDER,
metadata: {
name: providerName.value,
namespace,
},
spec,
});
await provider.save();
createdProvider.value = provider;
const newSecret = await store.dispatch(`${ inStore }/create`, {
type: SECRET,
metadata: {
name: secretName,
namespace,
labels: { 'ui.forklift/created-for-resource-type': 'forklift.konveyor.io.provider' },
ownerReferences: [
{
apiVersion: 'forklift.konveyor.io/v1beta1',
kind: 'Provider',
name: provider.metadata.name,
uid: provider.metadata.uid,
blockOwnerDeletion: true,
},
],
}
});
newSecret['_type'] = 'Opaque';
newSecret['data'] = {
user: btoa(username.value),
password: btoa(password.value),
insecureSkipVerify: btoa(String(skipTlsVerify.value)),
url: btoa(url.value),
};
await newSecret.save();
createdSecret.value = newSecret;
const result = await pollProviderReady(providerName.value);
if (!result.connected) {
await cleanupCreatedResources();
}
handlePollResult(result, buttonCb);
} catch (err) {
await cleanupCreatedResources();
testError.value = err.message || t('harvester.addons.vmMigration.configureProvider.testFailed');
testing.value = false;
buttonCb(false);
}
};
const init = async() => {
const inStore = store.getters['currentProduct'].inStore;
try {
allProviders.value = await store.dispatch(`${ inStore }/findAll`, { type: HCI.FORKLIFT_PROVIDER });
allSecrets.value = await store.dispatch(`${ inStore }/findAll`, {
type: SECRET,
opt: { labelSelector: `ui.forklift/created-for-resource-type=${ HCI.FORKLIFT_PROVIDER }` }
});
} catch (e) {
errors.value = [e?.message || t('harvester.addons.vmMigration.errors.failedLoadProviders')];
}
loading.value = false;
};
init();
const clickTestButton = () => {
testBtnRef.value?.$el?.click();
};
defineExpose({ testConnection, clickTestButton });
</script>
<template>
<Loading v-if="loading" />
<div
v-else
class="configure-provider-step"
>
<p class="text-deemphasized line-height-20">
{{ t('harvester.addons.vmMigration.configureProvider.description') }}
</p>
<div class="configure-provider-step-content">
<h3 class="table-title m-0">
<b>{{ t('harvester.addons.vmMigration.configureProvider.connectionDetails') }}</b>
</h3>
<Banner
class="requirements-banner m-0"
color="info"
>
<div class="requirements-banner-content">
<span class="requirements-banner-title">{{ t('harvester.addons.vmMigration.configureProvider.requirementsTitle') }}</span>
<br>
<span>{{ t('harvester.addons.vmMigration.configureProvider.requirementsText') }}</span>
</div>
</Banner>
<div class="configure-provider-step-form">
<div v-if="!createOnly && !editMode">
<LabeledSelect
v-model:value="selectedProvider"
required
:label="t('harvester.addons.vmMigration.configureProvider.providerSelect')"
:options="providerOptions"
:reduce="(opt) => opt.value"
/>
</div>
<div
v-if="!isExistingProvider || editMode"
>
<LabeledInput
v-model:value="providerName"
:label="t('harvester.addons.vmMigration.configureProvider.name')"
:disabled="editMode"
required
/>
</div>
<div class="row">
<div class="col span-6">
<LabeledInput
v-model:value="url"
:label="t('harvester.addons.vmMigration.configureProvider.urlLabel')"
:placeholder="t('harvester.addons.vmMigration.configureProvider.urlPlaceholder')"
:disabled="isExistingProvider && !editMode"
required
/>
<p class="text-deemphasized mt-5">
{{ t('harvester.addons.vmMigration.configureProvider.urlHint') }}
</p>
</div>
<div class="col span-6">
<LabeledInput
v-model:value="vddkInitImage"
:label="t('harvester.addons.vmMigration.configureProvider.vddkImageLabel')"
:placeholder="t('harvester.addons.vmMigration.configureProvider.vddkImagePlaceholder')"
:tooltip="t('harvester.addons.vmMigration.configureProvider.vddkImageTooltip')"
:disabled="isExistingProvider && !editMode"
/>
</div>
</div>
<div class="row">
<div class="col span-6">
<LabeledInput
v-model:value="username"
:label="t('harvester.addons.vmMigration.fields.username')"
:disabled="isExistingProvider && !editMode"
required
/>
</div>
<div class="col span-6">
<LabeledInput
v-model:value="password"
type="password"
:label="t('harvester.addons.vmMigration.fields.password')"
:disabled="isExistingProvider && !editMode"
required
/>
</div>
</div>
<div>
<Checkbox
v-model:value="skipTlsVerify"
:label="t('harvester.addons.vmMigration.configureProvider.skipSsl')"
:disabled="isExistingProvider && !editMode"
/>
<p class="text-deemphasized ml-20">
{{ t('harvester.addons.vmMigration.configureProvider.skipSslHint') }}
</p>
</div>
<div>
<AsyncButton
ref="testBtnRef"
mode="test"
:disabled="!isFormValid"
:action-label="t('harvester.addons.vmMigration.configureProvider.testConnection.action')"
:waiting-label="t('harvester.addons.vmMigration.configureProvider.testConnection.waiting')"
:success-label="t('harvester.addons.vmMigration.configureProvider.testConnection.success')"
:error-label="t('harvester.addons.vmMigration.configureProvider.testConnection.error')"
:action-color="'role-secondary'"
:waiting-color="'role-disabled'"
@click="testConnection"
/>
</div>
<Banner
v-if="testResult"
color="success"
>
{{ testResult }}
</Banner>
<Banner
v-if="testError"
color="error"
>
{{ testError }}
</Banner>
<Banner
v-for="(err, i) in errors"
:key="i"
color="error"
>
{{ err }}
</Banner>
</div>
</div>
</div>
</template>
<style lang="scss" scoped>
.requirements-banner {
font-weight: 400;
.requirements-banner-title {
font-weight: 600;
}
}
.configure-provider-step {
display: flex;
flex-direction: column;
gap: 24px;
.line-height-20 {
line-height: 20px;
}
.configure-provider-step-content {
display: flex;
flex-direction: column;
gap: 12px;
.configure-provider-step-form {
display: flex;
flex-direction: column;
gap: 20px;
}
}
:deep(.checkbox-label) {
color: var(--body-text);
}
}
</style>
@@ -0,0 +1,252 @@
<script setup>
import { useStore } from 'vuex';
import LabeledSelect from '@shell/components/form/LabeledSelect';
import { RcItemCard } from '@components/RcItemCard';
import { useI18n } from '@shell/composables/useI18n';
import { VOLUME_MODE } from '../../config/types';
const store = useStore();
const { t } = useI18n(store);
const props = defineProps({
title: { type: String, required: true },
description: { type: String, default: '' },
entries: { type: Array, default: () => [] },
options: { type: Array, default: () => [] },
placeholder: { type: String, default: '' },
showUsedBy: { type: Boolean, default: false },
clearable: { type: Boolean, default: false },
// Storage-specific: show the volume/access mode defaults row with an Edit action.
showVolumeSettings: { type: Boolean, default: false },
// When set, the defaults row shows an "Inherited from provider" hint (migration plan wizard only).
inheritedProviderName: { type: String, default: '' },
});
const emit = defineEmits(['edit-defaults']);
// Only offer "Remove Map" for entries that already have a target selected;
// entries without a selection just show the regular options.
const optionsFor = (entry) => {
if (!props.clearable || !entry.target) {
return props.options;
}
return [
{
label: t('harvester.addons.vmMigration.configureMappings.removeMap'),
value: null,
kind: 'highlighted',
},
{
label: 'divider',
disabled: true,
kind: 'divider',
},
...props.options,
];
};
const formatModes = (entry) => {
const volumeMode = entry.volumeMode || VOLUME_MODE.FILE_SYSTEM;
const accessModes = (entry.accessModes || []).join(', ');
return t('harvester.addons.vmMigration.storageDefaults.summary', { volumeMode, accessModes });
};
</script>
<template>
<div class="mapping-column">
<div>
<h3 class="mapping-section-title">
{{ title }}
</h3>
<p
v-if="description"
class="text-deemphasized line-height-20"
>
{{ description }}
</p>
</div>
<RcItemCard
v-for="entry in entries"
:id="entry._key"
:key="entry._key"
:variant="'small'"
:header="{}"
class="bg-light-gray"
>
<template #item-card-content>
<div class="card-content-column">
<div class="card-content-row">
<div class="mapping-source">
<span class="source-name">{{ entry.name }}</span>
<slot
name="source-detail"
:entry="entry"
/>
</div>
<div :class="['mapping-arrow', entry.target ? 'text-success' : 'text-deemphasized']">
<i
class="icon icon-right-arrow-alt"
aria-hidden="true"
/>
</div>
<div class="mapping-target">
<LabeledSelect
v-model:value="entry.target"
:options="optionsFor(entry)"
:placeholder="placeholder+'...'"
:searchable="true"
/>
</div>
</div>
<div
v-if="showVolumeSettings && entry.target"
class="storage-defaults-row"
>
<div class="storage-defaults">
<div class="storage-defaults-info">
<span class="storage-defaults-summary">{{ formatModes(entry) }}</span>
<span
v-if="inheritedProviderName && entry.inheritedFromProvider && !entry.overridden"
class="text-deemphasized storage-defaults-inherited"
>
{{ t('harvester.addons.vmMigration.storageDefaults.inherited', { provider: inheritedProviderName }) }}
</span>
</div>
<a
role="button"
class="storage-defaults-edit"
@click.prevent="emit('edit-defaults', entry)"
>
{{ t('harvester.addons.vmMigration.storageDefaults.edit') }}
</a>
</div>
</div>
<div v-if="showUsedBy && entry.usedBy && entry.usedBy.length">
<span class="used-by">
{{ t('harvester.addons.vmMigration.generic.usedBy') }} <b>{{ entry.usedBy.join(', ') }}</b>
</span>
</div>
</div>
</template>
</RcItemCard>
</div>
</template>
<style lang="scss" scoped>
.mapping-column {
display: flex;
gap: 12px;
flex-direction: column;
:deep(.item-card-header) {
display: none;
}
}
.mapping-section-title {
font-weight: 600;
margin: 0 0 5px 0;
line-height: 28px;
}
.card-content-row {
display: flex;
align-items: center;
gap: 16px;
width: 100%;
}
.card-content-column {
display: flex;
flex-direction: column;
gap: 8px;
width: 100%;
}
.mapping-source {
display: flex;
flex-direction: column;
flex: 2;
min-width: 100px;
font-size: 14px;
line-height: 20px;
.source-name {
font-weight: 600;
font-size: 14px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.source-detail {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.used-by {
margin-top: 4px;
font-size: 14px;
line-height: 24px;
}
}
.mapping-arrow {
font-size: 22px;
flex-shrink: 0;
}
.mapping-target {
flex: 3;
min-width: 0;
overflow: hidden;
}
.line-height-20 {
line-height: 20px;
}
.storage-defaults-row {
width: 100%;
}
.storage-defaults {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 8px 12px;
border-radius: 4px;
background-color: var(--body-bg);
.storage-defaults-info {
display: flex;
flex-direction: column;
min-width: 0;
}
.storage-defaults-summary {
font-size: 13px;
line-height: 20px;
}
.storage-defaults-inherited {
font-size: 12px;
line-height: 18px;
}
.storage-defaults-edit {
flex-shrink: 0;
cursor: pointer;
}
}
.bg-light-gray {
background-color: var(--category-active) !important;
border: 0;
}
</style>
@@ -0,0 +1,674 @@
<script setup>
import { ref, computed, watch } from 'vue';
import { useStore } from 'vuex';
import Loading from '@shell/components/Loading';
import SortableTable from '@shell/components/SortableTable';
import { Banner } from '@components/Banner';
import { BadgeState } from '@components/BadgeState';
import { RcDropdown, RcDropdownItem, RcDropdownTrigger } from '@components/RcDropdown';
import { LabeledInput } from '@components/Form/LabeledInput';
import LabeledSelect from '@shell/components/form/LabeledSelect';
import { useI18n } from '@shell/composables/useI18n';
import { NAMESPACE } from '@shell/config/types';
import { HCI } from '../../types';
import { FORKLIFT_NAMESPACE } from '../../config/harvester-map';
import {
FORKLIFT_API_VERSION, buildNetworkMapEntries, buildStorageMapEntries, bytesToGB, mbToGB
} from '../../utils/forklift';
const props = defineProps({
providerName: { type: String, default: '' },
provider: { type: Object, default: null },
selectedVms: { type: Array, default: () => [] },
mappingEntries: { type: Object, default: null },
stepData: { type: Object, required: true },
});
const emit = defineEmits(['ready', 'edit-selection', 'edit-mappings', 'remove-vm']);
const store = useStore();
const { t } = useI18n(store);
const vms = computed(() => props.selectedVms);
const networkMappings = ref([]);
const storageMappings = ref([]);
const planName = ref('');
const targetNamespace = ref('');
const namespaceOptions = ref([]);
const existingProviderNames = ref([]);
const existingPlanNames = ref([]);
const errors = ref([]);
const loading = ref(true);
// Restore persisted state
planName.value = props.stepData.planName;
targetNamespace.value = props.stepData.targetNamespace || '';
const NS = FORKLIFT_NAMESPACE;
const nameConflictError = computed(() => {
const name = (planName.value || '').trim();
if (!name) {
return '';
}
if (existingProviderNames.value.includes(name)) {
return t('harvester.addons.vmMigration.reviewMigration.planNameProviderConflict', { name });
}
if (existingPlanNames.value.includes(name)) {
return t('harvester.addons.vmMigration.reviewMigration.planNamePlanConflict', { name });
}
return '';
});
watch(planName, (val) => {
props.stepData.planName = val;
}, { immediate: true });
watch(targetNamespace, (val) => {
props.stepData.targetNamespace = val;
});
watch([planName, targetNamespace, nameConflictError], () => {
emit('ready', !!planName.value && !!targetNamespace.value && !nameConflictError.value);
}, { immediate: true });
const formatNetworkTarget = (target = '') => {
if (target === 'pod') {
return t('harvester.addons.vmMigration.configureMappings.networkMapping.options.podNetworking');
}
if (target === 'ignored') {
return t('harvester.addons.vmMigration.generic.ignored');
}
return target;
};
const totalVCpu = computed(() => vms.value.reduce((sum, vm) => sum + (vm.cpuCount || vm.numCPU || 0), 0));
const totalMemoryGB = computed(() => {
const totalMB = vms.value.reduce((sum, vm) => sum + (vm.memoryMB || vm.memory || 0), 0);
return mbToGB(totalMB);
});
const totalStorageGB = computed(() => {
let totalBytes = 0;
vms.value.forEach((vm) => {
if (vm.disks && vm.disks.length > 0) {
totalBytes += vm.disks.reduce((sum, d) => sum + (d.capacity || 0), 0);
}
});
return bytesToGB(totalBytes);
});
const vmRows = computed(() => {
return vms.value.map((vm) => {
const cpus = vm.cpuCount || vm.numCPU || 0;
const memMB = vm.memoryMB || vm.memory || 0;
const memGB = memMB ? t('harvester.addons.vmMigration.generic.memoryGb', { value: mbToGB(memMB) }) : '-';
let totalDiskBytes = 0;
if (vm.disks && vm.disks.length > 0) {
totalDiskBytes = vm.disks.reduce((sum, d) => sum + (d.capacity || 0), 0);
}
const diskDisplay = totalDiskBytes ? t('harvester.addons.vmMigration.generic.memoryGb', { value: bytesToGB(totalDiskBytes) }) : '-';
const os = vm.guestName || vm.guestOS || vm.os || '-';
const rawPowerState = vm.powerState || vm.status?.phase || '-';
const powerState = rawPowerState.replace(/([a-z])([A-Z])/g, '$1 $2').replace(/^./, (c) => c.toUpperCase());
const powerStateClass = powerState.toLowerCase().includes('on') || powerState.toLowerCase().includes('running') ? 'power-on' : 'power-off';
const vmNetworkMappings = networkMappings.value.filter((m) => m.usedBy && m.usedBy.includes(vm.name || vm.id));
const vmStorageMappings = storageMappings.value.filter((m) => m.usedBy && m.usedBy.includes(vm.name || vm.id));
const networkMappingSort = vmNetworkMappings.map((m) => `${ m.source } ${ formatNetworkTarget(m.target) }`).join(', ');
const storageMappingSort = vmStorageMappings.map((m) => `${ m.source } ${ m.target }`).join(', ');
return {
_key: vm.id || vm.vmId || vm.metadata?.name,
id: vm.id,
name: vm.name || vm.id,
identifier: vm.id || vm.vmId || vm.metadata?.name || '-',
os,
resources: t('harvester.addons.vmMigration.generic.vCpu', { count: cpus }),
resourcesSub: `${ memGB } • ${ diskDisplay }`,
powerState,
powerStateClass,
networkMappings: vmNetworkMappings,
storageMappings: vmStorageMappings,
networkMapping: networkMappingSort,
storageMapping: storageMappingSort,
};
});
});
const vmHeaders = [
{
name: 'vmName',
labelKey: 'harvester.addons.vmMigration.reviewMigration.columns.vmName',
value: 'name',
sort: ['name'],
subLabel: t('harvester.addons.vmMigration.generic.identifier'),
width: 200,
},
{
name: 'os',
labelKey: 'harvester.addons.vmMigration.reviewMigration.columns.os',
value: 'os',
sort: ['os'],
width: 140,
},
{
name: 'resources',
labelKey: 'harvester.addons.vmMigration.reviewMigration.columns.resources',
value: 'resources',
sort: false,
width: 120,
},
{
name: 'powerState',
labelKey: 'harvester.addons.vmMigration.reviewMigration.columns.powerState',
value: 'powerState',
sort: ['powerState'],
width: 100,
},
{
name: 'networkMapping',
labelKey: 'harvester.addons.vmMigration.reviewMigration.columns.networkMapping',
value: 'networkMapping',
sort: ['networkMapping'],
subLabel: t('harvester.addons.vmMigration.reviewMigration.columns.sourceTarget'),
width: 220,
},
{
name: 'storageMapping',
labelKey: 'harvester.addons.vmMigration.reviewMigration.columns.storageMapping',
value: 'storageMapping',
sort: ['storageMapping'],
subLabel: t('harvester.addons.vmMigration.reviewMigration.columns.sourceTarget'),
width: 220,
},
{
name: 'actions',
label: ' ',
align: 'right',
sort: false,
width: 40,
},
];
const onEditSelection = () => emit('edit-selection');
const onEditMappings = () => emit('edit-mappings');
const onRemoveVm = (id) => emit('remove-vm', id);
const startMigrationAction = async() => {
const inStore = store.getters['currentProduct'].inStore;
const providerRef = {
source: {
apiVersion: FORKLIFT_API_VERSION,
kind: 'Provider',
name: props.providerName,
namespace: NS,
},
destination: {
apiVersion: FORKLIFT_API_VERSION,
kind: 'Provider',
name: 'host',
namespace: NS,
},
};
const networkMapName = `${ planName.value }-network-map`;
const storageMapName = `${ planName.value }-storage-map`;
const networkMap = await store.dispatch(`${ inStore }/create`, {
type: HCI.FORKLIFT_NETWORK_MAP,
metadata: { name: networkMapName, namespace: NS },
spec: { map: buildNetworkMapEntries(props.mappingEntries?.networkEntries || [], NS), provider: providerRef },
});
await networkMap.save();
const storageMap = await store.dispatch(`${ inStore }/create`, {
type: HCI.FORKLIFT_STORAGE_MAP,
metadata: { name: storageMapName, namespace: NS },
spec: { map: buildStorageMapEntries(props.mappingEntries?.storageEntries || []), provider: providerRef },
});
await storageMap.save();
const plan = await store.dispatch(`${ inStore }/create`, {
type: HCI.FORKLIFT_PLAN,
metadata: { name: planName.value, namespace: NS },
spec: {
provider: providerRef,
map: {
network: {
apiVersion: FORKLIFT_API_VERSION,
kind: 'NetworkMap',
name: networkMapName,
namespace: NS,
},
storage: {
apiVersion: FORKLIFT_API_VERSION,
kind: 'StorageMap',
name: storageMapName,
namespace: NS,
},
},
targetNamespace: targetNamespace.value,
vms: vms.value.map((vm) => ({ id: vm.id, name: vm.name || vm.id })),
warm: false,
},
});
await plan.save();
// Kick off the first migration through the model so the Migration payload
// lives in a single place (also reused by the dashboard start/restart action).
await plan.startMigration();
};
const init = async() => {
const inStore = store.getters['currentProduct'].inStore;
try {
const namespaces = await store.dispatch(`${ inStore }/findAll`, { type: NAMESPACE });
namespaceOptions.value = namespaces.filter((ns) => !ns.isSystem).map((ns) => ns.metadata.name).sort().map((name) => ({ label: name, value: name }));
} catch (e) {
namespaceOptions.value = [];
}
try {
await store.dispatch(`${ inStore }/findAll`, { type: HCI.FORKLIFT_PROVIDER });
} catch (e) {}
existingProviderNames.value = (store.getters[`${ inStore }/all`](HCI.FORKLIFT_PROVIDER) || [])
.map((p) => p.metadata?.name)
.filter(Boolean);
try {
await store.dispatch(`${ inStore }/findAll`, { type: HCI.FORKLIFT_PLAN });
} catch (e) {}
existingPlanNames.value = (store.getters[`${ inStore }/all`](HCI.FORKLIFT_PLAN) || [])
.map((p) => p.metadata?.name)
.filter(Boolean);
if (props.mappingEntries) {
networkMappings.value = (props.mappingEntries.networkEntries || []).map((entry) => ({
source: entry.name || entry.id,
target: entry.target || '',
usedBy: entry.usedBy || [],
}));
storageMappings.value = (props.mappingEntries.storageEntries || []).map((entry) => ({
source: entry.name || entry.id,
target: entry.target || '',
usedBy: entry.usedBy || [],
}));
}
loading.value = false;
};
init();
defineExpose({ startMigration: startMigrationAction });
</script>
<template>
<Loading v-if="loading" />
<div
v-else
class="review-migration"
>
<div
class="review-migration-content"
>
<Banner
v-if="nameConflictError"
color="error"
:label="nameConflictError"
/>
<!-- Migration Details Summary -->
<div class="migration-details">
<div class="section-header">
<h3 class="section-title m-0">
{{ t('harvester.addons.vmMigration.reviewMigration.migrationDetails') }}
</h3>
<span class="section-description text-deemphasized">
{{ t('harvester.addons.vmMigration.reviewMigration.migrationDetailsDescription') }}
</span>
</div>
<div class="name-row">
<LabeledInput
v-model:value="planName"
class="name-input"
:label="t('harvester.addons.vmMigration.reviewMigration.planName')"
:placeholder="t('harvester.addons.vmMigration.reviewMigration.planNamePlaceholder')"
required
/>
<LabeledSelect
v-model:value="targetNamespace"
class="namespace-select"
:label="t('harvester.addons.vmMigration.reviewMigration.targetNamespace')"
:placeholder="t('harvester.addons.vmMigration.reviewMigration.targetNamespacePlaceholder')"
:options="namespaceOptions"
required
/>
</div>
<div class="summary-row">
<div class="migration-mode-column">
<span class="detail-label">{{ t('harvester.addons.vmMigration.reviewMigration.migrationMode') }}</span>
<span class="cold-migration-badge">{{ t('harvester.addons.vmMigration.reviewMigration.coldMigration') }}</span>
<span class="text-deemphasized">{{ t('harvester.addons.vmMigration.reviewMigration.coldMigrationDescription') }}</span>
<span class="text-deemphasized">{{ t('harvester.addons.vmMigration.reviewMigration.coldMigrationHint') }}</span>
</div>
<div class="stats-column">
<span class="detail-label">{{ t('harvester.addons.vmMigration.reviewMigration.provider') }}</span>
<span class="detail-value">{{ providerName }}</span>
<span class="detail-label">{{ t('harvester.addons.vmMigration.reviewMigration.totalVms') }}</span>
<span class="detail-value">{{ vms.length }}</span>
<span class="detail-label">{{ t('harvester.addons.vmMigration.reviewMigration.vcpu') }}</span>
<span class="detail-value">{{ totalVCpu }}</span>
<span class="detail-label">{{ t('harvester.addons.vmMigration.reviewMigration.memory') }}</span>
<span class="detail-value">{{ t('harvester.addons.vmMigration.generic.memoryGb', { value: totalMemoryGB }) }}</span>
<span class="detail-label">{{ t('harvester.addons.vmMigration.reviewMigration.storage') }}</span>
<span class="detail-value">{{ t('harvester.addons.vmMigration.generic.memoryGb', { value: totalStorageGB }) }}</span>
</div>
</div>
</div>
<!-- Virtual Machines -->
<div class="vm-section">
<SortableTable
class="vm-sortable-table"
:rows="vmRows"
:headers="vmHeaders"
:search="false"
:table-actions="false"
:row-actions="false"
:groupable="false"
:paging="true"
key-field="_key"
>
<template #header-left>
<h4 class="section-title m-0">
{{ t('harvester.addons.vmMigration.reviewMigration.virtualMachines') }} ({{ vms.length }})
</h4>
</template>
<template #header-right>
<a
href="#"
class="edit-selection-link"
@click.prevent="onEditSelection"
>
{{ t('harvester.addons.vmMigration.reviewMigration.editSelection') }}
</a>
</template>
<template #cell:vmName="{ row }">
<div class="vm-name-cell">
<span class="vm-name">{{ row.name }}</span>
<span class="vm-id text-deemphasized">{{ row.identifier }}</span>
</div>
</template>
<template #cell:resources="{ row }">
<span>{{ row.resources }}</span><br>
<span class="text-deemphasized">{{ row.resourcesSub }}</span>
</template>
<template #cell:powerState="{ row }">
<BadgeState
:label="row.powerState"
:color="row.powerStateClass === 'power-on' ? 'bg-warning' : 'bg-darker'"
/>
</template>
<template #cell:networkMapping="{ row }">
<template v-if="row.networkMappings.length">
<div
v-for="(m, i) in row.networkMappings"
:key="'net-' + i"
class="mapping-cell"
>
<span class="mapping-source">{{ m.source }}</span>
<span class="mapping-target text-deemphasized">&rarr; {{ formatNetworkTarget(m.target) }}</span>
</div>
</template>
<span
v-else
class="text-deemphasized"
>-</span>
</template>
<template #cell:storageMapping="{ row }">
<template v-if="row.storageMappings.length">
<div
v-for="(m, i) in row.storageMappings"
:key="'stor-' + i"
class="mapping-cell"
>
<span class="mapping-source">{{ m.source }}</span>
<span class="mapping-target text-deemphasized">&rarr; {{ m.target }}</span>
</div>
</template>
<span
v-else
class="text-deemphasized"
>-</span>
</template>
<template #cell:actions="{ row }">
<rc-dropdown :aria-label="t('harvester.addons.vmMigration.reviewMigration.actions.menuLabel')">
<rc-dropdown-trigger
variant="ghost"
:aria-label="t('harvester.addons.vmMigration.reviewMigration.actions.menuLabel')"
>
<i class="icon icon-actions" />
</rc-dropdown-trigger>
<template #dropdownCollection>
<rc-dropdown-item @click="onEditMappings">
{{ t('harvester.addons.vmMigration.reviewMigration.actions.editMappings') }}
</rc-dropdown-item>
<rc-dropdown-item
class="text-error"
@click="onRemoveVm(row.id)"
>
{{ t('harvester.addons.vmMigration.reviewMigration.actions.removeFromPlan') }}
</rc-dropdown-item>
</template>
</rc-dropdown>
</template>
<template #no-rows>
<tr class="no-rows">
<td
:colspan="vmHeaders.length"
class="text-center"
>
{{ t('harvester.addons.vmMigration.reviewMigration.noVmSelected') }}
<a
href="#"
class="edit-selection-link"
@click.prevent="onEditSelection"
>{{ t('harvester.addons.vmMigration.reviewMigration.noVmSelectedLink') }}</a>
</td>
</tr>
</template>
</SortableTable>
</div>
<!-- Error banner -->
<Banner
v-for="(err, i) in errors"
:key="i"
color="error"
:label="err"
/>
</div>
</div>
</template>
<style lang="scss" scoped>
.review-migration {
gap: 36px;
}
.review-migration-content {
display: flex;
flex-direction: column;
gap: 20px;
}
.section-title {
font-weight: 600;
}
.name-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px clamp(12px, 1vw, 96px);
align-items: start;
}
.summary-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px clamp(12px, 1vw, 96px);
line-height: 20px;
margin-top: 12px;
}
.section-header {
display: flex;
flex-direction: column;
gap: 4px;
.section-description {
font-size: 14px;
}
}
.migration-mode-column {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 8px;
font-size: 14px;
.cold-migration-badge {
padding: 2px 10px;
border-radius: 4px;
opacity: 0.8;
font-weight: 600;
background: rgba(224, 191, 90, 0.16);
color: #E0BF5A;
font-size: 12px;
line-height: 18px;
font-weight: 600;
.theme-light & {
background: rgba(168, 128, 26, 0.16);
}
}
}
.stats-column {
display: grid;
grid-template-columns: auto auto;
justify-content: start;
align-content: start;
column-gap: clamp(24px, 4vw, 64px);
row-gap: 8px;
}
.detail-label {
font-size: 14px;
color: var(--muted);
}
.detail-value {
font-weight: 600;
font-size: 14px;
}
.edit-selection-link {
cursor: pointer;
color: var(--link);
font-size: 14px;
}
.vm-sortable-table {
:deep(.fixed-header-actions) {
align-items: end;
}
:deep(table) {
table-layout: fixed;
}
:deep(td) {
vertical-align: middle;
overflow: hidden;
}
:deep(th:first-child),
:deep(td:first-child) {
padding-left: 16px;
}
}
.vm-name-cell {
display: flex;
flex-direction: column;
.vm-name {
font-weight: 600;
}
.vm-id {
font-size: 12px;
}
}
.mapping-cell {
.mapping-target {
margin-left: 4px;
white-space: nowrap;
}
}
.mapping-cell + .mapping-cell {
margin-top: 8px;
}
.banner-title {
font-weight: 600;
}
.migration-details {
display: flex;
flex-direction: column;
gap: 12px;
}
header {
margin: 0;
}
.vm-section {
display: flex;
flex-direction: column;
gap: 16px;
}
</style>
@@ -0,0 +1,668 @@
<script setup>
import {
ref, computed, watch, nextTick, onBeforeUnmount, toRefs
} from 'vue';
import { useStore } from 'vuex';
import Loading from '@shell/components/Loading';
import SortableTable from '@shell/components/SortableTable';
import { Banner } from '@components/Banner';
import { BadgeState } from '@components/BadgeState';
import { useI18n } from '@shell/composables/useI18n';
import { bytesToGB, mbToGB } from '../../utils/forklift';
const props = defineProps({
providerName: { type: String, default: '' },
provider: { type: Object, default: null },
stepData: { type: Object, required: true },
});
const emit = defineEmits(['complete', 'loading']);
const store = useStore();
const { t } = useI18n(store);
const { discoveredVMs, selectedVMIds, tableRows } = toRefs(props.stepData);
const selectedVMs = ref([]);
const loading = ref(true);
// Restored from stepData so friendly names survive step navigation / remount.
const networkMap = ref(props.stepData.networkMap || {});
const datastoreMap = ref(props.stepData.datastoreMap || {});
const sortableTableRef = ref(null);
const allVMsSelected = ref(false);
const errors = ref([]);
let skipNextSelectionEvent = false;
const lastFetchedAt = ref(null);
const now = ref(Date.now());
const formatElapsed = (ms) => {
const totalMinutes = Math.floor(ms / 60000);
const hours = Math.floor(totalMinutes / 60);
const minutes = totalMinutes % 60;
if (hours > 0 && minutes > 0) {
return t('harvester.addons.vmMigration.generic.elapsed.hoursAndMinutes', { hours, minutes });
}
if (hours > 0) {
return t('harvester.addons.vmMigration.generic.elapsed.hours', { hours });
}
return t('harvester.addons.vmMigration.generic.elapsed.minutes', { minutes: Math.max(1, minutes) });
};
const lastSyncedTime = computed(() => {
if (!lastFetchedAt.value) {
return '';
}
return formatElapsed(now.value - lastFetchedAt.value);
});
const nowTimer = setInterval(() => {
now.value = Date.now();
}, 30000);
onBeforeUnmount(() => {
clearInterval(nowTimer);
});
// Restore selection state from stepData
if (selectedVMIds.value.size > 0) {
selectedVMs.value = discoveredVMs.value.filter((vm) => selectedVMIds.value.has(vm.id));
allVMsSelected.value = selectedVMIds.value.size === discoveredVMs.value.length;
}
const vmCount = computed(() => discoveredVMs.value.length);
const selectedCount = computed(() => selectedVMs.value.length);
const showSelectAllBanner = computed(() => {
if (allVMsSelected.value) {
return true;
}
const pagedRows = sortableTableRef.value?.pagedRows || [];
if (pagedRows.length === 0) {
return false;
}
const allPageSelected = pagedRows.every((row) => selectedVMIds.value.has(row._original?.id));
return allPageSelected && tableRows.value.length > pagedRows.length;
});
const theadElement = computed(() => sortableTableRef.value?.$el?.querySelector('thead'));
const headers = ref([
{
name: 'vmName',
labelKey: 'harvester.addons.vmMigration.selectVms.columns.vmName',
value: 'vmName',
sort: ['vmName'],
subLabel: t('harvester.addons.vmMigration.generic.identifier'),
},
{
name: 'os',
labelKey: 'harvester.addons.vmMigration.selectVms.columns.os',
value: 'os',
sort: ['os'],
width: 180,
},
{
name: 'resources',
labelKey: 'harvester.addons.vmMigration.selectVms.columns.resources',
value: 'resources',
sort: false,
width: 140,
},
{
name: 'powerState',
labelKey: 'harvester.addons.vmMigration.selectVms.columns.powerState',
value: 'powerState',
sort: ['powerState'],
width: 130,
},
{
name: 'network',
labelKey: 'harvester.addons.vmMigration.selectVms.columns.network',
value: 'network',
sort: ['network'],
subLabel: t('harvester.addons.vmMigration.generic.identifier'),
width: 200,
},
{
name: 'datastore',
labelKey: 'harvester.addons.vmMigration.selectVms.columns.datastore',
value: 'datastore',
sort: ['datastore'],
subLabel: t('harvester.addons.vmMigration.generic.identifier'),
width: 200,
},
]);
const buildTableRows = () => {
return discoveredVMs.value.map((vm) => {
const cpus = vm.cpuCount || vm.numCPU || '-';
const memMB = vm.memoryMB || vm.memory || 0;
const memGB = memMB ? t('harvester.addons.vmMigration.generic.memoryGb', { value: mbToGB(memMB) }) : '-';
let totalDiskBytes = 0;
if (vm.disks && vm.disks.length > 0) {
totalDiskBytes = vm.disks.reduce((sum, d) => sum + (d.capacity || 0), 0);
}
const diskDisplay = totalDiskBytes ? t('harvester.addons.vmMigration.generic.memoryGb', { value: bytesToGB(totalDiskBytes) }) : '-';
const rawPowerState = vm.powerState || vm.status?.phase || '-';
const powerState = rawPowerState.replace(/([a-z])([A-Z])/g, '$1 $2').replace(/^./, (c) => c.toUpperCase());
let networks = [];
if (vm.networks && vm.networks.length > 0) {
networks = vm.networks.map((n) => ({
name: n.name || networkMap.value[n.id] || n.id || n,
id: n.id || '',
vlanId: n.vlanId || '',
}));
}
const datastores = [];
if (vm.disks && vm.disks.length > 0) {
const seen = new Set();
vm.disks.forEach((d) => {
const dsId = d.datastore?.id || d.datastore?.name;
if (dsId && !seen.has(dsId)) {
seen.add(dsId);
datastores.push({
name: d.datastore?.name || datastoreMap.value[dsId] || dsId,
id: d.datastore?.id || '',
type: d.datastore?.type || '',
capacity: d.capacity || 0,
});
}
});
}
return {
_original: vm,
_key: vm.id || vm.vmId || vm.metadata?.name,
selectedSort: selectedVMIds.value.has(vm.id) ? 0 : 1,
vmName: vm.name || vm.metadata?.name || '-',
vmId: vm.id || vm.vmId || vm.metadata?.name || '-',
os: vm.guestName || vm.guestOS || vm.os || '-',
resourcesDisplay: t('harvester.addons.vmMigration.generic.vCpu', { count: cpus }),
resourcesSub: `${ memGB } • ${ diskDisplay }`,
powerState,
powerStateClass: powerState.toLowerCase().includes('on') || powerState.toLowerCase().includes('running') ? 'power-on' : 'power-off',
networks,
network: networks.map((n) => n.name).join(', ') || '-',
datastores,
datastore: datastores.map((d) => d.name).join(', ') || '-',
};
});
};
const onSelect = (rows) => {
if (skipNextSelectionEvent) {
return;
}
const currentPageRows = sortableTableRef.value?.pagedRows || [];
const selectedKeys = new Set(rows.map((r) => r._key));
currentPageRows.forEach((row) => {
const vmId = row._original?.id;
if (selectedKeys.has(row._key)) {
selectedVMIds.value.add(vmId);
} else {
selectedVMIds.value.delete(vmId);
}
});
allVMsSelected.value = selectedVMIds.value.size === discoveredVMs.value.length;
selectedVMs.value = discoveredVMs.value.filter((vm) => selectedVMIds.value.has(vm.id));
emit('complete', { selectedVMs: selectedVMs.value });
};
const clearSelection = () => {
allVMsSelected.value = false;
selectedVMIds.value = new Set();
selectedVMs.value = [];
nextTick(() => {
const table = sortableTableRef.value;
if (table) {
table.clearSelection();
if (typeof table.setPage === 'function') {
table.setPage(1);
}
}
});
};
const selectAllVMs = () => {
allVMsSelected.value = true;
selectedVMIds.value = new Set(discoveredVMs.value.map((vm) => vm.id));
selectedVMs.value = discoveredVMs.value.slice();
};
// Moves currently-selected VMs to the first page(s) and re-checks them.
const sortSelectedToFront = () => {
if (selectedVMIds.value.size === 0) {
return;
}
tableRows.value.forEach((row) => {
row.selectedSort = selectedVMIds.value.has(row._original?.id) ? 0 : 1;
});
headers.value = headers.value.map((h) => (
h.name === 'vmName' ? { ...h, sort: ['selectedSort', 'vmName'] } : h
));
skipNextSelectionEvent = true;
nextTick(() => {
const table = sortableTableRef.value;
if (!table) {
skipNextSelectionEvent = false;
return;
}
if (typeof table.changeSort === 'function') {
table.changeSort('vmName', false);
} else if (typeof table.setPage === 'function') {
table.setPage(1);
}
nextTick(() => {
const rowsToReselect = (table.pagedRows || []).filter((row) => selectedVMIds.value.has(row._original?.id));
if (rowsToReselect.length > 0) {
table.update(rowsToReselect, []);
}
skipNextSelectionEvent = false;
});
});
};
watch(
() => sortableTableRef.value?.page,
() => {
skipNextSelectionEvent = true;
nextTick(() => {
const table = sortableTableRef.value;
if (!table) {
return;
}
const rowsToReselect = (table.pagedRows || []).filter((row) => selectedVMIds.value.has(row._original?.id));
if (rowsToReselect.length > 0) {
table.update(rowsToReselect, []);
}
skipNextSelectionEvent = false;
});
}
);
const refreshing = ref(false);
const isLoading = computed(() => loading.value || refreshing.value);
watch(isLoading, (val) => {
emit('loading', val);
}, { immediate: true });
const fetchVMs = async() => {
if (!props.provider) {
return;
}
const inStore = store.getters['currentProduct'].inStore;
const providerUid = props.provider.metadata.uid;
const providerType = props.provider.spec?.type || 'vsphere';
const baseUrl = store.getters['harvester-common/getHarvesterClusterUrl'](
`v1/harvester/providers/${ providerType }/${ providerUid }`
);
const [vmsResp, networksResp, datastoresResp] = await Promise.all([
store.dispatch(`${ inStore }/request`, { url: `${ baseUrl }/vms` }),
store.dispatch(`${ inStore }/request`, { url: `${ baseUrl }/networks` }).catch(() => []),
store.dispatch(`${ inStore }/request`, { url: `${ baseUrl }/datastores` }).catch(() => []),
]);
if (Array.isArray(vmsResp)) {
discoveredVMs.value = vmsResp;
} else if (vmsResp?.data && Array.isArray(vmsResp.data)) {
discoveredVMs.value = vmsResp.data;
}
const networks = Array.isArray(networksResp) ? networksResp : (networksResp?.data || []);
const datastores = Array.isArray(datastoresResp) ? datastoresResp : (datastoresResp?.data || []);
networkMap.value = networks.reduce((map, n) => {
map[n.id] = n.name;
return map;
}, {});
datastoreMap.value = datastores.reduce((map, d) => {
map[d.id] = d.name;
return map;
}, {});
props.stepData.networkMap = networkMap.value;
props.stepData.datastoreMap = datastoreMap.value;
lastFetchedAt.value = Date.now();
tableRows.value = buildTableRows();
};
const refreshVMs = async() => {
refreshing.value = true;
skipNextSelectionEvent = true;
const previousSelectedIds = new Set(selectedVMIds.value);
try {
errors.value = [];
await fetchVMs();
} catch (e) {
discoveredVMs.value = [];
tableRows.value = [];
errors.value = [e?.message || t('harvester.addons.vmMigration.errors.failedRefreshVms')];
}
selectedVMIds.value = new Set(
discoveredVMs.value
.filter((vm) => previousSelectedIds.has(vm.id))
.map((vm) => vm.id)
);
selectedVMs.value = discoveredVMs.value.filter((vm) => selectedVMIds.value.has(vm.id));
allVMsSelected.value = selectedVMIds.value.size > 0 && selectedVMIds.value.size === discoveredVMs.value.length;
props.stepData.discoveredVMs = discoveredVMs.value;
props.stepData.selectedVMIds = selectedVMIds.value;
props.stepData.tableRows = tableRows.value;
emit('complete', { selectedVMs: selectedVMs.value });
refreshing.value = false;
await nextTick();
const table = sortableTableRef.value;
if (table) {
const rowsToReselect = (table.pagedRows || []).filter((row) => selectedVMIds.value.has(row._original?.id));
if (rowsToReselect.length > 0) {
table.update(rowsToReselect, []);
}
}
skipNextSelectionEvent = false;
};
const init = async() => {
if (discoveredVMs.value.length > 0) {
if (!lastFetchedAt.value) {
lastFetchedAt.value = Date.now();
}
tableRows.value = buildTableRows();
loading.value = false;
// Returning to the step with an existing selection: bring selected VMs forward and re-check them.
await nextTick();
sortSelectedToFront();
return;
}
try {
await fetchVMs();
} catch (e) {
discoveredVMs.value = [];
errors.value = [e?.message || t('harvester.addons.vmMigration.errors.failedLoadVms')];
}
loading.value = false;
};
// Emit initial complete if VMs are already selected (restored from stepData)
if (selectedVMs.value.length > 0) {
emit('complete', { selectedVMs: selectedVMs.value });
}
init();
</script>
<template>
<Loading v-if="loading || refreshing" />
<div
v-else
class="select-vms-step"
>
<Banner
v-for="(err, i) in errors"
:key="i"
color="error"
:label="err"
/>
<p class="text-deemphasized line-height-20">
{{ t('harvester.addons.vmMigration.selectVms.discovered', { count: vmCount }) }}
<router-link
v-if="provider"
class="provider-link"
:to="provider._detailLocation"
>
{{ providerName }}
</router-link>
<br>
<span
v-if="lastSyncedTime"
>
{{ t('harvester.addons.vmMigration.selectVms.lastSynced', { time: lastSyncedTime }) }}
<a
role="button"
class="text-bold"
:class="{ disabled: refreshing }"
@click.prevent="refreshVMs"
>
{{ t('harvester.addons.vmMigration.selectVms.refreshNow') }}
</a>
</span>
</p>
<!-- Discovered VMs table -->
<SortableTable
ref="sortableTableRef"
:rows="tableRows"
:headers="headers"
:search="true"
:table-actions="true"
:row-actions="false"
:groupable="false"
:paging="true"
key-field="_key"
@selection="onSelect"
>
<template #header-left>
<div class="vm-table-title">
<h3 class="m-0">
{{ t('harvester.addons.vmMigration.selectVms.availableVms') }}
</h3>
<span class="selected-actions">
<span class="text-deemphasized">
{{ selectedCount }} {{ t('harvester.addons.vmMigration.selectVms.selected') }}
</span>
<template v-if="selectedCount > 0">
<span class="text-deemphasized">|</span>
<a
role="button"
@click.prevent="clearSelection"
>
{{ t('harvester.addons.vmMigration.selectVms.clearAll') }}
</a>
</template>
</span>
</div>
</template>
<template #cell:vmName="{ row }">
<div class="vm-name-cell">
<span class="vm-name">{{ row.vmName }}</span>
<span class="vm-id text-deemphasized">{{ row.vmId }}</span>
</div>
</template>
<template #cell:resources="{ row }">
<span>{{ row.resourcesDisplay }}</span><br>
<span class="text-deemphasized">{{ row.resourcesSub }}</span>
</template>
<template #cell:powerState="{ row }">
<BadgeState
:label="row.powerState"
:color="row.powerStateClass === 'power-on' ? 'bg-success' : 'bg-darker'"
/>
</template>
<template #cell:network="{ row }">
<div>
<div
v-for="(net, i) in row.networks"
:key="i"
:class="{ 'mt-4': i > 0 }"
>
<span>{{ net.name }}</span><br>
<span class="text-deemphasized">{{ net.id }}</span>
</div>
</div>
</template>
<template #cell:datastore="{ row }">
<div>
<div
v-for="(ds, i) in row.datastores"
:key="i"
:class="{ 'mt-4': i > 0 }"
>
<span>{{ ds.name }}</span><br>
<span class="text-deemphasized">{{ ds.id }}</span>
</div>
</div>
</template>
</SortableTable>
<Teleport
v-if="showSelectAllBanner && theadElement"
:to="theadElement"
>
<tr class="select-all-banner-row">
<td
:colspan="headers.length + 1"
class="select-all-banner-cell"
>
<template v-if="allVMsSelected">
<span>{{ t('harvester.addons.vmMigration.selectVms.selectAllBanner.allSelected') }}</span>
<a
role="button"
@click.prevent="clearSelection"
>
{{ t('harvester.addons.vmMigration.selectVms.selectAllBanner.clearSelection') }}
</a>
</template>
<template v-else>
<span>{{ t('harvester.addons.vmMigration.selectVms.selectAllBanner.pageOnly') }}</span>
<a
role="button"
@click.prevent="selectAllVMs"
>
{{ t('harvester.addons.vmMigration.selectVms.selectAllBanner.selectAll', { count: vmCount }) }}
</a>
</template>
</td>
</tr>
</Teleport>
</div>
</template>
<style lang="scss" scoped>
.vm-table-title {
.text-deemphasized {
font-size: 13px;
}
.selected-actions {
display: flex;
align-items: center;
gap: 8px;
font-size: 13px;
a {
cursor: pointer;
&.disabled {
color: var(--muted);
cursor: default;
pointer-events: none;
}
}
}
}
.vm-name-cell {
display: flex;
flex-direction: column;
font-size: 14px;
.vm-name {
line-height: 20px;
}
.vm-id {
line-height: 20px;
}
}
.select-vms-step {
position: relative;
display: flex;
flex-direction: column;
gap: 20px;
.line-height-20 {
line-height: 20px;
}
}
:deep(.select-all-banner-row) {
.select-all-banner-cell {
text-align: center;
padding: 8px 16px;
background-color: var(--sortable-table-header-bg);
border-bottom: 1px solid var(--border);
font-size: 13px;
a {
color: var(--primary);
cursor: pointer;
font-weight: 600;
margin-left: 5px;
&:hover {
text-decoration: underline;
}
}
}
}
</style>
@@ -0,0 +1,181 @@
<script setup>
import { ref } from 'vue';
import { useStore } from 'vuex';
import { Card } from '@components/Card';
import LabeledSelect from '@shell/components/form/LabeledSelect';
import AppModal from '@shell/components/AppModal';
import { useI18n } from '@shell/composables/useI18n';
import { VOLUME_MODE, ACCESS_MODE } from '../../config/types';
const VOLUME_MODE_OPTIONS = [VOLUME_MODE.FILE_SYSTEM, VOLUME_MODE.BLOCK];
const {
READ_WRITE_ONCE = 'ReadWriteOnce',
READ_ONLY_MANY = 'ReadOnlyMany',
READ_WRITE_MANY = 'ReadWriteMany',
READ_WRITE_ONCE_POD = 'ReadWriteOncePod'
} = ACCESS_MODE || {};
const ACCESS_MODE_OPTIONS = [READ_WRITE_ONCE, READ_WRITE_MANY, READ_ONLY_MANY, READ_WRITE_ONCE_POD];
const props = defineProps({
storageClassName: { type: String, default: '' },
providerName: { type: String, default: '' },
showInherited: { type: Boolean, default: false },
volumeMode: { type: String, default: VOLUME_MODE.FILE_SYSTEM },
accessModes: { type: Array, default: () => ['ReadWriteMany'] },
inheritedVolumeMode: { type: String, default: VOLUME_MODE.FILE_SYSTEM },
inheritedAccessModes: { type: Array, default: () => ['ReadWriteMany'] },
});
const emit = defineEmits(['apply', 'close']);
const store = useStore();
const { t } = useI18n(store);
const localVolumeMode = ref(props.volumeMode || VOLUME_MODE.FILE_SYSTEM);
const localAccessMode = ref(props.accessModes?.[0] || READ_WRITE_MANY);
const volumeModeOptions = VOLUME_MODE_OPTIONS.map((value) => ({ label: value, value }));
const accessModeOptions = ACCESS_MODE_OPTIONS.map((value) => ({ label: value, value }));
const apply = () => {
emit('apply', {
volumeMode: localVolumeMode.value,
accessModes: [localAccessMode.value],
});
emit('close');
};
// Repopulate the dropdowns with the provider default values; the user then applies.
const reset = () => {
localVolumeMode.value = props.inheritedVolumeMode || VOLUME_MODE.FILE_SYSTEM;
localAccessMode.value = props.inheritedAccessModes?.[0] || READ_WRITE_MANY;
};
const cancel = () => {
emit('close');
};
</script>
<template>
<app-modal
class="storage-defaults-modal"
name="storageDefaultsDialog"
:width="620"
height="auto"
:click-to-close="false"
@close="cancel"
>
<Card
class="storage-defaults-card"
:show-highlight-border="false"
>
<template #title>
<h4 class="text-default-text">
{{ t('harvester.addons.vmMigration.storageDefaults.title', { name: storageClassName }) }}
</h4>
</template>
<template #body>
<p class="text-deemphasized description">
<template v-if="showInherited">
{{ t('harvester.addons.vmMigration.storageDefaults.descriptionInherited', { name: storageClassName, provider: providerName }) }}
</template>
<template v-else>
{{ t('harvester.addons.vmMigration.storageDefaults.description', { name: storageClassName }) }}
</template>
</p>
<div class="settings-box">
<LabeledSelect
v-model:value="localVolumeMode"
class="volume-mode"
:label="t('harvester.addons.vmMigration.storageDefaults.volumeMode')"
:options="volumeModeOptions"
:searchable="false"
:clearable="false"
/>
<LabeledSelect
v-model:value="localAccessMode"
class="access-mode"
:label="t('harvester.addons.vmMigration.storageDefaults.accessMode')"
:options="accessModeOptions"
:searchable="false"
:clearable="false"
/>
</div>
</template>
<template #actions>
<div class="buttons">
<button
class="btn role-secondary"
@click="cancel"
>
{{ t('harvester.addons.vmMigration.storageDefaults.cancel') }}
</button>
<div class="right-buttons">
<button
v-if="showInherited"
class="btn role-secondary mr-10"
@click="reset"
>
{{ t('harvester.addons.vmMigration.storageDefaults.resetToProviderDefault') }}
</button>
<button
class="btn role-primary"
:disabled="!localAccessMode"
@click="apply"
>
{{ showInherited ? t('harvester.addons.vmMigration.storageDefaults.applyOverride') : t('harvester.addons.vmMigration.storageDefaults.apply') }}
</button>
</div>
</div>
</template>
</Card>
</app-modal>
</template>
<style lang="scss" scoped>
.storage-defaults-modal {
z-index: 45;
}
.storage-defaults-card {
margin: 0;
padding: 20px;
}
.description {
margin-bottom: 16px;
line-height: 20px;
}
.settings-box {
display: flex;
flex-direction: column;
gap: 20px;
padding: 16px;
border-radius: 6px;
background-color: var(--category-active);
}
.volume-mode {
max-width: 280px;
}
.access-mode {
max-width: 280px;
}
.buttons {
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
.right-buttons {
display: flex;
}
}
</style>
+29 -1
View File
@@ -56,9 +56,37 @@ const FEATURE_FLAGS = {
'kubevirtMigration',
'hotplugNic',
'resumeUpgradePausedNode',
'vncPreserveSession',
],
'v1.7.1': [],
'v1.8.0': []
'v1.8.0': [
'hotplugCdRom',
'supportBundleFileNameSetting',
'clusterRegistrationTLSVerify',
'vGPUAsPCIDevice',
'instanceManagerResourcesSetting',
'rwxNetworkSetting',
'createPVCWithDataVolume',
'clusterPodSecurityStandardSetting',
],
'v1.8.1': [],
'v1.9.0': [
'supportFilesystem',
'disableResourcePooling',
'expandOnlineEncryptedVolume',
'longhornV2HugepageSettings',
'staticIPForVM',
'fsFreezeDeadline',
],
'v1.9.1': [
'lvmDmThinOnly',
'highPerformanceStorage',
],
'v1.10.0': [
'maintenanceModeConditions',
'maintenanceModeDrainTimeoutSetting',
'componentHealth',
],
};
const generateFeatureFlags = () => {
+470 -40
View File
@@ -47,13 +47,34 @@ import {
VM_IMPORT_SOURCE_O_STATUS,
VM_IMPORT_SOURCE_OVA_URL,
VM_IMPORT_SOURCE_OVA_STATUS,
FORKLIFT_PROVIDER_TYPE,
FORKLIFT_PROVIDER_URL,
FORKLIFT_MAP_SOURCE_PROVIDER,
FORKLIFT_MAP_DEST_PROVIDER,
FORKLIFT_PLAN_TARGET_NS,
FORKLIFT_PLAN_VM_COUNT,
FORKLIFT_MIGRATION_PLAN,
} from './table-headers';
import { ADD_ONS } from './harvester-map';
import { registerAddonSideNav } from '../utils/dynamic-nav';
import { setStandalonePrime } from '../utils/l10n-globals';
import { setVendor } from '@shell/config/private-label';
import { CONFIGURABLE_TABLES } from '@shell/store/features';
import { tableViewsOffFeature } from '../utils/table-views';
import { SETTING } from '@shell/config/settings';
import { primeBrandUpdater } from '../utils/prime-brand';
const TEMPLATE = HCI.VM_VERSION;
const MONITORING_GROUP = 'Monitoring & Logging::Monitoring';
const LOGGING_GROUP = 'Monitoring & Logging::Logging';
const OVERLAY_NETWORKS_GROUP = 'Overlay Networks';
const UNDERLAY_NETWORKS_GROUP = 'Underlay Networks';
const NAT_INTERNET_GROUP = `${ OVERLAY_NETWORKS_GROUP }::NAT & Internet`;
const GATEWAYS_GROUP = `${ NAT_INTERNET_GROUP }::Gateways`;
const EXTERNAL_IPS_GROUP = `${ NAT_INTERNET_GROUP }::External IPs`;
const RULES_GROUP = `${ NAT_INTERNET_GROUP }::Rules`;
const SOURCE_RULES_GROUP = `${ RULES_GROUP }::Source Rules`;
const DESTINATION_RULES_GROUP = `${ RULES_GROUP }::Destination Rules`;
export const PRODUCT_NAME = 'harvester';
@@ -81,7 +102,6 @@ export function init($plugin, store) {
configureType,
virtualType,
weightGroup,
weightType,
} = $plugin.DSL(store, PRODUCT_NAME);
const isSingleVirtualCluster = process.env.rancherEnv === PRODUCT_NAME;
@@ -95,15 +115,57 @@ export function init($plugin, store) {
}
};
store.dispatch('setIsSingleProduct', {
productName: PRODUCT_NAME,
logo: require(`@shell/assets/images/providers/harvester.svg`),
productNameKey: 'harvester.productLabel',
getVersionInfo: (store) => store.getters[`${ PRODUCT_NAME }/byId`]?.(HCI.SETTING, 'server-version')?.value || 'unknown',
afterLoginRoute: home,
logoRoute: home,
supportCustomLogo: true
});
store.watch(
(_state, getters) => JSON.stringify([
!!getters['harvester-common/isHarvesterPrime'],
getters['prefs/theme'] === 'dark',
getters['harvester-common/privateLabel']
]),
(value) => {
const [isHarvesterPrime, isDark, privateLabel] = JSON.parse(value);
const primeLogo = isDark ? require('../assets/images/dark/suse-virtualization.svg') : require('../assets/images/suse-virtualization.svg');
setStandalonePrime(isHarvesterPrime);
setVendor(privateLabel || '');
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({
@@ -168,7 +230,7 @@ export function init($plugin, store) {
group: 'Root',
name: HCI.HOST,
namespaced: true,
weight: 399,
weight: 499,
route: {
name: `${ PRODUCT_NAME }-c-cluster-resource`,
params: { resource: HCI.HOST }
@@ -200,7 +262,7 @@ export function init($plugin, store) {
group: 'root',
name: HCI.VM,
namespaced: true,
weight: 299,
weight: 498,
route: {
name: `${ PRODUCT_NAME }-c-cluster-resource`,
params: { resource: HCI.VM }
@@ -238,6 +300,7 @@ export function init($plugin, store) {
labelKey: 'harvester.addons.vmImport.labels.vmimport',
group: 'vmimport',
namespaced: true,
ifHaveType: HCI.VMIMPORT,
route: {
name: `${ PRODUCT_NAME }-c-cluster-resource`,
params: { resource: HCI.VMIMPORT }
@@ -267,6 +330,7 @@ export function init($plugin, store) {
labelKey: 'harvester.addons.vmImport.labels.vmimportSourceVMWare',
group: 'vmimport',
namespaced: true,
ifHaveType: HCI.VMIMPORT_SOURCE_V,
route: {
name: `${ PRODUCT_NAME }-c-cluster-resource`,
params: { resource: HCI.VMIMPORT_SOURCE_V }
@@ -296,6 +360,7 @@ export function init($plugin, store) {
labelKey: 'harvester.addons.vmImport.labels.vmimportSourceOpenStack',
group: 'vmimport',
namespaced: true,
ifHaveType: HCI.VMIMPORT_SOURCE_O,
route: {
name: `${ PRODUCT_NAME }-c-cluster-resource`,
params: { resource: HCI.VMIMPORT_SOURCE_O }
@@ -324,6 +389,7 @@ export function init($plugin, store) {
labelKey: 'harvester.addons.vmImport.labels.vmimportSourceOVA',
group: 'vmimport',
namespaced: true,
ifHaveType: HCI.VMIMPORT_SOURCE_OVA,
route: {
name: `${ PRODUCT_NAME }-c-cluster-resource`,
params: { resource: HCI.VMIMPORT_SOURCE_OVA }
@@ -361,7 +427,7 @@ export function init($plugin, store) {
ifHaveType: PVC,
name: HCI.VOLUME,
namespaced: true,
weight: 199,
weight: 497,
route: {
name: `${ PRODUCT_NAME }-c-cluster-resource`,
params: { resource: HCI.VOLUME }
@@ -387,7 +453,7 @@ export function init($plugin, store) {
group: 'root',
name: HCI.IMAGE,
namespaced: true,
weight: 198,
weight: 496,
route: {
name: `${ PRODUCT_NAME }-c-cluster-resource`,
params: { resource: HCI.IMAGE }
@@ -402,7 +468,7 @@ export function init($plugin, store) {
group: 'root',
namespaced: true,
name: 'projects-namespaces',
weight: 98,
weight: 495,
route: { name: `${ PRODUCT_NAME }-c-cluster-projectsnamespaces` },
exact: true,
});
@@ -414,7 +480,7 @@ export function init($plugin, store) {
labelKey: 'harvester.namespace.label',
name: NAMESPACE,
namespaced: true,
weight: 89,
weight: 495,
route: {
name: `${ PRODUCT_NAME }-c-cluster-resource`,
params: { resource: NAMESPACE }
@@ -485,6 +551,7 @@ export function init($plugin, store) {
});
virtualType({
ifHaveType: LOGGING.CLUSTER_FLOW,
labelKey: 'harvester.logging.clusterFlow.label',
name: HCI.CLUSTER_FLOW,
namespaced: true,
@@ -508,6 +575,7 @@ export function init($plugin, store) {
});
virtualType({
ifHaveType: LOGGING.CLUSTER_OUTPUT,
labelKey: 'harvester.logging.clusterOutput.label',
name: HCI.CLUSTER_OUTPUT,
namespaced: true,
@@ -531,6 +599,7 @@ export function init($plugin, store) {
});
virtualType({
ifHaveType: LOGGING.FLOW,
labelKey: 'harvester.logging.flow.label',
name: HCI.FLOW,
namespaced: true,
@@ -554,6 +623,7 @@ export function init($plugin, store) {
});
virtualType({
ifHaveType: LOGGING.OUTPUT,
labelKey: 'harvester.logging.output.label',
name: HCI.OUTPUT,
namespaced: true,
@@ -574,14 +644,53 @@ export function init($plugin, store) {
[
HCI.CLUSTER_NETWORK,
HCI.NETWORK_ATTACHMENT,
HCI.VPC,
NETWORK_POLICY,
HCI.HOST_NETWORK_CONFIG,
HCI.LB,
HCI.IP_POOL,
],
'networks'
);
basicType(
[HCI.VPC],
OVERLAY_NETWORKS_GROUP
);
basicType(
[NETWORK_POLICY],
OVERLAY_NETWORKS_GROUP
);
basicType(
[HCI.VPC_NAT_GATEWAY],
GATEWAYS_GROUP
);
basicType(
[HCI.IPTABLES_EIP],
EXTERNAL_IPS_GROUP
);
basicType(
[HCI.IPTABLES_SNAT_RULE],
SOURCE_RULES_GROUP
);
basicType(
[HCI.IPTABLES_DNAT_RULE],
DESTINATION_RULES_GROUP
);
basicType(
[HCI.PROVIDER_NETWORK],
UNDERLAY_NETWORKS_GROUP
);
basicType(
[HCI.VLAN],
UNDERLAY_NETWORKS_GROUP
);
basicType(
[
HCI.SCHEDULE_VM_BACKUP,
@@ -592,9 +701,26 @@ export function init($plugin, store) {
'backupAndSnapshot'
);
weightGroup('networks', 300, true);
weightType(NAMESPACE, 299, true);
weightGroup('backupAndSnapshot', 289, true);
weightGroup('networks', 494, true);
weightGroup('Overlay Networks', 493, true);
weightGroup('NAT & Internet', 492, true);
weightGroup('Rules', 491, true);
weightGroup('Underlay Networks', 490, true);
weightGroup('backupAndSnapshot', 489, true);
basicType(
[
HCI.SR_IOV,
HCI.PCI_DEVICE,
HCI.SR_IOVGPU_DEVICE,
HCI.VGPU_DEVICE,
HCI.MIG_CONFIGURATION,
HCI.USB_DEVICE,
],
'hardwareDevices'
);
weightGroup('hardwareDevices', 488, true);
basicType(
[
@@ -602,12 +728,6 @@ export function init($plugin, store) {
HCI.SSH,
HCI.CLOUD_TEMPLATE,
HCI.STORAGE,
HCI.SR_IOV,
HCI.PCI_DEVICE,
HCI.SR_IOVGPU_DEVICE,
HCI.VGPU_DEVICE,
HCI.MIG_CONFIGURATION,
HCI.USB_DEVICE,
HCI.ADD_ONS,
HCI.SECRET,
HCI.SETTING
@@ -673,7 +793,7 @@ export function init($plugin, store) {
name: HCI.CLUSTER_NETWORK,
ifHaveType: HCI.CLUSTER_NETWORK,
namespaced: false,
weight: 189,
weight: 484,
route: {
name: `${ PRODUCT_NAME }-c-cluster-resource`,
params: { resource: HCI.CLUSTER_NETWORK }
@@ -688,14 +808,14 @@ export function init($plugin, store) {
},
resource: NETWORK_ATTACHMENT,
resourceDetail: HCI.NETWORK_ATTACHMENT,
resourceEdit: HCI.NETWORK_ATTACHMENT
resourceEdit: HCI.NETWORK_ATTACHMENT,
});
virtualType({
labelKey: 'harvester.network.label',
name: HCI.NETWORK_ATTACHMENT,
namespaced: true,
weight: 188,
weight: 485,
route: {
name: `${ PRODUCT_NAME }-c-cluster-resource`,
params: { resource: HCI.NETWORK_ATTACHMENT }
@@ -709,7 +829,7 @@ export function init($plugin, store) {
labelKey: 'harvester.vpc.label',
name: HCI.VPC,
namespaced: true,
weight: 187,
weight: 195,
route: {
name: `${ PRODUCT_NAME }-c-cluster-resource`,
params: { resource: HCI.VPC }
@@ -718,13 +838,73 @@ export function init($plugin, store) {
ifHaveType: HCI.VPC,
});
configureType(HCI.VPC_NAT_GATEWAY, { hiddenNamespaceGroupButton: true, canYaml: false });
virtualType({
labelKey: 'harvester.natGateway.label',
name: HCI.VPC_NAT_GATEWAY,
namespaced: false,
weight: 193,
route: {
name: `${ PRODUCT_NAME }-c-cluster-resource`,
params: { resource: HCI.VPC_NAT_GATEWAY }
},
exact: false,
ifHaveType: HCI.VPC_NAT_GATEWAY,
});
configureType(HCI.IPTABLES_EIP, { hiddenNamespaceGroupButton: true, canYaml: false });
virtualType({
labelKey: 'harvester.externalIP.label',
name: HCI.IPTABLES_EIP,
namespaced: false,
weight: 192,
route: {
name: `${ PRODUCT_NAME }-c-cluster-resource`,
params: { resource: HCI.IPTABLES_EIP }
},
exact: false,
ifHaveType: HCI.IPTABLES_EIP,
});
configureType(HCI.IPTABLES_SNAT_RULE, { hiddenNamespaceGroupButton: true, canYaml: false });
virtualType({
labelKey: 'harvester.snat.label',
name: HCI.IPTABLES_SNAT_RULE,
namespaced: false,
weight: 191,
route: {
name: `${ PRODUCT_NAME }-c-cluster-resource`,
params: { resource: HCI.IPTABLES_SNAT_RULE }
},
exact: false,
ifHaveType: HCI.IPTABLES_SNAT_RULE,
});
configureType(HCI.IPTABLES_DNAT_RULE, { hiddenNamespaceGroupButton: true, canYaml: false });
virtualType({
labelKey: 'harvester.dnat.label',
name: HCI.IPTABLES_DNAT_RULE,
namespaced: false,
weight: 190,
route: {
name: `${ PRODUCT_NAME }-c-cluster-resource`,
params: { resource: HCI.IPTABLES_DNAT_RULE }
},
exact: false,
ifHaveType: HCI.IPTABLES_DNAT_RULE,
});
configureType(NETWORK_POLICY, { hiddenNamespaceGroupButton: true, canYaml: false });
virtualType({
labelKey: 'harvester.networkPolicy.label',
name: NETWORK_POLICY,
namespaced: true,
weight: 186,
weight: 194,
route: {
name: `${ PRODUCT_NAME }-c-cluster-resource`,
params: { resource: NETWORK_POLICY }
@@ -733,6 +913,53 @@ export function init($plugin, store) {
ifHaveType: NETWORK_POLICY,
});
configureType(HCI.PROVIDER_NETWORK, { hiddenNamespaceGroupButton: true, canYaml: false });
virtualType({
labelKey: 'harvester.providerNetwork.label',
name: HCI.PROVIDER_NETWORK,
namespaced: false,
weight: 189,
route: {
name: `${ PRODUCT_NAME }-c-cluster-resource`,
params: { resource: HCI.PROVIDER_NETWORK }
},
exact: false,
ifHaveType: HCI.PROVIDER_NETWORK,
});
configureType(HCI.VLAN, { hiddenNamespaceGroupButton: true, canYaml: false });
headers(HCI.VLAN, [
STATE,
NAME_COL,
{
name: 'id',
label: 'ID',
value: 'spec.id',
sort: 'spec.id'
},
{
name: 'provider',
labelKey: 'harvester.subnet.provider.label',
value: 'spec.provider',
sort: 'spec.provider'
}
]);
virtualType({
labelKey: 'harvester.vlanNetwork.label',
name: HCI.VLAN,
namespaced: false,
weight: 188,
route: {
name: `${ PRODUCT_NAME }-c-cluster-resource`,
params: { resource: HCI.VLAN }
},
exact: false,
ifHaveType: HCI.VLAN,
});
configureType(HCI.SNAPSHOT, {
isCreatable: false,
location: {
@@ -898,7 +1125,7 @@ export function init($plugin, store) {
virtualType({
label: 'PCI Devices',
group: 'advanced',
group: 'hardwareDevices',
weight: 14,
name: HCI.PCI_DEVICE,
namespaced: false,
@@ -934,7 +1161,7 @@ export function init($plugin, store) {
virtualType({
ifHaveType: HCI.SR_IOV,
labelKey: 'harvester.sriov.label',
group: 'advanced',
group: 'hardwareDevices',
weight: 15,
name: HCI.SR_IOV,
namespaced: false,
@@ -954,7 +1181,7 @@ export function init($plugin, store) {
virtualType({
ifHaveType: HCI.SR_IOVGPU_DEVICE,
labelKey: 'harvester.sriovgpu.label',
group: 'advanced',
group: 'hardwareDevices',
weight: 13,
name: HCI.SR_IOVGPU_DEVICE,
namespaced: false,
@@ -973,7 +1200,7 @@ export function init($plugin, store) {
virtualType({
labelKey: 'harvester.vgpu.label',
group: 'advanced',
group: 'hardwareDevices',
weight: 12,
name: HCI.VGPU_DEVICE,
namespaced: false,
@@ -1001,7 +1228,7 @@ export function init($plugin, store) {
virtualType({
labelKey: 'harvester.migconfiguration.label',
group: 'advanced',
group: 'hardwareDevices',
weight: 12,
name: HCI.MIG_CONFIGURATION,
namespaced: false,
@@ -1021,7 +1248,7 @@ export function init($plugin, store) {
virtualType({
labelKey: 'harvester.usb.label',
group: 'advanced',
group: 'hardwareDevices',
weight: 11,
name: HCI.USB_DEVICE,
namespaced: false,
@@ -1087,7 +1314,7 @@ export function init($plugin, store) {
labelKey: 'harvester.loadBalancer.label',
name: HCI.LB,
namespaced: true,
weight: 185,
weight: 483,
route: {
name: `${ PRODUCT_NAME }-c-cluster-resource`,
params: { resource: HCI.LB }
@@ -1126,7 +1353,7 @@ export function init($plugin, store) {
labelKey: 'harvester.ipPool.label',
name: HCI.IP_POOL,
namespaced: false,
weight: 184,
weight: 482,
route: {
name: `${ PRODUCT_NAME }-c-cluster-resource`,
params: { resource: HCI.IP_POOL }
@@ -1135,4 +1362,207 @@ export function init($plugin, store) {
ifHaveType: HCI.IP_POOL,
});
headers(HCI.IP_POOL, IP_POOL_HEADERS);
configureType(HCI.HOST_NETWORK_CONFIG, {
location: {
name: `${ PRODUCT_NAME }-c-cluster-resource`,
params: { resource: HCI.HOST_NETWORK_CONFIG }
},
canYaml: false,
});
virtualType({
labelKey: 'harvester.hostNetworkConfig.label',
name: HCI.HOST_NETWORK_CONFIG,
namespaced: false,
weight: 481,
route: {
name: `${ PRODUCT_NAME }-c-cluster-resource`,
params: { resource: HCI.HOST_NETWORK_CONFIG }
},
exact: false,
ifHaveType: HCI.HOST_NETWORK_CONFIG,
});
// ===========================================================================
// Forklift Addon UI Flow
// ===========================================================================
weightGroup('vmMigration', 0, false);
// Provider
headers(HCI.FORKLIFT_PROVIDER, [
STATE,
NAME_COL,
NAMESPACE_COL,
FORKLIFT_PROVIDER_TYPE,
FORKLIFT_PROVIDER_URL,
AGE
]);
configureType(HCI.FORKLIFT_PROVIDER, {
resource: HCI.FORKLIFT_PROVIDER,
location: {
name: `${ PRODUCT_NAME }-c-cluster-resource`,
params: { resource: HCI.FORKLIFT_PROVIDER }
}
});
virtualType({
name: HCI.FORKLIFT_PROVIDER,
labelKey: 'harvester.addons.vmMigration.labels.provider',
group: 'vmMigration',
namespaced: true,
weight: 100,
route: {
name: `${ PRODUCT_NAME }-c-cluster-resource`,
params: { resource: HCI.FORKLIFT_PROVIDER }
}
});
// NetworkMap
headers(HCI.FORKLIFT_NETWORK_MAP, [
STATE,
NAME_COL,
NAMESPACE_COL,
FORKLIFT_MAP_SOURCE_PROVIDER,
FORKLIFT_MAP_DEST_PROVIDER,
AGE
]);
configureType(HCI.FORKLIFT_NETWORK_MAP, {
resource: HCI.FORKLIFT_NETWORK_MAP,
location: {
name: `${ PRODUCT_NAME }-c-cluster-resource`,
params: { resource: HCI.FORKLIFT_NETWORK_MAP }
}
});
virtualType({
name: HCI.FORKLIFT_NETWORK_MAP,
labelKey: 'harvester.addons.vmMigration.labels.networkMap',
group: 'vmMigration::Configurations',
namespaced: true,
route: {
name: `${ PRODUCT_NAME }-c-cluster-resource`,
params: { resource: HCI.FORKLIFT_NETWORK_MAP }
}
});
// StorageMap
headers(HCI.FORKLIFT_STORAGE_MAP, [
STATE,
NAME_COL,
NAMESPACE_COL,
FORKLIFT_MAP_SOURCE_PROVIDER,
FORKLIFT_MAP_DEST_PROVIDER,
AGE
]);
configureType(HCI.FORKLIFT_STORAGE_MAP, {
resource: HCI.FORKLIFT_STORAGE_MAP,
location: {
name: `${ PRODUCT_NAME }-c-cluster-resource`,
params: { resource: HCI.FORKLIFT_STORAGE_MAP }
}
});
virtualType({
name: HCI.FORKLIFT_STORAGE_MAP,
labelKey: 'harvester.addons.vmMigration.labels.storageMap',
group: 'vmMigration::Configurations',
namespaced: true,
route: {
name: `${ PRODUCT_NAME }-c-cluster-resource`,
params: { resource: HCI.FORKLIFT_STORAGE_MAP }
}
});
// Plan
headers(HCI.FORKLIFT_PLAN, [
STATE,
NAME_COL,
NAMESPACE_COL,
FORKLIFT_MAP_SOURCE_PROVIDER,
FORKLIFT_PLAN_TARGET_NS,
FORKLIFT_PLAN_VM_COUNT,
AGE
]);
configureType(HCI.FORKLIFT_PLAN, {
resource: HCI.FORKLIFT_PLAN,
location: {
name: `${ PRODUCT_NAME }-c-cluster-resource`,
params: { resource: HCI.FORKLIFT_PLAN }
}
});
virtualType({
name: HCI.FORKLIFT_PLAN,
labelKey: 'harvester.addons.vmMigration.labels.plan',
group: 'vmMigration::Configurations',
namespaced: true,
route: {
name: `${ PRODUCT_NAME }-c-cluster-resource`,
params: { resource: HCI.FORKLIFT_PLAN }
}
});
// Migration
headers(HCI.FORKLIFT_MIGRATION, [
STATE,
NAME_COL,
NAMESPACE_COL,
FORKLIFT_MIGRATION_PLAN,
AGE
]);
configureType(HCI.FORKLIFT_MIGRATION, {
resource: HCI.FORKLIFT_MIGRATION,
location: {
name: `${ PRODUCT_NAME }-c-cluster-resource`,
params: { resource: HCI.FORKLIFT_MIGRATION }
}
});
virtualType({
name: HCI.FORKLIFT_MIGRATION,
labelKey: 'harvester.addons.vmMigration.labels.migration',
group: 'vmMigration::Configurations',
namespaced: true,
route: {
name: `${ PRODUCT_NAME }-c-cluster-resource`,
params: { resource: HCI.FORKLIFT_MIGRATION }
}
});
configureType('forklift-create', { subTypes: [HCI.FORKLIFT_PLAN] });
virtualType({
name: 'forklift-create',
labelKey: 'harvester.addons.vmMigration.labels.dashboard',
group: 'vmMigration',
namespaced: true,
weight: 200,
route: {
name: `${ PRODUCT_NAME }-c-cluster-vm-migration`,
params: {}
}
});
// Enable SideNav based on Forklift Addon Status
// The dashboard entry ('forklift-create') is a schema-less virtual type, so it
// is registered with requireSchema:false to still be gated by the addon status.
registerAddonSideNav(store, PRODUCT_NAME, {
addonName: ADD_ONS.FORKLIFT_OPERATOR,
resourceType: HCI.ADD_ONS,
navGroup: 'vmMigration',
requireSchema: false,
types: ['forklift-create']
});
registerAddonSideNav(store, PRODUCT_NAME, {
addonName: ADD_ONS.FORKLIFT_OPERATOR,
resourceType: HCI.ADD_ONS,
navGroup: 'vmMigration',
types: [
HCI.FORKLIFT_PROVIDER,
]
});
registerAddonSideNav(store, PRODUCT_NAME, {
addonName: ADD_ONS.FORKLIFT_OPERATOR,
resourceType: HCI.ADD_ONS,
navGroup: 'vmMigration::Configurations',
types: [
HCI.FORKLIFT_NETWORK_MAP,
HCI.FORKLIFT_STORAGE_MAP,
HCI.FORKLIFT_PLAN,
HCI.FORKLIFT_MIGRATION,
]
});
// ===========================================================================
}
+27
View File
@@ -39,6 +39,27 @@ export const VOLUME_TYPE = [{
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 = {
INSERT_CDROM_IMAGE: 'INSERT_CDROM_IMAGE',
EJECT_CDROM_IMAGE: 'EJECT_CDROM_IMAGE',
DETACH_DISK: 'DETACH_DISK'
};
export const ACCESS_CREDENTIALS = {
RESET_PWD: 'userPassword',
INJECT_SSH: 'sshPublicKey'
@@ -73,6 +94,7 @@ export const ADD_ONS = {
VM_IMPORT_CONTROLLER: 'vm-import-controller',
LVM_DRIVER: 'lvm.driver.harvesterhci.io',
KUBEOVN_OPERATOR: 'kubeovn-operator',
FORKLIFT_OPERATOR: 'forklift-operator',
};
export const CSI_SECRETS = {
@@ -82,8 +104,13 @@ export const CSI_SECRETS = {
CSI_NODE_PUBLISH_SECRET_NAMESPACE: 'csi.storage.k8s.io/node-publish-secret-namespace',
CSI_NODE_STAGE_SECRET_NAME: 'csi.storage.k8s.io/node-stage-secret-name',
CSI_NODE_STAGE_SECRET_NAMESPACE: 'csi.storage.k8s.io/node-stage-secret-namespace',
CSI_NODE_EXPAND_SECRET_NAME: 'csi.storage.k8s.io/node-expand-secret-name',
CSI_NODE_EXPAND_SECRET_NAMESPACE: 'csi.storage.k8s.io/node-expand-secret-namespace'
};
export const FORKLIFT_API_VERSION = 'forklift.konveyor.io/v1beta1';
export const FORKLIFT_NAMESPACE = 'forklift';
// Some harvester CRD type is not equal to model file name, define the mapping here
export const HARVESTER_CRD_MAP = {
node: HCI.HOST,
+14 -1
View File
@@ -16,11 +16,13 @@ export const HCI = {
CREATOR: 'harvesterhci.io/creator',
OS: 'harvesterhci.io/os',
GOLDEN_IMAGE: 'harvesterhci.io/goldenImage',
CLUSTER_NETWORK: 'network.harvesterhci.io/clusternetwork',
NETWORK_TYPE: 'network.harvesterhci.io/type',
VM_NAME: 'harvesterhci.io/vmName',
VM_NAME_PREFIX: 'harvesterhci.io/vmNamePrefix',
VM_DISPLAY_NAME: 'harvesterhci.io/vmDisplayName',
VM_RESERVED_MEMORY: 'harvesterhci.io/reservedMemory',
MAINTENANCE_STATUS: 'harvesterhci.io/maintain-status',
MAINTENANCE_STATUS: 'harvesterhci.io/maintain-status', // Deprecated >= v1.10.0
HOST_CUSTOM_NAME: 'harvesterhci.io/host-custom-name',
HOST_CONSOLE_URL: 'harvesterhci.io/host-console-url',
RESTORE_NAME: 'restore.harvesterhci.io/name',
@@ -28,8 +30,14 @@ export const HCI = {
NODE_ROLE_CONTROL_PLANE: 'node-role.kubernetes.io/control-plane',
NODE_ROLE_ETCD: 'node-role.harvesterhci.io/witness',
PROMOTE_STATUS: 'harvesterhci.io/promote-status',
CLONE_BACKEND_STORAGE_STATUS: 'harvesterhci.io/clone-backend-storage-status',
MIGRATION_STATE: 'harvesterhci.io/migrationState',
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',
INIT_IP: 'etcd.rke2.cattle.io/node-address',
NODE_SCHEDULABLE: 'kubevirt.io/schedulable',
@@ -78,5 +86,10 @@ export const HCI = {
VOLUME_MODE_ACCESS_MODES: 'cdi.harvesterhci.io/storageProfileVolumeModeAccessModes',
VOLUME_SNAPSHOT_CLASS: 'cdi.harvesterhci.io/storageProfileVolumeSnapshotClass',
MAC_ADDRESS: 'harvesterhci.io/mac-address',
STATIC_IP: 'static-ip.harvesterhci.io',
NODE_UPGRADE_PAUSE_MAP: 'harvesterhci.io/node-upgrade-pause-map',
CDI_POPULATOR_KIND: 'cdi.kubevirt.io/storage.populator.kind',
CNI_NETWORKS: 'k8s.v1.cni.cncf.io/networks',
WINDOWS_SYSPREP: 'harvesterhci.io/windows-sysprep',
SKIP_MIG_CONFIGURATION: 'harvesterhci.io/skip-mig-configuration',
};

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