mirror of
https://github.com/harvester/harvester-ui-extension.git
synced 2026-11-16 13:56:08 +08:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
270977f884 |
@@ -1,12 +0,0 @@
|
||||
name: Run Unit Tests
|
||||
description: Run Unit Tests
|
||||
|
||||
runs:
|
||||
using: 'composite'
|
||||
steps:
|
||||
- name: Setup env
|
||||
uses: ./.github/actions/setup
|
||||
|
||||
- name: Run unit tests
|
||||
shell: bash
|
||||
run: yarn test:ci
|
||||
@@ -125,13 +125,6 @@ jobs:
|
||||
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
|
||||
|
||||
@@ -58,12 +58,6 @@ jobs:
|
||||
- name: Setup Nodejs with yarn install
|
||||
uses: ./.github/actions/setup
|
||||
|
||||
# The catalog image is tagged with the package.json version. Sprint tags
|
||||
# (vX.Y.Z-dev-YYYYMMDD) only share its prefix, so pin it to the tag here.
|
||||
- name: Pin package version to tag
|
||||
if: ${{ github.ref_type == 'tag' }}
|
||||
run: ./scripts/bump_version.sh "${{ github.ref_name }}"
|
||||
|
||||
- name: Build and push UI image
|
||||
run: |
|
||||
publish="yarn publish-pkgs -cp -r ${{ inputs.registry_target }} -o ${{ inputs.registry_user }}"
|
||||
|
||||
@@ -71,11 +71,3 @@ 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
|
||||
|
||||
@@ -59,8 +59,6 @@ You are an expert Senior Software Engineer specializing in Vue.js and TypeScript
|
||||
| `yarn serve-pkgs` | Serve the locally built extension for testing |
|
||||
| `yarn 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 |
|
||||
|
||||
@@ -97,16 +95,6 @@ You are an expert Senior Software Engineer specializing in Vue.js and TypeScript
|
||||
- ESLint covers `.js`, `.ts`, and `.vue` files.
|
||||
- Always run `yarn lint:fix` before committing.
|
||||
|
||||
### Unit Tests
|
||||
|
||||
- **Run**:
|
||||
```bash
|
||||
yarn test
|
||||
```
|
||||
- `yarn test` starts Jest in watch mode (like in the Rancher dashboard) and only runs the tests related to changed files. It does not exit, so use `yarn test:ci` for a single run of all tests, e.g. in scripts.
|
||||
- CI runs `yarn test:ci` on every pull request.
|
||||
- See the Unit Tests section of the Contributors Guide for how the tests are set up.
|
||||
|
||||
### Commit Conventions
|
||||
|
||||
- Commits are validated by [commitlint](https://commitlint.js.org/) via a Husky `commit-msg` hook.
|
||||
@@ -199,19 +187,6 @@ To add a feature in a new release, follow these steps:
|
||||
|
||||
See https://github.com/harvester/harvester-ui-tests
|
||||
|
||||
## Unit Tests (Jest)
|
||||
|
||||
Unit and component tests run with [Jest](https://jestjs.io/). The setup follows the Rancher dashboard and the Rancher extension template ([rancher/ui-plugin-examples](https://github.com/rancher/ui-plugin-examples)), so both stay aligned.
|
||||
|
||||
- Run the tests in watch mode with `yarn test`, all tests once with `yarn test:ci`, a single file with `yarn test <path>`. CI runs `yarn test:ci` on every pull request.
|
||||
- Test files live next to the code in `__tests__` folders and are named `<name>.test.js` or `<name>.test.ts`.
|
||||
- Configuration:
|
||||
- `jest.config.js`: environment, module aliases (`@shell`, `@components`, `@pkg`) and transforms.
|
||||
- `jest.setup.js`: global mocks (`t`, `$store`, common directives) and browser APIs that jsdom does not provide.
|
||||
- `vue3JestRegisterTs.js`: makes TypeScript available to the Vue compiler, otherwise `.vue` files with typed props fail to compile.
|
||||
- Components are tested with the Vue Test Utils 2 API: use `props` and `global.mocks`, not the Vue 2 options `propsData` and `mocks`.
|
||||
- Models and utils can be tested without mounting anything, see `pkg/harvester/models/__tests__` for examples.
|
||||
|
||||
## Node Dependencies
|
||||
|
||||
Dependencies are managed via `package.json` and `yarn`
|
||||
|
||||
@@ -15,8 +15,6 @@
|
||||
| `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 |
|
||||
|
||||
@@ -53,16 +51,6 @@
|
||||
- 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.
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
## Unit Tests (Jest)
|
||||
|
||||
Unit and component tests run with [Jest](https://jestjs.io/). The setup follows the Rancher dashboard and the Rancher extension template ([rancher/ui-plugin-examples](https://github.com/rancher/ui-plugin-examples)), so both stay aligned.
|
||||
|
||||
- Run the tests in watch mode with `yarn test`, all tests once with `yarn test:ci`, a single file with `yarn test <path>`. CI runs `yarn test:ci` on every pull request.
|
||||
- Test files live next to the code in `__tests__` folders and are named `<name>.test.js` or `<name>.test.ts`.
|
||||
- Configuration:
|
||||
- `jest.config.js`: environment, module aliases (`@shell`, `@components`, `@pkg`) and transforms.
|
||||
- `jest.setup.js`: global mocks (`t`, `$store`, common directives) and browser APIs that jsdom does not provide.
|
||||
- `vue3JestRegisterTs.js`: makes TypeScript available to the Vue compiler, otherwise `.vue` files with typed props fail to compile.
|
||||
- Components are tested with the Vue Test Utils 2 API: use `props` and `global.mocks`, not the Vue 2 options `propsData` and `mocks`.
|
||||
- Models and utils can be tested without mounting anything, see `pkg/harvester/models/__tests__` for examples.
|
||||
@@ -1,46 +0,0 @@
|
||||
// Same settings in every environment, otherwise tests that format dates depend on the machine
|
||||
process.env.TZ = 'UTC';
|
||||
|
||||
// The setup follows the one of the Rancher dashboard and of the Rancher extension template (rancher/ui-plugin-examples)
|
||||
module.exports = {
|
||||
roots: ['<rootDir>/pkg'],
|
||||
testEnvironment: 'jsdom',
|
||||
// Jest 28+ (jest-environment-jsdom) defaults package resolution to the "browser" export condition, which makes
|
||||
// packages like @vue/test-utils resolve their browser (global-Vue) build and throw "Vue is not defined".
|
||||
testEnvironmentOptions: { customExportConditions: ['node', 'node-addons'] },
|
||||
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
|
||||
watchman: false,
|
||||
moduleFileExtensions: ['js', 'mjs', 'json', 'vue', 'ts'],
|
||||
modulePaths: ['<rootDir>'],
|
||||
moduleNameMapper: {
|
||||
'^~/(.*)$': '<rootDir>/$1',
|
||||
'^@/(.*)$': '<rootDir>/$1',
|
||||
'^@shell/(.*)$': '<rootDir>/node_modules/@rancher/shell/$1',
|
||||
'^@components/(.*)$': '<rootDir>/node_modules/@rancher/shell/rancher-components/$1',
|
||||
// At build time @pkg/<path> is resolved to the package that imports it (see vue.config.js of @rancher/shell)
|
||||
'^@pkg/harvester/(.*)$': '<rootDir>/pkg/harvester/$1',
|
||||
'^@pkg/(.*)$': '<rootDir>/pkg/harvester/$1',
|
||||
// clipboard-polyfill's package `exports` only declares an `import` condition, so map it to its ESM build
|
||||
// (transpiled via transformIgnorePatterns below)
|
||||
'^clipboard-polyfill$': '<rootDir>/node_modules/clipboard-polyfill/dist/es6/clipboard-polyfill.es6.js',
|
||||
'\\.(jpe?g|png|gif|webp|svg|mp4|webm|ogg|mp3|wav|flac|aac|woff2?|eot|ttf|otf)$': '<rootDir>/svgTransform.js',
|
||||
},
|
||||
modulePathIgnorePatterns: ['<rootDir>/pkg/harvester/node_modules'],
|
||||
testPathIgnorePatterns: ['<rootDir>/node_modules/', '<rootDir>(/.*)*/__tests__/utils/'],
|
||||
transform: {
|
||||
// vue3-jest, but with TypeScript registered for the Vue compiler first, see vue3JestRegisterTs.js
|
||||
'^.+\\.vue$': '<rootDir>/vue3JestRegisterTs.js',
|
||||
// isolatedModules: transpile only, the types are not checked while testing
|
||||
'^.+\\.tsx?$': ['ts-jest', { tsconfig: { sourceMap: true, isolatedModules: true } }],
|
||||
// Use the project babel config (babel.config.js, which extends the one of @rancher/shell)
|
||||
'^.+\\.js$': '<rootDir>/node_modules/babel-jest',
|
||||
// process mjs (e.g. vee-validate ESM) with babel-jest
|
||||
'^.+\\.mjs$': '<rootDir>/node_modules/babel-jest',
|
||||
'^.+\\.svg$': '<rootDir>/svgTransform.js',
|
||||
},
|
||||
transformIgnorePatterns: [
|
||||
// @rancher/shell is shipped untranspiled, the other packages are ESM-only. @replit/codemirror-vim-core is
|
||||
// required by the CommonJS build of @replit/codemirror-vim, which the shell's YamlEditor imports
|
||||
'/node_modules/(?!(@rancher/shell|color|color-string|color-convert|color-name|vee-validate|@vee-validate|clipboard-polyfill|intl-messageformat|@formatjs|@replit/codemirror-vim-core)/)',
|
||||
],
|
||||
};
|
||||
-106
@@ -1,106 +0,0 @@
|
||||
/* eslint-env jest */
|
||||
import { createApp } from 'vue';
|
||||
import { config } from '@vue/test-utils';
|
||||
import i18n from '@shell/plugins/i18n';
|
||||
import FloatingVue from 'floating-vue';
|
||||
import { floatingVueOptions } from '@shell/plugins/floating-vue';
|
||||
import vSelect from 'vue-select';
|
||||
import cleanTooltipDirective from '@shell/directives/clean-tooltip';
|
||||
import cleanHtmlDirective from '@shell/directives/clean-html';
|
||||
import htmlStrippedAriaLabelDirective from '@shell/directives/strip-html-aria-label';
|
||||
import '@shell/plugins/replaceall';
|
||||
import { TextEncoder, TextDecoder } from 'util';
|
||||
|
||||
const vueApp = createApp({});
|
||||
|
||||
global.TextEncoder = TextEncoder;
|
||||
global.TextDecoder = TextDecoder;
|
||||
|
||||
// vueApp.config.productionTip = false;
|
||||
vueApp.use(i18n, { store: { dispatch() {} } });
|
||||
vueApp.use(FloatingVue, floatingVueOptions);
|
||||
vueApp.directive('clean-html', cleanHtmlDirective);
|
||||
vueApp.directive('clean-tooltip', cleanTooltipDirective);
|
||||
vueApp.component('v-select', vSelect);
|
||||
|
||||
config.global.components['v-select'] = vSelect;
|
||||
config.global.plugins = [FloatingVue];
|
||||
config.global.mocks['t'] = (key) => `%${ key }%`;
|
||||
config.global.mocks['$store'] = {
|
||||
getters: {},
|
||||
dispatch: jest.fn(),
|
||||
commit: jest.fn(),
|
||||
};
|
||||
|
||||
config.global.directives = {
|
||||
...config.global.directives,
|
||||
t: {
|
||||
mounted(el, binding) {
|
||||
el.textContent = `%${ binding.value }%`;
|
||||
},
|
||||
updated(el, binding) {
|
||||
el.textContent = `%${ binding.value }%`;
|
||||
}
|
||||
},
|
||||
'clean-tooltip': cleanTooltipDirective,
|
||||
'clean-html': cleanHtmlDirective,
|
||||
'stripped-aria-label': htmlStrippedAriaLabelDirective,
|
||||
};
|
||||
|
||||
config.global.stubs['t'] = { template: '<span><slot /></span>' };
|
||||
|
||||
/**
|
||||
* Global configuration for Jest tests
|
||||
*/
|
||||
beforeAll(() => {
|
||||
// matchMedia and getContext methods aren't included in jest's version of jsdom for us to mock
|
||||
// implemented as per jest documentation: https://jestjs.io/docs/manual-mocks#mocking-methods-which-are-not-implemented-in-jsdom
|
||||
Object.defineProperty(window, 'matchMedia', {
|
||||
value: jest.fn().mockImplementation(() => ({
|
||||
addListener: jest.fn(),
|
||||
removeListener: jest.fn(),
|
||||
addEventListener: jest.fn(),
|
||||
removeEventListener: jest.fn()
|
||||
}))
|
||||
});
|
||||
Object.defineProperty(HTMLCanvasElement.prototype, 'getContext', {
|
||||
value: jest.fn().mockImplementation(() => ({
|
||||
createLinearGradient: jest.fn(),
|
||||
fillRect: jest.fn(),
|
||||
getImageData: jest.fn(() => ({ data: [] }))
|
||||
}))
|
||||
});
|
||||
Object.defineProperty(window, 'IntersectionObserver', {
|
||||
writable: true,
|
||||
value: jest.fn().mockImplementation(() => ({
|
||||
observe: jest.fn(),
|
||||
unobserve: jest.fn(),
|
||||
disconnect: jest.fn(),
|
||||
})),
|
||||
});
|
||||
});
|
||||
jest.mock('@shell/composables/useI18n', () => {
|
||||
return {
|
||||
useI18n() {
|
||||
return { t: (key, options) => `${ key }${ options ? `-${ JSON.stringify(options) }` : '' }` };
|
||||
}
|
||||
};
|
||||
});
|
||||
// eslint-disable-next-line no-console
|
||||
jest.spyOn(console, 'warn').mockImplementation((warning) => warning.includes('[Vue warn]') ? null : console.log(warning));
|
||||
|
||||
/**
|
||||
* Common initialization for each test, required for resetting states
|
||||
*/
|
||||
beforeEach(() => {
|
||||
// jest.resetModules(); // Use this function inside your test if you need to remove any cache stored
|
||||
// jest.clearAllMocks(); // Use this function inside your test if you need to reset mocks
|
||||
jest.restoreAllMocks(); // Use this function inside your test if you need to reset mocks and restore existing functionality
|
||||
|
||||
// Mock the $extension object
|
||||
// config.mocks['$extension'] = { getDynamic: () => undefined };
|
||||
|
||||
config.global.mocks['$store'] = { getters: { 'i18n/t': jest.fn() } };
|
||||
// Overrides some components
|
||||
// config.stubs['my-component'] = { template: "<div></div> "};
|
||||
});
|
||||
+6
-28
@@ -7,8 +7,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@babel/plugin-transform-class-static-block": "7.29.7",
|
||||
"@novnc/novnc": "1.7.0",
|
||||
"@rancher/shell": "3.0.14",
|
||||
"@rancher/shell": "3.0.13",
|
||||
"@vue-flow/background": "^1.3.0",
|
||||
"@vue-flow/controls": "^1.1.1",
|
||||
"@vue-flow/core": "^1.33.5",
|
||||
@@ -28,32 +27,21 @@
|
||||
"yaml": "^2.5.1"
|
||||
},
|
||||
"resolutions": {
|
||||
"@novnc/novnc": "1.7.0",
|
||||
"@tootallnate/once": "^2.0.1",
|
||||
"@types/lodash": "4.17.27",
|
||||
"@types/node": "25.3.3",
|
||||
"cookie": "0.7.2",
|
||||
"@types/node": "25.9.5",
|
||||
"cronstrue": "2.59.0",
|
||||
"d3-color": "3.1.1",
|
||||
"**/diff2html/diff": "5.2.2",
|
||||
"d3-color": "3.1.0",
|
||||
"ejs": "3.1.10",
|
||||
"follow-redirects": "1.16.0",
|
||||
"glob": "7.2.3",
|
||||
"glob-parent": "6.0.2",
|
||||
"json5": "2.2.3",
|
||||
"markdown-it": "14.3.1",
|
||||
"@types/lodash": "4.17.25",
|
||||
"merge": "2.1.1",
|
||||
"node-forge": "1.4.0",
|
||||
"nth-check": "2.1.1",
|
||||
"postcss": "8.5.32",
|
||||
"postcss-selector-parser": "7.1.8",
|
||||
"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.7",
|
||||
"ws": "8.21.0",
|
||||
"semver": "7.8.5",
|
||||
"@vue/cli-service/html-webpack-plugin": "^5.0.0"
|
||||
},
|
||||
"scripts": {
|
||||
@@ -62,8 +50,6 @@
|
||||
"clean": "./node_modules/@rancher/shell/scripts/clean",
|
||||
"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",
|
||||
@@ -80,14 +66,6 @@
|
||||
"@commitlint/config-conventional": "^19.8.1",
|
||||
"eslint-plugin-node": "^11.1.0",
|
||||
"eslint-plugin-promise": "^7.1.0",
|
||||
"husky": "^9.1.7",
|
||||
"@types/jest": "29.5.14",
|
||||
"@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.15"
|
||||
"husky": "^9.1.7"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -128,7 +128,6 @@ export default {
|
||||
|
||||
try {
|
||||
await proxyResource.save();
|
||||
proxyResource.notifyGeneratedName?.();
|
||||
|
||||
this.cancel();
|
||||
} catch (err) {
|
||||
|
||||
@@ -10,7 +10,6 @@ import { docLink } from '../utils/feature-flags';
|
||||
const CATEGORY = {
|
||||
ui: [
|
||||
'branding',
|
||||
HCI_SETTING.SERVER_FLAVOR,
|
||||
'ui-source',
|
||||
'ui-index',
|
||||
]
|
||||
@@ -141,6 +140,10 @@ 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') {
|
||||
@@ -151,6 +154,10 @@ 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);
|
||||
},
|
||||
|
||||
@@ -1,336 +0,0 @@
|
||||
<script setup>
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useStore } from 'vuex';
|
||||
import SortableTable from '@shell/components/SortableTable';
|
||||
import { BadgeState } from '@components/BadgeState';
|
||||
import { RcCounterBadge, RcTag } from '@components/Pill';
|
||||
import { RcButton } from '@components/RcButton';
|
||||
import { useI18n } from '@shell/composables/useI18n';
|
||||
import { _CREATE, _EDIT, _VIEW } from '@shell/config/query-params';
|
||||
import { HCI } from '../../types';
|
||||
import {
|
||||
AFFECTED_RESOURCES_TRUNCATE_COUNT, MESSAGE_TRUNCATE_LENGTH, activeAffectedResourceNames, affectedResourceLabel,
|
||||
allAffectedResourceNames, 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>
|
||||
@@ -1,342 +0,0 @@
|
||||
<script setup>
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
import { HCI } from '../../types';
|
||||
import { useStore } from 'vuex';
|
||||
import { useI18n } from '@shell/composables/useI18n';
|
||||
import SortableTable from '@shell/components/SortableTable';
|
||||
import { exceptionToErrorsArray } from '@shell/utils/error';
|
||||
import Banner from '@components/Banner/Banner.vue';
|
||||
import { BadgeState } from '@components/BadgeState';
|
||||
import { Checkbox } from '@components/Form/Checkbox';
|
||||
import { 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>
|
||||
@@ -1,320 +0,0 @@
|
||||
<script setup>
|
||||
import { computed, ref } from 'vue';
|
||||
import { useStore } from 'vuex';
|
||||
import dayjs from 'dayjs';
|
||||
import isEqual from 'lodash/isEqual';
|
||||
import Banner from '@components/Banner/Banner.vue';
|
||||
import { LabeledInput } from '@components/Form/LabeledInput';
|
||||
import { RadioGroup } from '@components/Form/Radio';
|
||||
import { RcButton } from '@components/RcButton';
|
||||
import { RcHeading } from '@components/RcHeading';
|
||||
import { RcModal } from '@components/RcModal';
|
||||
import LabelValue from '@shell/components/LabelValue';
|
||||
import LabeledSelect from '@shell/components/form/LabeledSelect';
|
||||
import { useI18n } from '@shell/composables/useI18n';
|
||||
import { _CREATE, _VIEW } from '@shell/config/query-params';
|
||||
import { exceptionToErrorsArray } from '@shell/utils/error';
|
||||
import { dateTimeFormat } from '@shell/utils/time';
|
||||
import { HCI } from '../../types';
|
||||
import { IGNORE_DURATION_DAYS, IGNORE_RULE_SOURCE_LABEL, allAffectedResourceNames, ignoreRuleName } from '../../utils/component-health';
|
||||
|
||||
const props = defineProps({
|
||||
row: {
|
||||
type: Object,
|
||||
required: true,
|
||||
},
|
||||
// empty when the rule is created
|
||||
rule: {
|
||||
type: Object,
|
||||
default: null,
|
||||
},
|
||||
mode: {
|
||||
type: String,
|
||||
default: _CREATE,
|
||||
},
|
||||
// `show` and the `close` handler, from whoever owns this modal's visibility
|
||||
modal: {
|
||||
type: Object,
|
||||
required: true,
|
||||
},
|
||||
});
|
||||
|
||||
const store = useStore();
|
||||
const { t } = useI18n(store);
|
||||
|
||||
const isView = computed(() => props.mode === _VIEW);
|
||||
|
||||
const ruleResources = props.rule?.spec?.resources || [];
|
||||
const expiresAt = props.rule?.spec?.expiresAt;
|
||||
const hasExpired = !!expiresAt && !dayjs(expiresAt).isAfter(dayjs());
|
||||
|
||||
// a rule can still list resources that are no longer affected
|
||||
const resourceOptions = computed(() => [...new Set([...allAffectedResourceNames(props.row), ...ruleResources])]);
|
||||
|
||||
// a rule that lists no resource ignores the entire check
|
||||
const chosenScope = ref(props.rule && !ruleResources.length ? 'check' : null);
|
||||
const scope = computed({
|
||||
get: () => chosenScope.value || (resourceOptions.value.length ? 'resources' : 'check'),
|
||||
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>
|
||||
@@ -1,912 +0,0 @@
|
||||
import { mount as vtuMount, flushPromises } from '@vue/test-utils';
|
||||
import { createStore } from 'vuex';
|
||||
import Banner from '@components/Banner/Banner.vue';
|
||||
import { BadgeState } from '@components/BadgeState';
|
||||
import { Checkbox } from '@components/Form/Checkbox';
|
||||
import { LabeledInput } from '@components/Form/LabeledInput';
|
||||
import { RadioGroup } from '@components/Form/Radio';
|
||||
import { RcCounterBadge, RcTag } from '@components/Pill';
|
||||
import { RcModal } from '@components/RcModal';
|
||||
import LabeledSelect from '@shell/components/form/LabeledSelect';
|
||||
import { HCI } from '../../../types';
|
||||
import { affectedResourceLabel, 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();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,224 +0,0 @@
|
||||
<script>
|
||||
import { RcButton } from '@components/RcButton';
|
||||
import { RcDropdown, RcDropdownItem, RcDropdownSeparator, RcDropdownTrigger } from '@components/RcDropdown';
|
||||
import { RcIcon } from '@components/RcIcon';
|
||||
import RcStatusIndicator from '@components/Pill/RcStatusIndicator';
|
||||
import { CONSOLE_STATUS } from './NovncConsole';
|
||||
|
||||
export const CONNECTION_STATE = {
|
||||
CONNECTING: 'connecting',
|
||||
CONNECTED: 'connected',
|
||||
DISCONNECTED: 'disconnected',
|
||||
NOT_RUNNING: 'notRunning',
|
||||
};
|
||||
|
||||
export default {
|
||||
name: 'NovncConnectionStatus',
|
||||
|
||||
components: {
|
||||
RcButton, RcDropdown, RcDropdownItem, RcDropdownSeparator, RcDropdownTrigger, RcIcon, RcStatusIndicator
|
||||
},
|
||||
|
||||
props: {
|
||||
status: {
|
||||
type: String,
|
||||
default: CONSOLE_STATUS.CONNECTING,
|
||||
},
|
||||
|
||||
label: {
|
||||
type: String,
|
||||
default: '',
|
||||
},
|
||||
|
||||
vmName: {
|
||||
type: String,
|
||||
default: '',
|
||||
},
|
||||
},
|
||||
|
||||
emits: ['reconnect'],
|
||||
|
||||
computed: {
|
||||
// The console reports five states; the toolbar only tells the user whether they can type.
|
||||
state() {
|
||||
if (this.status === CONNECTION_STATE.NOT_RUNNING) {
|
||||
return CONNECTION_STATE.NOT_RUNNING;
|
||||
}
|
||||
|
||||
if (this.status === CONSOLE_STATUS.CONNECTED) {
|
||||
return CONNECTION_STATE.CONNECTED;
|
||||
}
|
||||
|
||||
if (this.status === CONSOLE_STATUS.DISCONNECTED || this.status === CONSOLE_STATUS.FAILED) {
|
||||
return CONNECTION_STATE.DISCONNECTED;
|
||||
}
|
||||
|
||||
return CONNECTION_STATE.CONNECTING;
|
||||
},
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="connection-status">
|
||||
<!-- Only the label is announced, not the menu that opens next to it. -->
|
||||
<span
|
||||
class="sr-only"
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
>{{ label }}</span>
|
||||
|
||||
<rc-dropdown
|
||||
v-if="state === 'connected'"
|
||||
:aria-label="t('harvester.virtualMachine.detail.console.connection.menuLabel')"
|
||||
placement="bottom-start"
|
||||
>
|
||||
<rc-dropdown-trigger
|
||||
variant="ghost"
|
||||
size="small"
|
||||
class="connection-status__pill"
|
||||
data-testid="vnc-connection-status"
|
||||
>
|
||||
<template #before>
|
||||
<rc-status-indicator
|
||||
shape="disc"
|
||||
status="success"
|
||||
/>
|
||||
</template>
|
||||
{{ label }}
|
||||
<template #after>
|
||||
<rc-icon
|
||||
type="chevron-down"
|
||||
size="inherit"
|
||||
/>
|
||||
</template>
|
||||
</rc-dropdown-trigger>
|
||||
|
||||
<template #dropdownCollection>
|
||||
<p class="connection-status__description">
|
||||
{{ t('harvester.virtualMachine.detail.console.connection.description', { name: vmName }) }}
|
||||
</p>
|
||||
<rc-dropdown-separator />
|
||||
<rc-dropdown-item
|
||||
data-testid="vnc-connection-reconnect"
|
||||
@click="$emit('reconnect')"
|
||||
>
|
||||
<template #before>
|
||||
<rc-icon
|
||||
type="refresh"
|
||||
size="inherit"
|
||||
/>
|
||||
</template>
|
||||
{{ t('harvester.action.reconnect') }}
|
||||
</rc-dropdown-item>
|
||||
</template>
|
||||
</rc-dropdown>
|
||||
|
||||
<span
|
||||
v-else-if="state === 'notRunning'"
|
||||
class="connection-status__pill"
|
||||
data-testid="vnc-connection-status"
|
||||
>
|
||||
<rc-status-indicator
|
||||
shape="disc"
|
||||
status="unknown"
|
||||
/>
|
||||
{{ label }}
|
||||
</span>
|
||||
|
||||
<span
|
||||
v-else-if="state === 'connecting'"
|
||||
class="connection-status__pill"
|
||||
data-testid="vnc-connection-status"
|
||||
>
|
||||
<rc-icon
|
||||
type="spinner"
|
||||
size="inherit"
|
||||
class="icon-spin"
|
||||
/>
|
||||
{{ label }}
|
||||
</span>
|
||||
|
||||
<span
|
||||
v-else
|
||||
class="connection-status__pill connection-status__pill--disconnected"
|
||||
data-testid="vnc-connection-status"
|
||||
>
|
||||
<rc-status-indicator
|
||||
shape="disc"
|
||||
status="error"
|
||||
/>
|
||||
{{ label }}
|
||||
<span
|
||||
class="connection-status__divider"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<rc-button
|
||||
variant="ghost"
|
||||
size="small"
|
||||
class="connection-status__reconnect"
|
||||
data-testid="vnc-connection-reconnect"
|
||||
@click="$emit('reconnect')"
|
||||
>
|
||||
<template #before>
|
||||
<rc-icon
|
||||
type="refresh"
|
||||
size="inherit"
|
||||
/>
|
||||
</template>
|
||||
{{ t('harvester.action.reconnect') }}
|
||||
</rc-button>
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.connection-status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
// Shared by the dropdown trigger and the plain pills, so every state has the same shape.
|
||||
&__pill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
height: 32px;
|
||||
padding: 0 10px 0 12px;
|
||||
// The connected pill is an RcButton, which takes its padding from this property.
|
||||
--rc-button-padding: 0 10px 0 12px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 16px;
|
||||
color: var(--body-text);
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
white-space: nowrap;
|
||||
|
||||
&--disconnected {
|
||||
border-color: var(--error);
|
||||
}
|
||||
}
|
||||
|
||||
&__divider {
|
||||
width: 1px;
|
||||
height: 16px;
|
||||
background: var(--error);
|
||||
}
|
||||
|
||||
// An RcButton keeps to its own small height, so its focus ring stays inside the pill.
|
||||
&__reconnect {
|
||||
--rc-button-padding: 0;
|
||||
color: var(--error);
|
||||
}
|
||||
|
||||
&__description {
|
||||
max-width: 248px;
|
||||
margin: 0;
|
||||
padding: 4px 17px 8px;
|
||||
color: var(--body-text);
|
||||
font-size: 12px;
|
||||
font-weight: 400;
|
||||
line-height: 18px;
|
||||
white-space: normal;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,606 +1,153 @@
|
||||
<template>
|
||||
<div>
|
||||
<div v-if="connected && disconnected">
|
||||
<main class="main-layout error">
|
||||
<div class="text-center">
|
||||
<BrandImage
|
||||
file-name="error-desert-landscape.svg"
|
||||
width="900"
|
||||
height="300"
|
||||
/>
|
||||
<h1>
|
||||
{{ t('generic.notification.title.warning') }}
|
||||
</h1>
|
||||
<h2 class="text-secondary mt-20">
|
||||
{{ t('vncConsole.error.message') }}
|
||||
</h2>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
<div v-if="reconnecting">
|
||||
<main class="main-layout">
|
||||
<div class="text-center">
|
||||
<h2 class="text-secondary mt-20">
|
||||
{{ t('vncConsole.reconnecting.message') }}:{{ retryTimes }} of {{ maximumRetryTimes }}
|
||||
</h2>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
<div
|
||||
ref="view"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
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);
|
||||
};
|
||||
import RFB from '@novnc/novnc/core/rfb';
|
||||
import BrandImage from '@shell/components/BrandImage';
|
||||
|
||||
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
|
||||
},
|
||||
}
|
||||
},
|
||||
|
||||
emits: ['status-changed', 'capabilities'],
|
||||
components: { BrandImage },
|
||||
|
||||
data() {
|
||||
return {
|
||||
rfb: null,
|
||||
status: CONSOLE_STATUS.CONNECTING,
|
||||
statusDetail: '',
|
||||
desktopName: '',
|
||||
connected: false,
|
||||
disconnected: false,
|
||||
reconnectDelay: 3000,
|
||||
reconnecting: false,
|
||||
maximumRetryTimes: 10,
|
||||
retryTimes: 0,
|
||||
maximumRetryTimes: MAXIMUM_RETRY_TIMES,
|
||||
reconnectTimer: null,
|
||||
isClosed: false,
|
||||
failure: '',
|
||||
showTakeOverModal: false,
|
||||
focused: false,
|
||||
setTimeout: null,
|
||||
};
|
||||
},
|
||||
|
||||
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.$refs.view?.removeEventListener('focusin', this.onFocusIn);
|
||||
this.$refs.view?.removeEventListener('focusout', this.onFocusOut);
|
||||
this.isClosed = true;
|
||||
this.clearReconnectTimer();
|
||||
this.teardown();
|
||||
this.clearTimeout();
|
||||
},
|
||||
|
||||
methods: {
|
||||
connect(takeOver = false) {
|
||||
if (!this.url || this.isClosed) {
|
||||
return;
|
||||
}
|
||||
connect() {
|
||||
const rfb = new RFB(this.$refs.view, this.url);
|
||||
|
||||
this.teardown();
|
||||
rfb.addEventListener('connect', () => {
|
||||
this.clearTimeout();
|
||||
|
||||
this.failure = '';
|
||||
this.status = this.retryTimes > 0 ? CONSOLE_STATUS.RECONNECTING : CONSOLE_STATUS.CONNECTING;
|
||||
this.connected = true;
|
||||
this.retryTimes = 0;
|
||||
this.reconnecting = false;
|
||||
});
|
||||
|
||||
let rfb;
|
||||
rfb.addEventListener('disconnect', (e) => {
|
||||
this.clearTimeout();
|
||||
|
||||
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.disconnected = true;
|
||||
this.rfb = null;
|
||||
this.reconnect();
|
||||
});
|
||||
|
||||
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.fail(this.vmRunning ? CONSOLE_FAILURE.IN_USE : CONSOLE_FAILURE.UNAVAILABLE);
|
||||
this.reconnecting = false;
|
||||
this.connected = true;
|
||||
this.disconnected = true;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
this.retryTimes += 1;
|
||||
this.status = CONSOLE_STATUS.RECONNECTING;
|
||||
this.reconnecting = true;
|
||||
this.connected = false;
|
||||
this.disconnected = false;
|
||||
|
||||
const delay = Math.min(BASE_RECONNECT_DELAY * (2 ** (this.retryTimes - 1)), MAXIMUM_RECONNECT_DELAY);
|
||||
|
||||
this.reconnectTimer = setTimeout(() => {
|
||||
this.reconnectTimer = null;
|
||||
this.setTimeout = setTimeout(() => {
|
||||
this.connect();
|
||||
}, delay);
|
||||
}, this.reconnectDelay);
|
||||
},
|
||||
|
||||
clearReconnectTimer() {
|
||||
if (this.reconnectTimer) {
|
||||
clearTimeout(this.reconnectTimer);
|
||||
this.reconnectTimer = null;
|
||||
clearTimeout() {
|
||||
if (this.setTimeout) {
|
||||
clearTimeout(this.setTimeout);
|
||||
}
|
||||
},
|
||||
|
||||
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);
|
||||
disconnect() {
|
||||
this.rfb.disconnect();
|
||||
},
|
||||
|
||||
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>
|
||||
// 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%;
|
||||
.error {
|
||||
overflow: hidden;
|
||||
background: #000;
|
||||
|
||||
&.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;
|
||||
.row {
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
max-width: 480px;
|
||||
padding: 0 20px;
|
||||
}
|
||||
|
||||
// RcIcon has no 20px size, the one the design uses here, so it inherits it.
|
||||
&__spinner {
|
||||
display: flex;
|
||||
font-size: 20px;
|
||||
h1 {
|
||||
font-size: 5rem;
|
||||
}
|
||||
|
||||
&__connecting-label {
|
||||
margin: 0;
|
||||
font-size: 16px;
|
||||
line-height: 21px;
|
||||
.desert-landscape {
|
||||
img {
|
||||
max-width: 100%;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
<style lang="scss">
|
||||
// noVNC sets an inline `outline: none` on its canvas, so frame the screen with a ring instead:
|
||||
// a thin border at rest and, while it holds the keyboard, a 2px ring set 2px off the screen so it
|
||||
// never blends into a dark framebuffer edge (the SUSE light focus colour is a very dark green).
|
||||
.novnc-screen canvas {
|
||||
box-shadow: 0 0 0 1px var(--border);
|
||||
}
|
||||
|
||||
.novnc-screen.is-focused canvas {
|
||||
box-shadow: 0 0 0 2px var(--body-bg), 0 0 0 4px var(--primary-keyboard-focus);
|
||||
}
|
||||
|
||||
.novnc-screen.is-edge-to-edge canvas {
|
||||
box-shadow: none;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,355 +1,264 @@
|
||||
<script>
|
||||
import { STEVE } from '@shell/config/types';
|
||||
import { stringify } from '@shell/utils/error';
|
||||
import Banner from '@components/Banner/Banner.vue';
|
||||
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';
|
||||
import AsyncButton from '@shell/components/AsyncButton';
|
||||
import ModalWithCard from '@shell/components/ModalWithCard';
|
||||
|
||||
const PREFERED_SHORTCUT_KEYS = 'prefered-shortcut-keys';
|
||||
|
||||
export default {
|
||||
name: 'NovncConsoleCustomKeys',
|
||||
|
||||
components: {
|
||||
Banner, RcButton, RcIcon, RcModal, RcTag, LabeledInput, NovncKeyRecorder
|
||||
},
|
||||
|
||||
props: {
|
||||
show: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
},
|
||||
|
||||
emits: ['close'],
|
||||
|
||||
components: {
|
||||
ModalWithCard, Banner, AsyncButton
|
||||
},
|
||||
|
||||
data() {
|
||||
return {
|
||||
keys: [],
|
||||
name: '',
|
||||
saving: false,
|
||||
error: '',
|
||||
keysRecord: [],
|
||||
addedShortcutKeys: [],
|
||||
preferredShortcutKeys: [],
|
||||
isRecording: false,
|
||||
};
|
||||
},
|
||||
|
||||
computed: {
|
||||
preference() {
|
||||
return this.$store.getters['management/all'](STEVE.PREFERENCE)?.[0];
|
||||
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;
|
||||
},
|
||||
|
||||
shortcuts() {
|
||||
return readShortcuts(this.preference).map((shortcut) => ({ ...shortcut, labels: shortcutLabels(shortcut) }));
|
||||
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;
|
||||
},
|
||||
|
||||
isDuplicate() {
|
||||
const id = shortcutId({ keys: this.keys });
|
||||
recordButton() {
|
||||
if (this.isRecording) {
|
||||
return 'harvester.virtualMachine.detail.console.record.stop';
|
||||
}
|
||||
|
||||
return !!this.keys.length && this.shortcuts.some((shortcut) => shortcutId(shortcut) === id);
|
||||
return 'harvester.virtualMachine.detail.console.record.start';
|
||||
},
|
||||
|
||||
keysRecordFormat() {
|
||||
if (!this.isRecording && this.keysRecord.length === 0) {
|
||||
return this.t('harvester.virtualMachine.detail.console.record.tips');
|
||||
}
|
||||
|
||||
const out = this.keysRecord.map((item) => ` <code>${ item.key.charAt(0).toUpperCase() + item.key.slice(1) }</code>`);
|
||||
|
||||
return `Keys: ${ out.join(',') }`;
|
||||
},
|
||||
|
||||
canAdd() {
|
||||
return !!this.keys.length && !this.isDuplicate;
|
||||
const hasRecord = this.keysRecord.length > 0;
|
||||
let validationList = [].concat(this.preferredShortcutKeys, this.addedShortcutKeys);
|
||||
|
||||
if (!hasRecord) {
|
||||
return false;
|
||||
}
|
||||
|
||||
validationList.push(this.keysRecord);
|
||||
|
||||
validationList = validationList.map((item) => {
|
||||
const out = item.map((K) => K.key);
|
||||
|
||||
return out.join(',');
|
||||
});
|
||||
|
||||
return validationList.length === new Set(validationList).size;
|
||||
},
|
||||
},
|
||||
|
||||
watch: {
|
||||
show(show) {
|
||||
if (!show) {
|
||||
this.error = '';
|
||||
}
|
||||
savedShortcutKeys: {
|
||||
handler() {
|
||||
this.preferredShortcutKeys = [].concat(this.savedShortcutKeys) || [];
|
||||
},
|
||||
immediate: true
|
||||
},
|
||||
},
|
||||
|
||||
methods: {
|
||||
clear() {
|
||||
this.keys = [];
|
||||
this.name = '';
|
||||
closeRecordingModal() {
|
||||
window.removeEventListener('keydown', this.handleShortcut);
|
||||
this.$emit('close');
|
||||
},
|
||||
|
||||
// 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;
|
||||
}
|
||||
toggleRecording() {
|
||||
this.isRecording = !this.isRecording;
|
||||
|
||||
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;
|
||||
if (this.isRecording) {
|
||||
this.keysRecord = [];
|
||||
window.addEventListener('keydown', this.handleShortcut);
|
||||
} else {
|
||||
window.removeEventListener('keydown', this.handleShortcut);
|
||||
}
|
||||
},
|
||||
|
||||
async remove(index) {
|
||||
if (this.saving) {
|
||||
return;
|
||||
}
|
||||
handleShortcut(event) {
|
||||
event.preventDefault();
|
||||
|
||||
const removed = await this.save(this.shortcuts.filter((_, i) => i !== index));
|
||||
const {
|
||||
key, keyCode, code, location, charCode
|
||||
} = event;
|
||||
|
||||
// The row may be gone with the button that had the focus: the delete button now in its place, or
|
||||
// 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();
|
||||
});
|
||||
}
|
||||
this.keysRecord.push({
|
||||
key, keyCode, code, location, charCode
|
||||
});
|
||||
},
|
||||
|
||||
// Every change is saved straight away, so closing the modal can never lose one.
|
||||
async save(shortcuts) {
|
||||
this.saving = true;
|
||||
this.error = '';
|
||||
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];
|
||||
|
||||
try {
|
||||
await writeShortcuts(this.preference, shortcuts.map(({ name, keys }) => ({ name, keys })));
|
||||
|
||||
return true;
|
||||
preference.data[PREFERED_SHORTCUT_KEYS] = JSON.stringify(out);
|
||||
await preference.save();
|
||||
this.closeRecordingModal();
|
||||
buttonCb(true);
|
||||
} catch (err) {
|
||||
// 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;
|
||||
buttonCb(false);
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<RcModal
|
||||
:show="show"
|
||||
size="medium"
|
||||
:title="t('harvester.virtualMachine.detail.console.customKeys.title')"
|
||||
data-testid="vnc-custom-keys-modal"
|
||||
@close="$emit('close')"
|
||||
<ModalWithCard
|
||||
name="recordShortcutKeys"
|
||||
:width="550"
|
||||
>
|
||||
<Banner
|
||||
v-if="error"
|
||||
color="error"
|
||||
role="alert"
|
||||
data-testid="vnc-custom-keys-error"
|
||||
>
|
||||
{{ error }}
|
||||
</Banner>
|
||||
|
||||
<p class="custom-keys__intro">
|
||||
{{ t('harvester.virtualMachine.detail.console.customKeys.description') }}
|
||||
</p>
|
||||
|
||||
<section class="custom-keys__new">
|
||||
<h3 class="custom-keys__heading">
|
||||
{{ t('harvester.virtualMachine.detail.console.customKeys.new') }}
|
||||
</h3>
|
||||
|
||||
<div class="custom-keys__field">
|
||||
<span
|
||||
id="vnc-key-combination-label"
|
||||
class="custom-keys__label"
|
||||
>{{ t('harvester.virtualMachine.detail.console.customKeys.combination') }}</span>
|
||||
<NovncKeyRecorder
|
||||
ref="recorder"
|
||||
v-model:value="keys"
|
||||
aria-labelledby="vnc-key-combination-label"
|
||||
/>
|
||||
<p
|
||||
v-if="isDuplicate"
|
||||
class="custom-keys__error"
|
||||
role="alert"
|
||||
>
|
||||
{{ t('harvester.virtualMachine.detail.console.customKeys.duplicate') }}
|
||||
</p>
|
||||
<p class="custom-keys__help">
|
||||
{{ t('harvester.virtualMachine.detail.console.customKeys.reserved') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<LabeledInput
|
||||
v-model:value="name"
|
||||
:label="t('harvester.virtualMachine.detail.console.customKeys.name')"
|
||||
data-testid="vnc-shortcut-name"
|
||||
@keyup.enter="add"
|
||||
/>
|
||||
|
||||
<div class="custom-keys__new-actions">
|
||||
<RcButton
|
||||
variant="secondary"
|
||||
:disabled="!keys.length && !name"
|
||||
@click="clear"
|
||||
>
|
||||
{{ t('harvester.virtualMachine.detail.console.customKeys.clear') }}
|
||||
</RcButton>
|
||||
<RcButton
|
||||
variant="primary"
|
||||
data-testid="vnc-add-shortcut"
|
||||
:disabled="!canAdd"
|
||||
@click="add"
|
||||
>
|
||||
{{ t('harvester.virtualMachine.detail.console.customKeys.add') }}
|
||||
</RcButton>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section v-if="shortcuts.length">
|
||||
<h3 class="custom-keys__heading">
|
||||
{{ t('harvester.virtualMachine.detail.console.customKeys.saved', { count: shortcuts.length }) }}
|
||||
</h3>
|
||||
<ul
|
||||
ref="list"
|
||||
class="custom-keys__list"
|
||||
>
|
||||
<li
|
||||
v-for="(shortcut, index) in shortcuts"
|
||||
:key="index"
|
||||
class="custom-keys__item"
|
||||
data-testid="vnc-custom-shortcut"
|
||||
>
|
||||
<span class="custom-keys__item-name">{{ shortcut.name || shortcut.labels.join('+') }}</span>
|
||||
<span class="custom-keys__item-keys">
|
||||
<RcTag
|
||||
v-for="(label, i) in shortcut.labels"
|
||||
:key="i"
|
||||
type="active"
|
||||
>
|
||||
{{ label }}
|
||||
</RcTag>
|
||||
</span>
|
||||
<RcButton
|
||||
variant="tertiary"
|
||||
:aria-label="t('harvester.virtualMachine.detail.console.customKeys.delete', { name: shortcut.name || shortcut.labels.join('+') }, true)"
|
||||
@click="remove(index)"
|
||||
>
|
||||
<RcIcon
|
||||
type="trash"
|
||||
size="inherit"
|
||||
/>
|
||||
</RcButton>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<template #actions="{ close }">
|
||||
<RcButton
|
||||
variant="primary"
|
||||
size="large"
|
||||
data-testid="vnc-custom-keys-done"
|
||||
@click="close"
|
||||
>
|
||||
{{ t('harvester.virtualMachine.detail.console.customKeys.done') }}
|
||||
</RcButton>
|
||||
<template #title>
|
||||
<t k="harvester.virtualMachine.detail.console.customShortcutKeys" />
|
||||
</template>
|
||||
</RcModal>
|
||||
|
||||
<template #content>
|
||||
<div class="row">
|
||||
<div class="col span-12">
|
||||
<Banner color="info">
|
||||
<span v-clean-html="keysRecordFormat"></span>
|
||||
</Banner>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col span-12">
|
||||
<button
|
||||
class="btn bg-primary"
|
||||
@click="toggleRecording"
|
||||
>
|
||||
<t :k="recordButton" />
|
||||
<i
|
||||
class="icon icon-fw"
|
||||
:class="isRecording ? 'icon-dot-open' : 'icon-dot'"
|
||||
/>
|
||||
</button>
|
||||
<button
|
||||
:disabled="!canAdd"
|
||||
class="btn bg-primary"
|
||||
@click="addShortcutKey"
|
||||
>
|
||||
<t k="generic.add" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<hr>
|
||||
|
||||
<div class="displayed-keys mt-20">
|
||||
<h4
|
||||
v-clean-html="t('harvester.virtualMachine.detail.console.record.preferredKeys')"
|
||||
class="text-default-text"
|
||||
/>
|
||||
|
||||
<div class="displayed-banners">
|
||||
<Banner
|
||||
v-for="(keys,index) in displayedKeys"
|
||||
:key="index"
|
||||
>
|
||||
<span v-clean-html="keys"></span>
|
||||
</Banner>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template #footer>
|
||||
<div class="actions">
|
||||
<button
|
||||
class="btn role-secondary mr-20"
|
||||
@click.prevent="closeRecordingModal"
|
||||
>
|
||||
<t k="generic.close" />
|
||||
</button>
|
||||
<AsyncButton
|
||||
mode="done"
|
||||
@click="saveKeys"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</ModalWithCard>
|
||||
</template>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.custom-keys {
|
||||
&__intro {
|
||||
.displayed-keys {
|
||||
.banner {
|
||||
margin: 0;
|
||||
}
|
||||
}
|
||||
|
||||
&__new {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
padding: 16px 20px 20px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
}
|
||||
.displayed-banners {
|
||||
max-height: 155px;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
&__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;
|
||||
}
|
||||
.actions {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
<script>
|
||||
export default {
|
||||
name: 'NovncConsoleItem',
|
||||
|
||||
emits: ['send-keys', 'update'],
|
||||
|
||||
props: {
|
||||
items: {
|
||||
type: Object,
|
||||
required: true,
|
||||
default: () => {
|
||||
return {};
|
||||
}
|
||||
},
|
||||
|
||||
path: {
|
||||
type: Array,
|
||||
required: true,
|
||||
default: () => {
|
||||
return [];
|
||||
}
|
||||
},
|
||||
|
||||
pos: {
|
||||
type: Number,
|
||||
required: true,
|
||||
default: 0,
|
||||
}
|
||||
},
|
||||
|
||||
methods: {
|
||||
keysDown(key, pos) {
|
||||
this.addKeys({ key, pos });
|
||||
this.$emit('send-keys');
|
||||
},
|
||||
|
||||
addKeys({ key, pos }) {
|
||||
this.$emit('update', { key, pos });
|
||||
},
|
||||
|
||||
sendKeys() {
|
||||
this.$emit('send-keys');
|
||||
},
|
||||
|
||||
getOpenStatus(key, pos) {
|
||||
return this.path[pos] === key;
|
||||
}
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ul class="list-unstyled dropdown combination-keys__container">
|
||||
<li
|
||||
v-for="(item, key) in items"
|
||||
:key="key"
|
||||
>
|
||||
<v-dropdown
|
||||
v-if="!!item.keys"
|
||||
placement="right-start"
|
||||
trigger="click"
|
||||
:container="false"
|
||||
>
|
||||
<span
|
||||
:class="{ open: getOpenStatus(key, pos) }"
|
||||
class="p-10 hand"
|
||||
@click="addKeys({ key, pos })"
|
||||
>{{ item.label }}</span>
|
||||
|
||||
<template #popper>
|
||||
<novnc-console-item
|
||||
:items="item.keys"
|
||||
:path="path"
|
||||
:pos="pos+1"
|
||||
@update="addKeys"
|
||||
@send-keys="sendKeys"
|
||||
/>
|
||||
</template>
|
||||
</v-dropdown>
|
||||
|
||||
<span
|
||||
v-else
|
||||
class="p-10 hand"
|
||||
@click="keysDown(key, pos)"
|
||||
>{{ item.label }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</template>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.combination-keys__container {
|
||||
max-width: 60px;
|
||||
|
||||
DIV, SPAN {
|
||||
display: block;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
SPAN {
|
||||
border-radius: 3px;
|
||||
|
||||
&:hover, &.open {
|
||||
color: var(--primary-hover-text);
|
||||
background: var(--primary-hover-bg);
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,41 +1,15 @@
|
||||
<script>
|
||||
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, { CONSOLE_STATUS } from './NovncConsole';
|
||||
import NovncConsole from './NovncConsole';
|
||||
import NovncConsoleItem from './NovncConsoleItem';
|
||||
import NovncConsoleCustomKeys from './NovncConsoleCustomKeys';
|
||||
import NovncConnectionStatus, { CONNECTION_STATE } from './NovncConnectionStatus';
|
||||
import NovncIcon from './NovncIcon';
|
||||
import NovncShortcutKeysMenu from './NovncShortcutKeysMenu';
|
||||
import NovncStatusCard from './NovncStatusCard';
|
||||
import NovncViewOptions, { VIEW_MODE } from './NovncViewOptions';
|
||||
import { baseKey, readShortcuts } from './shortcuts';
|
||||
import { normalizeZoom } from './ZoomableRFB';
|
||||
|
||||
// The previous console saved its defaults under its key the first time it opened, so they can't tell a
|
||||
// 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 PREFERED_SHORTCUT_KEYS = 'prefered-shortcut-keys';
|
||||
|
||||
const SHORT_KEYS = {
|
||||
ControlLeft: {
|
||||
@@ -132,29 +106,15 @@ const F_KEYS = {
|
||||
export default {
|
||||
name: 'NovncConsoleWrapper',
|
||||
components: {
|
||||
RcButton, RcModal, Checkbox, NovncConsole, NovncConsoleCustomKeys, NovncConnectionStatus, NovncIcon, NovncShortcutKeysMenu, NovncStatusCard, NovncViewOptions
|
||||
NovncConsole, NovncConsoleItem, NovncConsoleCustomKeys
|
||||
},
|
||||
|
||||
// A VM that is not running has no instance, so find it by the uid in the route instead.
|
||||
async fetch() {
|
||||
if (this.value?.id) {
|
||||
const hash = await allHash({ vmResource: this.$store.dispatch('harvester/find', { type: HCI.VM, id: this.value.id }) });
|
||||
const _hash = { vmResource: this.$store.dispatch('harvester/find', { type: HCI.VM, id: this.value.id }) };
|
||||
|
||||
this.vmResource = hash.vmResource;
|
||||
const hash = await allHash(_hash);
|
||||
|
||||
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 = {};
|
||||
}
|
||||
this.vmResource = hash.vmResource;
|
||||
},
|
||||
|
||||
props: {
|
||||
@@ -169,89 +129,45 @@ export default {
|
||||
|
||||
data() {
|
||||
return {
|
||||
keysRecord: [],
|
||||
vmResource: {},
|
||||
renderKeysModal: false,
|
||||
settings: { ...DEFAULT_SETTINGS },
|
||||
capabilities: {},
|
||||
isFullscreen: false,
|
||||
confirmAction: null,
|
||||
startedAt: 0,
|
||||
consoleStatus: {
|
||||
status: 'connecting',
|
||||
retryTimes: 0,
|
||||
maximumRetryTimes: 0,
|
||||
desktopName: '',
|
||||
},
|
||||
currentUser: null,
|
||||
hideCustomKeysBar: false,
|
||||
};
|
||||
},
|
||||
|
||||
computed: {
|
||||
preference() {
|
||||
return this.$store.getters['management/all'](STEVE.PREFERENCE)?.[0];
|
||||
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;
|
||||
},
|
||||
|
||||
// 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) || !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';
|
||||
return this.isEmpty(this.value);
|
||||
},
|
||||
|
||||
url() {
|
||||
@@ -269,132 +185,84 @@ export default {
|
||||
};
|
||||
},
|
||||
|
||||
keymap() {
|
||||
const out = {
|
||||
...SHORT_KEYS,
|
||||
PrintScreen: FUNCTION_KEYS.PrintScreen,
|
||||
...F_KEYS,
|
||||
};
|
||||
|
||||
out.AltLeft.keys = { PrintScreen: FUNCTION_KEYS.PrintScreen, ...F_KEYS };
|
||||
out.ControlLeft.keys = {
|
||||
AltLeft: {
|
||||
...Object.assign(SHORT_KEYS.AltLeft, {}),
|
||||
keys: { Delete: FUNCTION_KEYS.Delete }
|
||||
},
|
||||
...NORMAL_KEYS,
|
||||
};
|
||||
|
||||
return out;
|
||||
},
|
||||
|
||||
hasSoftRebootAction() {
|
||||
return !!this.vmResource?.actions?.softreboot;
|
||||
},
|
||||
|
||||
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: ''
|
||||
preferredShortcutKeys() {
|
||||
return (this.savedShortcutKeys || []).map((item) => {
|
||||
return {
|
||||
label: item.map((K) => K.key.charAt(0).toUpperCase() + K.key.slice(1)).join('+'),
|
||||
value: item
|
||||
};
|
||||
} else if (wasDown) {
|
||||
this.startedAt = Date.now();
|
||||
}
|
||||
});
|
||||
},
|
||||
},
|
||||
|
||||
mounted() {
|
||||
this.loadSettings();
|
||||
document.addEventListener('fullscreenchange', this.onFullscreenChange);
|
||||
},
|
||||
|
||||
beforeUnmount() {
|
||||
document.removeEventListener('fullscreenchange', this.onFullscreenChange);
|
||||
},
|
||||
|
||||
methods: {
|
||||
isEmpty(o) {
|
||||
return o !== undefined && Object.keys(o).length === 0;
|
||||
},
|
||||
|
||||
close() {
|
||||
this.$refs.novncConsole?.disconnect();
|
||||
this.$refs.novncConsole.disconnect();
|
||||
},
|
||||
|
||||
// Press the keys in order, then release them in reverse, e.g. Ctrl+Alt+F2.
|
||||
sendKeys(keys) {
|
||||
if (!this.canSendKeys || !this.$refs.novncConsole) {
|
||||
return;
|
||||
}
|
||||
update({ key, pos }) {
|
||||
this.keysRecord.splice(pos, this.keysRecord.length - pos, key);
|
||||
},
|
||||
|
||||
keys.forEach((key) => {
|
||||
// Send function key, e.g. ALT + F
|
||||
sendKeys() {
|
||||
this.keysRecord.forEach((key) => {
|
||||
this.$refs.novncConsole.sendKey(this.allKeys[key].value, key, true);
|
||||
});
|
||||
|
||||
[...keys].reverse().forEach((key) => {
|
||||
this.keysRecord.reverse().forEach((key) => {
|
||||
this.$refs.novncConsole.sendKey(this.allKeys[key].value, key, false);
|
||||
});
|
||||
|
||||
this.focusConsole();
|
||||
this.$refs.popover.isOpen = false;
|
||||
this.keysRecord = [];
|
||||
},
|
||||
|
||||
sendCustomKeys(keys) {
|
||||
if (!this.canSendKeys || !this.$refs.novncConsole) {
|
||||
return;
|
||||
}
|
||||
|
||||
const combination = [].concat(keys);
|
||||
const keyList = combination.map((K) => baseKey(K, combination));
|
||||
const keyList = [].concat(keys);
|
||||
|
||||
keyList.forEach((K) => {
|
||||
this.$refs.novncConsole.sendKey(KeyboardUtil.getKeysym(K), KeyboardUtil.getKeycode(K), true);
|
||||
});
|
||||
|
||||
[...keyList].reverse().forEach((K) => {
|
||||
keyList.reverse().forEach((K) => {
|
||||
this.$refs.novncConsole.sendKey(KeyboardUtil.getKeysym(K), KeyboardUtil.getKeycode(K), false);
|
||||
});
|
||||
|
||||
this.focusConsole();
|
||||
},
|
||||
|
||||
// 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());
|
||||
reconnect() {
|
||||
this.$refs.novncConsole.reconnect();
|
||||
},
|
||||
|
||||
// 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();
|
||||
}
|
||||
softReboot() {
|
||||
this.vmResource.doSoftReboot();
|
||||
},
|
||||
|
||||
showKeysModal() {
|
||||
@@ -403,516 +271,116 @@ 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
|
||||
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"
|
||||
<div class="vm-console">
|
||||
<div class="combination-keys">
|
||||
<v-dropdown
|
||||
ref="popover"
|
||||
placement="top"
|
||||
trigger="click"
|
||||
:container="false"
|
||||
@auto-hide="keysRecord = []"
|
||||
>
|
||||
<template #before>
|
||||
<NovncIcon type="minimize" />
|
||||
<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>
|
||||
{{ t('harvester.virtualMachine.detail.console.fullscreen.exit') }}
|
||||
</RcButton>
|
||||
</div>
|
||||
</v-dropdown>
|
||||
|
||||
<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>
|
||||
<button
|
||||
v-if="hasSoftRebootAction"
|
||||
class="btn btn-sm bg-primary"
|
||||
@click="softReboot"
|
||||
>
|
||||
{{ t("harvester.action.softreboot") }}
|
||||
</button>
|
||||
|
||||
<NovncConnectionStatus
|
||||
:status="connectionStatus"
|
||||
:label="statusLabel"
|
||||
:vm-name="vmName"
|
||||
@reconnect="reconnect"
|
||||
/>
|
||||
<button
|
||||
class="btn btn-sm bg-primary"
|
||||
@click="reconnect"
|
||||
>
|
||||
{{ t("harvester.action.reconnect") }}
|
||||
</button>
|
||||
|
||||
<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>
|
||||
<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>
|
||||
|
||||
<div class="console-toolbar__group">
|
||||
<NovncShortcutKeysMenu
|
||||
v-bind="shortcutMenuProps"
|
||||
@send-keys="sendKeys"
|
||||
@send-shortcut="sendCustomKeys"
|
||||
@manage="showKeysModal"
|
||||
@ctrl-alt-del="ctrlAltDelete"
|
||||
/>
|
||||
</div>
|
||||
<template #popper>
|
||||
<div>
|
||||
<button
|
||||
class="btn btn-sm bg-primary"
|
||||
@click="showKeysModal"
|
||||
>
|
||||
{{ t("harvester.virtualMachine.detail.console.management") }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<span
|
||||
class="console-toolbar__divider"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<hr>
|
||||
|
||||
<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"
|
||||
<div
|
||||
v-for="(keys, index) in preferredShortcutKeys"
|
||||
:key="index"
|
||||
>
|
||||
{{ t("harvester.virtualMachine.detail.console.view") }}
|
||||
</RcButton>
|
||||
<button
|
||||
class="btn btn-sm bg-primary"
|
||||
@click="sendCustomKeys(keys.value)"
|
||||
>
|
||||
{{ keys.label }}
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
</v-dropdown>
|
||||
|
||||
<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"
|
||||
<NovncConsoleCustomKeys
|
||||
v-if="renderKeysModal"
|
||||
:current-user="currentUser"
|
||||
@close="hideKeysModal"
|
||||
/>
|
||||
<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"
|
||||
<NovncConsole
|
||||
v-if="url && !isDown"
|
||||
ref="novncConsole"
|
||||
:url="url"
|
||||
/>
|
||||
<p v-if="isDown">
|
||||
{{ t("harvester.virtualMachine.detail.console.down") }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.vm-console {
|
||||
height: 100vh;
|
||||
height: 100dvh;
|
||||
height: 100%;
|
||||
display: grid;
|
||||
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;
|
||||
}
|
||||
}
|
||||
grid-template-rows: 30px auto;
|
||||
}
|
||||
|
||||
.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);
|
||||
}
|
||||
.combination-keys {
|
||||
background: rgb(40, 40, 40);
|
||||
}
|
||||
</style>
|
||||
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
<script>
|
||||
// Icons the console needs that RcIcon does not have yet. Paths come from the VNC console design, on
|
||||
// its 24px grid.
|
||||
const ICONS = {
|
||||
power: {
|
||||
viewBox: '0 0 24 24',
|
||||
paths: [
|
||||
'M11.1253 12V2C11.1253 1.51675 11.517 1.125 12.0003 1.125C12.4835 1.125 12.8753 1.51675 12.8753 2V12C12.8753 12.4832 12.4835 12.875 12.0003 12.875C11.517 12.875 11.1253 12.4832 11.1253 12Z',
|
||||
'M17.7812 5.98086C18.123 5.63921 18.6779 5.64006 19.0195 5.98184C20.398 7.361 21.337 9.11746 21.7187 11.0297C22.1004 12.9421 21.9076 14.9251 21.1641 16.7279C20.4204 18.5309 19.1592 20.0733 17.54 21.1605C15.921 22.2477 14.0166 22.8311 12.0664 22.8373C10.1161 22.8434 8.20695 22.2728 6.58105 21.1957C4.95519 20.1186 3.68464 18.5838 2.92968 16.7855C2.1748 14.9875 1.96928 13.006 2.33886 11.0912C2.70859 9.17628 3.63766 7.41274 5.00781 6.0248C5.3473 5.68128 5.90132 5.67771 6.24511 6.01699C6.58896 6.35643 6.59224 6.91038 6.25292 7.2543C5.12564 8.39621 4.36185 9.84678 4.05761 11.4223C3.75341 12.9978 3.92278 14.6283 4.54394 16.1078C5.16512 17.5874 6.21008 18.8505 7.54785 19.7367C8.88557 20.6229 10.4559 21.0923 12.0605 21.0873C13.6651 21.0823 15.2323 20.6028 16.5644 19.7084C17.8966 18.8138 18.934 17.5443 19.5459 16.0609C20.1578 14.5775 20.317 12.9461 20.0029 11.3725C19.6888 9.79885 18.9157 8.35303 17.7812 7.21816C17.4399 6.87639 17.4396 6.3224 17.7812 5.98086Z',
|
||||
],
|
||||
},
|
||||
maximize: {
|
||||
viewBox: '0 0 24 24',
|
||||
paths: [
|
||||
'M2.125 19V16C2.125 15.5168 2.51675 15.125 3 15.125C3.48325 15.125 3.875 15.5168 3.875 16V19C3.875 19.2984 3.99312 19.5849 4.2041 19.7959C4.41508 20.0069 4.70163 20.125 5 20.125H8C8.48325 20.125 8.875 20.5168 8.875 21C8.875 21.4832 8.48325 21.875 8 21.875H5C4.2375 21.875 3.50596 21.5724 2.9668 21.0332C2.42763 20.494 2.125 19.7625 2.125 19ZM20.125 19V16C20.125 15.5168 20.5168 15.125 21 15.125C21.4832 15.125 21.875 15.5168 21.875 16V19C21.875 19.7625 21.5724 20.494 21.0332 21.0332C20.494 21.5724 19.7625 21.875 19 21.875H16C15.5168 21.875 15.125 21.4832 15.125 21C15.125 20.5168 15.5168 20.125 16 20.125H19C19.2984 20.125 19.5849 20.0069 19.7959 19.7959C20.0069 19.5849 20.125 19.2984 20.125 19ZM2.125 8V5C2.125 4.2375 2.42763 3.50596 2.9668 2.9668C3.50596 2.42763 4.2375 2.125 5 2.125H8C8.48325 2.125 8.875 2.51675 8.875 3C8.875 3.48325 8.48325 3.875 8 3.875H5C4.70163 3.875 4.41508 3.99312 4.2041 4.2041C3.99312 4.41508 3.875 4.70163 3.875 5V8C3.875 8.48325 3.48325 8.875 3 8.875C2.51675 8.875 2.125 8.48325 2.125 8ZM20.125 8V5C20.125 4.70163 20.0069 4.41508 19.7959 4.2041C19.5849 3.99312 19.2984 3.875 19 3.875H16C15.5168 3.875 15.125 3.48325 15.125 3C15.125 2.51675 15.5168 2.125 16 2.125H19C19.7625 2.125 20.494 2.42763 21.0332 2.9668C21.5724 3.50596 21.875 4.2375 21.875 5V8C21.875 8.48325 21.4832 8.875 21 8.875C20.5168 8.875 20.125 8.48325 20.125 8Z',
|
||||
],
|
||||
},
|
||||
minimize: {
|
||||
viewBox: '0 0 24 24',
|
||||
paths: [
|
||||
'M7.125 21V18C7.125 17.7016 7.00688 17.4151 6.7959 17.2041C6.58492 16.9931 6.29837 16.875 6 16.875H3C2.51675 16.875 2.125 16.4832 2.125 16C2.125 15.5168 2.51675 15.125 3 15.125H6C6.7625 15.125 7.49404 15.4276 8.0332 15.9668C8.57237 16.506 8.875 17.2375 8.875 18V21C8.875 21.4832 8.48325 21.875 8 21.875C7.51675 21.875 7.125 21.4832 7.125 21ZM15.125 21V18C15.125 17.2375 15.4276 16.506 15.9668 15.9668C16.506 15.4276 17.2375 15.125 18 15.125H21C21.4832 15.125 21.875 15.5168 21.875 16C21.875 16.4832 21.4832 16.875 21 16.875H18C17.7016 16.875 17.4151 16.9931 17.2041 17.2041C16.9931 17.4151 16.875 17.7016 16.875 18V21C16.875 21.4832 16.4832 21.875 16 21.875C15.5168 21.875 15.125 21.4832 15.125 21ZM7.125 6V3C7.125 2.51675 7.51675 2.125 8 2.125C8.48325 2.125 8.875 2.51675 8.875 3V6C8.875 6.7625 8.57237 7.49404 8.0332 8.0332C7.49404 8.57237 6.7625 8.875 6 8.875H3C2.51675 8.875 2.125 8.48325 2.125 8C2.125 7.51675 2.51675 7.125 3 7.125H6C6.29837 7.125 6.58492 7.00688 6.7959 6.7959C7.00688 6.58492 7.125 6.29837 7.125 6ZM15.125 6V3C15.125 2.51675 15.5168 2.125 16 2.125C16.4832 2.125 16.875 2.51675 16.875 3V6C16.875 6.29837 16.9931 6.58492 17.2041 6.7959C17.4151 7.00688 17.7016 7.125 18 7.125H21C21.4832 7.125 21.875 7.51675 21.875 8C21.875 8.48325 21.4832 8.875 21 8.875H18C17.2375 8.875 16.506 8.57237 15.9668 8.0332C15.4276 7.49404 15.125 6.7625 15.125 6Z',
|
||||
],
|
||||
},
|
||||
'wifi-off': {
|
||||
viewBox: '0 0 24 24',
|
||||
paths: [
|
||||
'M1.38128 1.38128C1.72299 1.03957 2.27785 1.03957 2.61956 1.38128L22.6196 21.3813C22.9613 21.723 22.9613 22.2779 22.6196 22.6196C22.2779 22.9613 21.723 22.9613 21.3813 22.6196L15.9448 17.183C15.6121 17.3797 15.1772 17.3385 14.8881 17.0551C14.117 16.2993 13.0802 15.8764 12.0004 15.8764C10.9207 15.8764 9.88381 16.2993 9.11273 17.0551C8.76768 17.3933 8.21371 17.3883 7.87542 17.0434C7.53715 16.6983 7.54301 16.1434 7.88812 15.8051C8.98629 14.7288 10.4628 14.1264 12.0004 14.1264C12.3272 14.1264 12.651 14.1543 12.9692 14.2075L9.88714 11.1254C8.27735 11.5087 6.79851 12.3224 5.61273 13.4848C5.26764 13.8231 4.71371 13.8182 4.37542 13.4731C4.03714 13.128 4.04303 12.5741 4.38812 12.2358C5.55033 11.0965 6.94797 10.2366 8.47503 9.71331L5.98577 7.22405C4.74971 7.80461 3.60363 8.56219 2.58343 9.47308C2.22296 9.79494 1.66993 9.76324 1.34808 9.40277C1.02629 9.04229 1.05697 8.48925 1.41741 8.16741C2.40785 7.28308 3.5045 6.52832 4.68011 5.91839L1.38128 2.61956C1.03957 2.27785 1.03957 1.72299 1.38128 1.38128ZM12.0102 19.1254C12.4934 19.1254 12.8852 19.5172 12.8852 20.0004C12.8852 20.4837 12.4934 20.8754 12.0102 20.8754H12.0004C11.5172 20.8754 11.1254 20.4837 11.1254 20.0004C11.1254 19.5172 11.5172 19.1254 12.0004 19.1254H12.0102ZM16.2426 10.9028C16.4843 10.4845 17.0195 10.341 17.4379 10.5825C18.2294 11.0398 18.9602 11.5956 19.6127 12.2358C19.9576 12.5741 19.9636 13.1281 19.6254 13.4731C19.287 13.818 18.7331 13.8231 18.3881 13.4848C17.8406 12.9476 17.2271 12.4818 16.5629 12.0981C16.1445 11.8563 16.001 11.3212 16.2426 10.9028ZM10.6352 4.1889C12.7929 4.00208 14.9661 4.25848 17.0209 4.94281C19.0757 5.62716 20.9686 6.72516 22.5834 8.16839C22.9436 8.49044 22.9748 9.04348 22.6528 9.40374C22.3308 9.76385 21.7777 9.7949 21.4174 9.47308C19.9807 8.18898 18.2964 7.21188 16.4682 6.60296C14.6399 5.99405 12.7055 5.7658 10.7856 5.93206C10.3043 5.97356 9.88011 5.61739 9.83831 5.13616C9.79662 4.65472 10.1537 4.23059 10.6352 4.1889Z',
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
export default {
|
||||
name: 'NovncIcon',
|
||||
|
||||
props: {
|
||||
type: {
|
||||
type: String,
|
||||
required: true,
|
||||
validator: (value) => Object.keys(ICONS).includes(value),
|
||||
},
|
||||
},
|
||||
|
||||
computed: {
|
||||
icon() {
|
||||
return ICONS[this.type];
|
||||
},
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<svg
|
||||
class="novnc-icon"
|
||||
:viewBox="icon.viewBox"
|
||||
fill="currentColor"
|
||||
aria-hidden="true"
|
||||
focusable="false"
|
||||
>
|
||||
<path
|
||||
v-for="(d, i) in icon.paths"
|
||||
:key="i"
|
||||
:d="d"
|
||||
/>
|
||||
</svg>
|
||||
</template>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.novnc-icon {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
</style>
|
||||
@@ -1,232 +0,0 @@
|
||||
<script>
|
||||
import RcStatusIndicator from '@components/Pill/RcStatusIndicator';
|
||||
import RcTag from '@components/Pill/RcTag';
|
||||
import { MODIFIER_KEYS, baseKey, keyLabel, recordKey } from './shortcuts';
|
||||
|
||||
export default {
|
||||
name: 'NovncKeyRecorder',
|
||||
|
||||
components: { RcStatusIndicator, RcTag },
|
||||
|
||||
props: {
|
||||
// The recorded keys, as stored for a shortcut.
|
||||
value: {
|
||||
type: Array,
|
||||
default: () => [],
|
||||
},
|
||||
|
||||
ariaLabelledby: {
|
||||
type: String,
|
||||
default: undefined,
|
||||
},
|
||||
},
|
||||
|
||||
emits: ['update:value'],
|
||||
|
||||
data() {
|
||||
return { recording: false, pending: [] };
|
||||
},
|
||||
|
||||
computed: {
|
||||
state() {
|
||||
if (this.recording) {
|
||||
return 'recording';
|
||||
}
|
||||
|
||||
return this.value.length ? 'captured' : 'empty';
|
||||
},
|
||||
|
||||
labels() {
|
||||
return this.value.map((K) => keyLabel(baseKey(K, this.value).key));
|
||||
},
|
||||
|
||||
valueId() {
|
||||
return `vnc-key-recorder-value-${ this.$.uid }`;
|
||||
},
|
||||
|
||||
// Read out with the field's label, so screen readers hear what is recorded.
|
||||
announcement() {
|
||||
if (this.state === 'recording') {
|
||||
return this.t('harvester.virtualMachine.detail.console.customKeys.recorder.recordingStatus');
|
||||
}
|
||||
|
||||
return this.labels.join('+');
|
||||
},
|
||||
},
|
||||
|
||||
methods: {
|
||||
start() {
|
||||
this.pending = [];
|
||||
this.recording = true;
|
||||
},
|
||||
|
||||
stop() {
|
||||
this.recording = false;
|
||||
this.pending = [];
|
||||
},
|
||||
|
||||
// Modifiers wait for the key they go with; the first other key ends the combination.
|
||||
onKeydown(event) {
|
||||
if (!this.recording) {
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault();
|
||||
this.start();
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Esc or Tab on their own leave the field, so it never traps the keyboard; with a modifier
|
||||
// they are part of the combination (Ctrl+Shift+Esc).
|
||||
if (!this.pending.length && (event.key === 'Escape' || event.key === 'Tab')) {
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}
|
||||
this.stop();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
|
||||
if (event.repeat) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (MODIFIER_KEYS.includes(event.key)) {
|
||||
if (!this.pending.some((K) => K.key === event.key)) {
|
||||
this.pending.push(recordKey(event));
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
this.$emit('update:value', [...this.pending, recordKey(event, this.pending)]);
|
||||
this.stop();
|
||||
},
|
||||
|
||||
// Modifiers released before any other key are the combination themselves, such as the Windows key on
|
||||
// its own. It waits for the last one, so Ctrl+Shift can be let go one key at a time.
|
||||
onKeyup(event) {
|
||||
if (!this.recording || !this.pending.length || !MODIFIER_KEYS.includes(event.key)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.ctrlKey || event.altKey || event.shiftKey || event.metaKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
this.$emit('update:value', [...this.pending]);
|
||||
this.stop();
|
||||
},
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="key-recorder"
|
||||
:class="`key-recorder--${ state }`"
|
||||
role="button"
|
||||
tabindex="0"
|
||||
:aria-labelledby="ariaLabelledby ? `${ ariaLabelledby } ${ valueId }` : valueId"
|
||||
:aria-pressed="recording"
|
||||
data-testid="vnc-key-recorder"
|
||||
@click="start"
|
||||
@keydown="onKeydown"
|
||||
@keyup="onKeyup"
|
||||
@blur="stop"
|
||||
>
|
||||
<span
|
||||
:id="valueId"
|
||||
class="sr-only"
|
||||
aria-live="polite"
|
||||
>{{ announcement }}</span>
|
||||
|
||||
<template v-if="state === 'recording'">
|
||||
<span class="key-recorder__hint">{{ t('harvester.virtualMachine.detail.console.customKeys.recorder.recording') }}</span>
|
||||
<span class="key-recorder__status">
|
||||
<RcStatusIndicator
|
||||
shape="disc"
|
||||
status="error"
|
||||
/>
|
||||
{{ t('harvester.virtualMachine.detail.console.customKeys.recorder.recordingStatus') }}
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<template v-else-if="state === 'captured'">
|
||||
<span class="key-recorder__keys">
|
||||
<RcTag
|
||||
v-for="(label, i) in labels"
|
||||
:key="i"
|
||||
type="active"
|
||||
>
|
||||
{{ label }}
|
||||
</RcTag>
|
||||
</span>
|
||||
<span class="key-recorder__again">{{ t('harvester.virtualMachine.detail.console.customKeys.recorder.again') }}</span>
|
||||
</template>
|
||||
|
||||
<span
|
||||
v-else
|
||||
class="key-recorder__hint"
|
||||
>{{ t('harvester.virtualMachine.detail.console.customKeys.recorder.empty') }}</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.key-recorder {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-height: 48px;
|
||||
padding: 0 14px;
|
||||
border: 1px solid var(--input-border);
|
||||
border-radius: 4px;
|
||||
background: var(--input-bg);
|
||||
cursor: pointer;
|
||||
|
||||
&--empty {
|
||||
border-style: dashed;
|
||||
}
|
||||
|
||||
&--recording {
|
||||
border: 2px solid var(--primary-keyboard-focus);
|
||||
padding: 0 13px;
|
||||
}
|
||||
|
||||
&:focus-visible {
|
||||
@include focus-outline;
|
||||
}
|
||||
|
||||
&__hint {
|
||||
color: var(--muted);
|
||||
font-size: 14px;
|
||||
line-height: 21px;
|
||||
}
|
||||
|
||||
&__keys {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
&__status,
|
||||
&__again {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-left: auto;
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
}
|
||||
|
||||
&__again {
|
||||
color: var(--muted);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,404 +0,0 @@
|
||||
<script>
|
||||
import { h, inject } from 'vue';
|
||||
import {
|
||||
RcDropdown, RcDropdownGroup, RcDropdownItem, RcDropdownItemCheckbox, RcDropdownSeparator, RcDropdownTrigger
|
||||
} from '@components/RcDropdown';
|
||||
import { RcIcon } from '@components/RcIcon';
|
||||
import { shortcutLabels } from './shortcuts';
|
||||
|
||||
export const MODIFIERS = [
|
||||
{ key: 'ControlLeft', label: 'Ctrl' },
|
||||
{ key: 'AltLeft', label: 'Alt' },
|
||||
];
|
||||
|
||||
export const FUNCTION_KEYS = ['F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12'];
|
||||
|
||||
// Ctrl alone offers the browser shortcuts the guest cannot get from the keyboard (the browser keeps
|
||||
// Ctrl+N/T/W for itself), as the old cascading menu did.
|
||||
export const CTRL_KEYS = [
|
||||
{ key: 'KeyN', label: 'N' },
|
||||
{ key: 'KeyT', label: 'T' },
|
||||
{ key: 'KeyW', label: 'W' },
|
||||
{ key: 'KeyY', label: 'Y' },
|
||||
];
|
||||
|
||||
// RcDropdown collects its items when the menu opens, and the arrow keys walk that list. Holding a modifier
|
||||
// swaps the keys below it while the menu is open, so, as RcDropdown does for its submenus, the items are
|
||||
// collected again on each key press and the arrows reach the keys shown now.
|
||||
export const ShortcutMenuBody = {
|
||||
name: 'ShortcutMenuBody',
|
||||
|
||||
setup(_props, { slots }) {
|
||||
const dropdown = inject('dropdownContext', null);
|
||||
|
||||
const collectItems = (event) => {
|
||||
const menu = event.currentTarget.closest('[dropdown-menu-collection]');
|
||||
|
||||
if (dropdown?.dropdownItems && menu) {
|
||||
dropdown.dropdownItems.value = [...menu.querySelectorAll('[dropdown-menu-item]')];
|
||||
}
|
||||
};
|
||||
|
||||
return () => h('div', { class: 'shortcut-menu', onKeydownCapture: collectItems }, slots.default?.());
|
||||
},
|
||||
};
|
||||
|
||||
export default {
|
||||
name: 'NovncShortcutKeysMenu',
|
||||
|
||||
components: {
|
||||
RcDropdown, RcDropdownGroup, RcDropdownItem, RcDropdownItemCheckbox, RcDropdownSeparator, RcDropdownTrigger, RcIcon, ShortcutMenuBody
|
||||
},
|
||||
|
||||
props: {
|
||||
disabled: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
|
||||
// Saved custom shortcuts, as { name, keys }.
|
||||
shortcuts: {
|
||||
type: Array,
|
||||
default: () => [],
|
||||
},
|
||||
|
||||
// Keys only go out over a connected console; the menu still opens to manage shortcuts.
|
||||
canSend: {
|
||||
type: Boolean,
|
||||
default: true,
|
||||
},
|
||||
|
||||
// Why keys cannot be sent right now, shown at the top of the menu.
|
||||
blockedReason: {
|
||||
type: String,
|
||||
default: '',
|
||||
},
|
||||
|
||||
// Custom shortcuts are stored in the user preference, which standalone setups may not have.
|
||||
canManage: {
|
||||
type: Boolean,
|
||||
default: true,
|
||||
},
|
||||
},
|
||||
|
||||
emits: ['send-keys', 'send-shortcut', 'manage', 'ctrl-alt-del'],
|
||||
|
||||
data() {
|
||||
return { held: [] };
|
||||
},
|
||||
|
||||
computed: {
|
||||
modifiers() {
|
||||
return MODIFIERS;
|
||||
},
|
||||
|
||||
functionKeys() {
|
||||
return FUNCTION_KEYS;
|
||||
},
|
||||
|
||||
holdsCtrl() {
|
||||
return this.held.includes('ControlLeft');
|
||||
},
|
||||
|
||||
holdsAlt() {
|
||||
return this.held.includes('AltLeft');
|
||||
},
|
||||
|
||||
// What the keys below the toggles offer follows what is held, so the menu sends the same
|
||||
// combinations as the old one: Ctrl+N/T/W/Y, Ctrl+Alt+Del, Alt+Print Screen and Alt+F1-F12, plus
|
||||
// Ctrl+Alt+F1-F12 to switch Linux consoles.
|
||||
keyOptions() {
|
||||
if (this.holdsCtrl && this.holdsAlt) {
|
||||
return [{ key: 'Delete', label: 'Del' }];
|
||||
}
|
||||
|
||||
if (this.holdsCtrl) {
|
||||
return CTRL_KEYS;
|
||||
}
|
||||
|
||||
return [{ key: 'PrintScreen', label: this.t('harvester.virtualMachine.detail.console.shortcutMenu.printScreen') }];
|
||||
},
|
||||
|
||||
showFunctionKeys() {
|
||||
return !this.holdsCtrl || this.holdsAlt;
|
||||
},
|
||||
|
||||
heldCombo() {
|
||||
return MODIFIERS.filter((M) => this.held.includes(M.key)).map((M) => M.label).join('+');
|
||||
},
|
||||
|
||||
items() {
|
||||
return this.shortcuts.map((shortcut, index) => {
|
||||
const label = shortcutLabels(shortcut).join('+');
|
||||
|
||||
return {
|
||||
index, name: shortcut.name || label, label, keys: shortcut.keys
|
||||
};
|
||||
});
|
||||
},
|
||||
},
|
||||
|
||||
methods: {
|
||||
// Held modifiers belong to this visit of the menu; closing it without a key lets them go.
|
||||
onOpen(open) {
|
||||
if (!open) {
|
||||
this.held = [];
|
||||
}
|
||||
},
|
||||
|
||||
toggleModifier(key, on) {
|
||||
this.held = on ? [...this.held, key] : this.held.filter((K) => K !== key);
|
||||
},
|
||||
|
||||
// Held modifiers apply to the next key only, then the toggles reset.
|
||||
sendKey(key) {
|
||||
const modifiers = MODIFIERS.map((M) => M.key).filter((K) => this.held.includes(K));
|
||||
|
||||
// Ctrl+Alt+Del restarts most guests, so it goes through the same confirmation as its button.
|
||||
if (key === 'Delete' && this.holdsCtrl && this.holdsAlt) {
|
||||
this.$emit('ctrl-alt-del');
|
||||
} else {
|
||||
this.$emit('send-keys', [...modifiers, key]);
|
||||
}
|
||||
this.held = [];
|
||||
},
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<rc-dropdown
|
||||
:aria-label="t('harvester.virtualMachine.detail.console.shortcutKeys')"
|
||||
placement="bottom-start"
|
||||
@update:open="onOpen"
|
||||
>
|
||||
<rc-dropdown-trigger
|
||||
variant="tertiary"
|
||||
data-testid="vnc-shortcut-keys"
|
||||
:disabled="disabled"
|
||||
>
|
||||
<template #before>
|
||||
<rc-icon
|
||||
type="keyboard"
|
||||
size="inherit"
|
||||
/>
|
||||
</template>
|
||||
{{ t('harvester.virtualMachine.detail.console.shortcutKeys') }}
|
||||
<template #after>
|
||||
<rc-icon
|
||||
type="chevron-down"
|
||||
size="inherit"
|
||||
/>
|
||||
</template>
|
||||
</rc-dropdown-trigger>
|
||||
|
||||
<template #dropdownCollection>
|
||||
<shortcut-menu-body>
|
||||
<p
|
||||
v-if="!canSend && blockedReason"
|
||||
class="shortcut-menu__blocked"
|
||||
data-testid="vnc-shortcut-blocked"
|
||||
>
|
||||
{{ blockedReason }}
|
||||
</p>
|
||||
<template v-if="canManage && items.length">
|
||||
<rc-dropdown-group :label="t('harvester.virtualMachine.detail.console.shortcutMenu.yourShortcuts')">
|
||||
<rc-dropdown-item
|
||||
v-for="item in items"
|
||||
:key="item.index"
|
||||
:disabled="!canSend"
|
||||
class="shortcut-menu__saved"
|
||||
data-testid="vnc-saved-shortcut"
|
||||
:title="item.name"
|
||||
@click="$emit('send-shortcut', item.keys)"
|
||||
>
|
||||
<span class="shortcut-menu__saved-name">{{ item.name }}</span>
|
||||
<template #after>
|
||||
<span class="shortcut-menu__chip">{{ item.label }}</span>
|
||||
</template>
|
||||
</rc-dropdown-item>
|
||||
</rc-dropdown-group>
|
||||
<rc-dropdown-separator />
|
||||
</template>
|
||||
|
||||
<rc-dropdown-group :label="t('harvester.virtualMachine.detail.console.shortcutMenu.holdModifiers')">
|
||||
<div class="shortcut-menu__row">
|
||||
<rc-dropdown-item-checkbox
|
||||
v-for="modifier in modifiers"
|
||||
:key="modifier.key"
|
||||
:disabled="!canSend"
|
||||
indicator="checkmark"
|
||||
class="shortcut-menu__chip shortcut-menu__toggle"
|
||||
:class="{ 'is-on': held.includes(modifier.key) }"
|
||||
:data-testid="`vnc-hold-${ modifier.label.toLowerCase() }`"
|
||||
:model-value="held.includes(modifier.key)"
|
||||
@update:model-value="toggleModifier(modifier.key, $event)"
|
||||
>
|
||||
{{ modifier.label }}
|
||||
</rc-dropdown-item-checkbox>
|
||||
</div>
|
||||
<p
|
||||
v-if="heldCombo"
|
||||
class="shortcut-menu__help"
|
||||
>
|
||||
{{ t('harvester.virtualMachine.detail.console.shortcutMenu.holdHint', { combo: heldCombo }) }}
|
||||
</p>
|
||||
</rc-dropdown-group>
|
||||
<rc-dropdown-separator />
|
||||
|
||||
<rc-dropdown-group :label="t('harvester.virtualMachine.detail.console.shortcutMenu.keys')">
|
||||
<div class="shortcut-menu__row">
|
||||
<rc-dropdown-item
|
||||
v-for="option in keyOptions"
|
||||
:key="option.key"
|
||||
:disabled="!canSend"
|
||||
class="shortcut-menu__chip"
|
||||
:data-testid="`vnc-key-${ option.key }`"
|
||||
@click="sendKey(option.key)"
|
||||
>
|
||||
{{ option.label }}
|
||||
</rc-dropdown-item>
|
||||
</div>
|
||||
</rc-dropdown-group>
|
||||
|
||||
<rc-dropdown-group
|
||||
v-if="showFunctionKeys"
|
||||
:label="t('harvester.virtualMachine.detail.console.shortcutMenu.functionKeys')"
|
||||
>
|
||||
<div class="shortcut-menu__grid">
|
||||
<rc-dropdown-item
|
||||
v-for="key in functionKeys"
|
||||
:key="key"
|
||||
:disabled="!canSend"
|
||||
class="shortcut-menu__chip"
|
||||
:data-testid="`vnc-key-${ key }`"
|
||||
@click="sendKey(key)"
|
||||
>
|
||||
{{ key }}
|
||||
</rc-dropdown-item>
|
||||
</div>
|
||||
</rc-dropdown-group>
|
||||
|
||||
<template v-if="canManage">
|
||||
<rc-dropdown-separator />
|
||||
<rc-dropdown-item
|
||||
class="shortcut-menu__manage"
|
||||
data-testid="vnc-manage-shortcuts"
|
||||
@click="$emit('manage')"
|
||||
>
|
||||
<template #before>
|
||||
<rc-icon
|
||||
type="edit"
|
||||
size="inherit"
|
||||
/>
|
||||
</template>
|
||||
{{ t('harvester.virtualMachine.detail.console.shortcutMenu.manage') }}
|
||||
</rc-dropdown-item>
|
||||
</template>
|
||||
</shortcut-menu-body>
|
||||
</template>
|
||||
</rc-dropdown>
|
||||
</template>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
// The menu items are styled as the key chips of the design; `.shortcut-menu` raises the
|
||||
// specificity above RcDropdownItem's own item styles.
|
||||
.shortcut-menu {
|
||||
width: 320px;
|
||||
|
||||
&__row,
|
||||
&__grid {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
padding: 4px 16px 8px;
|
||||
}
|
||||
|
||||
&__grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(6, 1fr);
|
||||
}
|
||||
|
||||
// The chips are the design's small secondary buttons, so they take RcButton's secondary tokens
|
||||
// (with its fallbacks) and follow the brand like every other button.
|
||||
.shortcut-menu__chip {
|
||||
justify-content: center;
|
||||
min-height: 24px;
|
||||
margin: 0;
|
||||
padding: 0 8px;
|
||||
border: 1px solid var(--secondary-border, var(--primary));
|
||||
border-radius: 4px;
|
||||
background: var(--secondary, transparent);
|
||||
color: var(--on-secondary, var(--primary));
|
||||
font-size: 12px;
|
||||
line-height: 16px;
|
||||
white-space: nowrap;
|
||||
|
||||
&:hover {
|
||||
background: var(--secondary-hover, var(--accent-btn));
|
||||
}
|
||||
}
|
||||
|
||||
.shortcut-menu__chip[disabled],
|
||||
.shortcut-menu__saved[disabled] .shortcut-menu__chip {
|
||||
&,
|
||||
&:hover {
|
||||
border-color: var(--disabled-bg, var(--border));
|
||||
background: transparent;
|
||||
color: var(--disabled-text);
|
||||
cursor: not-allowed;
|
||||
}
|
||||
}
|
||||
|
||||
&__blocked {
|
||||
margin: 0;
|
||||
padding: 4px 16px 8px;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
}
|
||||
|
||||
.shortcut-menu__toggle.is-on {
|
||||
&,
|
||||
&:hover {
|
||||
border-color: var(--active, var(--primary));
|
||||
background: var(--active, var(--primary));
|
||||
color: var(--on-active, var(--primary-text));
|
||||
}
|
||||
}
|
||||
|
||||
.shortcut-menu__saved {
|
||||
margin: 0 9px;
|
||||
padding: 4px 8px;
|
||||
font-size: 14px;
|
||||
|
||||
// Long names stay on two lines; the full one is in the tooltip.
|
||||
.shortcut-menu__saved-name {
|
||||
display: -webkit-box;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
-webkit-box-orient: vertical;
|
||||
-webkit-line-clamp: 2;
|
||||
line-clamp: 2;
|
||||
}
|
||||
|
||||
.shortcut-menu__chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
}
|
||||
}
|
||||
|
||||
&__help {
|
||||
margin: 0;
|
||||
padding: 0 16px 8px;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
}
|
||||
|
||||
// The design's tertiary button.
|
||||
.shortcut-menu__manage {
|
||||
color: var(--on-tertiary, var(--primary));
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,104 +0,0 @@
|
||||
<script>
|
||||
import NovncIcon from './NovncIcon';
|
||||
|
||||
// The card the console shows on its black screen when there is nothing to type into: a failed
|
||||
// connection, or a virtual machine that is not running.
|
||||
export default {
|
||||
name: 'NovncStatusCard',
|
||||
|
||||
components: { NovncIcon },
|
||||
|
||||
props: {
|
||||
icon: {
|
||||
type: String,
|
||||
default: 'wifi-off',
|
||||
},
|
||||
|
||||
title: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
|
||||
detail: {
|
||||
type: String,
|
||||
default: '',
|
||||
},
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="status-card">
|
||||
<span
|
||||
class="status-card__badge"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<NovncIcon :type="icon" />
|
||||
</span>
|
||||
<h3 class="status-card__title">
|
||||
{{ title }}
|
||||
</h3>
|
||||
<p
|
||||
v-if="detail"
|
||||
class="status-card__detail"
|
||||
>
|
||||
{{ detail }}
|
||||
</p>
|
||||
<div
|
||||
v-if="$slots.default"
|
||||
class="status-card__actions"
|
||||
>
|
||||
<slot />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
// Always on the black screen, whatever the theme, so the text is light.
|
||||
.status-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
max-width: 480px;
|
||||
padding: 32px;
|
||||
color: #fff;
|
||||
text-align: center;
|
||||
|
||||
&__badge {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 56px;
|
||||
height: 56px;
|
||||
border-radius: 50%;
|
||||
background: rgba(255, 255, 255, 0.12);
|
||||
color: rgba(255, 255, 255, 0.8);
|
||||
|
||||
.novnc-icon {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
}
|
||||
}
|
||||
|
||||
&__title {
|
||||
margin: 0;
|
||||
color: #fff;
|
||||
font-size: 16px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
&__detail {
|
||||
margin: 0;
|
||||
color: rgba(255, 255, 255, 0.8);
|
||||
font-size: 13px;
|
||||
line-height: 16px;
|
||||
}
|
||||
|
||||
&__actions {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
padding-top: 8px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,302 +0,0 @@
|
||||
<script>
|
||||
import ButtonGroup from '@shell/components/ButtonGroup';
|
||||
import { RcButton } from '@components/RcButton';
|
||||
import { RcIcon } from '@components/RcIcon';
|
||||
import { MAXIMUM_ZOOM, MINIMUM_ZOOM, ZOOM_STEP } from './ZoomableRFB';
|
||||
|
||||
export const VIEW_MODE = {
|
||||
SCALE: 'scale',
|
||||
NONE: 'none',
|
||||
};
|
||||
|
||||
const MAXIMUM_LEVEL = 9;
|
||||
|
||||
export default {
|
||||
name: 'NovncViewOptions',
|
||||
|
||||
components: {
|
||||
ButtonGroup, RcButton, RcIcon
|
||||
},
|
||||
|
||||
props: {
|
||||
settings: {
|
||||
type: Object,
|
||||
required: true,
|
||||
},
|
||||
},
|
||||
|
||||
emits: ['update', 'reset'],
|
||||
|
||||
computed: {
|
||||
modeOptions() {
|
||||
return [
|
||||
{ value: VIEW_MODE.SCALE, label: this.t('harvester.virtualMachine.detail.console.viewOptions.automatic') },
|
||||
{ value: VIEW_MODE.NONE, label: this.t('harvester.virtualMachine.detail.console.viewOptions.manual') },
|
||||
];
|
||||
},
|
||||
|
||||
isManual() {
|
||||
return this.settings.viewMode === VIEW_MODE.NONE;
|
||||
},
|
||||
|
||||
zoom() {
|
||||
return {
|
||||
min: MINIMUM_ZOOM, max: MAXIMUM_ZOOM, step: ZOOM_STEP
|
||||
};
|
||||
},
|
||||
|
||||
maximumLevel() {
|
||||
return MAXIMUM_LEVEL;
|
||||
},
|
||||
},
|
||||
|
||||
methods: {
|
||||
update(key, value) {
|
||||
this.$emit('update', { ...this.settings, [key]: value });
|
||||
},
|
||||
|
||||
stepZoom(direction) {
|
||||
const next = this.settings.zoomPercent + (direction * ZOOM_STEP);
|
||||
|
||||
this.update('zoomPercent', Math.min(Math.max(next, MINIMUM_ZOOM), MAXIMUM_ZOOM));
|
||||
},
|
||||
|
||||
// Feeds the filled part of the track, which native range inputs do not draw on their own.
|
||||
fill(value, min, max) {
|
||||
return { '--fill': `${ ((value - min) / (max - min)) * 100 }%` };
|
||||
},
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="view-options"
|
||||
data-testid="vnc-view-options"
|
||||
>
|
||||
<section class="view-options__section">
|
||||
<span class="view-options__label">{{ t('harvester.virtualMachine.detail.console.viewOptions.scaling') }}</span>
|
||||
<ButtonGroup
|
||||
class="view-options__mode"
|
||||
size="medium"
|
||||
:value="settings.viewMode"
|
||||
:options="modeOptions"
|
||||
@update:value="update('viewMode', $event)"
|
||||
/>
|
||||
<p class="view-options__help">
|
||||
{{ t(`harvester.virtualMachine.detail.console.viewOptions.${ isManual ? 'manualHelp' : 'automaticHelp' }`) }}
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section class="view-options__section">
|
||||
<label
|
||||
for="vnc-zoom"
|
||||
class="view-options__row"
|
||||
>
|
||||
<span class="view-options__label">{{ t('harvester.virtualMachine.detail.console.viewOptions.zoom') }}</span>
|
||||
<span class="view-options__value">{{ settings.zoomPercent }}%</span>
|
||||
</label>
|
||||
<div class="view-options__zoom">
|
||||
<RcButton
|
||||
variant="secondary"
|
||||
size="small"
|
||||
:aria-label="t('harvester.virtualMachine.detail.console.viewOptions.zoomOut')"
|
||||
:disabled="!isManual || settings.zoomPercent <= zoom.min"
|
||||
@click="stepZoom(-1)"
|
||||
>
|
||||
<RcIcon
|
||||
type="minus"
|
||||
size="inherit"
|
||||
/>
|
||||
</RcButton>
|
||||
<input
|
||||
id="vnc-zoom"
|
||||
class="view-options__slider"
|
||||
type="range"
|
||||
:min="zoom.min"
|
||||
:max="zoom.max"
|
||||
:step="zoom.step"
|
||||
:value="settings.zoomPercent"
|
||||
:disabled="!isManual"
|
||||
:aria-valuetext="`${ settings.zoomPercent }%`"
|
||||
:style="fill(settings.zoomPercent, zoom.min, zoom.max)"
|
||||
@input="update('zoomPercent', Number($event.target.value))"
|
||||
>
|
||||
<RcButton
|
||||
variant="secondary"
|
||||
size="small"
|
||||
:aria-label="t('harvester.virtualMachine.detail.console.viewOptions.zoomIn')"
|
||||
:disabled="!isManual || settings.zoomPercent >= zoom.max"
|
||||
@click="stepZoom(1)"
|
||||
>
|
||||
<RcIcon
|
||||
type="plus"
|
||||
size="inherit"
|
||||
/>
|
||||
</RcButton>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<hr class="view-options__divider">
|
||||
|
||||
<section
|
||||
v-for="level in ['qualityLevel', 'compressionLevel']"
|
||||
:key="level"
|
||||
class="view-options__section"
|
||||
>
|
||||
<label
|
||||
:for="`vnc-${ level }`"
|
||||
class="view-options__row"
|
||||
>
|
||||
<span class="view-options__label">{{ t(`harvester.virtualMachine.detail.console.viewOptions.${ level }.label`) }}</span>
|
||||
<span class="view-options__value">{{ t('harvester.virtualMachine.detail.console.viewOptions.levelOf', { value: settings[level], max: maximumLevel }) }}</span>
|
||||
</label>
|
||||
<input
|
||||
:id="`vnc-${ level }`"
|
||||
class="view-options__slider"
|
||||
type="range"
|
||||
min="0"
|
||||
:max="maximumLevel"
|
||||
step="1"
|
||||
:value="settings[level]"
|
||||
:style="fill(settings[level], 0, maximumLevel)"
|
||||
@input="update(level, Number($event.target.value))"
|
||||
>
|
||||
<p class="view-options__help">
|
||||
{{ t(`harvester.virtualMachine.detail.console.viewOptions.${ level }.help`) }}
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<RcButton
|
||||
variant="link"
|
||||
class="view-options__reset"
|
||||
data-testid="vnc-view-reset"
|
||||
@click="$emit('reset')"
|
||||
>
|
||||
{{ t('harvester.virtualMachine.detail.console.viewOptions.reset') }}
|
||||
</RcButton>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.view-options {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
width: 336px;
|
||||
padding: 16px;
|
||||
box-sizing: border-box;
|
||||
|
||||
&__section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
&__row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
&__label {
|
||||
color: var(--body-text);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
line-height: 18px;
|
||||
}
|
||||
|
||||
&__value,
|
||||
&__help {
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
&__help {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
&__mode {
|
||||
display: flex;
|
||||
|
||||
button {
|
||||
flex: 1;
|
||||
}
|
||||
}
|
||||
|
||||
&__zoom {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
|
||||
// Between the zoom buttons the slider takes the room that is left. In the other sections, which
|
||||
// are columns, the same rule would set its height and squash it to the track.
|
||||
.view-options__slider {
|
||||
flex: 1;
|
||||
}
|
||||
}
|
||||
|
||||
&__divider {
|
||||
margin: 0;
|
||||
border: 0;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
|
||||
// Links sit flush with the panel text instead of carrying button padding.
|
||||
&__reset {
|
||||
align-self: flex-start;
|
||||
--rc-button-padding: 0;
|
||||
}
|
||||
|
||||
&__slider {
|
||||
width: 100%;
|
||||
height: 20px;
|
||||
margin: 0;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
appearance: none;
|
||||
|
||||
&::-webkit-slider-runnable-track {
|
||||
height: 4px;
|
||||
border-radius: 2px;
|
||||
background: linear-gradient(to right, var(--primary) var(--fill), var(--muted) var(--fill));
|
||||
}
|
||||
|
||||
&::-moz-range-track {
|
||||
height: 4px;
|
||||
border-radius: 2px;
|
||||
background: linear-gradient(to right, var(--primary) var(--fill), var(--muted) var(--fill));
|
||||
}
|
||||
|
||||
&::-webkit-slider-thumb {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
margin-top: -6px;
|
||||
border: 2px solid var(--nav-bg);
|
||||
border-radius: 50%;
|
||||
background: var(--primary);
|
||||
appearance: none;
|
||||
}
|
||||
|
||||
&::-moz-range-thumb {
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
border: 2px solid var(--nav-bg);
|
||||
border-radius: 50%;
|
||||
background: var(--primary);
|
||||
}
|
||||
|
||||
&:focus-visible {
|
||||
@include focus-outline;
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.5;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,73 +0,0 @@
|
||||
import RFB from '@novnc/novnc/core/rfb';
|
||||
|
||||
export const MINIMUM_ZOOM = 50;
|
||||
export const MAXIMUM_ZOOM = 200;
|
||||
export const ZOOM_STEP = 10;
|
||||
|
||||
// The focus ring and the gap before it, drawn outside the canvas.
|
||||
const FOCUS_RING_WIDTH = 4;
|
||||
|
||||
export function normalizeZoom(value) {
|
||||
const percent = Number(value);
|
||||
|
||||
if (!Number.isFinite(percent)) {
|
||||
return 100;
|
||||
}
|
||||
|
||||
return Math.min(MAXIMUM_ZOOM, Math.max(MINIMUM_ZOOM, Math.round(percent / ZOOM_STEP) * ZOOM_STEP));
|
||||
}
|
||||
|
||||
export default class ZoomableRFB extends RFB {
|
||||
get zoomPercent() {
|
||||
return this._zoomPercent ?? 100;
|
||||
}
|
||||
|
||||
set zoomPercent(value) {
|
||||
this._zoomPercent = normalizeZoom(value);
|
||||
this._updateScale();
|
||||
}
|
||||
|
||||
// The screen takes all the room it has, without a focus ring around it.
|
||||
get edgeToEdge() {
|
||||
return !!this._edgeToEdge;
|
||||
}
|
||||
|
||||
set edgeToEdge(value) {
|
||||
this._edgeToEdge = value;
|
||||
this._updateScale();
|
||||
}
|
||||
|
||||
_updateScale() {
|
||||
if (this.scaleViewport) {
|
||||
// Fit inside the focus ring the console draws around the canvas, instead of under it.
|
||||
const size = this._screenSize();
|
||||
const inset = this.edgeToEdge ? 0 : 2 * FOCUS_RING_WIDTH;
|
||||
|
||||
this._display.autoscale(size.w - inset, size.h - inset);
|
||||
this._fixScrollbars();
|
||||
} else {
|
||||
this._display.scale = this.zoomPercent / 100;
|
||||
this._fixScrollbars();
|
||||
}
|
||||
}
|
||||
|
||||
// noVNC only stops a click on the screen, which Firefox delivers there (others to the page, past
|
||||
// noVNC's mouse capture). An open menu would never see the click outside it and would stay open.
|
||||
_handleMouse(ev) {
|
||||
if (ev.type !== 'click') {
|
||||
super._handleMouse(ev);
|
||||
}
|
||||
}
|
||||
|
||||
// noVNC hides the mouse over the screen until the guest sends a pointer image, and a text console
|
||||
// or a guest that draws its own pointer never does. Show the system pointer unless one arrives.
|
||||
_refreshCursor() {
|
||||
super._refreshCursor();
|
||||
|
||||
const hasGuestPointer = this._cursorImage.rgbaPixels.some((value, index) => index % 4 === 3 && value > 0);
|
||||
|
||||
if (!hasGuestPointer) {
|
||||
this._canvas.style.cursor = 'default';
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
import { shallowMount } from '@vue/test-utils';
|
||||
import { RcButton } from '@components/RcButton';
|
||||
import NovncConnectionStatus from '../NovncConnectionStatus.vue';
|
||||
|
||||
jest.mock('../ZoomableRFB', () => ({}));
|
||||
|
||||
describe('component: NovncConnectionStatus', () => {
|
||||
// A plain button takes the global 40px button height, taller than the 32px pill around it.
|
||||
it('should offer Reconnect as an RcButton when the console is disconnected', () => {
|
||||
const wrapper = shallowMount(NovncConnectionStatus, { props: { status: 'disconnected', label: 'Disconnected' } });
|
||||
const reconnect = wrapper.findComponent(RcButton);
|
||||
|
||||
expect(reconnect.attributes('data-testid')).toBe('vnc-connection-reconnect');
|
||||
|
||||
reconnect.vm.$emit('click');
|
||||
|
||||
expect(wrapper.emitted('reconnect')).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -1,241 +0,0 @@
|
||||
import { shallowMount } from '@vue/test-utils';
|
||||
import NovncConsole, { CONSOLE_STATUS, CONSOLE_FAILURE } from '../NovncConsole.vue';
|
||||
|
||||
const mockInstances = [];
|
||||
|
||||
jest.mock('../ZoomableRFB', () => {
|
||||
return jest.fn().mockImplementation((el, url) => {
|
||||
const listeners = {};
|
||||
const rfb = {
|
||||
url,
|
||||
addEventListener: jest.fn((name, cb) => {
|
||||
listeners[name] = cb;
|
||||
}),
|
||||
removeEventListener: jest.fn(),
|
||||
disconnect: jest.fn(),
|
||||
focus: jest.fn(),
|
||||
emit: (name, detail) => listeners[name]?.({ detail }),
|
||||
};
|
||||
|
||||
mockInstances.push(rfb);
|
||||
|
||||
return rfb;
|
||||
});
|
||||
});
|
||||
|
||||
const URL = 'wss://example.com/apis/subresources.kubevirt.io/v1/namespaces/default/virtualmachineinstances/vm/vnc';
|
||||
|
||||
const mountConsole = (props = {}) => {
|
||||
mockInstances.length = 0;
|
||||
jest.useFakeTimers();
|
||||
|
||||
return shallowMount(NovncConsole, { props: { url: URL, ...props } });
|
||||
};
|
||||
|
||||
const lastRFB = () => mockInstances[mockInstances.length - 1];
|
||||
|
||||
describe('component: NovncConsole', () => {
|
||||
it('should connect with preserveSession so an existing session is not kicked', async() => {
|
||||
mountConsole();
|
||||
await jest.runOnlyPendingTimersAsync();
|
||||
|
||||
expect(new window.URL(lastRFB().url).searchParams.get('preserveSession')).toBe('true');
|
||||
});
|
||||
|
||||
it('should keep retrying while the console is held by another session', async() => {
|
||||
const wrapper = mountConsole();
|
||||
|
||||
await jest.runOnlyPendingTimersAsync();
|
||||
lastRFB().emit('connect');
|
||||
|
||||
// Dropped by another session taking over.
|
||||
lastRFB().emit('disconnect');
|
||||
expect(wrapper.vm.status).toBe(CONSOLE_STATUS.RECONNECTING);
|
||||
|
||||
// The first retry is rejected because the other session is still active.
|
||||
jest.advanceTimersByTime(1000);
|
||||
lastRFB().emit('disconnect');
|
||||
|
||||
expect(wrapper.vm.status).toBe(CONSOLE_STATUS.RECONNECTING);
|
||||
expect(wrapper.vm.retryTimes).toBe(2);
|
||||
expect(wrapper.vm.statusDetail).toBe('%harvester.virtualMachine.detail.console.status.inUse%');
|
||||
expect(new window.URL(lastRFB().url).searchParams.get('preserveSession')).toBe('true');
|
||||
});
|
||||
|
||||
it('should fail with a take over option after the retries are exhausted', async() => {
|
||||
const wrapper = mountConsole();
|
||||
|
||||
await jest.runOnlyPendingTimersAsync();
|
||||
lastRFB().emit('connect');
|
||||
lastRFB().emit('disconnect');
|
||||
|
||||
for (let i = 0; i < wrapper.vm.maximumRetryTimes; i++) {
|
||||
jest.runOnlyPendingTimers();
|
||||
lastRFB().emit('disconnect');
|
||||
}
|
||||
|
||||
expect(wrapper.vm.status).toBe(CONSOLE_STATUS.FAILED);
|
||||
expect(wrapper.vm.failure).toBe(CONSOLE_FAILURE.IN_USE);
|
||||
expect(wrapper.vm.isClosed).toBe(false);
|
||||
});
|
||||
|
||||
it('should show the console as in use when a running VM refuses the first connection', async() => {
|
||||
const wrapper = mountConsole();
|
||||
|
||||
await jest.runOnlyPendingTimersAsync();
|
||||
lastRFB().emit('disconnect');
|
||||
|
||||
expect(wrapper.vm.status).toBe(CONSOLE_STATUS.FAILED);
|
||||
expect(wrapper.vm.failure).toBe(CONSOLE_FAILURE.IN_USE);
|
||||
expect(wrapper.vm.canTakeOver).toBe(true);
|
||||
});
|
||||
|
||||
it('should not claim the console is in use when the VM is not running', async() => {
|
||||
const wrapper = mountConsole({ vmRunning: false });
|
||||
|
||||
await jest.runOnlyPendingTimersAsync();
|
||||
lastRFB().emit('disconnect');
|
||||
|
||||
expect(wrapper.vm.failure).toBe(CONSOLE_FAILURE.UNAVAILABLE);
|
||||
expect(wrapper.vm.canTakeOver).toBe(false);
|
||||
});
|
||||
|
||||
it('should retry, not report in use, when a VM that just started refuses the first connection', async() => {
|
||||
const wrapper = mountConsole({ startedAt: Date.now() });
|
||||
|
||||
await jest.runOnlyPendingTimersAsync();
|
||||
lastRFB().emit('disconnect');
|
||||
|
||||
expect(wrapper.vm.status).toBe(CONSOLE_STATUS.RECONNECTING);
|
||||
expect(wrapper.vm.failure).toBe('');
|
||||
});
|
||||
|
||||
it('should keep counting retries when Reconnect now skips the wait', async() => {
|
||||
const wrapper = mountConsole();
|
||||
|
||||
await jest.runOnlyPendingTimersAsync();
|
||||
lastRFB().emit('connect');
|
||||
lastRFB().emit('disconnect');
|
||||
expect(wrapper.vm.retryTimes).toBe(1);
|
||||
|
||||
wrapper.vm.retryNow();
|
||||
|
||||
expect(wrapper.vm.retryTimes).toBe(1);
|
||||
expect(wrapper.vm.status).toBe(CONSOLE_STATUS.RECONNECTING);
|
||||
|
||||
// Still held by the other session: back to waiting, not the in-use failure.
|
||||
lastRFB().emit('disconnect');
|
||||
expect(wrapper.vm.status).toBe(CONSOLE_STATUS.RECONNECTING);
|
||||
expect(wrapper.vm.retryTimes).toBe(2);
|
||||
});
|
||||
|
||||
it('should only take over after the modal is confirmed', async() => {
|
||||
const wrapper = mountConsole();
|
||||
|
||||
await jest.runOnlyPendingTimersAsync();
|
||||
const connections = mockInstances.length;
|
||||
|
||||
wrapper.vm.takeOver();
|
||||
expect(wrapper.vm.showTakeOverModal).toBe(true);
|
||||
expect(mockInstances).toHaveLength(connections);
|
||||
|
||||
wrapper.vm.confirmTakeOver();
|
||||
|
||||
expect(wrapper.vm.showTakeOverModal).toBe(false);
|
||||
expect(new window.URL(lastRFB().url).searchParams.get('preserveSession')).toBe('false');
|
||||
});
|
||||
|
||||
it('should not take over when the modal is cancelled', async() => {
|
||||
const wrapper = mountConsole();
|
||||
|
||||
await jest.runOnlyPendingTimersAsync();
|
||||
const connections = mockInstances.length;
|
||||
|
||||
wrapper.vm.takeOver();
|
||||
wrapper.vm.cancelTakeOver();
|
||||
|
||||
expect(wrapper.vm.showTakeOverModal).toBe(false);
|
||||
expect(mockInstances).toHaveLength(connections);
|
||||
});
|
||||
|
||||
it('should focus the console once it connects, so typing reaches the VM', async() => {
|
||||
mountConsole();
|
||||
|
||||
await jest.runOnlyPendingTimersAsync();
|
||||
lastRFB().emit('connect');
|
||||
|
||||
expect(lastRFB().focus).toHaveBeenCalledWith();
|
||||
});
|
||||
|
||||
it('should mark the console while it has keyboard focus', async() => {
|
||||
const wrapper = mountConsole();
|
||||
const view = wrapper.find('.novnc-screen');
|
||||
|
||||
await jest.runOnlyPendingTimersAsync();
|
||||
|
||||
view.element.dispatchEvent(new FocusEvent('focusin'));
|
||||
await wrapper.vm.$nextTick();
|
||||
expect(view.classes()).toContain('is-focused');
|
||||
|
||||
view.element.dispatchEvent(new FocusEvent('focusout'));
|
||||
await wrapper.vm.$nextTick();
|
||||
expect(view.classes()).not.toContain('is-focused');
|
||||
});
|
||||
|
||||
it('should drop the focus ring and its room when the screen goes edge to edge', async() => {
|
||||
const wrapper = mountConsole();
|
||||
const view = wrapper.find('.novnc-screen');
|
||||
|
||||
await jest.runOnlyPendingTimersAsync();
|
||||
expect(view.classes()).not.toContain('is-edge-to-edge');
|
||||
expect(lastRFB().edgeToEdge).toBe(false);
|
||||
|
||||
await wrapper.setProps({ settings: { edgeToEdge: true } });
|
||||
|
||||
expect(view.classes()).toContain('is-edge-to-edge');
|
||||
expect(lastRFB().edgeToEdge).toBe(true);
|
||||
});
|
||||
|
||||
describe('when the cluster does not support preserveSession', () => {
|
||||
it('should connect without the parameter and offer no take over', async() => {
|
||||
const wrapper = mountConsole({ preserveSession: false });
|
||||
|
||||
await jest.runOnlyPendingTimersAsync();
|
||||
expect(new window.URL(lastRFB().url).searchParams.has('preserveSession')).toBe(false);
|
||||
|
||||
lastRFB().emit('disconnect');
|
||||
|
||||
expect(wrapper.vm.failure).toBe(CONSOLE_FAILURE.UNAVAILABLE);
|
||||
expect(wrapper.vm.canTakeOver).toBe(false);
|
||||
});
|
||||
|
||||
it('should not reconnect on its own after the session drops', async() => {
|
||||
const wrapper = mountConsole({ preserveSession: false });
|
||||
|
||||
await jest.runOnlyPendingTimersAsync();
|
||||
lastRFB().emit('connect');
|
||||
const connections = mockInstances.length;
|
||||
|
||||
lastRFB().emit('disconnect');
|
||||
jest.runOnlyPendingTimers();
|
||||
|
||||
expect(wrapper.vm.status).toBe(CONSOLE_STATUS.DISCONNECTED);
|
||||
expect(wrapper.vm.failure).toBe(CONSOLE_FAILURE.DROPPED);
|
||||
expect(wrapper.vm.showError).toBe(true);
|
||||
expect(mockInstances).toHaveLength(connections);
|
||||
});
|
||||
});
|
||||
|
||||
it('should close the socket when credentials are required', async() => {
|
||||
const wrapper = mountConsole();
|
||||
|
||||
await jest.runOnlyPendingTimersAsync();
|
||||
const rfb = lastRFB();
|
||||
|
||||
rfb.emit('credentialsrequired');
|
||||
|
||||
expect(rfb.disconnect).toHaveBeenCalledWith();
|
||||
expect(wrapper.vm.rfb).toBeNull();
|
||||
expect(wrapper.vm.status).toBe(CONSOLE_STATUS.FAILED);
|
||||
});
|
||||
});
|
||||
@@ -1,161 +0,0 @@
|
||||
import { reactive } from 'vue';
|
||||
import { flushPromises, mount, shallowMount } from '@vue/test-utils';
|
||||
import { RcButton } from '@components/RcButton';
|
||||
import NovncConsoleCustomKeys from '../NovncConsoleCustomKeys.vue';
|
||||
import { SHORTCUTS_PREFERENCE, SHORTCUT_NAMES_PREFERENCE } from '../shortcuts';
|
||||
|
||||
const key = (value, code) => ({ key: value, code });
|
||||
|
||||
const CTRL_F2 = [key('Control', 'ControlLeft'), key('F2', 'F2')];
|
||||
const CTRL_SPACE = [key('Control', 'ControlLeft'), key(' ', 'Space')];
|
||||
const ALT_T = [key('Alt', 'AltLeft'), key('t', 'KeyT')];
|
||||
|
||||
// `rendered` mounts the buttons and the recorder for real, in the document, so the focus can be checked.
|
||||
const mountKeys = (saved = [], { rendered = false } = {}) => {
|
||||
// Reactive like the store's, so the list follows what is saved.
|
||||
const preference = reactive({
|
||||
data: { [SHORTCUTS_PREFERENCE]: JSON.stringify(saved) },
|
||||
save: jest.fn().mockResolvedValue(),
|
||||
});
|
||||
|
||||
const wrapper = (rendered ? mount : shallowMount)(NovncConsoleCustomKeys, {
|
||||
props: { show: true },
|
||||
attachTo: rendered ? document.body : undefined,
|
||||
global: {
|
||||
mocks: { $store: { getters: { 'management/all': () => [preference] } } },
|
||||
stubs: {
|
||||
RcModal: { template: '<div><slot /></div>' }, Banner: { template: '<div><slot /></div>' }, LabeledInput: true
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return { wrapper, preference };
|
||||
};
|
||||
|
||||
const listed = (wrapper) => wrapper.findAll('[data-testid="vnc-custom-shortcut"]');
|
||||
|
||||
const removeShortcut = async(wrapper, index) => {
|
||||
listed(wrapper)[index].findComponent(RcButton).vm.$emit('click');
|
||||
await flushPromises();
|
||||
};
|
||||
|
||||
const savedKeys = (preference) => JSON.parse(preference.data[SHORTCUTS_PREFERENCE]);
|
||||
|
||||
describe('component: NovncConsoleCustomKeys', () => {
|
||||
it('should offer to remove every saved shortcut', () => {
|
||||
const { wrapper } = mountKeys([CTRL_F2, ALT_T]);
|
||||
|
||||
expect(listed(wrapper).map((item) => item.findComponent(RcButton).exists())).toStrictEqual([true, true]);
|
||||
});
|
||||
|
||||
it('should save the list without the shortcut that was removed', async() => {
|
||||
const { wrapper, preference } = mountKeys([CTRL_F2, ALT_T]);
|
||||
|
||||
await removeShortcut(wrapper, 0);
|
||||
|
||||
expect(preference.save).toHaveBeenCalledTimes(1);
|
||||
expect(savedKeys(preference)).toStrictEqual([ALT_T]);
|
||||
expect(listed(wrapper)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('should remove a shortcut with the Space key in it', async() => {
|
||||
const { wrapper, preference } = mountKeys([CTRL_SPACE, ALT_T]);
|
||||
|
||||
await removeShortcut(wrapper, 0);
|
||||
|
||||
expect(savedKeys(preference)).toStrictEqual([ALT_T]);
|
||||
});
|
||||
|
||||
it('should keep the shortcut when removing it cannot be saved, and say so in the dialog', async() => {
|
||||
const { wrapper, preference } = mountKeys([CTRL_F2, ALT_T]);
|
||||
|
||||
preference.save.mockRejectedValue(new Error('forbidden'));
|
||||
await removeShortcut(wrapper, 0);
|
||||
|
||||
expect(savedKeys(preference)).toStrictEqual([CTRL_F2, ALT_T]);
|
||||
expect(listed(wrapper)).toHaveLength(2);
|
||||
expect(wrapper.find('[data-testid="vnc-custom-keys-error"]').text()).toBe('%harvester.virtualMachine.detail.console.customKeys.saveError%: forbidden');
|
||||
|
||||
await wrapper.setProps({ show: false });
|
||||
|
||||
expect(wrapper.find('[data-testid="vnc-custom-keys-error"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('should not start a second save while one is running', async() => {
|
||||
const { wrapper, preference } = mountKeys([CTRL_F2, ALT_T]);
|
||||
|
||||
wrapper.vm.remove(0);
|
||||
wrapper.vm.remove(1);
|
||||
await flushPromises();
|
||||
|
||||
expect(preference.save).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should keep the focus on a delete button after a removal, and hand it to the recorder once the list is empty', async() => {
|
||||
const { wrapper } = mountKeys([CTRL_F2, ALT_T], { rendered: true });
|
||||
const deleteButtons = () => wrapper.findAll('[data-testid="vnc-custom-shortcut"] button');
|
||||
|
||||
deleteButtons()[1].element.focus();
|
||||
await deleteButtons()[1].trigger('click');
|
||||
await flushPromises();
|
||||
expect(document.activeElement).toBe(deleteButtons()[0].element);
|
||||
|
||||
await deleteButtons()[0].trigger('click');
|
||||
await flushPromises();
|
||||
expect(document.activeElement).toBe(wrapper.find('[data-testid="vnc-key-recorder"]').element);
|
||||
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it('should give the recorder the focus after a shortcut is added', async() => {
|
||||
const { wrapper } = mountKeys([CTRL_F2], { rendered: true });
|
||||
|
||||
wrapper.vm.keys = ALT_T;
|
||||
await wrapper.vm.$nextTick();
|
||||
wrapper.find('[data-testid="vnc-add-shortcut"]').element.focus();
|
||||
await wrapper.find('[data-testid="vnc-add-shortcut"]').trigger('click');
|
||||
await flushPromises();
|
||||
|
||||
expect(document.activeElement).toBe(wrapper.find('[data-testid="vnc-key-recorder"]').element);
|
||||
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it('should empty the form as soon as a shortcut is added, so it does not say it is already saved while it saves', async() => {
|
||||
const { wrapper, preference } = mountKeys([CTRL_F2]);
|
||||
|
||||
preference.save.mockReturnValue(new Promise(() => {}));
|
||||
wrapper.vm.keys = ALT_T;
|
||||
wrapper.vm.add();
|
||||
await wrapper.vm.$nextTick();
|
||||
|
||||
expect(listed(wrapper)).toHaveLength(2);
|
||||
expect(wrapper.vm.keys).toStrictEqual([]);
|
||||
expect(wrapper.find('.custom-keys__error').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('should put the shortcut back in the form when it cannot be saved', async() => {
|
||||
const { wrapper, preference } = mountKeys([CTRL_F2]);
|
||||
|
||||
preference.save.mockRejectedValue(new Error('forbidden'));
|
||||
wrapper.vm.keys = ALT_T;
|
||||
wrapper.vm.name = 'Task manager';
|
||||
await wrapper.vm.add();
|
||||
|
||||
expect(listed(wrapper)).toHaveLength(1);
|
||||
expect(wrapper.vm.keys).toStrictEqual(ALT_T);
|
||||
expect(wrapper.vm.name).toBe('Task manager');
|
||||
});
|
||||
|
||||
it('should save a new shortcut straight away, with its name', async() => {
|
||||
const { wrapper, preference } = mountKeys([CTRL_F2]);
|
||||
|
||||
wrapper.vm.keys = ALT_T;
|
||||
wrapper.vm.name = ' Task manager ';
|
||||
await wrapper.vm.add();
|
||||
|
||||
expect(savedKeys(preference)).toStrictEqual([CTRL_F2, ALT_T]);
|
||||
expect(JSON.parse(preference.data[SHORTCUT_NAMES_PREFERENCE])).toStrictEqual({ 'AltLeft+KeyT': 'Task manager' });
|
||||
expect(wrapper.vm.keys).toStrictEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,321 +0,0 @@
|
||||
import { shallowMount } from '@vue/test-utils';
|
||||
import NovncConsoleWrapper, { CONFIRM_ACTION } from '../NovncConsoleWrapper.vue';
|
||||
|
||||
jest.mock('../ZoomableRFB', () => ({ normalizeZoom: (value) => value }));
|
||||
jest.mock('@novnc/novnc/core/input/keysym', () => ({}), { virtual: true });
|
||||
jest.mock('@novnc/novnc/core/input/util', () => ({}), { virtual: true });
|
||||
|
||||
const consoleRef = {
|
||||
ctrlAltDelete: jest.fn(),
|
||||
focus: jest.fn(),
|
||||
};
|
||||
|
||||
const CHECKBOX = { name: 'Checkbox' };
|
||||
|
||||
const mountWrapper = ({ preferences = [], storage = {} } = {}) => {
|
||||
// The console settings are saved there, so one test's would load in the next.
|
||||
window.localStorage.clear();
|
||||
Object.entries(storage).forEach(([key, value]) => window.localStorage.setItem(key, JSON.stringify(value)));
|
||||
consoleRef.ctrlAltDelete.mockClear();
|
||||
consoleRef.focus.mockClear();
|
||||
|
||||
const wrapper = shallowMount(NovncConsoleWrapper, {
|
||||
props: {
|
||||
value: {
|
||||
id: 'default/vm', metadata: { name: 'vm' }, status: { phase: 'Running' }
|
||||
}
|
||||
},
|
||||
global: {
|
||||
mocks: {
|
||||
$store: {
|
||||
getters: {
|
||||
'management/all': () => preferences,
|
||||
'harvester-common/getFeatureEnabled': () => true,
|
||||
},
|
||||
},
|
||||
$fetchState: { pending: false },
|
||||
},
|
||||
stubs: {
|
||||
NovncConsole: {
|
||||
template: '<div />',
|
||||
methods: {
|
||||
ctrlAltDelete: consoleRef.ctrlAltDelete,
|
||||
focus: consoleRef.focus,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
wrapper.vm.onStatusChanged({ status: 'connected' });
|
||||
|
||||
return wrapper;
|
||||
};
|
||||
|
||||
describe('component: NovncConsoleWrapper', () => {
|
||||
it('should only send Ctrl+Alt+Del after it is confirmed', async() => {
|
||||
const wrapper = mountWrapper();
|
||||
|
||||
wrapper.vm.ctrlAltDelete();
|
||||
expect(wrapper.vm.confirmAction).toBe(CONFIRM_ACTION.CTRL_ALT_DEL);
|
||||
expect(consoleRef.ctrlAltDelete).not.toHaveBeenCalled();
|
||||
|
||||
wrapper.vm.runConfirmedAction();
|
||||
|
||||
expect(consoleRef.ctrlAltDelete).toHaveBeenCalledTimes(1);
|
||||
expect(wrapper.vm.confirmAction).toBeNull();
|
||||
});
|
||||
|
||||
it('should not send Ctrl+Alt+Del when the confirmation is cancelled', () => {
|
||||
const wrapper = mountWrapper();
|
||||
|
||||
wrapper.vm.ctrlAltDelete();
|
||||
wrapper.vm.cancelConfirm();
|
||||
|
||||
expect(consoleRef.ctrlAltDelete).not.toHaveBeenCalled();
|
||||
expect(wrapper.vm.confirmAction).toBeNull();
|
||||
});
|
||||
|
||||
it('should only soft reboot after it is confirmed', () => {
|
||||
const wrapper = mountWrapper();
|
||||
const doSoftReboot = jest.fn();
|
||||
|
||||
wrapper.vm.vmResource = { doSoftReboot };
|
||||
|
||||
wrapper.vm.softReboot();
|
||||
expect(doSoftReboot).not.toHaveBeenCalled();
|
||||
|
||||
wrapper.vm.runConfirmedAction();
|
||||
expect(doSoftReboot).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should keep the shortcut menu open to use while keys cannot be sent, and say why', () => {
|
||||
const wrapper = mountWrapper();
|
||||
|
||||
wrapper.vm.onStatusChanged({ status: 'reconnecting' });
|
||||
|
||||
expect(wrapper.vm.shortcutMenuProps.canSend).toBe(false);
|
||||
expect(wrapper.vm.sendBlockedReason).toBe('%harvester.virtualMachine.detail.console.shortcutMenu.blockedDisconnected%');
|
||||
// Without a user preference there is nothing to manage either, so only then is it disabled.
|
||||
expect(wrapper.vm.shortcutMenuProps.disabled).toBe(true);
|
||||
});
|
||||
|
||||
it('should keep the shortcut menu enabled while disconnected when there are shortcuts to manage', () => {
|
||||
const wrapper = mountWrapper({ preferences: [{ data: {} }] });
|
||||
|
||||
wrapper.vm.onStatusChanged({ status: 'reconnecting' });
|
||||
|
||||
expect(wrapper.vm.shortcutMenuProps.canSend).toBe(false);
|
||||
expect(wrapper.vm.shortcutMenuProps.disabled).toBe(false);
|
||||
});
|
||||
|
||||
it('should disable the shortcut menu, managing shortcuts included, while view only is on', () => {
|
||||
const wrapper = mountWrapper({ preferences: [{ data: {} }] });
|
||||
|
||||
expect(wrapper.vm.shortcutMenuProps.disabled).toBe(false);
|
||||
|
||||
wrapper.vm.setViewOnly(true);
|
||||
|
||||
expect(wrapper.vm.shortcutMenuProps.disabled).toBe(true);
|
||||
});
|
||||
|
||||
it('should disable Ctrl+Alt+Del and Soft reboot while view only is on', async() => {
|
||||
const wrapper = mountWrapper();
|
||||
const doSoftReboot = jest.fn();
|
||||
const button = (id) => wrapper.find(`[data-testid="${ id }"]`);
|
||||
|
||||
wrapper.vm.vmResource = { doSoftReboot, actions: { softreboot: 'url' } };
|
||||
await wrapper.vm.$nextTick();
|
||||
|
||||
expect(button('vnc-soft-reboot').attributes('disabled')).toBe('false');
|
||||
expect(button('vnc-ctrl-alt-del').attributes('disabled')).toBe('false');
|
||||
|
||||
wrapper.vm.setViewOnly(true);
|
||||
await wrapper.vm.$nextTick();
|
||||
|
||||
expect(button('vnc-soft-reboot').attributes('disabled')).toBe('true');
|
||||
expect(button('vnc-ctrl-alt-del').attributes('disabled')).toBe('true');
|
||||
|
||||
wrapper.vm.softReboot();
|
||||
wrapper.vm.ctrlAltDelete();
|
||||
|
||||
expect(wrapper.vm.confirmAction).toBeNull();
|
||||
expect(doSoftReboot).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should say so under the console while view only is on', async() => {
|
||||
const wrapper = mountWrapper();
|
||||
const hint = () => wrapper.find('.console-area__hint').text();
|
||||
|
||||
expect(hint()).toBe('%harvester.virtualMachine.detail.console.hint%');
|
||||
|
||||
wrapper.vm.setViewOnly(true);
|
||||
await wrapper.vm.$nextTick();
|
||||
|
||||
expect(hint()).toBe('%harvester.virtualMachine.detail.console.hintViewOnly%');
|
||||
});
|
||||
|
||||
it('should not send keys while view only is on', () => {
|
||||
const wrapper = mountWrapper();
|
||||
|
||||
wrapper.vm.setViewOnly(true);
|
||||
|
||||
expect(wrapper.vm.canSendKeys).toBe(false);
|
||||
});
|
||||
|
||||
it('should switch view only with the checkbox, and not repeat it in the connection status', async() => {
|
||||
const wrapper = mountWrapper();
|
||||
const checkbox = () => wrapper.findComponent(CHECKBOX);
|
||||
|
||||
expect(checkbox().props('value')).toBe(false);
|
||||
|
||||
checkbox().vm.$emit('update:value', true);
|
||||
await wrapper.vm.$nextTick();
|
||||
|
||||
expect(wrapper.vm.settings.viewOnly).toBe(true);
|
||||
expect(checkbox().props('value')).toBe(true);
|
||||
expect(wrapper.vm.statusLabel).toBe('%harvester.virtualMachine.detail.console.status.connected%');
|
||||
});
|
||||
|
||||
it('should give the console the keyboard when view only is turned off, not when it is turned on', async() => {
|
||||
const wrapper = mountWrapper();
|
||||
|
||||
wrapper.vm.setViewOnly(true);
|
||||
await wrapper.vm.$nextTick();
|
||||
expect(consoleRef.focus).not.toHaveBeenCalled();
|
||||
|
||||
wrapper.vm.setViewOnly(false);
|
||||
await wrapper.vm.$nextTick();
|
||||
expect(consoleRef.focus).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should not ask to send Ctrl+Alt+Del while keys cannot be sent', () => {
|
||||
const wrapper = mountWrapper();
|
||||
|
||||
wrapper.vm.onStatusChanged({ status: 'reconnecting' });
|
||||
wrapper.vm.ctrlAltDelete();
|
||||
|
||||
expect(wrapper.vm.confirmAction).toBeNull();
|
||||
});
|
||||
|
||||
describe('view settings', () => {
|
||||
it('should not take what the previous console saved on its first open as a choice', () => {
|
||||
const wrapper = mountWrapper({
|
||||
storage: {
|
||||
'harvester-vnc-console-settings': {
|
||||
viewMode: 'none', zoomPercent: 100, viewOnly: false, qualityLevel: 6, compressionLevel: 2
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
expect(wrapper.vm.settings.viewMode).toBe('scale');
|
||||
});
|
||||
|
||||
it('should carry view only over from the previous console, which saved it on only when the user turned it on', () => {
|
||||
const wrapper = mountWrapper({
|
||||
storage: {
|
||||
'harvester-vnc-console-settings': {
|
||||
viewMode: 'none', zoomPercent: 150, viewOnly: true, qualityLevel: 9, compressionLevel: 0
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
expect(wrapper.vm.settings).toMatchObject({
|
||||
viewOnly: true, viewMode: 'scale', zoomPercent: 100
|
||||
});
|
||||
});
|
||||
|
||||
it('should take view only from its own settings once it has saved them', () => {
|
||||
const wrapper = mountWrapper({
|
||||
storage: {
|
||||
'harvester-vnc-console-settings': { viewOnly: true },
|
||||
'harvester-vnc-console-view': { viewOnly: false },
|
||||
}
|
||||
});
|
||||
|
||||
expect(wrapper.vm.settings.viewOnly).toBe(false);
|
||||
});
|
||||
|
||||
it('should save the settings only once the user changes one, and load them next time', async() => {
|
||||
const wrapper = mountWrapper();
|
||||
|
||||
await wrapper.vm.$nextTick();
|
||||
expect(window.localStorage).toHaveLength(0);
|
||||
|
||||
wrapper.vm.updateSettings({
|
||||
...wrapper.vm.settings, viewMode: 'none', zoomPercent: 150
|
||||
});
|
||||
|
||||
const reopened = mountWrapper({ storage: { 'harvester-vnc-console-view': JSON.parse(window.localStorage.getItem('harvester-vnc-console-view')) } });
|
||||
|
||||
expect(reopened.vm.settings).toMatchObject({ viewMode: 'none', zoomPercent: 150 });
|
||||
});
|
||||
|
||||
it('should keep view only on when the View panel resets its settings', () => {
|
||||
const wrapper = mountWrapper();
|
||||
|
||||
wrapper.vm.setViewOnly(true);
|
||||
wrapper.vm.updateSettings({ ...wrapper.vm.settings, zoomPercent: 150 });
|
||||
wrapper.vm.resetSettings();
|
||||
|
||||
expect(wrapper.vm.settings).toMatchObject({ viewOnly: true, zoomPercent: 100 });
|
||||
expect(wrapper.vm.rfbSettings.viewOnly).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('in full screen', () => {
|
||||
it('should fill the window whatever the saved view mode, and go back to it afterwards', () => {
|
||||
const wrapper = mountWrapper();
|
||||
|
||||
wrapper.vm.updateSettings({ ...wrapper.vm.settings, viewMode: 'none' });
|
||||
expect(wrapper.vm.rfbSettings).toMatchObject({ scaleViewport: false, edgeToEdge: false });
|
||||
|
||||
wrapper.vm.isFullscreen = true;
|
||||
expect(wrapper.vm.rfbSettings).toMatchObject({ scaleViewport: true, edgeToEdge: true });
|
||||
|
||||
wrapper.vm.isFullscreen = false;
|
||||
expect(wrapper.vm.rfbSettings).toMatchObject({ scaleViewport: false, edgeToEdge: false });
|
||||
});
|
||||
|
||||
it('should leave the view only checkbox out of the bar, and keep view only as it was', async() => {
|
||||
const wrapper = mountWrapper();
|
||||
|
||||
wrapper.vm.setViewOnly(true);
|
||||
wrapper.vm.isFullscreen = true;
|
||||
await wrapper.vm.$nextTick();
|
||||
|
||||
expect(wrapper.findComponent(CHECKBOX).exists()).toBe(false);
|
||||
expect(wrapper.vm.rfbSettings.viewOnly).toBe(true);
|
||||
expect(wrapper.vm.shortcutMenuProps.disabled).toBe(true);
|
||||
|
||||
wrapper.vm.isFullscreen = false;
|
||||
await wrapper.vm.$nextTick();
|
||||
|
||||
expect(wrapper.findComponent(CHECKBOX).props('value')).toBe(true);
|
||||
});
|
||||
|
||||
it('should leave Ctrl+Alt+Del out of the bar', async() => {
|
||||
const wrapper = mountWrapper();
|
||||
|
||||
wrapper.vm.isFullscreen = true;
|
||||
await wrapper.vm.$nextTick();
|
||||
|
||||
expect(wrapper.find('[data-testid="vnc-fullscreen-bar"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="vnc-ctrl-alt-del"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="vnc-fullscreen-ctrl-alt-del"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('should put the whole page in full screen, so that dialogs rendered outside the console show', async() => {
|
||||
const wrapper = mountWrapper();
|
||||
const requestFullscreen = jest.fn().mockResolvedValue();
|
||||
|
||||
document.documentElement.requestFullscreen = requestFullscreen;
|
||||
|
||||
await wrapper.vm.toggleFullscreen();
|
||||
|
||||
expect(requestFullscreen).toHaveBeenCalledTimes(1);
|
||||
|
||||
delete document.documentElement.requestFullscreen;
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,91 +0,0 @@
|
||||
import { shallowMount } from '@vue/test-utils';
|
||||
import NovncKeyRecorder from '../NovncKeyRecorder.vue';
|
||||
|
||||
const key = (k, code, extra = {}) => ({
|
||||
key: k, code, keyCode: 0, location: 0, charCode: 0, repeat: false, preventDefault: jest.fn(), stopPropagation: jest.fn(), ...extra
|
||||
});
|
||||
|
||||
describe('component: NovncKeyRecorder', () => {
|
||||
it('should hold modifiers until another key ends the combination', () => {
|
||||
const wrapper = shallowMount(NovncKeyRecorder);
|
||||
|
||||
wrapper.vm.start();
|
||||
wrapper.vm.onKeydown(key('Control', 'ControlLeft'));
|
||||
wrapper.vm.onKeydown(key('Shift', 'ShiftLeft'));
|
||||
wrapper.vm.onKeydown(key('Control', 'ControlLeft', { repeat: true }));
|
||||
wrapper.vm.onKeydown(key('Escape', 'Escape'));
|
||||
|
||||
expect(wrapper.emitted('update:value')[0][0].map((K) => K.code)).toStrictEqual(['ControlLeft', 'ShiftLeft', 'Escape']);
|
||||
expect(wrapper.vm.recording).toBe(false);
|
||||
});
|
||||
|
||||
it('should keep the browser from acting on keys while recording', () => {
|
||||
const wrapper = shallowMount(NovncKeyRecorder);
|
||||
const event = key('w', 'KeyW');
|
||||
|
||||
wrapper.vm.start();
|
||||
wrapper.vm.onKeydown(event);
|
||||
|
||||
expect(event.preventDefault).toHaveBeenCalledWith();
|
||||
});
|
||||
|
||||
it('should record a modifier pressed and released on its own, such as the Windows key', () => {
|
||||
const wrapper = shallowMount(NovncKeyRecorder);
|
||||
|
||||
wrapper.vm.start();
|
||||
wrapper.vm.onKeydown(key('Meta', 'MetaLeft'));
|
||||
wrapper.vm.onKeyup(key('Meta', 'MetaLeft'));
|
||||
|
||||
expect(wrapper.emitted('update:value')[0][0].map((K) => K.code)).toStrictEqual(['MetaLeft']);
|
||||
expect(wrapper.vm.recording).toBe(false);
|
||||
});
|
||||
|
||||
it('should wait for the last modifier to be released before recording them', () => {
|
||||
const wrapper = shallowMount(NovncKeyRecorder);
|
||||
|
||||
wrapper.vm.start();
|
||||
wrapper.vm.onKeydown(key('Control', 'ControlLeft'));
|
||||
wrapper.vm.onKeydown(key('Shift', 'ShiftLeft'));
|
||||
wrapper.vm.onKeyup(key('Shift', 'ShiftLeft', { ctrlKey: true }));
|
||||
expect(wrapper.emitted('update:value')).toBeUndefined();
|
||||
|
||||
wrapper.vm.onKeyup(key('Control', 'ControlLeft'));
|
||||
expect(wrapper.emitted('update:value')[0][0].map((K) => K.code)).toStrictEqual(['ControlLeft', 'ShiftLeft']);
|
||||
});
|
||||
|
||||
it('should drop a combination of modifiers only when it loses focus', () => {
|
||||
const wrapper = shallowMount(NovncKeyRecorder);
|
||||
|
||||
wrapper.vm.start();
|
||||
wrapper.vm.onKeydown(key('Alt', 'AltLeft'));
|
||||
wrapper.vm.stop();
|
||||
|
||||
expect(wrapper.emitted('update:value')).toBeUndefined();
|
||||
expect(wrapper.vm.state).toBe('empty');
|
||||
});
|
||||
|
||||
it('should stop recording on Esc or Tab alone, without recording them', () => {
|
||||
const wrapper = shallowMount(NovncKeyRecorder);
|
||||
const tab = key('Tab', 'Tab');
|
||||
|
||||
wrapper.vm.start();
|
||||
wrapper.vm.onKeydown(key('Escape', 'Escape'));
|
||||
expect(wrapper.vm.recording).toBe(false);
|
||||
|
||||
wrapper.vm.start();
|
||||
wrapper.vm.onKeydown(tab);
|
||||
expect(wrapper.vm.recording).toBe(false);
|
||||
expect(tab.preventDefault).not.toHaveBeenCalled();
|
||||
expect(wrapper.emitted('update:value')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should record a letter by its key, not the symbol a layout made of it', () => {
|
||||
const wrapper = shallowMount(NovncKeyRecorder);
|
||||
|
||||
wrapper.vm.start();
|
||||
wrapper.vm.onKeydown(key('Alt', 'AltLeft'));
|
||||
wrapper.vm.onKeydown(key('©', 'KeyG'));
|
||||
|
||||
expect(wrapper.emitted('update:value')[0][0].map((K) => K.key)).toStrictEqual(['Alt', 'g']);
|
||||
});
|
||||
});
|
||||
@@ -1,158 +0,0 @@
|
||||
import { ref } from 'vue';
|
||||
import { mount, shallowMount } from '@vue/test-utils';
|
||||
import NovncShortcutKeysMenu, { ShortcutMenuBody } from '../NovncShortcutKeysMenu.vue';
|
||||
import {
|
||||
keyLabel, normalizeShortcut, readShortcuts, shortcutLabels, writeShortcuts, SHORTCUTS_PREFERENCE, SHORTCUT_NAMES_PREFERENCE
|
||||
} from '../shortcuts';
|
||||
|
||||
const mountMenu = (props = {}) => shallowMount(NovncShortcutKeysMenu, { props });
|
||||
|
||||
describe('component: NovncShortcutKeysMenu', () => {
|
||||
it('should send a key on its own when no modifier is held', () => {
|
||||
const wrapper = mountMenu();
|
||||
|
||||
wrapper.vm.sendKey('F5');
|
||||
|
||||
expect(wrapper.emitted('send-keys')).toStrictEqual([[['F5']]]);
|
||||
});
|
||||
|
||||
it('should send held modifiers with the next key and then release them', () => {
|
||||
const wrapper = mountMenu();
|
||||
|
||||
wrapper.vm.toggleModifier('AltLeft', true);
|
||||
wrapper.vm.toggleModifier('ControlLeft', true);
|
||||
expect(wrapper.vm.heldCombo).toBe('Ctrl+Alt');
|
||||
|
||||
wrapper.vm.sendKey('F2');
|
||||
|
||||
expect(wrapper.emitted('send-keys')).toStrictEqual([[['ControlLeft', 'AltLeft', 'F2']]]);
|
||||
expect(wrapper.vm.held).toStrictEqual([]);
|
||||
});
|
||||
|
||||
it('should offer the keys that go with what is held, like the old menu', async() => {
|
||||
const wrapper = mountMenu();
|
||||
const keys = () => wrapper.vm.keyOptions.map((K) => K.key);
|
||||
|
||||
expect(keys()).toStrictEqual(['PrintScreen']);
|
||||
expect(wrapper.vm.showFunctionKeys).toBe(true);
|
||||
|
||||
wrapper.vm.toggleModifier('ControlLeft', true);
|
||||
expect(keys()).toStrictEqual(['KeyN', 'KeyT', 'KeyW', 'KeyY']);
|
||||
expect(wrapper.vm.showFunctionKeys).toBe(false);
|
||||
|
||||
wrapper.vm.toggleModifier('AltLeft', true);
|
||||
expect(keys()).toStrictEqual(['Delete']);
|
||||
expect(wrapper.vm.showFunctionKeys).toBe(true);
|
||||
|
||||
wrapper.vm.toggleModifier('ControlLeft', false);
|
||||
expect(keys()).toStrictEqual(['PrintScreen']);
|
||||
expect(wrapper.vm.showFunctionKeys).toBe(true);
|
||||
});
|
||||
|
||||
it('should send Ctrl+W from the menu', () => {
|
||||
const wrapper = mountMenu();
|
||||
|
||||
wrapper.vm.toggleModifier('ControlLeft', true);
|
||||
wrapper.vm.sendKey('KeyW');
|
||||
|
||||
expect(wrapper.emitted('send-keys')).toStrictEqual([[['ControlLeft', 'KeyW']]]);
|
||||
});
|
||||
|
||||
it('should hand Ctrl+Alt+Del to the confirmation instead of sending it', () => {
|
||||
const wrapper = mountMenu();
|
||||
|
||||
wrapper.vm.toggleModifier('ControlLeft', true);
|
||||
wrapper.vm.toggleModifier('AltLeft', true);
|
||||
wrapper.vm.sendKey('Delete');
|
||||
|
||||
expect(wrapper.emitted('ctrl-alt-del')).toHaveLength(1);
|
||||
expect(wrapper.emitted('send-keys')).toBeUndefined();
|
||||
expect(wrapper.vm.held).toStrictEqual([]);
|
||||
});
|
||||
|
||||
it('should let held modifiers go when the menu closes without a key', () => {
|
||||
const wrapper = mountMenu();
|
||||
|
||||
wrapper.vm.toggleModifier('ControlLeft', true);
|
||||
wrapper.vm.onOpen(false);
|
||||
|
||||
expect(wrapper.vm.held).toStrictEqual([]);
|
||||
});
|
||||
|
||||
it('should name saved shortcuts by their keys when they have no name', () => {
|
||||
const wrapper = mountMenu({
|
||||
shortcuts: [
|
||||
{ name: 'Open terminal', keys: [{ key: 'Control' }, { key: 'Alt' }, { key: 't' }] },
|
||||
{ name: '', keys: [{ key: 'Escape' }] },
|
||||
]
|
||||
});
|
||||
|
||||
expect(wrapper.vm.items.map(({ name, label }) => [name, label])).toStrictEqual([
|
||||
['Open terminal', 'Ctrl+Alt+T'],
|
||||
['Esc', 'Esc'],
|
||||
]);
|
||||
});
|
||||
|
||||
it('should give the arrow keys the items shown after a modifier swapped them', async() => {
|
||||
const dropdownItems = ref([]);
|
||||
const keys = ref(['PrintScreen']);
|
||||
const wrapper = mount({
|
||||
components: { ShortcutMenuBody },
|
||||
setup: () => ({ keys }),
|
||||
template: '<div dropdown-menu-collection><shortcut-menu-body><div v-for="key in keys" :key="key" dropdown-menu-item>{{ key }}</div></shortcut-menu-body></div>',
|
||||
}, { global: { provide: { dropdownContext: { dropdownItems } } } });
|
||||
|
||||
keys.value = ['KeyN', 'KeyT'];
|
||||
await wrapper.vm.$nextTick();
|
||||
await wrapper.find('[dropdown-menu-item]').trigger('keydown', { key: 'ArrowDown' });
|
||||
|
||||
expect(dropdownItems.value.map((item) => item.textContent)).toStrictEqual(['KeyN', 'KeyT']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('shortcuts', () => {
|
||||
it('should read both the old list format and the named format', () => {
|
||||
const keys = [{ key: 'Control', code: 'ControlLeft' }];
|
||||
|
||||
expect(normalizeShortcut(keys)).toStrictEqual({ name: '', keys });
|
||||
expect(normalizeShortcut({ name: 'Task manager', keys })).toStrictEqual({ name: 'Task manager', keys });
|
||||
expect(normalizeShortcut({ name: 'Broken' })).toStrictEqual({ name: 'Broken', keys: [] });
|
||||
});
|
||||
|
||||
it('should label keys the way the console menus show them', () => {
|
||||
expect(keyLabel('Control')).toBe('Ctrl');
|
||||
expect(keyLabel('a')).toBe('A');
|
||||
expect(keyLabel('F2')).toBe('F2');
|
||||
expect(shortcutLabels({ keys: [{ key: 'Shift' }, { key: ' ' }] })).toStrictEqual(['Shift', 'Space']);
|
||||
expect(shortcutLabels({ keys: [{ key: 'Alt', code: 'AltLeft' }, { key: '©', code: 'KeyG' }] })).toStrictEqual(['Alt', 'G']);
|
||||
// Real keys of other layouts stay as typed: AZERTY comma on KeyM, Windows AltGr (Ctrl+Alt) letters.
|
||||
expect(shortcutLabels({ keys: [{ key: 'Control', code: 'ControlLeft' }, { key: ',', code: 'KeyM' }] })).toStrictEqual(['Ctrl', ',']);
|
||||
expect(shortcutLabels({ keys: [{ key: 'Control', code: 'ControlLeft' }, { key: 'Alt', code: 'AltRight' }, { key: 'ą', code: 'KeyA' }] })).toStrictEqual(['Ctrl', 'Alt', 'Ą']);
|
||||
expect(shortcutLabels({ keys: [{ key: 'Alt', code: 'AltLeft' }, { key: 'Dead', code: 'KeyE' }] })).toStrictEqual(['Alt', 'E']);
|
||||
});
|
||||
|
||||
it('should keep the key list in the format older versions read and store names apart', async() => {
|
||||
const keys = [{ key: 'Control', code: 'ControlLeft' }, { key: 't', code: 'KeyT' }];
|
||||
const preference = { data: {}, save: jest.fn().mockResolvedValue() };
|
||||
|
||||
await writeShortcuts(preference, [{ name: 'Open terminal', keys }, { name: '', keys: [{ key: 'F2', code: 'F2' }] }]);
|
||||
|
||||
expect(JSON.parse(preference.data[SHORTCUTS_PREFERENCE])).toStrictEqual([keys, [{ key: 'F2', code: 'F2' }]]);
|
||||
expect(JSON.parse(preference.data[SHORTCUT_NAMES_PREFERENCE])).toStrictEqual({ 'ControlLeft+KeyT': 'Open terminal' });
|
||||
expect(readShortcuts(preference).map((shortcut) => shortcut.name)).toStrictEqual(['Open terminal', '']);
|
||||
});
|
||||
|
||||
it('should put the preference back when the save fails', async() => {
|
||||
const saved = JSON.stringify([[{ key: 'F2', code: 'F2' }]]);
|
||||
const preference = { data: { [SHORTCUTS_PREFERENCE]: saved }, save: jest.fn().mockRejectedValue(new Error('403')) };
|
||||
|
||||
await expect(writeShortcuts(preference, [])).rejects.toThrow('403');
|
||||
|
||||
expect(preference.data).toStrictEqual({ [SHORTCUTS_PREFERENCE]: saved });
|
||||
});
|
||||
|
||||
it('should read nothing from a preference it cannot parse', () => {
|
||||
expect(readShortcuts({ data: { [SHORTCUTS_PREFERENCE]: '{not json' } })).toStrictEqual([]);
|
||||
expect(readShortcuts(undefined)).toStrictEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,36 +0,0 @@
|
||||
import { shallowMount } from '@vue/test-utils';
|
||||
import NovncViewOptions, { VIEW_MODE } from '../NovncViewOptions.vue';
|
||||
|
||||
jest.mock('../ZoomableRFB', () => ({
|
||||
MINIMUM_ZOOM: 50, MAXIMUM_ZOOM: 200, ZOOM_STEP: 10
|
||||
}));
|
||||
|
||||
const settings = {
|
||||
viewMode: VIEW_MODE.NONE, zoomPercent: 100, qualityLevel: 6, compressionLevel: 2
|
||||
};
|
||||
|
||||
const mountOptions = (overrides = {}) => shallowMount(NovncViewOptions, { props: { settings: { ...settings, ...overrides } } });
|
||||
|
||||
describe('component: NovncViewOptions', () => {
|
||||
it('should emit the whole settings object with the changed value', () => {
|
||||
const wrapper = mountOptions();
|
||||
|
||||
wrapper.vm.update('qualityLevel', 9);
|
||||
|
||||
expect(wrapper.emitted('update')).toStrictEqual([[{ ...settings, qualityLevel: 9 }]]);
|
||||
});
|
||||
|
||||
it('should step the zoom and stop at its limits', () => {
|
||||
const wrapper = mountOptions({ zoomPercent: 200 });
|
||||
|
||||
wrapper.vm.stepZoom(1);
|
||||
wrapper.vm.stepZoom(-1);
|
||||
|
||||
expect(wrapper.emitted('update').map(([value]) => value.zoomPercent)).toStrictEqual([200, 190]);
|
||||
});
|
||||
|
||||
it('should only treat the manual mode as manual', () => {
|
||||
expect(mountOptions().vm.isManual).toBe(true);
|
||||
expect(mountOptions({ viewMode: VIEW_MODE.SCALE }).vm.isManual).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,109 +0,0 @@
|
||||
import ZoomableRFB from '../ZoomableRFB';
|
||||
|
||||
const GUEST_POINTER = 'url(guest-pointer) 0 0, default';
|
||||
|
||||
jest.mock('@novnc/novnc/core/rfb', () => ({
|
||||
__esModule: true,
|
||||
default: class {
|
||||
constructor() {
|
||||
this.scaleViewport = true;
|
||||
this._canvas = { style: {} };
|
||||
this._cursorImage = { rgbaPixels: new Uint8Array() };
|
||||
this._display = { autoscale: jest.fn() };
|
||||
}
|
||||
|
||||
_screenSize() {
|
||||
return { w: 1000, h: 500 };
|
||||
}
|
||||
|
||||
_fixScrollbars() {}
|
||||
|
||||
_handleMouse(ev) {
|
||||
ev.stopPropagation();
|
||||
}
|
||||
|
||||
// As noVNC does: nothing visible hides the mouse, an image is shown as the pointer.
|
||||
_refreshCursor() {
|
||||
this._canvas.style.cursor = this._cursorImage.rgbaPixels.length ? 'url(guest-pointer) 0 0, default' : 'none';
|
||||
}
|
||||
},
|
||||
}), { virtual: true });
|
||||
|
||||
describe('zoomableRFB', () => {
|
||||
describe('the pointer over the screen', () => {
|
||||
it('should be the system one while the guest sends no pointer image', () => {
|
||||
const rfb = new ZoomableRFB();
|
||||
|
||||
rfb._refreshCursor();
|
||||
|
||||
expect(rfb._canvas.style.cursor).toBe('default');
|
||||
});
|
||||
|
||||
it('should be the system one when the image the guest sends is fully transparent', () => {
|
||||
const rfb = new ZoomableRFB();
|
||||
|
||||
rfb._cursorImage = { rgbaPixels: new Uint8Array([255, 255, 255, 0, 0, 0, 0, 0]) };
|
||||
rfb._refreshCursor();
|
||||
|
||||
expect(rfb._canvas.style.cursor).toBe('default');
|
||||
});
|
||||
|
||||
it('should be the one the guest sends when it has visible pixels', () => {
|
||||
const rfb = new ZoomableRFB();
|
||||
|
||||
rfb._cursorImage = { rgbaPixels: new Uint8Array([0, 0, 0, 0, 0, 0, 0, 255]) };
|
||||
rfb._refreshCursor();
|
||||
|
||||
expect(rfb._canvas.style.cursor).toBe(GUEST_POINTER);
|
||||
});
|
||||
|
||||
it('should go back to the system one when the guest stops sending an image', () => {
|
||||
const rfb = new ZoomableRFB();
|
||||
|
||||
rfb._cursorImage = { rgbaPixels: new Uint8Array([0, 0, 0, 255]) };
|
||||
rfb._refreshCursor();
|
||||
rfb._cursorImage = { rgbaPixels: [] };
|
||||
rfb._refreshCursor();
|
||||
|
||||
expect(rfb._canvas.style.cursor).toBe('default');
|
||||
});
|
||||
});
|
||||
|
||||
describe('mouse events on the screen', () => {
|
||||
it('should let a click through, so an open menu sees it as a click outside', () => {
|
||||
const rfb = new ZoomableRFB();
|
||||
const stopPropagation = jest.fn();
|
||||
|
||||
rfb._handleMouse({ type: 'click', stopPropagation });
|
||||
|
||||
expect(stopPropagation).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should leave the others to noVNC', () => {
|
||||
const rfb = new ZoomableRFB();
|
||||
const stopPropagation = jest.fn();
|
||||
|
||||
rfb._handleMouse({ type: 'mousedown', stopPropagation });
|
||||
|
||||
expect(stopPropagation).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the fitted screen', () => {
|
||||
it('should keep room for the focus ring', () => {
|
||||
const rfb = new ZoomableRFB();
|
||||
|
||||
rfb._updateScale();
|
||||
|
||||
expect(rfb._display.autoscale).toHaveBeenLastCalledWith(992, 492);
|
||||
});
|
||||
|
||||
it('should take all the room when it is edge to edge', () => {
|
||||
const rfb = new ZoomableRFB();
|
||||
|
||||
rfb.edgeToEdge = true;
|
||||
|
||||
expect(rfb._display.autoscale).toHaveBeenLastCalledWith(1000, 500);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,118 +0,0 @@
|
||||
// Saved custom shortcuts live in the Rancher user preference, which every Harvester UI the user opens
|
||||
// shares. The keys stay a list of recorded keydown events per shortcut, the format older versions read;
|
||||
// names go in a separate preference so those versions keep working.
|
||||
export const SHORTCUTS_PREFERENCE = 'prefered-shortcut-keys';
|
||||
export const SHORTCUT_NAMES_PREFERENCE = 'vnc-shortcut-names';
|
||||
|
||||
const KEY_LABELS = {
|
||||
Control: 'Ctrl',
|
||||
Escape: 'Esc',
|
||||
Delete: 'Del',
|
||||
' ': 'Space',
|
||||
};
|
||||
|
||||
export const MODIFIER_KEYS = ['Control', 'Shift', 'Alt', 'Meta'];
|
||||
|
||||
export function keyLabel(key = '') {
|
||||
if (KEY_LABELS[key]) {
|
||||
return KEY_LABELS[key];
|
||||
}
|
||||
|
||||
return key.length === 1 ? key.toUpperCase() : key;
|
||||
}
|
||||
|
||||
// macOS Option turns a letter into a symbol (Option+G gives ©, Option+E a dead key). The key that was
|
||||
// pressed is still in `code`, so in that case the letter is named after it. Only with Alt and no Ctrl:
|
||||
// AZERTY's comma on KeyM, Dvorak's punctuation or Cyrillic letters are real keys, and Windows AltGr
|
||||
// reports Ctrl+Alt with a real character.
|
||||
export function baseKey(K, combination = []) {
|
||||
const letter = /^Key([A-Z])$/.exec(K?.code || '');
|
||||
|
||||
if (!letter || /^[a-z]$/i.test(K.key || '')) {
|
||||
return K;
|
||||
}
|
||||
|
||||
const held = combination.map((M) => M.key);
|
||||
const isOptionSymbol = held.includes('Alt') && !held.includes('Control');
|
||||
|
||||
return K.key === 'Dead' || isOptionSymbol ? { ...K, key: letter[1].toLowerCase() } : K;
|
||||
}
|
||||
|
||||
export function normalizeShortcut(item) {
|
||||
if (Array.isArray(item)) {
|
||||
return { name: '', keys: item };
|
||||
}
|
||||
|
||||
return { name: item?.name || '', keys: Array.isArray(item?.keys) ? item.keys : [] };
|
||||
}
|
||||
|
||||
export function shortcutLabels(shortcut) {
|
||||
const keys = shortcut?.keys || [];
|
||||
|
||||
return keys.map((K) => keyLabel(baseKey(K, keys).key));
|
||||
}
|
||||
|
||||
// Two shortcuts are the same when they press the same keys, whatever they are called.
|
||||
export function shortcutId(shortcut) {
|
||||
return (shortcut?.keys || []).map((K) => K.code || K.key).join('+');
|
||||
}
|
||||
|
||||
// Only what sending a shortcut needs, so a recorded KeyboardEvent can be stored.
|
||||
export function recordKey(event, combination = []) {
|
||||
const {
|
||||
key, keyCode, code, location, charCode
|
||||
} = event;
|
||||
|
||||
return baseKey({
|
||||
key, keyCode, code, location, charCode
|
||||
}, combination);
|
||||
}
|
||||
|
||||
function parse(value, fallback) {
|
||||
try {
|
||||
return value ? JSON.parse(value) : fallback;
|
||||
} catch (err) {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
export function readShortcuts(preference) {
|
||||
const list = parse(preference?.data?.[SHORTCUTS_PREFERENCE], []);
|
||||
const names = parse(preference?.data?.[SHORTCUT_NAMES_PREFERENCE], {});
|
||||
|
||||
return (Array.isArray(list) ? list : [])
|
||||
.map(normalizeShortcut)
|
||||
.filter((shortcut) => shortcut.keys.length)
|
||||
.map((shortcut) => ({ ...shortcut, name: shortcut.name || names?.[shortcutId(shortcut)] || '' }));
|
||||
}
|
||||
|
||||
export function writeShortcuts(preference, shortcuts) {
|
||||
const names = {};
|
||||
|
||||
shortcuts.forEach((shortcut) => {
|
||||
if (shortcut.name) {
|
||||
names[shortcutId(shortcut)] = shortcut.name;
|
||||
}
|
||||
});
|
||||
|
||||
const previous = {
|
||||
[SHORTCUTS_PREFERENCE]: preference.data[SHORTCUTS_PREFERENCE],
|
||||
[SHORTCUT_NAMES_PREFERENCE]: preference.data[SHORTCUT_NAMES_PREFERENCE],
|
||||
};
|
||||
|
||||
preference.data[SHORTCUTS_PREFERENCE] = JSON.stringify(shortcuts.map((shortcut) => shortcut.keys));
|
||||
preference.data[SHORTCUT_NAMES_PREFERENCE] = JSON.stringify(names);
|
||||
|
||||
// The lists read straight from the preference, so a failed save must not leave the change showing.
|
||||
return preference.save().catch((err) => {
|
||||
Object.entries(previous).forEach(([key, value]) => {
|
||||
if (value === undefined) {
|
||||
delete preference.data[key];
|
||||
} else {
|
||||
preference.data[key] = value;
|
||||
}
|
||||
});
|
||||
|
||||
throw err;
|
||||
});
|
||||
}
|
||||
@@ -19,8 +19,7 @@ export default {
|
||||
<div class="row mb-20">
|
||||
<div class="col span-12">
|
||||
<FileSelector
|
||||
variant="primary"
|
||||
class="mb-10"
|
||||
class="btn btn-sm bg-primary mb-10"
|
||||
:label="t('generic.readFromFile')"
|
||||
@selected="onKeySelected"
|
||||
/>
|
||||
|
||||
@@ -191,8 +191,7 @@ export default {
|
||||
>
|
||||
<div class="col span-12">
|
||||
<FileSelector
|
||||
variant="primary"
|
||||
class="mb-10"
|
||||
class="btn btn-sm bg-primary mb-10"
|
||||
:label="t('generic.readFromFile')"
|
||||
@selected="onKeySelected"
|
||||
/>
|
||||
@@ -214,7 +213,9 @@ $yaml-height: 540px;
|
||||
:deep() .yaml-editor{
|
||||
flex: 1;
|
||||
min-height: $yaml-height;
|
||||
& .code-mirror .cm-editor {
|
||||
& .code-mirror .CodeMirror {
|
||||
position: initial;
|
||||
height: auto;
|
||||
min-height: $yaml-height;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { LabeledInput } from '@components/Form/LabeledInput';
|
||||
import LabeledSelect from '@shell/components/form/LabeledSelect.vue';
|
||||
import { RadioGroup } from '@components/Form/Radio';
|
||||
import ArrayList from '@shell/components/form/ArrayList';
|
||||
import { isValidCIDR } from '@pkg/harvester/utils/regular';
|
||||
import { isValidCIDR } from '@shell/utils/validators/cidr';
|
||||
import { _EDIT } from '@shell/config/query-params';
|
||||
import { Banner } from '@components/Banner';
|
||||
import { allHash } from '@shell/utils/promise';
|
||||
|
||||
@@ -62,8 +62,7 @@ export default {
|
||||
<div class="chooseFile">
|
||||
<FileSelector
|
||||
:include-file-name="true"
|
||||
variant="primary"
|
||||
class="mr-20"
|
||||
class="btn btn-sm bg-primary mr-20"
|
||||
label="Choose File"
|
||||
@selected="onKeySelectedCa('publicCertificate', $event)"
|
||||
/>
|
||||
@@ -81,8 +80,7 @@ export default {
|
||||
<div class="chooseFile">
|
||||
<FileSelector
|
||||
:include-file-name="true"
|
||||
variant="primary"
|
||||
class="mr-20"
|
||||
class="btn btn-sm bg-primary mr-20"
|
||||
label="Choose File"
|
||||
@selected="onKeySelectedCa('privateKey', $event)"
|
||||
/>
|
||||
@@ -100,8 +98,7 @@ export default {
|
||||
<div class="chooseFile">
|
||||
<FileSelector
|
||||
:include-file-name="true"
|
||||
variant="primary"
|
||||
class="mr-20"
|
||||
class="btn btn-sm bg-primary 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 '@pkg/harvester/utils/regular';
|
||||
import { isValidCIDR } from '@shell/utils/validators/cidr';
|
||||
import { _EDIT } from '@shell/config/query-params';
|
||||
import { Banner } from '@components/Banner';
|
||||
import Tip from '@shell/components/Tip';
|
||||
|
||||
@@ -5,7 +5,7 @@ import { RadioGroup } from '@components/Form/Radio';
|
||||
import { Banner } from '@components/Banner';
|
||||
import ArrayList from '@shell/components/form/ArrayList';
|
||||
import { allHash } from '@shell/utils/promise';
|
||||
import { isValidCIDR } from '@pkg/harvester/utils/regular';
|
||||
import { isValidCIDR } from '@shell/utils/validators/cidr';
|
||||
import { NODE } from '@shell/config/types';
|
||||
import { _EDIT } from '@shell/config/query-params';
|
||||
import { HCI } from '../../types';
|
||||
|
||||
@@ -56,7 +56,6 @@ const FEATURE_FLAGS = {
|
||||
'kubevirtMigration',
|
||||
'hotplugNic',
|
||||
'resumeUpgradePausedNode',
|
||||
'vncPreserveSession',
|
||||
],
|
||||
'v1.7.1': [],
|
||||
'v1.8.0': [
|
||||
@@ -78,15 +77,6 @@ const FEATURE_FLAGS = {
|
||||
'staticIPForVM',
|
||||
'fsFreezeDeadline',
|
||||
],
|
||||
'v1.9.1': [
|
||||
'lvmDmThinOnly',
|
||||
'highPerformanceStorage',
|
||||
],
|
||||
'v1.10.0': [
|
||||
'maintenanceModeConditions',
|
||||
'maintenanceModeDrainTimeoutSetting',
|
||||
'componentHealth',
|
||||
],
|
||||
};
|
||||
|
||||
const generateFeatureFlags = () => {
|
||||
|
||||
@@ -57,12 +57,7 @@ import {
|
||||
} from './table-headers';
|
||||
import { ADD_ONS } from './harvester-map';
|
||||
import { registerAddonSideNav } from '../utils/dynamic-nav';
|
||||
import { setStandalonePrime } from '../utils/l10n-globals';
|
||||
import { setVendor } from '@shell/config/private-label';
|
||||
import { 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';
|
||||
@@ -116,16 +111,14 @@ export function init($plugin, store) {
|
||||
};
|
||||
|
||||
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);
|
||||
(_state, getters) => ({
|
||||
isHarvesterPrime: !!getters['harvester-common/isHarvesterPrime'],
|
||||
isDark: getters['prefs/theme'] === 'dark',
|
||||
privateLabel: getters['harvester-common/privateLabel']
|
||||
}),
|
||||
({ isHarvesterPrime, isDark, privateLabel }) => {
|
||||
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';
|
||||
@@ -142,30 +135,6 @@ export function init($plugin, store) {
|
||||
},
|
||||
{ immediate: true }
|
||||
);
|
||||
|
||||
// Keep the shell's table views off: they drop the filters the lists put in the table header
|
||||
store.watch(
|
||||
(_state, getters) => getters['management/byId'](MANAGEMENT.FEATURE, CONFIGURABLE_TABLES),
|
||||
(feature) => {
|
||||
if (!feature) {
|
||||
store.dispatch('management/load', { data: tableViewsOffFeature() });
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
);
|
||||
|
||||
const updateBrand = primeBrandUpdater();
|
||||
|
||||
// The value is read too: a change event from the server is loaded into the same setting object
|
||||
store.watch(
|
||||
(_state, getters) => {
|
||||
const brandSetting = getters['management/byId'](MANAGEMENT.SETTING, SETTING.BRAND);
|
||||
|
||||
return [!!getters['harvester-common/isHarvesterPrime'], brandSetting, brandSetting?.value];
|
||||
},
|
||||
([isHarvesterPrime, brandSetting]) => updateBrand(brandSetting, isHarvesterPrime),
|
||||
{ immediate: true }
|
||||
);
|
||||
}
|
||||
|
||||
product({
|
||||
@@ -710,24 +679,16 @@ export function init($plugin, store) {
|
||||
|
||||
basicType(
|
||||
[
|
||||
TEMPLATE,
|
||||
HCI.SSH,
|
||||
HCI.CLOUD_TEMPLATE,
|
||||
HCI.STORAGE,
|
||||
HCI.SR_IOV,
|
||||
HCI.PCI_DEVICE,
|
||||
HCI.SR_IOVGPU_DEVICE,
|
||||
HCI.VGPU_DEVICE,
|
||||
HCI.MIG_CONFIGURATION,
|
||||
HCI.USB_DEVICE,
|
||||
],
|
||||
'hardwareDevices'
|
||||
);
|
||||
|
||||
weightGroup('hardwareDevices', 488, true);
|
||||
|
||||
basicType(
|
||||
[
|
||||
TEMPLATE,
|
||||
HCI.SSH,
|
||||
HCI.CLOUD_TEMPLATE,
|
||||
HCI.STORAGE,
|
||||
HCI.ADD_ONS,
|
||||
HCI.SECRET,
|
||||
HCI.SETTING
|
||||
@@ -1125,7 +1086,7 @@ export function init($plugin, store) {
|
||||
|
||||
virtualType({
|
||||
label: 'PCI Devices',
|
||||
group: 'hardwareDevices',
|
||||
group: 'advanced',
|
||||
weight: 14,
|
||||
name: HCI.PCI_DEVICE,
|
||||
namespaced: false,
|
||||
@@ -1161,7 +1122,7 @@ export function init($plugin, store) {
|
||||
virtualType({
|
||||
ifHaveType: HCI.SR_IOV,
|
||||
labelKey: 'harvester.sriov.label',
|
||||
group: 'hardwareDevices',
|
||||
group: 'advanced',
|
||||
weight: 15,
|
||||
name: HCI.SR_IOV,
|
||||
namespaced: false,
|
||||
@@ -1181,7 +1142,7 @@ export function init($plugin, store) {
|
||||
virtualType({
|
||||
ifHaveType: HCI.SR_IOVGPU_DEVICE,
|
||||
labelKey: 'harvester.sriovgpu.label',
|
||||
group: 'hardwareDevices',
|
||||
group: 'advanced',
|
||||
weight: 13,
|
||||
name: HCI.SR_IOVGPU_DEVICE,
|
||||
namespaced: false,
|
||||
@@ -1200,7 +1161,7 @@ export function init($plugin, store) {
|
||||
|
||||
virtualType({
|
||||
labelKey: 'harvester.vgpu.label',
|
||||
group: 'hardwareDevices',
|
||||
group: 'advanced',
|
||||
weight: 12,
|
||||
name: HCI.VGPU_DEVICE,
|
||||
namespaced: false,
|
||||
@@ -1228,7 +1189,7 @@ export function init($plugin, store) {
|
||||
|
||||
virtualType({
|
||||
labelKey: 'harvester.migconfiguration.label',
|
||||
group: 'hardwareDevices',
|
||||
group: 'advanced',
|
||||
weight: 12,
|
||||
name: HCI.MIG_CONFIGURATION,
|
||||
namespaced: false,
|
||||
@@ -1248,7 +1209,7 @@ export function init($plugin, store) {
|
||||
|
||||
virtualType({
|
||||
labelKey: 'harvester.usb.label',
|
||||
group: 'hardwareDevices',
|
||||
group: 'advanced',
|
||||
weight: 11,
|
||||
name: HCI.USB_DEVICE,
|
||||
namespaced: false,
|
||||
|
||||
@@ -39,21 +39,6 @@ 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',
|
||||
|
||||
@@ -22,7 +22,7 @@ export const HCI = {
|
||||
VM_NAME_PREFIX: 'harvesterhci.io/vmNamePrefix',
|
||||
VM_DISPLAY_NAME: 'harvesterhci.io/vmDisplayName',
|
||||
VM_RESERVED_MEMORY: 'harvesterhci.io/reservedMemory',
|
||||
MAINTENANCE_STATUS: 'harvesterhci.io/maintain-status', // Deprecated >= v1.10.0
|
||||
MAINTENANCE_STATUS: 'harvesterhci.io/maintain-status',
|
||||
HOST_CUSTOM_NAME: 'harvesterhci.io/host-custom-name',
|
||||
HOST_CONSOLE_URL: 'harvesterhci.io/host-console-url',
|
||||
RESTORE_NAME: 'restore.harvesterhci.io/name',
|
||||
@@ -33,11 +33,6 @@ export const HCI = {
|
||||
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',
|
||||
|
||||
@@ -3,7 +3,6 @@ export const HCI_SETTING = {
|
||||
CONTAINERD_REGISTRY: 'containerd-registry',
|
||||
LOG_LEVEL: 'log-level',
|
||||
SERVER_VERSION: 'server-version',
|
||||
SERVER_FLAVOR: 'server-flavor',
|
||||
UI_INDEX: 'ui-index',
|
||||
UPGRADE_CHECKER_ENABLED: 'upgrade-checker-enabled',
|
||||
UPGRADE_CHECKER_URL: 'upgrade-checker-url',
|
||||
@@ -45,8 +44,7 @@ export const HCI_SETTING = {
|
||||
MAX_HOTPLUG_RATIO: 'max-hotplug-ratio',
|
||||
KUBEVIRT_MIGRATION: 'kubevirt-migration',
|
||||
INSTANCE_MANAGER_RESOURCES: 'instance-manager-resources',
|
||||
CLUSTER_POD_SECURITY_STANDARD: 'cluster-pod-security-standard',
|
||||
MAINTENANCE_MODE_DRAIN_TIMEOUT: 'maintenance-mode-drain-timeout'
|
||||
CLUSTER_POD_SECURITY_STANDARD: 'cluster-pod-security-standard'
|
||||
};
|
||||
|
||||
export const HCI_ALLOWED_SETTINGS = {
|
||||
@@ -70,7 +68,6 @@ export const HCI_ALLOWED_SETTINGS = {
|
||||
kind: 'json', from: 'import', featureFlag: 'csiOnlineExpandValidation'
|
||||
},
|
||||
[HCI_SETTING.SERVER_VERSION]: { readOnly: true },
|
||||
[HCI_SETTING.SERVER_FLAVOR]: { readOnly: true },
|
||||
[HCI_SETTING.UPGRADE_CHECKER_ENABLED]: { kind: 'boolean' },
|
||||
[HCI_SETTING.UPGRADE_CHECKER_URL]: { kind: 'url' },
|
||||
[HCI_SETTING.HTTP_PROXY]: { kind: 'json', from: 'import' },
|
||||
@@ -149,9 +146,6 @@ export const HCI_ALLOWED_SETTINGS = {
|
||||
},
|
||||
[HCI_SETTING.CLUSTER_POD_SECURITY_STANDARD]: {
|
||||
kind: 'json', from: 'import', canReset: true, featureFlag: 'clusterPodSecurityStandardSetting'
|
||||
},
|
||||
[HCI_SETTING.MAINTENANCE_MODE_DRAIN_TIMEOUT]: {
|
||||
kind: 'number', canReset: true, featureFlag: 'maintenanceModeDrainTimeoutSetting'
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -15,7 +15,6 @@ import OverviewKeypairs from '../kubevirt.io.virtualmachine/VirtualMachineTabs/V
|
||||
import Volume from '../../edit/kubevirt.io.virtualmachine/VirtualMachineVolume';
|
||||
import Network from '../../edit/kubevirt.io.virtualmachine/VirtualMachineNetwork';
|
||||
import CloudConfig from '../../edit/kubevirt.io.virtualmachine/VirtualMachineCloudConfig';
|
||||
import { getBootDevices } from '../../utils/vm';
|
||||
const UNDEFINED = 'n/a';
|
||||
|
||||
export default {
|
||||
@@ -75,8 +74,18 @@ export default {
|
||||
return image?.spec?.displayName || '-';
|
||||
},
|
||||
|
||||
bootDevices() {
|
||||
return getBootDevices(this?.spec?.template?.spec?.domain?.devices);
|
||||
disks() {
|
||||
const disks = this?.spec?.template?.spec?.domain?.devices?.disks || [];
|
||||
|
||||
return disks.filter((disk) => {
|
||||
return !!disk.bootOrder;
|
||||
}).sort((a, b) => {
|
||||
if (a.bootOrder < b.bootOrder) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
return 1;
|
||||
});
|
||||
},
|
||||
|
||||
cdroms() {
|
||||
@@ -92,10 +101,8 @@ export default {
|
||||
getDeviceType(o) {
|
||||
if (o.disk) {
|
||||
return 'Disk';
|
||||
} else if (o.cdrom) {
|
||||
return 'CD-ROM';
|
||||
} else {
|
||||
return 'Network';
|
||||
return 'CD-ROM';
|
||||
}
|
||||
},
|
||||
isEmpty(o) {
|
||||
@@ -177,10 +184,10 @@ export default {
|
||||
<div>
|
||||
<ul>
|
||||
<li
|
||||
v-for="(device, i) in bootDevices"
|
||||
v-for="(disk, i) in disks"
|
||||
:key="i"
|
||||
>
|
||||
{{ device.bootOrder }}. {{ device.name }} ({{ getDeviceType(device) }})
|
||||
{{ disk.bootOrder }}. {{ disk.name }} ({{ getDeviceType(disk) }})
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
@@ -226,7 +233,6 @@ export default {
|
||||
>
|
||||
<Network
|
||||
v-model:value="networkRows"
|
||||
:network-boot-first="networkBootFirst"
|
||||
:mode="mode"
|
||||
/>
|
||||
</Tab>
|
||||
|
||||
@@ -15,7 +15,6 @@ import OverviewKeypairs from '../kubevirt.io.virtualmachine/VirtualMachineTabs/V
|
||||
import Volume from '../../edit/kubevirt.io.virtualmachine/VirtualMachineVolume';
|
||||
import Network from '../../edit/kubevirt.io.virtualmachine/VirtualMachineNetwork';
|
||||
import CloudConfig from '../../edit/kubevirt.io.virtualmachine/VirtualMachineCloudConfig';
|
||||
import { getBootDevices } from '../../utils/vm';
|
||||
const UNDEFINED = 'n/a';
|
||||
|
||||
export default {
|
||||
@@ -75,8 +74,18 @@ export default {
|
||||
return image?.spec?.displayName || '-';
|
||||
},
|
||||
|
||||
bootDevices() {
|
||||
return getBootDevices(this?.spec?.template?.spec?.domain?.devices);
|
||||
disks() {
|
||||
const disks = this?.spec?.template?.spec?.domain?.devices?.disks || [];
|
||||
|
||||
return disks.filter((disk) => {
|
||||
return !!disk.bootOrder;
|
||||
}).sort((a, b) => {
|
||||
if (a.bootOrder < b.bootOrder) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
return 1;
|
||||
});
|
||||
},
|
||||
|
||||
cdroms() {
|
||||
@@ -92,10 +101,8 @@ export default {
|
||||
getDeviceType(o) {
|
||||
if (o.disk) {
|
||||
return 'Disk';
|
||||
} else if (o.cdrom) {
|
||||
return 'CD-ROM';
|
||||
} else {
|
||||
return 'Network';
|
||||
return 'CD-ROM';
|
||||
}
|
||||
},
|
||||
isEmpty(o) {
|
||||
@@ -177,10 +184,10 @@ export default {
|
||||
<div>
|
||||
<ul>
|
||||
<li
|
||||
v-for="(device, i) in bootDevices"
|
||||
v-for="(disk, i) in disks"
|
||||
:key="i"
|
||||
>
|
||||
{{ device.bootOrder }}. {{ device.name }} ({{ getDeviceType(device) }})
|
||||
{{ disk.bootOrder }}. {{ disk.name }} ({{ getDeviceType(disk) }})
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
@@ -227,7 +234,6 @@ export default {
|
||||
>
|
||||
<Network
|
||||
v-model:value="networkRows"
|
||||
:network-boot-first="networkBootFirst"
|
||||
:mode="mode"
|
||||
/>
|
||||
</Tab>
|
||||
|
||||
+16
-9
@@ -6,7 +6,6 @@ import HarvesterIpAddress from '../../../formatters/HarvesterIpAddress';
|
||||
import VMConsoleBar from '../../../components/VMConsoleBar';
|
||||
import { HCI } from '../../../types';
|
||||
import { getVmCPUMemoryValues } from '../../../utils/cpuMemory';
|
||||
import { getBootDevices } from '../../../utils/vm';
|
||||
|
||||
const UNDEFINED = 'n/a';
|
||||
|
||||
@@ -70,8 +69,18 @@ export default {
|
||||
return image?.spec?.displayName || 'N/A';
|
||||
},
|
||||
|
||||
bootDevices() {
|
||||
return getBootDevices(this.value?.spec?.template?.spec?.domain?.devices);
|
||||
disks() {
|
||||
const disks = this.value?.spec?.template?.spec?.domain?.devices?.disks || [];
|
||||
|
||||
return disks.filter((disk) => {
|
||||
return !!disk.bootOrder;
|
||||
}).sort((a, b) => {
|
||||
if (a.bootOrder < b.bootOrder) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
return 1;
|
||||
});
|
||||
},
|
||||
|
||||
cdroms() {
|
||||
@@ -113,10 +122,8 @@ export default {
|
||||
getDeviceType(o) {
|
||||
if (o.disk) {
|
||||
return 'Disk';
|
||||
} else if (o.cdrom) {
|
||||
return 'CD-ROM';
|
||||
} else {
|
||||
return 'Network';
|
||||
return 'CD-ROM';
|
||||
}
|
||||
},
|
||||
isEmpty(o) {
|
||||
@@ -212,16 +219,16 @@ export default {
|
||||
<div class="col span-6">
|
||||
<InputOrDisplay
|
||||
:name="t('harvester.virtualMachine.detail.details.bootOrder')"
|
||||
:value="bootDevices"
|
||||
:value="disks"
|
||||
:mode="mode"
|
||||
>
|
||||
<template #value>
|
||||
<ul>
|
||||
<li
|
||||
v-for="(device, i) in bootDevices"
|
||||
v-for="(disk, i) in disks"
|
||||
:key="i"
|
||||
>
|
||||
{{ device.bootOrder }}. {{ device.name }} ({{ getDeviceType(device) }})
|
||||
{{ disk.bootOrder }}. {{ disk.name }} ({{ getDeviceType(disk) }})
|
||||
</li>
|
||||
</ul>
|
||||
</template>
|
||||
|
||||
@@ -14,11 +14,9 @@ import Labels from '@shell/components/form/Labels';
|
||||
import LabelValue from '@shell/components/LabelValue';
|
||||
import { HCI } from '../../types';
|
||||
import VM_MIXIN from '../../mixins/harvester-vm';
|
||||
import { getLatestMigration } from '../../utils/vm';
|
||||
|
||||
import CloudConfig from '../../edit/kubevirt.io.virtualmachine/VirtualMachineCloudConfig';
|
||||
import Volume from '../../edit/kubevirt.io.virtualmachine/VirtualMachineVolume';
|
||||
import VMPerformanceOptions from '../../edit/kubevirt.io.virtualmachine/VirtualMachineVolume/VMPerformanceOptions';
|
||||
import Network from '../../edit/kubevirt.io.virtualmachine/VirtualMachineNetwork';
|
||||
import AccessCredentials from '../../edit/kubevirt.io.virtualmachine/VirtualMachineAccessCredentials';
|
||||
import Events from './VirtualMachineTabs/VirtualMachineEvents';
|
||||
@@ -41,7 +39,6 @@ export default {
|
||||
OverviewBasics,
|
||||
LabelValue,
|
||||
Volume,
|
||||
VMPerformanceOptions,
|
||||
Network,
|
||||
OverviewKeypairs,
|
||||
CloudConfig,
|
||||
@@ -142,7 +139,18 @@ export default {
|
||||
const inStore = this.$store.getters['currentProduct'].inStore;
|
||||
const vmimList = this.$store.getters[`${ inStore }/all`](HCI.VMIM) || [];
|
||||
|
||||
return getLatestMigration(vmimList, this.vmi?.metadata?.namespace, this.vmi?.name) || null;
|
||||
const vmiName = this.vmi?.name || '';
|
||||
|
||||
// filter the corresponding vmims by vmim.spec.vmiName and find the latest one by creationTimestamp
|
||||
const vmim = vmimList.filter((VMIM) => VMIM?.spec?.vmiName === vmiName).sort((a, b) => {
|
||||
if (a?.metadata?.creationTimestamp > b?.metadata?.creationTimestamp) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
return 1;
|
||||
});
|
||||
|
||||
return vmim.length > 0 && vmim[0] ? vmim[0] : null;
|
||||
},
|
||||
|
||||
migrationEvents() {
|
||||
@@ -206,15 +214,6 @@ export default {
|
||||
|
||||
this['diskRows'] = diskRows;
|
||||
this['networkRows'] = this.getNetworkRows(neu, { fromTemplate: false, init: false });
|
||||
this['networkBootFirst'] = this.isNetworkBootFirst(neu.spec);
|
||||
|
||||
// getInitConfig() seeds these on created(); refresh them here too so the
|
||||
// VM-wide performance panel does not go stale when the spec changes.
|
||||
const domain = neu?.spec?.template?.spec?.domain;
|
||||
|
||||
this['blockMultiQueue'] = domain?.devices?.blockMultiQueue || false;
|
||||
this['ioThreadsPolicy'] = domain?.ioThreadsPolicy || '';
|
||||
this['ioThreadCount'] = domain?.ioThreads?.supplementalPoolThreadCount || 2;
|
||||
},
|
||||
deep: true
|
||||
}
|
||||
@@ -256,15 +255,6 @@ export default {
|
||||
:vm="value"
|
||||
:resource-type="value.type"
|
||||
/>
|
||||
<VMPerformanceOptions
|
||||
:block-multi-queue="blockMultiQueue"
|
||||
:io-threads-policy="ioThreadsPolicy"
|
||||
:io-thread-count="ioThreadCount"
|
||||
:has-virtio-disk="hasVirtioDisk"
|
||||
:has-dedicated-iothread="hasDedicatedIOThread"
|
||||
mode="view"
|
||||
class="mt-20"
|
||||
/>
|
||||
</Tab>
|
||||
|
||||
<Tab
|
||||
@@ -275,7 +265,6 @@ export default {
|
||||
>
|
||||
<Network
|
||||
v-model:value="networkRows"
|
||||
:network-boot-first="networkBootFirst"
|
||||
mode="view"
|
||||
:vm="value"
|
||||
/>
|
||||
|
||||
@@ -1,141 +0,0 @@
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { _CREATE, _EDIT, _VIEW } from '@shell/config/query-params';
|
||||
import YamlEditor from '@shell/components/YamlEditor';
|
||||
import { HCI } from '@pkg/harvester/config/labels-annotations';
|
||||
import HarvesterEditCloudTemplate from '../harvesterhci.io.cloudtemplate.vue';
|
||||
|
||||
const OLD_CONFIG = '#cloud-config\npassword: old\n';
|
||||
const NEW_CONFIG = '#cloud-config\npassword: new\n';
|
||||
|
||||
// A cloud-config template as the store gives it, `save` records what would be sent to the API
|
||||
function cloudTemplate({ isNew = false } = {}) {
|
||||
const value = {
|
||||
type: 'configmap',
|
||||
metadata: {
|
||||
name: 'tpl',
|
||||
namespace: 'default',
|
||||
...(isNew ? {} : { labels: { [HCI.CLOUD_INIT]: 'user' } }),
|
||||
},
|
||||
data: isNew ? undefined : { cloudInit: OLD_CONFIG },
|
||||
$dispatch: jest.fn(),
|
||||
save: () => Promise.resolve(),
|
||||
saved: [],
|
||||
};
|
||||
|
||||
jest.spyOn(value, 'save').mockImplementation(() => {
|
||||
value.saved.push(JSON.parse(JSON.stringify({ metadata: value.metadata, data: value.data })));
|
||||
|
||||
return Promise.resolve();
|
||||
});
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
// The real shell YamlEditor, with only its CodeMirror editor stubbed, so the events the form listens to are the
|
||||
// ones the shell emits
|
||||
function mountForm(mode, value) {
|
||||
return mount(HarvesterEditCloudTemplate, {
|
||||
props: { value, mode },
|
||||
global: {
|
||||
stubs: {
|
||||
CruResource: { template: '<div><slot /></div>' },
|
||||
Tabbed: { template: '<div><slot /></div>' },
|
||||
Tab: { template: '<div><slot /></div>' },
|
||||
NameNsDescription: true,
|
||||
LabeledSelect: true,
|
||||
CodeMirror: {
|
||||
name: 'CodeMirror', template: '<div />', emits: ['onInput', 'onReady', 'validationChanged']
|
||||
},
|
||||
FileDiff: true,
|
||||
},
|
||||
mocks: {
|
||||
$store: {
|
||||
getters: {
|
||||
'prefs/get': jest.fn(),
|
||||
'type-map/isSpoofed': () => false,
|
||||
currentStore: () => 'harvester',
|
||||
'harvester/schemaFor': () => ({ linkFor: () => '/v1/harvester/configmaps' }),
|
||||
'i18n/t': (key) => key,
|
||||
},
|
||||
},
|
||||
$router: { replace: jest.fn() },
|
||||
$route: {
|
||||
name: 'c-cluster-product-resource-id', params: {}, query: {}
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// What a user typing in the editor does: CodeMirror reports the new text to the YamlEditor
|
||||
async function typeInEditor(wrapper, text) {
|
||||
wrapper.findComponent(YamlEditor).findComponent({ name: 'CodeMirror' }).vm.$emit('onInput', text);
|
||||
await wrapper.vm.$nextTick();
|
||||
}
|
||||
|
||||
describe('component: HarvesterEditCloudTemplate', () => {
|
||||
it('should save the edited cloud config when editing a template', async() => {
|
||||
const value = cloudTemplate();
|
||||
const wrapper = mountForm(_EDIT, value);
|
||||
|
||||
await typeInEditor(wrapper, NEW_CONFIG);
|
||||
await wrapper.vm.save(jest.fn());
|
||||
|
||||
expect(value.save).toHaveBeenCalledTimes(1);
|
||||
expect(value.saved[0].data).toStrictEqual({ cloudInit: NEW_CONFIG });
|
||||
});
|
||||
|
||||
it('should keep the template type label when editing a template', async() => {
|
||||
const value = cloudTemplate();
|
||||
const wrapper = mountForm(_EDIT, value);
|
||||
|
||||
await typeInEditor(wrapper, NEW_CONFIG);
|
||||
await wrapper.vm.save(jest.fn());
|
||||
|
||||
expect(value.saved[0].metadata.labels).toStrictEqual({ [HCI.CLOUD_INIT]: 'user' });
|
||||
});
|
||||
|
||||
it('should save the last text when the cloud config is edited several times', async() => {
|
||||
const value = cloudTemplate();
|
||||
const wrapper = mountForm(_EDIT, value);
|
||||
|
||||
await typeInEditor(wrapper, '#cloud-config\n');
|
||||
await typeInEditor(wrapper, NEW_CONFIG);
|
||||
await wrapper.vm.save(jest.fn());
|
||||
|
||||
expect(value.saved[0].data).toStrictEqual({ cloudInit: NEW_CONFIG });
|
||||
});
|
||||
|
||||
it('should save the cloud config unchanged when only saving a template', async() => {
|
||||
const value = cloudTemplate();
|
||||
const wrapper = mountForm(_EDIT, value);
|
||||
|
||||
await wrapper.vm.save(jest.fn());
|
||||
|
||||
expect(value.saved[0].data).toStrictEqual({ cloudInit: OLD_CONFIG });
|
||||
});
|
||||
|
||||
it('should save the cloud config and the template type when creating a template', async() => {
|
||||
const value = cloudTemplate({ isNew: true });
|
||||
const wrapper = mountForm(_CREATE, value);
|
||||
|
||||
await typeInEditor(wrapper, NEW_CONFIG);
|
||||
await wrapper.vm.save(jest.fn());
|
||||
|
||||
expect(value.save).toHaveBeenCalledWith({ url: '/v1/harvester/configmaps' });
|
||||
expect(value.saved[0]).toStrictEqual({
|
||||
metadata: {
|
||||
name: 'tpl', namespace: 'default', labels: { [HCI.CLOUD_INIT]: 'user' }
|
||||
},
|
||||
data: { cloudInit: NEW_CONFIG },
|
||||
});
|
||||
});
|
||||
|
||||
it('should show the template cloud config in the editor when viewing a template', () => {
|
||||
const value = cloudTemplate();
|
||||
const wrapper = mountForm(_VIEW, value);
|
||||
|
||||
expect(wrapper.findComponent(YamlEditor).props('value')).toBe(OLD_CONFIG);
|
||||
expect(value.data).toStrictEqual({ cloudInit: OLD_CONFIG });
|
||||
});
|
||||
});
|
||||
@@ -1,36 +0,0 @@
|
||||
import { HCI } from '@pkg/harvester/types';
|
||||
import VM_MIXIN from '@pkg/harvester/mixins/harvester-vm';
|
||||
import HarvesterEditTemplateVersion from '../harvesterhci.io.virtualmachinetemplateversion.vue';
|
||||
|
||||
async function saveWith(userScript) {
|
||||
const buttonCb = jest.fn();
|
||||
const form = {
|
||||
userScript,
|
||||
errors: [],
|
||||
t: (key) => key,
|
||||
parseVM: jest.fn(),
|
||||
validateCloudInit: VM_MIXIN.methods.validateCloudInit,
|
||||
templateValue: { metadata: {} },
|
||||
$store: { dispatch: jest.fn().mockResolvedValue([]) },
|
||||
};
|
||||
|
||||
await HarvesterEditTemplateVersion.methods.saveVMT.call(form, buttonCb);
|
||||
|
||||
return { form, buttonCb };
|
||||
}
|
||||
|
||||
describe('page: harvesterhci.io.virtualmachinetemplateversion edit', () => {
|
||||
it('should stop the save when the cloud config is invalid', async() => {
|
||||
const { form, buttonCb } = await saveWith('#cloud-config\nsome words\n');
|
||||
|
||||
expect(form.errors).toStrictEqual(['harvester.virtualMachine.cloudConfig.user.invalidYaml']);
|
||||
expect(buttonCb).toHaveBeenCalledWith(false);
|
||||
expect(form.$store.dispatch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should go on with the save when the user data is a script', async() => {
|
||||
const { form } = await saveWith('#!/bin/bash\napt-get update\n# start it\nsystemctl enable --now nginx\n');
|
||||
|
||||
expect(form.$store.dispatch).toHaveBeenCalledWith('harvester/findAll', { type: HCI.VM_TEMPLATE });
|
||||
});
|
||||
});
|
||||
@@ -7,7 +7,6 @@ import NameNsDescription from '@shell/components/form/NameNsDescription';
|
||||
import YamlEditor from '@shell/components/YamlEditor';
|
||||
|
||||
import CreateEditView from '@shell/mixins/create-edit-view';
|
||||
import FormValidation from '@shell/mixins/form-validation';
|
||||
import { HCI } from '@pkg/harvester/config/labels-annotations';
|
||||
|
||||
export default {
|
||||
@@ -24,19 +23,14 @@ export default {
|
||||
NameNsDescription,
|
||||
},
|
||||
|
||||
mixins: [CreateEditView, FormValidation],
|
||||
mixins: [CreateEditView],
|
||||
|
||||
inheritAttrs: false,
|
||||
|
||||
data() {
|
||||
return {
|
||||
config: this.value.data?.cloudInit || '',
|
||||
type: this.value?.metadata?.labels?.[HCI.CLOUD_INIT] || 'user',
|
||||
fvFormRuleSets: [{
|
||||
path: 'metadata.name',
|
||||
rules: ['required'],
|
||||
translationKey: 'nameNsDescription.name.label',
|
||||
}],
|
||||
config: this.value.data?.cloudInit || '',
|
||||
type: this.value?.metadata?.labels?.[HCI.CLOUD_INIT] || 'user',
|
||||
};
|
||||
},
|
||||
|
||||
@@ -59,8 +53,8 @@ export default {
|
||||
},
|
||||
|
||||
methods: {
|
||||
update(config) {
|
||||
this.value.data = { cloudInit: config };
|
||||
update() {
|
||||
this.value.data = { cloudInit: this.config };
|
||||
},
|
||||
|
||||
updateBeforeSave() {
|
||||
@@ -84,7 +78,6 @@ export default {
|
||||
:resource="value"
|
||||
:errors="errors"
|
||||
:apply-hooks="applyHooks"
|
||||
:validation-passed="fvFormIsValid"
|
||||
@finish="save"
|
||||
@cancel="done"
|
||||
@error="e=>errors=e"
|
||||
@@ -93,7 +86,6 @@ export default {
|
||||
:value="value"
|
||||
:mode="mode"
|
||||
:namespaced="true"
|
||||
:rules="{ name: fvGetAndReportPathRules('metadata.name') }"
|
||||
@update:value="$emit('update:value', $event)"
|
||||
/>
|
||||
|
||||
@@ -119,7 +111,7 @@ export default {
|
||||
:mode="mode"
|
||||
class="yaml-editor"
|
||||
:editor-mode="mode === 'view' ? 'VIEW_CODE' : 'EDIT_CODE'"
|
||||
@update:value="update"
|
||||
@onChanges="update"
|
||||
/>
|
||||
</div>
|
||||
</Tab>
|
||||
@@ -133,7 +125,9 @@ export default {
|
||||
:deep() .yaml-editor{
|
||||
flex: 1;
|
||||
min-height: $yaml-height;
|
||||
& .code-mirror .cm-editor {
|
||||
& .code-mirror .CodeMirror {
|
||||
position: initial;
|
||||
height: auto;
|
||||
min-height: $yaml-height;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,8 +88,7 @@ export default {
|
||||
<div class="header mb-20">
|
||||
<FileSelector
|
||||
v-if="isCreate"
|
||||
variant="primary"
|
||||
class="mt-10"
|
||||
class="btn btn-sm bg-primary mt-10"
|
||||
:label="t('generic.readFromFile')"
|
||||
accept=".pub"
|
||||
@selected="onKeySelected"
|
||||
|
||||
@@ -16,8 +16,6 @@ import isEmpty from 'lodash/isEmpty';
|
||||
import jsyaml from 'js-yaml';
|
||||
import { createYaml } from '@shell/utils/create-yaml';
|
||||
import YamlEditor, { EDITOR_MODES } from '@shell/components/YamlEditor';
|
||||
import { foldAllComments } from '@components/RcCodeMirror';
|
||||
import { unfoldCode } from '@codemirror/language';
|
||||
import { FLOW_TYPE } from '../config/harvester-map';
|
||||
|
||||
const LOGGING_EVENT = 'Logging/Event';
|
||||
@@ -174,9 +172,10 @@ export default {
|
||||
});
|
||||
}
|
||||
},
|
||||
onYamlEditorReady(view) {
|
||||
foldAllComments(view);
|
||||
unfoldCode(view);
|
||||
onYamlEditorReady(cm) {
|
||||
cm.getMode().fold = 'yamlcomments';
|
||||
cm.execCommand('foldAll');
|
||||
cm.execCommand('unfold');
|
||||
},
|
||||
}
|
||||
};
|
||||
|
||||
+1
-14
@@ -7,12 +7,8 @@ import { allHash } from '@shell/utils/promise';
|
||||
import { clone } from '@shell/utils/object';
|
||||
import { HCI } from '../../../types';
|
||||
import { NODE } from '@shell/config/types';
|
||||
import { _CREATE, _CLONE } from '@shell/config/query-params';
|
||||
import { LVM_TOPOLOGY_LABEL } from '../index.vue';
|
||||
|
||||
const STRIPED_TYPE = 'striped';
|
||||
const DM_THIN_TYPE = 'dm-thin';
|
||||
|
||||
const DEFAULT_PARAMETERS = [
|
||||
'type',
|
||||
'vgName'
|
||||
@@ -58,17 +54,8 @@ export default {
|
||||
data() {
|
||||
const node = (this.value.allowedTopologies?.[0]?.matchLabelExpressions || []).find((t) => t.key === LVM_TOPOLOGY_LABEL)?.values[0];
|
||||
|
||||
// striped is dropped once the LVM add-on reaches GA (v1.9.1); dm-thin is the only supported type.
|
||||
const dmThinOnly = this.$store.getters['harvester-common/getFeatureEnabled']('lvmDmThinOnly');
|
||||
const volumeGroupTypes = dmThinOnly ? [DM_THIN_TYPE] : [STRIPED_TYPE, DM_THIN_TYPE];
|
||||
|
||||
// Default new storage classes to dm-thin, and reset a cloned striped type that is no longer selectable.
|
||||
if (dmThinOnly && [_CREATE, _CLONE].includes(this.realMode) && !volumeGroupTypes.includes(this.value.parameters.type)) {
|
||||
this.value.parameters.type = DM_THIN_TYPE;
|
||||
}
|
||||
|
||||
return {
|
||||
volumeGroupTypes,
|
||||
volumeGroupTypes: ['striped', 'dm-thin'],
|
||||
node,
|
||||
};
|
||||
},
|
||||
|
||||
@@ -173,7 +173,6 @@ export default {
|
||||
|
||||
try {
|
||||
await proxyResource.save();
|
||||
proxyResource.notifyGeneratedName?.();
|
||||
buttonCb(true);
|
||||
|
||||
this.$router.push({
|
||||
|
||||
@@ -299,7 +299,6 @@ export default {
|
||||
|
||||
const res = await this.value.save();
|
||||
|
||||
res.notifyGeneratedName?.();
|
||||
res.uploadImage(file);
|
||||
|
||||
buttonCb(true);
|
||||
|
||||
@@ -21,7 +21,6 @@ import { HCI } from '../types';
|
||||
import VM_MIXIN from '../mixins/harvester-vm';
|
||||
import Reserved from './kubevirt.io.virtualmachine/VirtualMachineReserved';
|
||||
import Volume from './kubevirt.io.virtualmachine/VirtualMachineVolume';
|
||||
import VMPerformanceOptions from './kubevirt.io.virtualmachine/VirtualMachineVolume/VMPerformanceOptions';
|
||||
import Network from './kubevirt.io.virtualmachine/VirtualMachineNetwork';
|
||||
import CpuMemory from './kubevirt.io.virtualmachine/VirtualMachineCpuMemory';
|
||||
import CpuModel from './kubevirt.io.virtualmachine/VirtualMachineCpuModel';
|
||||
@@ -38,7 +37,6 @@ export default {
|
||||
Tab,
|
||||
SSHKey,
|
||||
Volume,
|
||||
VMPerformanceOptions,
|
||||
Tabbed,
|
||||
Network,
|
||||
Checkbox,
|
||||
@@ -179,17 +177,8 @@ export default {
|
||||
},
|
||||
|
||||
async saveVMT(buttonCb) {
|
||||
this.errors = [];
|
||||
this.parseVM();
|
||||
|
||||
this.validateCloudInit();
|
||||
|
||||
if (this.errors.length) {
|
||||
buttonCb(false);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const templates = await this.$store.dispatch('harvester/findAll', { type: HCI.VM_TEMPLATE });
|
||||
const template = templates.find( (O) => O.metadata.name === this.templateValue.metadata.name);
|
||||
|
||||
@@ -289,25 +278,6 @@ export default {
|
||||
name="Basics"
|
||||
:label="t('harvester.vmTemplate.tabs.basics')"
|
||||
>
|
||||
<div class="row mb-20">
|
||||
<div class="col span-6">
|
||||
<LabeledSelect
|
||||
v-model:value="osType"
|
||||
label-key="harvester.virtualMachine.osType"
|
||||
:mode="mode"
|
||||
:options="OS"
|
||||
:tooltip="isCreate ? t('harvester.virtualMachine.osTypeTooltip') : null"
|
||||
/>
|
||||
</div>
|
||||
<div class="col span-6">
|
||||
<CpuModel
|
||||
:value="spec.template.spec.domain.cpu?.model || ''"
|
||||
:mode="mode"
|
||||
@update:value="updateCpuModel"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<CpuMemory
|
||||
class="mb-20"
|
||||
:cpu="cpu"
|
||||
@@ -319,69 +289,6 @@ export default {
|
||||
@updateCpuMemory="updateCpuMemory"
|
||||
/>
|
||||
|
||||
<div class="mb-20">
|
||||
<Checkbox
|
||||
v-if="value.cpuPinningFeatureEnabled"
|
||||
v-model:value="cpuPinning"
|
||||
class="check"
|
||||
type="checkbox"
|
||||
tooltip-key="harvester.virtualMachine.cpuPinning.tooltip"
|
||||
label-key="harvester.virtualMachine.cpuPinning.label"
|
||||
:mode="mode"
|
||||
/>
|
||||
|
||||
<Checkbox
|
||||
v-model:value="installUSBTablet"
|
||||
class="check"
|
||||
type="checkbox"
|
||||
:label="t('harvester.virtualMachine.enableUsb')"
|
||||
:mode="mode"
|
||||
/>
|
||||
|
||||
<Checkbox
|
||||
v-model:value="tpmEnabled"
|
||||
class="check"
|
||||
type="checkbox"
|
||||
label-key="harvester.virtualMachine.systemOptions.tpm"
|
||||
:mode="mode"
|
||||
/>
|
||||
|
||||
<Checkbox
|
||||
v-if="value.tpmPersistentStateFeatureEnabled && tpmEnabled"
|
||||
v-model:value="tpmPersistentStateEnabled"
|
||||
class="check"
|
||||
type="checkbox"
|
||||
:label="t('harvester.virtualMachine.systemOptions.tpmPersistentState')"
|
||||
:mode="mode"
|
||||
/>
|
||||
|
||||
<Checkbox
|
||||
v-model:value="efiEnabled"
|
||||
class="check"
|
||||
type="checkbox"
|
||||
:label="t('harvester.virtualMachine.systemOptions.efiEnabled')"
|
||||
:mode="mode"
|
||||
/>
|
||||
|
||||
<Checkbox
|
||||
v-if="value.efiPersistentStateFeatureEnabled && efiEnabled"
|
||||
v-model:value="efiPersistentStateEnabled"
|
||||
class="check"
|
||||
type="checkbox"
|
||||
:label="t('harvester.virtualMachine.systemOptions.efiPersistentState')"
|
||||
:mode="mode"
|
||||
/>
|
||||
|
||||
<Checkbox
|
||||
v-if="efiEnabled"
|
||||
v-model:value="secureBoot"
|
||||
class="check"
|
||||
type="checkbox"
|
||||
:label="t('harvester.virtualMachine.systemOptions.secureBoot')"
|
||||
:mode="mode"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="mb-20">
|
||||
<SSHKey
|
||||
v-model:value="sshKey"
|
||||
@@ -414,7 +321,6 @@ export default {
|
||||
>
|
||||
<Network
|
||||
v-model:value="networkRows"
|
||||
v-model:network-boot-first="networkBootFirst"
|
||||
:mode="mode"
|
||||
/>
|
||||
</Tab>
|
||||
@@ -536,6 +442,18 @@ export default {
|
||||
:mode="mode"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="col span-6">
|
||||
<LabeledSelect
|
||||
v-model:value="osType"
|
||||
label-key="harvester.virtualMachine.osType"
|
||||
:mode="mode"
|
||||
:options="OS"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row mb-20">
|
||||
<div class="col span-6">
|
||||
<LabeledSelect
|
||||
v-model:value="maintenanceStrategy"
|
||||
@@ -545,9 +463,6 @@ export default {
|
||||
:mode="mode"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row mb-20">
|
||||
<div class="col span-6">
|
||||
<Reserved
|
||||
:reserved-memory="reservedMemory"
|
||||
@@ -557,6 +472,16 @@ export default {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row mb-20">
|
||||
<div class="col span-6">
|
||||
<CpuModel
|
||||
:value="spec.template.spec.domain.cpu?.model || ''"
|
||||
:mode="mode"
|
||||
@update:value="updateCpuModel"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row mb-20">
|
||||
<a
|
||||
v-if="showAdvanced"
|
||||
@@ -586,16 +511,6 @@ export default {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<VMPerformanceOptions
|
||||
v-model:block-multi-queue="blockMultiQueue"
|
||||
v-model:io-threads-policy="ioThreadsPolicy"
|
||||
v-model:io-thread-count="ioThreadCount"
|
||||
:has-virtio-disk="hasVirtioDisk"
|
||||
:has-dedicated-iothread="hasDedicatedIOThread"
|
||||
:mode="mode"
|
||||
class="mb-20"
|
||||
/>
|
||||
|
||||
<CloudConfig
|
||||
ref="yamlEditor"
|
||||
:mode="mode"
|
||||
@@ -604,17 +519,76 @@ export default {
|
||||
:network-script="networkScript"
|
||||
@updateUserData="updateUserData"
|
||||
@updateNetworkData="updateNetworkData"
|
||||
>
|
||||
<template #after-user-data>
|
||||
<Checkbox
|
||||
v-model:value="installAgent"
|
||||
class="check mb-20"
|
||||
type="checkbox"
|
||||
label-key="harvester.virtualMachine.installAgent"
|
||||
:mode="mode"
|
||||
/>
|
||||
</template>
|
||||
</CloudConfig>
|
||||
/>
|
||||
|
||||
<div class="spacer"></div>
|
||||
<Checkbox
|
||||
v-if="value.cpuPinningFeatureEnabled"
|
||||
v-model:value="cpuPinning"
|
||||
class="check"
|
||||
type="checkbox"
|
||||
tooltip-key="harvester.virtualMachine.cpuPinning.tooltip"
|
||||
label-key="harvester.virtualMachine.cpuPinning.label"
|
||||
:mode="mode"
|
||||
/>
|
||||
<Checkbox
|
||||
v-model:value="installUSBTablet"
|
||||
class="check"
|
||||
type="checkbox"
|
||||
:label="t('harvester.virtualMachine.enableUsb')"
|
||||
:mode="mode"
|
||||
/>
|
||||
|
||||
<Checkbox
|
||||
v-model:value="installAgent"
|
||||
class="check"
|
||||
type="checkbox"
|
||||
label-key="harvester.virtualMachine.installAgent"
|
||||
:mode="mode"
|
||||
/>
|
||||
|
||||
<Checkbox
|
||||
v-model:value="tpmEnabled"
|
||||
class="check"
|
||||
type="checkbox"
|
||||
label-key="harvester.virtualMachine.advancedOptions.tpm"
|
||||
:mode="mode"
|
||||
/>
|
||||
|
||||
<Checkbox
|
||||
v-if="value.tpmPersistentStateFeatureEnabled && tpmEnabled"
|
||||
v-model:value="tpmPersistentStateEnabled"
|
||||
class="check"
|
||||
type="checkbox"
|
||||
:label="t('harvester.virtualMachine.advancedOptions.tpmPersistentState')"
|
||||
:mode="mode"
|
||||
/>
|
||||
|
||||
<Checkbox
|
||||
v-model:value="efiEnabled"
|
||||
class="check"
|
||||
type="checkbox"
|
||||
:label="t('harvester.virtualMachine.advancedOptions.efiEnabled')"
|
||||
:mode="mode"
|
||||
/>
|
||||
|
||||
<Checkbox
|
||||
v-if="value.efiPersistentStateFeatureEnabled && efiEnabled"
|
||||
v-model:value="efiPersistentStateEnabled"
|
||||
class="check"
|
||||
type="checkbox"
|
||||
:label="t('harvester.virtualMachine.advancedOptions.efiPersistentState')"
|
||||
:mode="mode"
|
||||
/>
|
||||
|
||||
<Checkbox
|
||||
v-if="efiEnabled"
|
||||
v-model:value="secureBoot"
|
||||
class="check"
|
||||
type="checkbox"
|
||||
:label="t('harvester.virtualMachine.advancedOptions.secureBoot')"
|
||||
:mode="mode"
|
||||
/>
|
||||
</Tab>
|
||||
</Tabbed>
|
||||
</CruResource>
|
||||
|
||||
@@ -172,7 +172,6 @@ export default {
|
||||
|
||||
try {
|
||||
await proxyResource.save();
|
||||
proxyResource.notifyGeneratedName?.();
|
||||
buttonCb(true);
|
||||
|
||||
this.$router.push({
|
||||
|
||||
@@ -8,7 +8,6 @@ import LabeledSelect from '@shell/components/form/LabeledSelect';
|
||||
import { LabeledInput } from '@components/Form/LabeledInput';
|
||||
import NameNsDescription from '@shell/components/form/NameNsDescription';
|
||||
import Conditions from '@shell/components/form/Conditions';
|
||||
import DiskPerformanceOptions from './kubevirt.io.virtualmachine/VirtualMachineVolume/DiskPerformanceOptions';
|
||||
import { Banner } from '@components/Banner';
|
||||
import { Checkbox } from '@components/Form/Checkbox';
|
||||
import jsyaml from 'js-yaml';
|
||||
@@ -48,8 +47,7 @@ export default {
|
||||
LabeledSelect,
|
||||
LabeledInput,
|
||||
NameNsDescription,
|
||||
Conditions,
|
||||
DiskPerformanceOptions
|
||||
Conditions
|
||||
},
|
||||
|
||||
mixins: [CreateEditView],
|
||||
@@ -102,15 +100,7 @@ export default {
|
||||
createWithDataVolume: false,
|
||||
snapshots: [],
|
||||
images: [],
|
||||
GIBIBYTE,
|
||||
// Default KubeVirt high-performance disk profile, stored as annotations and
|
||||
// applied when this volume is later attached to a VM as a disk.
|
||||
perf: {
|
||||
cache: get(this.value, `metadata.annotations."${ HCI_ANNOTATIONS.DISK_CACHE_MODE }"`) || '',
|
||||
io: get(this.value, `metadata.annotations."${ HCI_ANNOTATIONS.DISK_IO_MODE }"`) || '',
|
||||
dedicatedIOThread: get(this.value, `metadata.annotations."${ HCI_ANNOTATIONS.DISK_DEDICATED_IOTHREAD }"`) === 'true',
|
||||
volumeMode: this.value?.spec?.volumeMode,
|
||||
},
|
||||
GIBIBYTE
|
||||
};
|
||||
},
|
||||
|
||||
@@ -342,7 +332,6 @@ export default {
|
||||
}
|
||||
},
|
||||
'value.spec.volumeMode'(neu) {
|
||||
this.perf.volumeMode = neu;
|
||||
if (neu === VOLUME_MODE.FILE_SYSTEM) {
|
||||
this.setVolumeForVmAnnotation();
|
||||
} else if (neu === VOLUME_MODE.BLOCK ) {
|
||||
@@ -457,23 +446,6 @@ export default {
|
||||
imageAnnotations = { ...this.value.metadata.annotations };
|
||||
}
|
||||
|
||||
// Persist the default high-performance disk profile as annotations.
|
||||
if (this.perf.cache) {
|
||||
imageAnnotations[HCI_ANNOTATIONS.DISK_CACHE_MODE] = this.perf.cache;
|
||||
} else {
|
||||
delete imageAnnotations[HCI_ANNOTATIONS.DISK_CACHE_MODE];
|
||||
}
|
||||
if (this.perf.io) {
|
||||
imageAnnotations[HCI_ANNOTATIONS.DISK_IO_MODE] = this.perf.io;
|
||||
} else {
|
||||
delete imageAnnotations[HCI_ANNOTATIONS.DISK_IO_MODE];
|
||||
}
|
||||
if (this.perf.dedicatedIOThread) {
|
||||
imageAnnotations[HCI_ANNOTATIONS.DISK_DEDICATED_IOTHREAD] = 'true';
|
||||
} else {
|
||||
delete imageAnnotations[HCI_ANNOTATIONS.DISK_DEDICATED_IOTHREAD];
|
||||
}
|
||||
|
||||
const spec = {
|
||||
...this.value.spec,
|
||||
resources: { requests: { storage: this.storage } },
|
||||
@@ -638,16 +610,6 @@ export default {
|
||||
class="mb-20"
|
||||
@update:value="update"
|
||||
/>
|
||||
|
||||
<Banner
|
||||
color="info"
|
||||
:label="t('harvester.volume.performance.pvcTip')"
|
||||
/>
|
||||
<DiskPerformanceOptions
|
||||
:value="perf"
|
||||
:mode="mode"
|
||||
@update="update"
|
||||
/>
|
||||
</Tab>
|
||||
<Tab
|
||||
v-if="!isCreate"
|
||||
|
||||
+1
-1
@@ -157,7 +157,7 @@ $yaml-height: 200px;
|
||||
flex: 1;
|
||||
min-height: $yaml-height;
|
||||
|
||||
& .code-mirror .cm-editor {
|
||||
& .code-mirror .CodeMirror {
|
||||
min-height: $yaml-height;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -219,8 +219,6 @@ export default {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<slot name="after-user-data" />
|
||||
|
||||
<div class="mb-20">
|
||||
<DataTemplate
|
||||
ref="networkTemplate"
|
||||
@@ -289,7 +287,7 @@ $yaml-height: 350px;
|
||||
flex: 1;
|
||||
min-height: $yaml-height;
|
||||
|
||||
& .code-mirror .cm-editor {
|
||||
& .code-mirror .CodeMirror {
|
||||
min-height: $yaml-height;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
import InputOrDisplay from '@shell/components/InputOrDisplay';
|
||||
import { LabeledInput } from '@components/Form/LabeledInput';
|
||||
import LabeledSelect from '@shell/components/form/LabeledSelect';
|
||||
import { Checkbox } from '@components/Form/Checkbox';
|
||||
|
||||
import { clone } from '@shell/utils/object';
|
||||
import { _CREATE, _VIEW } from '@shell/config/query-params';
|
||||
@@ -34,7 +33,7 @@ export default {
|
||||
emits: ['update'],
|
||||
|
||||
components: {
|
||||
LabeledInput, LabeledSelect, InputOrDisplay, Checkbox
|
||||
LabeledInput, LabeledSelect, InputOrDisplay
|
||||
},
|
||||
|
||||
props: {
|
||||
@@ -170,7 +169,6 @@ export default {
|
||||
this.value.isPod = true;
|
||||
this.value.macAddress = '';
|
||||
this.value.staticIp = '';
|
||||
this.value.networkBoot = false;
|
||||
} else {
|
||||
this.value.isPod = false;
|
||||
}
|
||||
@@ -287,22 +285,6 @@ export default {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="!isMasquerade"
|
||||
data-testid="input-hen-networkBoot"
|
||||
class="row mb-20"
|
||||
>
|
||||
<div class="col span-12">
|
||||
<Checkbox
|
||||
v-model:value="value.networkBoot"
|
||||
:label="t('harvester.virtualMachine.network.networkBoot.label')"
|
||||
:tooltip="t('harvester.virtualMachine.network.networkBoot.tip')"
|
||||
:mode="mode"
|
||||
@update:value="update"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="!isMasquerade && isSingle">
|
||||
<div class="row mb-20">
|
||||
<a
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
<script>
|
||||
import InfoBox from '@shell/components/InfoBox';
|
||||
import { RadioGroup } from '@components/Form/Radio';
|
||||
import { NETWORK_ATTACHMENT } from '@shell/config/types';
|
||||
import { sortBy } from '@shell/utils/sort';
|
||||
import { clone } from '@shell/utils/object';
|
||||
@@ -11,11 +10,7 @@ import { HCI as HCI_ANNOTATIONS } from '../../../config/labels-annotations';
|
||||
import Base from './base';
|
||||
|
||||
export default {
|
||||
components: {
|
||||
InfoBox, Base, RadioGroup
|
||||
},
|
||||
|
||||
emits: ['update:value', 'update:networkBootFirst'],
|
||||
components: { InfoBox, Base },
|
||||
|
||||
props: {
|
||||
vm: {
|
||||
@@ -40,11 +35,6 @@ export default {
|
||||
isSingle: {
|
||||
type: Boolean,
|
||||
default: true
|
||||
},
|
||||
|
||||
networkBootFirst: {
|
||||
type: Boolean,
|
||||
default: true
|
||||
}
|
||||
},
|
||||
|
||||
@@ -92,20 +82,6 @@ export default {
|
||||
|
||||
vmState() {
|
||||
return this.vm?.stateDisplay;
|
||||
},
|
||||
|
||||
hasNetworkBoot() {
|
||||
return this.rows.some((R) => R.networkBoot);
|
||||
},
|
||||
|
||||
networkBootOrderOptions() {
|
||||
return [{
|
||||
label: this.t('harvester.virtualMachine.network.networkBoot.first'),
|
||||
value: true
|
||||
}, {
|
||||
label: this.t('harvester.virtualMachine.network.networkBoot.last'),
|
||||
value: false
|
||||
}];
|
||||
}
|
||||
},
|
||||
|
||||
@@ -242,22 +218,6 @@ export default {
|
||||
/>
|
||||
</InfoBox>
|
||||
|
||||
<div
|
||||
v-if="hasNetworkBoot"
|
||||
data-testid="input-hen-networkBootFirst"
|
||||
class="mb-20"
|
||||
>
|
||||
<RadioGroup
|
||||
:value="networkBootFirst"
|
||||
name="networkBootFirst"
|
||||
:label="t('harvester.virtualMachine.network.networkBoot.order')"
|
||||
:options="networkBootOrderOptions"
|
||||
:mode="mode"
|
||||
:row="true"
|
||||
@update:value="$emit('update:networkBootFirst', $event)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
v-if="!isView"
|
||||
type="button"
|
||||
|
||||
-301
@@ -1,301 +0,0 @@
|
||||
<script>
|
||||
import LabeledSelect from '@shell/components/form/LabeledSelect';
|
||||
import { Checkbox } from '@components/Form/Checkbox';
|
||||
import { Banner } from '@components/Banner';
|
||||
import { DISK_CACHE_MODE, DISK_IO_MODE, DISK_PERFORMANCE_PROFILE } from '../../../config/harvester-map';
|
||||
|
||||
const { DEFAULT, HIGH, CUSTOM } = DISK_PERFORMANCE_PROFILE;
|
||||
|
||||
export default {
|
||||
name: 'DiskPerformanceOptions',
|
||||
|
||||
components: {
|
||||
LabeledSelect, Checkbox, Banner
|
||||
},
|
||||
|
||||
emits: ['update'],
|
||||
|
||||
props: {
|
||||
// The disk row. This component reads/writes value.cache, value.io,
|
||||
// value.dedicatedIOThread and (for the "High Performance" preset) value.bus.
|
||||
value: {
|
||||
type: Object,
|
||||
default: () => ({})
|
||||
},
|
||||
|
||||
mode: {
|
||||
type: String,
|
||||
default: 'create'
|
||||
},
|
||||
},
|
||||
|
||||
data() {
|
||||
return {
|
||||
DISK_PERFORMANCE_PROFILE,
|
||||
profile: this.detectProfile(),
|
||||
// Bus the disk used before the "High Performance" preset switched it to
|
||||
// virtio, so returning to "Default" can put it back.
|
||||
busBeforeHighProfile: null,
|
||||
// True only while the user has explicitly picked "Custom" in the selector.
|
||||
userSelectedCustom: false,
|
||||
};
|
||||
},
|
||||
|
||||
computed: {
|
||||
storagePerformanceEnabled() {
|
||||
return this.$store.getters['harvester-common/getFeatureEnabled']('highPerformanceStorage');
|
||||
},
|
||||
|
||||
isCdRom() {
|
||||
return this.value.type === 'cd-rom';
|
||||
},
|
||||
|
||||
isCustom() {
|
||||
return this.profile === CUSTOM;
|
||||
},
|
||||
|
||||
isNativeIo() {
|
||||
return this.value.io === 'native';
|
||||
},
|
||||
|
||||
profileOptions() {
|
||||
return [DEFAULT, HIGH, CUSTOM].map((value) => ({
|
||||
label: this.t(`harvester.virtualMachine.volume.performance.profile.${ value }`),
|
||||
value,
|
||||
}));
|
||||
},
|
||||
|
||||
cacheOptions() {
|
||||
return DISK_CACHE_MODE.map((value) => ({
|
||||
label: this.cacheLabel(value),
|
||||
value,
|
||||
// Native AIO only works with an uncached (O_DIRECT) disk, so while it is
|
||||
// selected the only valid cache option is "none" — disable everything
|
||||
// else, including "Default", to prevent an invalid combination.
|
||||
disabled: this.isNativeIo && value !== 'none',
|
||||
}));
|
||||
},
|
||||
|
||||
ioOptions() {
|
||||
return DISK_IO_MODE.map((value) => ({
|
||||
label: value === '' ? this.t('harvester.virtualMachine.volume.performance.ioMode.default') : this.t(`harvester.virtualMachine.volume.performance.ioMode.${ value }`),
|
||||
value,
|
||||
}));
|
||||
},
|
||||
|
||||
showFilesystemCacheWarning() {
|
||||
return this.value.cache === 'none' && this.value.volumeMode === 'Filesystem';
|
||||
},
|
||||
|
||||
showBusTip() {
|
||||
const hasPerf = !!(this.value.cache || this.value.io || this.value.dedicatedIOThread);
|
||||
|
||||
return hasPerf && this.value.bus && this.value.bus !== 'virtio';
|
||||
},
|
||||
},
|
||||
|
||||
watch: {
|
||||
// Keep the profile selector in sync if the row is repopulated (e.g. editing an existing VM).
|
||||
'value.cache'() {
|
||||
this.syncProfile();
|
||||
},
|
||||
'value.io'() {
|
||||
this.syncProfile();
|
||||
},
|
||||
'value.dedicatedIOThread'() {
|
||||
this.syncProfile();
|
||||
},
|
||||
},
|
||||
|
||||
methods: {
|
||||
detectProfile() {
|
||||
const { cache, io, dedicatedIOThread } = this.value;
|
||||
|
||||
if (!cache && !io && !dedicatedIOThread) {
|
||||
return DEFAULT;
|
||||
}
|
||||
|
||||
if (cache === 'none' && io === 'native' && dedicatedIOThread) {
|
||||
return HIGH;
|
||||
}
|
||||
|
||||
return CUSTOM;
|
||||
},
|
||||
|
||||
syncProfile() {
|
||||
// An explicit "Custom" choice sticks, even if the options happen to
|
||||
// match the Default or High Performance preset. An inferred "Custom"
|
||||
// still follows the disk values.
|
||||
if (this.userSelectedCustom) {
|
||||
return;
|
||||
}
|
||||
this.profile = this.detectProfile();
|
||||
},
|
||||
|
||||
cacheLabel(value) {
|
||||
if (value === '') {
|
||||
return this.t('harvester.virtualMachine.volume.performance.cacheMode.default');
|
||||
}
|
||||
|
||||
return this.t(`harvester.virtualMachine.volume.performance.cacheMode.${ value }`);
|
||||
},
|
||||
|
||||
onProfileChange(profile) {
|
||||
const previous = this.profile;
|
||||
|
||||
this.profile = profile;
|
||||
this.userSelectedCustom = profile === CUSTOM;
|
||||
|
||||
if (profile === DEFAULT) {
|
||||
this.value.cache = '';
|
||||
this.value.io = '';
|
||||
this.value.dedicatedIOThread = false;
|
||||
|
||||
// "Default" means no overrides, so also undo the virtio bus that the
|
||||
// "High Performance" preset applied. Skip it if the user has since
|
||||
// picked a different bus themselves — that choice is theirs to keep.
|
||||
if (this.busBeforeHighProfile !== null) {
|
||||
if (this.value.bus === 'virtio') {
|
||||
this.value.bus = this.busBeforeHighProfile;
|
||||
}
|
||||
this.busBeforeHighProfile = null;
|
||||
}
|
||||
} else if (profile === HIGH) {
|
||||
this.value.cache = 'none';
|
||||
this.value.io = 'native';
|
||||
this.value.dedicatedIOThread = true;
|
||||
|
||||
if (previous !== HIGH) {
|
||||
this.busBeforeHighProfile = this.value.bus || '';
|
||||
}
|
||||
this.value.bus = 'virtio';
|
||||
}
|
||||
// CUSTOM keeps whatever is currently set, including the bus.
|
||||
|
||||
this.update();
|
||||
},
|
||||
|
||||
onIoChange(io) {
|
||||
this.value.io = io;
|
||||
// Native AIO requires an uncached disk; force cache to "none" to keep the
|
||||
// combo valid — including when cache is still on its "Default" ('') value,
|
||||
// which libvirt would otherwise reject at domain start.
|
||||
if (io === 'native' && this.value.cache !== 'none') {
|
||||
this.value.cache = 'none';
|
||||
}
|
||||
this.update();
|
||||
},
|
||||
|
||||
update() {
|
||||
this.$emit('update');
|
||||
},
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="!isCdRom && storagePerformanceEnabled"
|
||||
class="disk-performance"
|
||||
>
|
||||
<div class="row mb-20">
|
||||
<div
|
||||
class="col span-6"
|
||||
data-testid="input-disk-perf-profile"
|
||||
>
|
||||
<LabeledSelect
|
||||
:value="profile"
|
||||
:label="t('harvester.virtualMachine.volume.performance.profile.label')"
|
||||
:tooltip="t('harvester.virtualMachine.volume.performance.profile.tip')"
|
||||
:options="profileOptions"
|
||||
:mode="mode"
|
||||
@update:value="onProfileChange"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Banner
|
||||
v-if="profile === DISK_PERFORMANCE_PROFILE.HIGH"
|
||||
color="info"
|
||||
label-key="harvester.virtualMachine.volume.performance.highProfileTip"
|
||||
/>
|
||||
|
||||
<!-- Always rendered, so screen readers announce these warnings when changing the fields below makes them appear
|
||||
above the focused field -->
|
||||
<div
|
||||
role="status"
|
||||
data-testid="disk-perf-warning-status"
|
||||
>
|
||||
<Banner
|
||||
v-if="showBusTip"
|
||||
color="warning"
|
||||
data-testid="disk-perf-bus-tip"
|
||||
:label="t('harvester.virtualMachine.volume.performance.busTip', { bus: value.bus }, true)"
|
||||
/>
|
||||
<Banner
|
||||
v-if="showFilesystemCacheWarning"
|
||||
color="warning"
|
||||
label-key="harvester.virtualMachine.volume.performance.cacheMode.filesystemWarning"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<template v-if="isCustom">
|
||||
<div class="row mb-20">
|
||||
<div
|
||||
class="col span-6"
|
||||
data-testid="input-disk-cache"
|
||||
>
|
||||
<LabeledSelect
|
||||
v-model:value="value.cache"
|
||||
:label="t('harvester.virtualMachine.volume.performance.cacheMode.label')"
|
||||
:tooltip="t('harvester.virtualMachine.volume.performance.cacheMode.tip')"
|
||||
:options="cacheOptions"
|
||||
:mode="mode"
|
||||
@update:value="update"
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
class="col span-6"
|
||||
data-testid="input-disk-io"
|
||||
>
|
||||
<LabeledSelect
|
||||
:value="value.io"
|
||||
:label="t('harvester.virtualMachine.volume.performance.ioMode.label')"
|
||||
:tooltip="t('harvester.virtualMachine.volume.performance.ioMode.tip')"
|
||||
:options="ioOptions"
|
||||
:mode="mode"
|
||||
@update:value="onIoChange"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row mb-20">
|
||||
<div
|
||||
class="col span-12"
|
||||
data-testid="input-disk-dedicated-iothread"
|
||||
>
|
||||
<Checkbox
|
||||
v-model:value="value.dedicatedIOThread"
|
||||
:label="t('harvester.virtualMachine.volume.performance.dedicatedIOThread.label')"
|
||||
:tooltip="t('harvester.virtualMachine.volume.performance.dedicatedIOThread.tip')"
|
||||
:mode="mode"
|
||||
@update:value="update"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- Always rendered, also outside Custom, so screen readers announce the tip when picking Native I/O changes
|
||||
the cache mode, even if the new values switch the profile to High Performance -->
|
||||
<div
|
||||
role="status"
|
||||
data-testid="disk-perf-native-status"
|
||||
>
|
||||
<Banner
|
||||
v-if="isNativeIo"
|
||||
color="info"
|
||||
label-key="harvester.virtualMachine.volume.performance.ioMode.nativeRequiresNoCacheTip"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
-150
@@ -1,150 +0,0 @@
|
||||
<script>
|
||||
import LabeledSelect from '@shell/components/form/LabeledSelect';
|
||||
import { LabeledInput } from '@components/Form/LabeledInput';
|
||||
import { Checkbox } from '@components/Form/Checkbox';
|
||||
import { Banner } from '@components/Banner';
|
||||
import { _VIEW } from '@shell/config/query-params';
|
||||
import { IO_THREADS_POLICY } from '../../../config/harvester-map';
|
||||
|
||||
export default {
|
||||
name: 'VMPerformanceOptions',
|
||||
|
||||
components: {
|
||||
LabeledSelect, LabeledInput, Checkbox, Banner
|
||||
},
|
||||
|
||||
emits: ['update:blockMultiQueue', 'update:ioThreadsPolicy', 'update:ioThreadCount'],
|
||||
|
||||
props: {
|
||||
blockMultiQueue: {
|
||||
type: Boolean,
|
||||
default: false
|
||||
},
|
||||
|
||||
ioThreadsPolicy: {
|
||||
type: String,
|
||||
default: ''
|
||||
},
|
||||
|
||||
ioThreadCount: {
|
||||
type: Number,
|
||||
default: 2
|
||||
},
|
||||
|
||||
mode: {
|
||||
type: String,
|
||||
default: 'create'
|
||||
},
|
||||
|
||||
// Whether the current disk set contains a virtio disk (VM context only).
|
||||
hasVirtioDisk: {
|
||||
type: Boolean,
|
||||
default: true
|
||||
},
|
||||
|
||||
// Whether any disk requests a dedicated I/O thread (drives the auto-enable hint).
|
||||
hasDedicatedIothread: {
|
||||
type: Boolean,
|
||||
default: false
|
||||
},
|
||||
},
|
||||
|
||||
computed: {
|
||||
isView() {
|
||||
return this.mode === _VIEW;
|
||||
},
|
||||
|
||||
storagePerformanceEnabled() {
|
||||
return this.$store.getters['harvester-common/getFeatureEnabled']('highPerformanceStorage');
|
||||
},
|
||||
|
||||
ioThreadsPolicyOptions() {
|
||||
return IO_THREADS_POLICY.map((value) => ({
|
||||
label: value === '' ? this.t('harvester.virtualMachine.volume.diskPerformance.ioThreadsPolicy.default') : this.t(`harvester.virtualMachine.volume.diskPerformance.ioThreadsPolicy.${ value }`),
|
||||
value,
|
||||
}));
|
||||
},
|
||||
},
|
||||
|
||||
watch: {
|
||||
// Block Multi-Queue only applies to virtio disks. If the last virtio disk is
|
||||
// removed while it is enabled, clear it so the VM is not left with an invalid
|
||||
// setting the disabled checkbox can no longer surface.
|
||||
hasVirtioDisk(neu) {
|
||||
if (!neu && this.blockMultiQueue) {
|
||||
this.$emit('update:blockMultiQueue', false);
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="storagePerformanceEnabled && (!isView || blockMultiQueue || !!ioThreadsPolicy)"
|
||||
class="vm-perf"
|
||||
>
|
||||
<h3>
|
||||
{{ t('harvester.virtualMachine.volume.diskPerformance.title') }}
|
||||
</h3>
|
||||
<p class="text-muted mb-10">
|
||||
{{ t('harvester.virtualMachine.volume.diskPerformance.description') }}
|
||||
</p>
|
||||
|
||||
<div
|
||||
class="mb-10"
|
||||
data-testid="input-vm-block-multi-queue"
|
||||
>
|
||||
<Checkbox
|
||||
:value="blockMultiQueue"
|
||||
:label="t('harvester.virtualMachine.volume.diskPerformance.blockMultiQueue.label')"
|
||||
:tooltip="t('harvester.virtualMachine.volume.diskPerformance.blockMultiQueue.tip')"
|
||||
:mode="mode"
|
||||
:disabled="!hasVirtioDisk"
|
||||
@update:value="$emit('update:blockMultiQueue', $event)"
|
||||
/>
|
||||
</div>
|
||||
<Banner
|
||||
v-if="!hasVirtioDisk && !isView"
|
||||
color="info"
|
||||
label-key="harvester.virtualMachine.volume.diskPerformance.blockMultiQueue.noVirtioTip"
|
||||
/>
|
||||
|
||||
<div class="row mb-20">
|
||||
<div
|
||||
class="col span-6"
|
||||
data-testid="input-vm-iothreads-policy"
|
||||
>
|
||||
<LabeledSelect
|
||||
:value="ioThreadsPolicy"
|
||||
:label="t('harvester.virtualMachine.volume.diskPerformance.ioThreadsPolicy.label')"
|
||||
:tooltip="t('harvester.virtualMachine.volume.diskPerformance.ioThreadsPolicy.tip')"
|
||||
:options="ioThreadsPolicyOptions"
|
||||
:mode="mode"
|
||||
@update:value="$emit('update:ioThreadsPolicy', $event)"
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
v-if="ioThreadsPolicy === 'supplementalPool'"
|
||||
class="col span-6"
|
||||
data-testid="input-vm-iothread-count"
|
||||
>
|
||||
<LabeledInput
|
||||
type="integer"
|
||||
min="1"
|
||||
:required="!isView"
|
||||
:value="ioThreadCount"
|
||||
:label="t('harvester.virtualMachine.volume.diskPerformance.ioThreadCount.label')"
|
||||
:tooltip="t('harvester.virtualMachine.volume.diskPerformance.ioThreadCount.tip')"
|
||||
:mode="mode"
|
||||
@update:value="$emit('update:ioThreadCount', Number($event))"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<Banner
|
||||
v-if="hasDedicatedIothread && !ioThreadsPolicy"
|
||||
color="info"
|
||||
label-key="harvester.virtualMachine.volume.diskPerformance.ioThreadsPolicy.autoEnabledTip"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
-286
@@ -1,286 +0,0 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { load } from 'js-yaml';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { nextTick } from 'vue';
|
||||
import { _EDIT } from '@shell/config/query-params';
|
||||
import { Banner } from '@components/Banner';
|
||||
import DiskPerformanceOptions from '../DiskPerformanceOptions.vue';
|
||||
|
||||
const mountOptions = (value, { featureEnabled = true } = {}) => ({
|
||||
props: { value, mode: _EDIT },
|
||||
global: {
|
||||
mocks: {
|
||||
$store: {
|
||||
getters: {
|
||||
'harvester-common/getFeatureEnabled': () => featureEnabled,
|
||||
'i18n/t': (key) => key,
|
||||
'i18n/exists': () => true,
|
||||
}
|
||||
},
|
||||
t: (key) => key,
|
||||
},
|
||||
}
|
||||
});
|
||||
|
||||
const hardDisk = (overrides = {}) => ({
|
||||
type: 'disk', bus: 'virtio', cache: '', io: '', dedicatedIOThread: false, ...overrides
|
||||
});
|
||||
|
||||
const nativeTip = (wrapper) => wrapper.findAllComponents(Banner)
|
||||
.find((b) => b.props('labelKey') === 'harvester.virtualMachine.volume.performance.ioMode.nativeRequiresNoCacheTip');
|
||||
|
||||
const filesystemWarning = (wrapper) => wrapper.findAllComponents(Banner)
|
||||
.find((b) => b.props('labelKey') === 'harvester.virtualMachine.volume.performance.cacheMode.filesystemWarning');
|
||||
|
||||
describe('component: DiskPerformanceOptions', () => {
|
||||
it('is hidden when the highPerformanceStorage feature is disabled', () => {
|
||||
const wrapper = mount(DiskPerformanceOptions, mountOptions(hardDisk(), { featureEnabled: false }));
|
||||
|
||||
expect(wrapper.find('.disk-performance').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('renders for a hard disk when the feature is enabled', () => {
|
||||
const wrapper = mount(DiskPerformanceOptions, mountOptions(hardDisk()));
|
||||
|
||||
expect(wrapper.find('.disk-performance').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('shows the profile without a toggle, and the individual fields only for Custom', () => {
|
||||
const wrapper = mount(DiskPerformanceOptions, mountOptions(hardDisk()));
|
||||
|
||||
expect(wrapper.find('.expand-toggle').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="input-disk-perf-profile"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="input-disk-cache"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="input-disk-dedicated-iothread"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('shows the individual fields for a disk with custom options', () => {
|
||||
const wrapper = mount(DiskPerformanceOptions, mountOptions(hardDisk({ cache: 'writeback', io: 'threads' })));
|
||||
|
||||
expect(wrapper.find('[data-testid="input-disk-cache"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="input-disk-io"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="input-disk-dedicated-iothread"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('is hidden for a CD-ROM', () => {
|
||||
const wrapper = mount(DiskPerformanceOptions, mountOptions(hardDisk({ type: 'cd-rom' })));
|
||||
|
||||
expect(wrapper.find('.disk-performance').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('names the bus in the bus tip once the disk uses an option', () => {
|
||||
const plain = mount(DiskPerformanceOptions, mountOptions(hardDisk({ bus: 'sata' })));
|
||||
const tuned = mount(DiskPerformanceOptions, mountOptions(hardDisk({ bus: 'sata', cache: 'writeback' })));
|
||||
|
||||
expect(plain.find('[data-testid="disk-perf-bus-tip"]').exists()).toBe(false);
|
||||
expect(tuned.find('[data-testid="disk-perf-bus-tip"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('says in the bus tip that a dedicated I/O thread needs the virtio bus', () => {
|
||||
const translations = load(fs.readFileSync(path.join(__dirname, '../../../../l10n/en-us.yaml'), 'utf8'));
|
||||
const { busTip } = translations.harvester.virtualMachine.volume.performance;
|
||||
|
||||
expect(busTip).toContain('{bus}');
|
||||
expect(busTip).toContain('A dedicated I/O thread needs the virtio bus');
|
||||
});
|
||||
|
||||
it('shows the bus tip and the Filesystem warning inside a live region that is there before they appear', async() => {
|
||||
const disk = { bus: 'sata', volumeMode: 'Filesystem' };
|
||||
const wrapper = mount(DiskPerformanceOptions, mountOptions(hardDisk(disk)));
|
||||
const status = wrapper.find('[data-testid="disk-perf-warning-status"]');
|
||||
|
||||
expect(status.attributes('role')).toBe('status');
|
||||
expect(status.find('[data-testid="disk-perf-bus-tip"]').exists()).toBe(false);
|
||||
expect(filesystemWarning(wrapper)).toBeUndefined();
|
||||
|
||||
await wrapper.setProps({ value: hardDisk({ ...disk, cache: 'none' }) });
|
||||
|
||||
expect(wrapper.find('[data-testid="disk-perf-warning-status"]').element).toBe(status.element);
|
||||
expect(status.find('[data-testid="disk-perf-bus-tip"]').exists()).toBe(true);
|
||||
expect(status.element.contains(filesystemWarning(wrapper)?.element)).toBe(true);
|
||||
});
|
||||
|
||||
it('shows the Native I/O tip inside a live region that is there before Native I/O is picked', async() => {
|
||||
const value = hardDisk({ cache: 'writeback', io: 'threads' });
|
||||
const wrapper = mount(DiskPerformanceOptions, mountOptions(value));
|
||||
const status = wrapper.find('[data-testid="disk-perf-native-status"]');
|
||||
|
||||
expect(status.attributes('role')).toBe('status');
|
||||
expect(nativeTip(wrapper)).toBeUndefined();
|
||||
|
||||
wrapper.vm.onIoChange('native');
|
||||
await wrapper.vm.$nextTick();
|
||||
|
||||
expect(wrapper.find('[data-testid="disk-perf-native-status"]').element).toBe(status.element);
|
||||
expect(status.element.contains(nativeTip(wrapper)?.element)).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps the live region and the Native I/O tip when picking Native I/O switches Custom to High Performance', async() => {
|
||||
const value = hardDisk({
|
||||
cache: 'writeback', io: 'threads', dedicatedIOThread: true
|
||||
});
|
||||
const wrapper = mount(DiskPerformanceOptions, mountOptions(value));
|
||||
const status = wrapper.find('[data-testid="disk-perf-native-status"]');
|
||||
|
||||
expect(wrapper.vm.profile).toBe('custom');
|
||||
|
||||
wrapper.vm.onIoChange('native');
|
||||
await wrapper.vm.$nextTick();
|
||||
|
||||
expect(wrapper.vm.profile).toBe('highPerformance');
|
||||
expect(wrapper.find('[data-testid="input-disk-cache"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="disk-perf-native-status"]').element).toBe(status.element);
|
||||
expect(status.element.contains(nativeTip(wrapper)?.element)).toBe(true);
|
||||
});
|
||||
|
||||
it('passes the Filesystem warning as a label key so its quotes are not double-escaped', () => {
|
||||
const wrapper = mount(DiskPerformanceOptions, mountOptions(hardDisk({ cache: 'none', volumeMode: 'Filesystem' })));
|
||||
const banner = filesystemWarning(wrapper);
|
||||
|
||||
expect(banner).toBeDefined();
|
||||
expect(banner?.props('label')).toBeFalsy();
|
||||
});
|
||||
|
||||
it('applies the High Performance preset and emits update', () => {
|
||||
const value = hardDisk();
|
||||
const wrapper = mount(DiskPerformanceOptions, mountOptions(value));
|
||||
|
||||
wrapper.vm.onProfileChange('highPerformance');
|
||||
|
||||
expect(value.cache).toBe('none');
|
||||
expect(value.io).toBe('native');
|
||||
expect(value.dedicatedIOThread).toBe(true);
|
||||
expect(value.bus).toBe('virtio');
|
||||
expect(wrapper.emitted('update')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('clears all overrides when switching back to Default', () => {
|
||||
const value = hardDisk({
|
||||
cache: 'none', io: 'native', dedicatedIOThread: true
|
||||
});
|
||||
const wrapper = mount(DiskPerformanceOptions, mountOptions(value));
|
||||
|
||||
wrapper.vm.onProfileChange('default');
|
||||
|
||||
expect(value.cache).toBe('');
|
||||
expect(value.io).toBe('');
|
||||
expect(value.dedicatedIOThread).toBe(false);
|
||||
expect(wrapper.emitted('update')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('restores the original bus when leaving High Performance for Default', () => {
|
||||
const value = hardDisk({ bus: 'sata' });
|
||||
const wrapper = mount(DiskPerformanceOptions, mountOptions(value));
|
||||
|
||||
wrapper.vm.onProfileChange('highPerformance');
|
||||
expect(value.bus).toBe('virtio');
|
||||
|
||||
wrapper.vm.onProfileChange('default');
|
||||
expect(value.bus).toBe('sata');
|
||||
});
|
||||
|
||||
it('keeps a bus the user picked themselves after High Performance', () => {
|
||||
const value = hardDisk({ bus: 'sata' });
|
||||
const wrapper = mount(DiskPerformanceOptions, mountOptions(value));
|
||||
|
||||
wrapper.vm.onProfileChange('highPerformance');
|
||||
value.bus = 'scsi';
|
||||
|
||||
wrapper.vm.onProfileChange('default');
|
||||
expect(value.bus).toBe('scsi');
|
||||
});
|
||||
|
||||
it('leaves the bus alone for a disk that never used the High Performance preset', () => {
|
||||
const value = hardDisk({
|
||||
bus: 'sata', cache: 'writeback', io: 'threads'
|
||||
});
|
||||
const wrapper = mount(DiskPerformanceOptions, mountOptions(value));
|
||||
|
||||
wrapper.vm.onProfileChange('default');
|
||||
expect(value.bus).toBe('sata');
|
||||
});
|
||||
|
||||
it.each([
|
||||
['a cached state', 'writeback'],
|
||||
['the Default cache', ''],
|
||||
])('forces cache to none when Native I/O is selected from %s', (_label, cache) => {
|
||||
const value = hardDisk({ cache });
|
||||
const wrapper = mount(DiskPerformanceOptions, mountOptions(value));
|
||||
|
||||
wrapper.vm.onIoChange('native');
|
||||
|
||||
expect(value.io).toBe('native');
|
||||
expect(value.cache).toBe('none');
|
||||
expect(wrapper.emitted('update')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('disables every cache option except none while Native I/O is active', () => {
|
||||
const wrapper = mount(DiskPerformanceOptions, mountOptions(hardDisk({ io: 'native' })));
|
||||
|
||||
const disabledByValue = wrapper.vm.cacheOptions.reduce((acc, opt) => {
|
||||
acc[opt.value] = opt.disabled;
|
||||
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
expect(disabledByValue['none']).toBe(false);
|
||||
expect(disabledByValue['']).toBe(true);
|
||||
expect(disabledByValue['writeback']).toBe(true);
|
||||
expect(disabledByValue['writethrough']).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['Default', {
|
||||
cache: '', io: '', dedicatedIOThread: false
|
||||
}],
|
||||
['High Performance', {
|
||||
cache: 'none', io: 'native', dedicatedIOThread: true
|
||||
}],
|
||||
])('stays on Custom when the options match the %s preset', async(_label, opts) => {
|
||||
const value = hardDisk({ cache: 'writeback' });
|
||||
const wrapper = mount(DiskPerformanceOptions, mountOptions(value));
|
||||
|
||||
wrapper.vm.onProfileChange('custom');
|
||||
await wrapper.setProps({ value: { ...value, ...opts } });
|
||||
await nextTick();
|
||||
|
||||
expect(wrapper.vm.profile).toBe('custom');
|
||||
});
|
||||
|
||||
it('detects the profile from an existing disk', async() => {
|
||||
const wrapper = mount(DiskPerformanceOptions, mountOptions(hardDisk()));
|
||||
|
||||
expect(wrapper.vm.profile).toBe('default');
|
||||
|
||||
await wrapper.setProps({
|
||||
value: hardDisk({
|
||||
cache: 'none', io: 'native', dedicatedIOThread: true
|
||||
})
|
||||
});
|
||||
|
||||
expect(wrapper.vm.profile).toBe('highPerformance');
|
||||
});
|
||||
|
||||
it('updates an automatically detected Custom profile when preset values are loaded', async() => {
|
||||
const wrapper = mount(DiskPerformanceOptions, mountOptions(hardDisk({ cache: 'writeback' })));
|
||||
|
||||
expect(wrapper.vm.profile).toBe('custom');
|
||||
|
||||
await wrapper.setProps({
|
||||
value: hardDisk({
|
||||
cache: 'none', io: 'native', dedicatedIOThread: true
|
||||
})
|
||||
});
|
||||
|
||||
expect(wrapper.vm.profile).toBe('highPerformance');
|
||||
});
|
||||
|
||||
it('passes the Native I/O hint as a label key so its quotes are not double-escaped', () => {
|
||||
const wrapper = mount(DiskPerformanceOptions, mountOptions(hardDisk({ io: 'native' })));
|
||||
const banner = nativeTip(wrapper);
|
||||
|
||||
expect(banner).toBeDefined();
|
||||
expect(banner?.props('label')).toBeFalsy();
|
||||
});
|
||||
});
|
||||
-105
@@ -1,105 +0,0 @@
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { _CREATE, _VIEW } from '@shell/config/query-params';
|
||||
import { Banner } from '@components/Banner';
|
||||
import VMPerformanceOptions from '../VMPerformanceOptions.vue';
|
||||
|
||||
const AUTO_ENABLED_TIP = 'harvester.virtualMachine.volume.diskPerformance.ioThreadsPolicy.autoEnabledTip';
|
||||
const NO_VIRTIO_TIP = 'harvester.virtualMachine.volume.diskPerformance.blockMultiQueue.noVirtioTip';
|
||||
|
||||
function mountOptions(props = {}, { featureEnabled = true } = {}) {
|
||||
return mount(VMPerformanceOptions, {
|
||||
props: { mode: _CREATE, ...props },
|
||||
global: {
|
||||
mocks: {
|
||||
$store: {
|
||||
getters: {
|
||||
'harvester-common/getFeatureEnabled': () => featureEnabled,
|
||||
'i18n/t': (key) => key,
|
||||
'i18n/exists': () => true,
|
||||
}
|
||||
},
|
||||
t: (key) => key,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function bannerFor(wrapper, labelKey) {
|
||||
return wrapper.findAllComponents(Banner).find((b) => b.props('labelKey') === labelKey);
|
||||
}
|
||||
|
||||
describe('component: VMPerformanceOptions', () => {
|
||||
it('should be hidden when the highPerformanceStorage feature is disabled', () => {
|
||||
const wrapper = mountOptions({}, { featureEnabled: false });
|
||||
|
||||
expect(wrapper.find('.vm-perf').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('should show the section with its title and fields, without a toggle', () => {
|
||||
const wrapper = mountOptions();
|
||||
|
||||
expect(wrapper.find('h3').text()).toBe('harvester.virtualMachine.volume.diskPerformance.title');
|
||||
expect(wrapper.find('.expand-toggle').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="input-vm-block-multi-queue"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="input-vm-iothreads-policy"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="input-vm-iothread-count"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('should only accept whole numbers as the supplemental pool thread count', () => {
|
||||
const wrapper = mountOptions({ ioThreadsPolicy: 'supplementalPool', ioThreadCount: 4 });
|
||||
const input = wrapper.find('[data-testid="input-vm-iothread-count"] input');
|
||||
|
||||
expect(input.attributes('inputmode')).toBe('numeric');
|
||||
});
|
||||
|
||||
it.each([
|
||||
[_CREATE, true],
|
||||
[_VIEW, false],
|
||||
])('in %s mode, should mark the supplemental pool thread count as required: %p', (mode, required) => {
|
||||
const wrapper = mountOptions({
|
||||
mode, ioThreadsPolicy: 'supplementalPool', ioThreadCount: 4
|
||||
});
|
||||
|
||||
expect(wrapper.find('[data-testid="input-vm-iothread-count"] .required').exists()).toBe(required);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[{}, false],
|
||||
[{ blockMultiQueue: true }, true],
|
||||
[{ ioThreadsPolicy: 'auto' }, true],
|
||||
])('in view mode with %p, should show the section: %p', (props, shown) => {
|
||||
const wrapper = mountOptions({ ...props, mode: _VIEW });
|
||||
|
||||
expect(wrapper.find('.vm-perf').exists()).toBe(shown);
|
||||
});
|
||||
|
||||
it('should clear Block Multi-Queue when the last virtio disk goes away', async() => {
|
||||
const wrapper = mountOptions({ blockMultiQueue: true, hasVirtioDisk: true });
|
||||
|
||||
await wrapper.setProps({ hasVirtioDisk: false });
|
||||
|
||||
expect(wrapper.emitted('update:blockMultiQueue')).toStrictEqual([[false]]);
|
||||
});
|
||||
|
||||
it('should pass the I/O threads policy hint as a label key so its quotes are not double-escaped', () => {
|
||||
const wrapper = mountOptions({ hasDedicatedIothread: true });
|
||||
const banner = bannerFor(wrapper, AUTO_ENABLED_TIP);
|
||||
|
||||
expect(banner).toBeDefined();
|
||||
expect(banner.props('label')).toBeFalsy();
|
||||
});
|
||||
|
||||
it('should not show the I/O threads policy hint when a policy is set', () => {
|
||||
const wrapper = mountOptions({ hasDedicatedIothread: true, ioThreadsPolicy: 'shared' });
|
||||
|
||||
expect(bannerFor(wrapper, AUTO_ENABLED_TIP)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should pass the no virtio disk hint as a label key', () => {
|
||||
const wrapper = mountOptions({ hasVirtioDisk: false });
|
||||
const banner = bannerFor(wrapper, NO_VIRTIO_TIP);
|
||||
|
||||
expect(banner).toBeDefined();
|
||||
expect(banner.props('label')).toBeFalsy();
|
||||
});
|
||||
});
|
||||
@@ -7,13 +7,13 @@ import UnitInput from '@shell/components/form/UnitInput';
|
||||
import { LabeledInput } from '@components/Form/LabeledInput';
|
||||
import LabeledSelect from '@shell/components/form/LabeledSelect';
|
||||
import ModalWithCard from '@shell/components/ModalWithCard';
|
||||
import { VOLUME_HOTPLUG_ACTION, SOURCE_TYPE } from '../../../config/harvester-map';
|
||||
import { PVC, STORAGE_CLASS } from '@shell/config/types';
|
||||
import { clone } from '@shell/utils/object';
|
||||
import { ucFirst, randomStr } from '@shell/utils/string';
|
||||
import { removeObject } from '@shell/utils/array';
|
||||
import { _VIEW, _EDIT, _CREATE } from '@shell/config/query-params';
|
||||
import { PLUGIN_DEVELOPER, DEV } from '@shell/store/prefs';
|
||||
import { VOLUME_HOTPLUG_ACTION, SOURCE_TYPE } from '../../../config/harvester-map';
|
||||
import { PRODUCT_NAME as HARVESTER_PRODUCT } from '../../../config/harvester';
|
||||
import { HCI } from '../../../types';
|
||||
import { VOLUME_MODE, ACCESS_MODE } from '@pkg/harvester/config/types';
|
||||
|
||||
+3
-24
@@ -2,23 +2,9 @@ import { mount } from '@vue/test-utils';
|
||||
import { _EDIT } from '@shell/config/query-params';
|
||||
import HarvesterEditContainer from '../container.vue';
|
||||
|
||||
const mountOptions = () => ({
|
||||
props: { mode: _EDIT, value: {} },
|
||||
global: {
|
||||
mocks: {
|
||||
$store: {
|
||||
getters: {
|
||||
'harvester-common/getFeatureEnabled': () => true,
|
||||
'i18n/t': jest.fn(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
describe('component: HarvesterEditContainer', () => {
|
||||
it('should display all the inputs', () => {
|
||||
const wrapper = mount(HarvesterEditContainer, mountOptions());
|
||||
const wrapper = mount(HarvesterEditContainer, { propsData: { mode: _EDIT, value: {} } });
|
||||
|
||||
const inputWraps = wrapper.findAll('[data-testid^=input-hec-]');
|
||||
|
||||
@@ -29,7 +15,7 @@ describe('component: HarvesterEditContainer', () => {
|
||||
'name',
|
||||
'container',
|
||||
])('should emit an update on %p input', (field) => {
|
||||
const wrapper = mount(HarvesterEditContainer, mountOptions());
|
||||
const wrapper = mount(HarvesterEditContainer, { propsData: { mode: _EDIT, value: {} } });
|
||||
const input = wrapper.find(`[data-testid="input-hec-${ field }"]`).find('input');
|
||||
const newValue = 123;
|
||||
|
||||
@@ -42,7 +28,7 @@ describe('component: HarvesterEditContainer', () => {
|
||||
'type',
|
||||
'bus',
|
||||
])('should emit an update on %p selection change', async(field) => {
|
||||
const wrapper = mount(HarvesterEditContainer, mountOptions());
|
||||
const wrapper = mount(HarvesterEditContainer, { propsData: { mode: _EDIT, value: {} } });
|
||||
const select = wrapper.find(`[data-testid="input-hec-${ field }"]`);
|
||||
|
||||
select.find('button').trigger('click');
|
||||
@@ -51,11 +37,4 @@ describe('component: HarvesterEditContainer', () => {
|
||||
|
||||
expect(wrapper.emitted('update')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('should not render an empty row when there is no backup to show', () => {
|
||||
const wrapper = mount(HarvesterEditContainer, mountOptions());
|
||||
const emptyRows = wrapper.findAll('.row').filter((row) => row.element.children.length === 0);
|
||||
|
||||
expect(emptyRows).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
+24
-36
@@ -5,17 +5,14 @@ import HarvesterEditExisting from '../existing.vue';
|
||||
describe('component: HarvesterEditExisting', () => {
|
||||
it('should display all the inputs', () => {
|
||||
const wrapper = mount(HarvesterEditExisting, {
|
||||
props: {
|
||||
propsData: {
|
||||
mode: _EDIT, value: {}, rows: []
|
||||
},
|
||||
global: {
|
||||
mocks: {
|
||||
$store: {
|
||||
getters: {
|
||||
'harvester-common/getFeatureEnabled': () => true,
|
||||
'harvester/all': () => [],
|
||||
'i18n/t': jest.fn()
|
||||
}
|
||||
mocks: {
|
||||
$store: {
|
||||
getters: {
|
||||
'harvester/all': () => [],
|
||||
'i18n/t': jest.fn()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -30,17 +27,14 @@ describe('component: HarvesterEditExisting', () => {
|
||||
'name',
|
||||
])('should emit an update on %p input', (field) => {
|
||||
const wrapper = mount(HarvesterEditExisting, {
|
||||
props: {
|
||||
propsData: {
|
||||
mode: _EDIT, value: {}, rows: []
|
||||
},
|
||||
global: {
|
||||
mocks: {
|
||||
$store: {
|
||||
getters: {
|
||||
'harvester-common/getFeatureEnabled': () => true,
|
||||
'harvester/all': () => [],
|
||||
'i18n/t': jest.fn()
|
||||
}
|
||||
mocks: {
|
||||
$store: {
|
||||
getters: {
|
||||
'harvester/all': () => [],
|
||||
'i18n/t': jest.fn()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -59,17 +53,14 @@ describe('component: HarvesterEditExisting', () => {
|
||||
'size',
|
||||
])('should emit an update on %p input and blur', (field) => {
|
||||
const wrapper = mount(HarvesterEditExisting, {
|
||||
props: {
|
||||
propsData: {
|
||||
mode: _EDIT, value: {}, rows: []
|
||||
},
|
||||
global: {
|
||||
mocks: {
|
||||
$store: {
|
||||
getters: {
|
||||
'harvester-common/getFeatureEnabled': () => true,
|
||||
'harvester/all': () => [],
|
||||
'i18n/t': jest.fn()
|
||||
}
|
||||
mocks: {
|
||||
$store: {
|
||||
getters: {
|
||||
'harvester/all': () => [],
|
||||
'i18n/t': jest.fn()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -89,17 +80,14 @@ describe('component: HarvesterEditExisting', () => {
|
||||
// 'bus', // disabled
|
||||
])('should emit an update on %p selection change', async(field) => {
|
||||
const wrapper = mount(HarvesterEditExisting, {
|
||||
props: {
|
||||
propsData: {
|
||||
mode: _EDIT, value: {}, rows: []
|
||||
},
|
||||
global: {
|
||||
mocks: {
|
||||
$store: {
|
||||
getters: {
|
||||
'harvester-common/getFeatureEnabled': () => true,
|
||||
'harvester/all': () => [],
|
||||
'i18n/t': jest.fn()
|
||||
}
|
||||
mocks: {
|
||||
$store: {
|
||||
getters: {
|
||||
'harvester/all': () => [],
|
||||
'i18n/t': jest.fn()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+36
-81
@@ -2,29 +2,23 @@ import { mount } from '@vue/test-utils';
|
||||
import { _CREATE } from '@shell/config/query-params';
|
||||
import HarvesterEditVMImage from '../vmImage.vue';
|
||||
|
||||
// The form emits an update when it is created, so count only the updates that an interaction adds
|
||||
const updates = (wrapper) => wrapper.emitted('update')?.length ?? 0;
|
||||
|
||||
describe('component: HarvesterEditVMImage', () => {
|
||||
it('should display all the inputs', () => {
|
||||
const wrapper = mount(HarvesterEditVMImage, {
|
||||
props: {
|
||||
propsData: {
|
||||
mode: _CREATE,
|
||||
isVirtualType: false,
|
||||
newCreateId: '123',
|
||||
validateRequired: true,
|
||||
idx: 1
|
||||
},
|
||||
global: {
|
||||
mocks: {
|
||||
$store: {
|
||||
getters: {
|
||||
'harvester-common/getFeatureEnabled': () => true,
|
||||
'harvester/all': jest.fn(),
|
||||
'i18n/t': jest.fn(),
|
||||
}
|
||||
},
|
||||
}
|
||||
mocks: {
|
||||
$store: {
|
||||
getters: {
|
||||
'harvester/all': jest.fn(),
|
||||
'i18n/t': jest.fn(),
|
||||
}
|
||||
},
|
||||
}
|
||||
});
|
||||
|
||||
@@ -37,23 +31,20 @@ describe('component: HarvesterEditVMImage', () => {
|
||||
'name',
|
||||
])('should emit an update on %p input', (field) => {
|
||||
const wrapper = mount(HarvesterEditVMImage, {
|
||||
props: {
|
||||
propsData: {
|
||||
mode: _CREATE,
|
||||
isVirtualType: false,
|
||||
newCreateId: '123',
|
||||
validateRequired: true,
|
||||
idx: 1
|
||||
},
|
||||
global: {
|
||||
mocks: {
|
||||
$store: {
|
||||
getters: {
|
||||
'harvester-common/getFeatureEnabled': () => true,
|
||||
'harvester/all': jest.fn(),
|
||||
'i18n/t': jest.fn(),
|
||||
}
|
||||
},
|
||||
}
|
||||
mocks: {
|
||||
$store: {
|
||||
getters: {
|
||||
'harvester/all': jest.fn(),
|
||||
'i18n/t': jest.fn(),
|
||||
}
|
||||
},
|
||||
}
|
||||
});
|
||||
const input = wrapper.find(`[data-testid="input-hevi-${ field }"]`).find('input');
|
||||
@@ -66,38 +57,31 @@ describe('component: HarvesterEditVMImage', () => {
|
||||
|
||||
it.each([
|
||||
'size',
|
||||
])('should emit an update on %p input blur', async(field) => {
|
||||
])('should emit an update on %p input blur', (field) => {
|
||||
const wrapper = mount(HarvesterEditVMImage, {
|
||||
props: {
|
||||
propsData: {
|
||||
mode: _CREATE,
|
||||
isVirtualType: false,
|
||||
newCreateId: '123',
|
||||
validateRequired: true,
|
||||
idx: 1
|
||||
},
|
||||
global: {
|
||||
mocks: {
|
||||
$store: {
|
||||
getters: {
|
||||
'harvester-common/getFeatureEnabled': () => true,
|
||||
'harvester/all': jest.fn(),
|
||||
'i18n/t': jest.fn(),
|
||||
}
|
||||
},
|
||||
}
|
||||
mocks: {
|
||||
$store: {
|
||||
getters: {
|
||||
'harvester/all': jest.fn(),
|
||||
'i18n/t': jest.fn(),
|
||||
}
|
||||
},
|
||||
}
|
||||
});
|
||||
const input = wrapper.find(`[data-testid="input-hevi-${ field }"]`).find('input');
|
||||
const newValue = 123;
|
||||
|
||||
// setting the value already emits an update, so the blur has to add one on top of that
|
||||
await input.setValue(newValue);
|
||||
input.setValue(newValue);
|
||||
input.trigger('blur');
|
||||
|
||||
const afterSetValue = updates(wrapper);
|
||||
|
||||
await input.trigger('blur');
|
||||
|
||||
expect(updates(wrapper)).toBeGreaterThan(afterSetValue);
|
||||
expect(wrapper.emitted('update')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it.each([
|
||||
@@ -106,23 +90,20 @@ describe('component: HarvesterEditVMImage', () => {
|
||||
'bus',
|
||||
])('should emit an update on %p selection change', async(field) => {
|
||||
const wrapper = mount(HarvesterEditVMImage, {
|
||||
props: {
|
||||
propsData: {
|
||||
mode: _CREATE,
|
||||
isVirtualType: false,
|
||||
newCreateId: '123',
|
||||
validateRequired: true,
|
||||
idx: 1
|
||||
},
|
||||
global: {
|
||||
mocks: {
|
||||
$store: {
|
||||
getters: {
|
||||
'harvester-common/getFeatureEnabled': () => true,
|
||||
'harvester/all': jest.fn(),
|
||||
'i18n/t': jest.fn(),
|
||||
}
|
||||
},
|
||||
}
|
||||
mocks: {
|
||||
$store: {
|
||||
getters: {
|
||||
'harvester/all': jest.fn(),
|
||||
'i18n/t': jest.fn(),
|
||||
}
|
||||
},
|
||||
}
|
||||
});
|
||||
const select = wrapper.find(`[data-testid="input-hevi-${ field }"]`);
|
||||
@@ -133,30 +114,4 @@ describe('component: HarvesterEditVMImage', () => {
|
||||
|
||||
expect(wrapper.emitted('update')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('should not render an empty row when there is no backup to show', () => {
|
||||
const wrapper = mount(HarvesterEditVMImage, {
|
||||
props: {
|
||||
mode: _CREATE,
|
||||
isVirtualType: false,
|
||||
newCreateId: '123',
|
||||
validateRequired: true,
|
||||
idx: 1
|
||||
},
|
||||
global: {
|
||||
mocks: {
|
||||
$store: {
|
||||
getters: {
|
||||
'harvester-common/getFeatureEnabled': () => true,
|
||||
'harvester/all': jest.fn(),
|
||||
'i18n/t': jest.fn(),
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
});
|
||||
const emptyRows = wrapper.findAll('.row').filter((row) => row.element.children.length === 0);
|
||||
|
||||
expect(emptyRows).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
+37
-74
@@ -2,24 +2,18 @@ import { mount } from '@vue/test-utils';
|
||||
import { _EDIT } from '@shell/config/query-params';
|
||||
import HarvesterEditVolume from '../volume.vue';
|
||||
|
||||
// The form emits an update when it is created, so count only the updates that an interaction adds
|
||||
const updates = (wrapper) => wrapper.emitted('update')?.length ?? 0;
|
||||
|
||||
describe('component: HarvesterEditVolume', () => {
|
||||
it('should display all the inputs', () => {
|
||||
const wrapper = mount(HarvesterEditVolume, {
|
||||
props: { validateRequired: true },
|
||||
global: {
|
||||
mocks: {
|
||||
$store: {
|
||||
getters: {
|
||||
'harvester-common/getFeatureEnabled': () => true,
|
||||
'harvester/all': jest.fn(),
|
||||
'i18n/t': jest.fn(),
|
||||
'i18n/exists': jest.fn(),
|
||||
}
|
||||
},
|
||||
}
|
||||
propsData: { validateRequired: true },
|
||||
mocks: {
|
||||
$store: {
|
||||
getters: {
|
||||
'harvester/all': jest.fn(),
|
||||
'i18n/t': jest.fn(),
|
||||
'i18n/exists': jest.fn(),
|
||||
}
|
||||
},
|
||||
}
|
||||
});
|
||||
|
||||
@@ -28,56 +22,29 @@ describe('component: HarvesterEditVolume', () => {
|
||||
expect(inputWraps).toHaveLength(4);
|
||||
});
|
||||
|
||||
it('should emit an update on name input', async() => {
|
||||
it.each([
|
||||
'name',
|
||||
'size',
|
||||
])('should emit an update on %p input blur', (field) => {
|
||||
const wrapper = mount(HarvesterEditVolume, {
|
||||
props: { mode: _EDIT, validateRequired: true },
|
||||
global: {
|
||||
mocks: {
|
||||
$store: {
|
||||
getters: {
|
||||
'harvester-common/getFeatureEnabled': () => true,
|
||||
'harvester/all': jest.fn(),
|
||||
'i18n/t': jest.fn(),
|
||||
'i18n/exists': jest.fn(),
|
||||
}
|
||||
},
|
||||
}
|
||||
propsData: { mode: _EDIT, validateRequired: true },
|
||||
mocks: {
|
||||
$store: {
|
||||
getters: {
|
||||
'harvester/all': jest.fn(),
|
||||
'i18n/t': jest.fn(),
|
||||
'i18n/exists': jest.fn(),
|
||||
}
|
||||
},
|
||||
}
|
||||
});
|
||||
const before = updates(wrapper);
|
||||
const input = wrapper.find('[data-testid="input-hev-name"]').find('input');
|
||||
const input = wrapper.find(`[data-testid="input-hev-${ field }"]`).find('input');
|
||||
const newValue = 123;
|
||||
|
||||
await input.setValue(123);
|
||||
input.setValue(newValue);
|
||||
input.trigger('blur');
|
||||
|
||||
expect(updates(wrapper)).toBeGreaterThan(before);
|
||||
});
|
||||
|
||||
it('should emit an update on size input blur', async() => {
|
||||
const wrapper = mount(HarvesterEditVolume, {
|
||||
props: { mode: _EDIT, validateRequired: true },
|
||||
global: {
|
||||
mocks: {
|
||||
$store: {
|
||||
getters: {
|
||||
'harvester-common/getFeatureEnabled': () => true,
|
||||
'harvester/all': jest.fn(),
|
||||
'i18n/t': jest.fn(),
|
||||
'i18n/exists': jest.fn(),
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
});
|
||||
const input = wrapper.find('[data-testid="input-hev-size"]').find('input');
|
||||
|
||||
// setting the value already emits an update, so the blur has to add one on top of that
|
||||
await input.setValue(123);
|
||||
|
||||
const afterSetValue = updates(wrapper);
|
||||
|
||||
await input.trigger('blur');
|
||||
|
||||
expect(updates(wrapper)).toBeGreaterThan(afterSetValue);
|
||||
expect(wrapper.emitted('update')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it.each([
|
||||
@@ -85,27 +52,23 @@ describe('component: HarvesterEditVolume', () => {
|
||||
'bus'
|
||||
])('should emit an update on %p selection change', async(field) => {
|
||||
const wrapper = mount(HarvesterEditVolume, {
|
||||
props: { mode: _EDIT, validateRequired: true },
|
||||
global: {
|
||||
mocks: {
|
||||
$store: {
|
||||
getters: {
|
||||
'harvester-common/getFeatureEnabled': () => true,
|
||||
'harvester/all': jest.fn(),
|
||||
'i18n/t': jest.fn(),
|
||||
'i18n/exists': jest.fn(),
|
||||
}
|
||||
},
|
||||
}
|
||||
propsData: { mode: _EDIT, validateRequired: true },
|
||||
mocks: {
|
||||
$store: {
|
||||
getters: {
|
||||
'harvester/all': jest.fn(),
|
||||
'i18n/t': jest.fn(),
|
||||
'i18n/exists': jest.fn(),
|
||||
}
|
||||
},
|
||||
}
|
||||
});
|
||||
const before = updates(wrapper);
|
||||
const select = wrapper.find(`[data-testid="input-hev-${ field }"]`);
|
||||
|
||||
select.find('button').trigger('click');
|
||||
await wrapper.trigger('keydown.down');
|
||||
await wrapper.trigger('keydown.enter');
|
||||
|
||||
expect(updates(wrapper)).toBeGreaterThan(before);
|
||||
expect(wrapper.emitted('update')).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
+6
-14
@@ -2,10 +2,8 @@
|
||||
import { LabeledInput } from '@components/Form/LabeledInput';
|
||||
import LabeledSelect from '@shell/components/form/LabeledSelect';
|
||||
import InputOrDisplay from '@shell/components/InputOrDisplay';
|
||||
import LabelValue from '@shell/components/LabelValue';
|
||||
import { VOLUME_TYPE, InterfaceOption } from '../../../../config/harvester-map';
|
||||
import { Banner } from '@components/Banner';
|
||||
import DiskPerformanceOptions from '../DiskPerformanceOptions';
|
||||
|
||||
export default {
|
||||
name: 'HarvesterEditContainer',
|
||||
@@ -13,7 +11,7 @@ export default {
|
||||
emits: ['update'],
|
||||
|
||||
components: {
|
||||
LabeledInput, LabeledSelect, InputOrDisplay, LabelValue, Banner, DiskPerformanceOptions
|
||||
LabeledInput, LabeledSelect, InputOrDisplay, Banner
|
||||
},
|
||||
|
||||
props: {
|
||||
@@ -132,11 +130,11 @@ export default {
|
||||
</InputOrDisplay>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
v-if="value.volumeBackups"
|
||||
class="row mb-20"
|
||||
>
|
||||
<div class="col span-6">
|
||||
<div class="row mb-20">
|
||||
<div
|
||||
v-if="value.volumeBackups"
|
||||
class="col span-6"
|
||||
>
|
||||
<InputOrDisplay
|
||||
:name="t('harvester.virtualMachine.volume.readyToUse')"
|
||||
:value="value.volumeBackups.readyToUse"
|
||||
@@ -155,11 +153,5 @@ export default {
|
||||
class="mb-20"
|
||||
:label="value.volumeBackups.error.message"
|
||||
/>
|
||||
|
||||
<DiskPerformanceOptions
|
||||
:value="value"
|
||||
:mode="mode"
|
||||
@update="update"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
+1
-16
@@ -14,7 +14,6 @@ import { VOLUME_MODE } from '@pkg/harvester/config/types';
|
||||
import { HCI } from '../../../../types';
|
||||
import { VOLUME_TYPE, InterfaceOption } from '../../../../config/harvester-map';
|
||||
import { GIBIBYTE } from '../../../../utils/unit';
|
||||
import DiskPerformanceOptions from '../DiskPerformanceOptions';
|
||||
|
||||
export default {
|
||||
name: 'HarvesterEditExisting',
|
||||
@@ -22,7 +21,7 @@ export default {
|
||||
emits: ['update'],
|
||||
|
||||
components: {
|
||||
UnitInput, LabeledInput, LabeledSelect, InputOrDisplay, LabelValue, Banner, Checkbox, DiskPerformanceOptions
|
||||
UnitInput, LabeledInput, LabeledSelect, InputOrDisplay, LabelValue, Banner, Checkbox
|
||||
},
|
||||
|
||||
props: {
|
||||
@@ -173,14 +172,6 @@ export default {
|
||||
this.value.storageClassName = pvcResource.spec.storageClassName;
|
||||
this.value.volumeMode = pvcResource.spec.volumeMode;
|
||||
this.value.shareable = false;
|
||||
|
||||
// Adopt the volume's default high-performance profile (if any) as a starting point.
|
||||
const ann = pvcResource.metadata?.annotations || {};
|
||||
|
||||
this.value.cache = ann[HCI_ANNOTATIONS.DISK_CACHE_MODE] || '';
|
||||
this.value.io = ann[HCI_ANNOTATIONS.DISK_IO_MODE] || '';
|
||||
this.value.dedicatedIOThread = ann[HCI_ANNOTATIONS.DISK_DEDICATED_IOTHREAD] === 'true';
|
||||
|
||||
this.update();
|
||||
},
|
||||
|
||||
@@ -388,11 +379,5 @@ export default {
|
||||
class="mb-20"
|
||||
:label="value.volumeBackups.error.message"
|
||||
/>
|
||||
|
||||
<DiskPerformanceOptions
|
||||
:value="value"
|
||||
:mode="mode"
|
||||
@update="update"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
+6
-13
@@ -15,7 +15,6 @@ import LabelValue from '@shell/components/LabelValue';
|
||||
import { ucFirst } from '@shell/utils/string';
|
||||
import { GIBIBYTE } from '../../../../utils/unit';
|
||||
import { EMPTY_IMAGE } from '../../../../utils/vm';
|
||||
import DiskPerformanceOptions from '../DiskPerformanceOptions';
|
||||
|
||||
export default {
|
||||
name: 'HarvesterEditVMImage',
|
||||
@@ -23,7 +22,7 @@ export default {
|
||||
emits: ['update'],
|
||||
|
||||
components: {
|
||||
UnitInput, LabeledInput, LabeledSelect, InputOrDisplay, LabelValue, Banner, DiskPerformanceOptions
|
||||
UnitInput, LabeledInput, LabeledSelect, InputOrDisplay, LabelValue, Banner
|
||||
},
|
||||
|
||||
props: {
|
||||
@@ -461,11 +460,11 @@ export default {
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
v-if="value.volumeBackups && isView"
|
||||
class="row mb-20"
|
||||
>
|
||||
<div class="col span-3">
|
||||
<div class="row mb-20">
|
||||
<div
|
||||
v-if="value.volumeBackups && isView"
|
||||
class="col span-3"
|
||||
>
|
||||
<LabelValue
|
||||
:name="t('harvester.virtualMachine.volume.readyToUse')"
|
||||
:value="readyToUse"
|
||||
@@ -483,11 +482,5 @@ export default {
|
||||
color="error"
|
||||
:label="t('harvester.virtualMachine.volume.vmImageVolumeTip', {diskSize: diskSize, imageVirtualSize: imageVirtualSize})"
|
||||
/>
|
||||
|
||||
<DiskPerformanceOptions
|
||||
:value="value"
|
||||
:mode="mode"
|
||||
@update="update"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -9,7 +9,6 @@ import { formatSi, parseSi } from '@shell/utils/units';
|
||||
import { VOLUME_TYPE, InterfaceOption } from '../../../../config/harvester-map';
|
||||
import { _VIEW } from '@shell/config/query-params';
|
||||
import LabelValue from '@shell/components/LabelValue';
|
||||
import DiskPerformanceOptions from '../DiskPerformanceOptions';
|
||||
import { ucFirst } from '@shell/utils/string';
|
||||
import { LVM_DRIVER } from '../../../../models/harvester/storage.k8s.io.storageclass';
|
||||
import { DATA_ENGINE_V2 } from '../../../../models/harvester/persistentvolumeclaim';
|
||||
@@ -25,7 +24,7 @@ export default {
|
||||
emits: ['update'],
|
||||
|
||||
components: {
|
||||
InputOrDisplay, Loading, LabeledInput, LabeledSelect, UnitInput, LabelValue, DiskPerformanceOptions
|
||||
InputOrDisplay, Loading, LabeledInput, LabeledSelect, UnitInput, LabelValue
|
||||
},
|
||||
|
||||
props: {
|
||||
@@ -363,11 +362,6 @@ export default {
|
||||
</InputOrDisplay>
|
||||
</div>
|
||||
</div>
|
||||
<DiskPerformanceOptions
|
||||
:value="value"
|
||||
:mode="mode"
|
||||
@update="update"
|
||||
/>
|
||||
<div class="row mb-20">
|
||||
<div
|
||||
v-if="value.volumeEncryptionFeatureEnabled && isView"
|
||||
|
||||
+1
-1
@@ -333,7 +333,7 @@ $xml-height: 350px;
|
||||
min-height: $xml-height;
|
||||
font-family: monospace;
|
||||
|
||||
& .code-mirror .cm-editor {
|
||||
& .code-mirror .CodeMirror {
|
||||
min-height: $xml-height;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
import VM_MIXIN from '@pkg/harvester/mixins/harvester-vm';
|
||||
import HarvesterEditVM from '../index.vue';
|
||||
|
||||
function saveWith(userScript) {
|
||||
const buttonCb = jest.fn();
|
||||
const form = {
|
||||
userScript,
|
||||
errors: [],
|
||||
isSingle: true,
|
||||
t: (key) => key,
|
||||
validateCPUMemory: jest.fn(),
|
||||
validateWindowsSysprep: jest.fn(),
|
||||
validateCloudInit: VM_MIXIN.methods.validateCloudInit,
|
||||
saveSingle: jest.fn(),
|
||||
};
|
||||
|
||||
HarvesterEditVM.methods.saveVM.call(form, buttonCb);
|
||||
|
||||
return { form, buttonCb };
|
||||
}
|
||||
|
||||
describe('page: kubevirt.io.virtualmachine edit', () => {
|
||||
it('should stop the save when the cloud config is invalid', () => {
|
||||
const { form, buttonCb } = saveWith('#cloud-config\nsome words\n');
|
||||
|
||||
expect(form.errors).toStrictEqual(['harvester.virtualMachine.cloudConfig.user.invalidYaml']);
|
||||
expect(buttonCb).toHaveBeenCalledWith(false);
|
||||
expect(form.saveSingle).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should save when the user data is a script', () => {
|
||||
const { form, buttonCb } = saveWith('#!/bin/bash\napt-get update\n# start it\nsystemctl enable --now nginx\n');
|
||||
|
||||
expect(form.errors).toStrictEqual([]);
|
||||
expect(form.saveSingle).toHaveBeenCalledWith(buttonCb);
|
||||
});
|
||||
});
|
||||
@@ -34,7 +34,6 @@ import CpuMemory from './VirtualMachineCpuMemory';
|
||||
import CpuModel from './VirtualMachineCpuModel';
|
||||
import Network from './VirtualMachineNetwork';
|
||||
import Volume from './VirtualMachineVolume';
|
||||
import VMPerformanceOptions from './VirtualMachineVolume/VMPerformanceOptions';
|
||||
import SSHKey from './VirtualMachineSSHKey';
|
||||
import Reserved from './VirtualMachineReserved';
|
||||
import Filesystem from './VirtualMachineFilesystem';
|
||||
@@ -56,7 +55,6 @@ export default {
|
||||
LabeledSelect,
|
||||
NameNsDescription,
|
||||
Volume,
|
||||
VMPerformanceOptions,
|
||||
SSHKey,
|
||||
Network,
|
||||
CpuMemory,
|
||||
@@ -381,7 +379,6 @@ export default {
|
||||
|
||||
this.validateCPUMemory();
|
||||
this.validateWindowsSysprep();
|
||||
this.validateCloudInit();
|
||||
|
||||
// block create VM flow if has validation errors
|
||||
if (this.errors.length) {
|
||||
@@ -745,25 +742,6 @@ export default {
|
||||
name="basics"
|
||||
:label="t('harvester.virtualMachine.detail.tabs.basics')"
|
||||
>
|
||||
<div class="row mb-20">
|
||||
<div class="col span-6">
|
||||
<LabeledSelect
|
||||
v-model:value="osType"
|
||||
label-key="harvester.virtualMachine.osType"
|
||||
:options="OS"
|
||||
:disabled="!isCreate"
|
||||
:tooltip="isCreate ? t('harvester.virtualMachine.osTypeTooltip') : null"
|
||||
/>
|
||||
</div>
|
||||
<div class="col span-6">
|
||||
<CpuModel
|
||||
v-model:value="cpuModel"
|
||||
:mode="mode"
|
||||
@update:value="updateCpuModel"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<CpuMemory
|
||||
class="mb-20"
|
||||
:cpu="cpu"
|
||||
@@ -775,87 +753,6 @@ export default {
|
||||
@updateCpuMemory="updateCpuMemory"
|
||||
/>
|
||||
|
||||
<div class="mb-20">
|
||||
<Checkbox
|
||||
v-if="value.cpuPinningFeatureEnabled"
|
||||
v-model:value="cpuPinning"
|
||||
:disabled="!enableCpuPinningCheckbox"
|
||||
class="check"
|
||||
type="checkbox"
|
||||
tooltip-key="harvester.virtualMachine.cpuPinning.tooltip"
|
||||
label-key="harvester.virtualMachine.cpuPinning.label"
|
||||
:mode="mode"
|
||||
/>
|
||||
|
||||
<Checkbox
|
||||
v-model:value="installUSBTablet"
|
||||
class="check"
|
||||
type="checkbox"
|
||||
tooltip-key="harvester.virtualMachine.usbTip"
|
||||
label-key="harvester.virtualMachine.enableUsb"
|
||||
:mode="mode"
|
||||
/>
|
||||
|
||||
<Checkbox
|
||||
v-model:value="tpmEnabled"
|
||||
class="check"
|
||||
type="checkbox"
|
||||
label-key="harvester.virtualMachine.systemOptions.tpm"
|
||||
:mode="mode"
|
||||
/>
|
||||
|
||||
<Checkbox
|
||||
v-if="value.tpmPersistentStateFeatureEnabled && tpmEnabled"
|
||||
v-model:value="tpmPersistentStateEnabled"
|
||||
class="check"
|
||||
type="checkbox"
|
||||
:label="t('harvester.virtualMachine.systemOptions.tpmPersistentState')"
|
||||
:mode="mode"
|
||||
/>
|
||||
|
||||
<Checkbox
|
||||
v-model:value="efiEnabled"
|
||||
class="check"
|
||||
type="checkbox"
|
||||
:label="t('harvester.virtualMachine.systemOptions.efiEnabled')"
|
||||
:mode="mode"
|
||||
/>
|
||||
|
||||
<Checkbox
|
||||
v-if="value.efiPersistentStateFeatureEnabled && efiEnabled"
|
||||
v-model:value="efiPersistentStateEnabled"
|
||||
class="check"
|
||||
type="checkbox"
|
||||
:label="t('harvester.virtualMachine.systemOptions.efiPersistentState')"
|
||||
:mode="mode"
|
||||
/>
|
||||
|
||||
<Checkbox
|
||||
v-if="efiEnabled"
|
||||
v-model:value="secureBoot"
|
||||
class="check"
|
||||
type="checkbox"
|
||||
:label="t('harvester.virtualMachine.systemOptions.secureBoot')"
|
||||
:mode="mode"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Banner
|
||||
v-if="showCpuPinningBanner"
|
||||
:color="mode === 'create' ? 'info' : 'warning'"
|
||||
>
|
||||
<MessageLink
|
||||
v-if="mode === 'create'"
|
||||
:to="to"
|
||||
prefix-label="harvester.virtualMachine.cpuPinning.cpuManager.prefix"
|
||||
middle-label="harvester.virtualMachine.cpuPinning.cpuManager.middle"
|
||||
suffix-label="harvester.virtualMachine.cpuPinning.cpuManager.suffix"
|
||||
/>
|
||||
<span v-if="mode==='edit'">
|
||||
{{ t('harvester.virtualMachine.cpuPinning.restartVMMessage') }}
|
||||
</span>
|
||||
</Banner>
|
||||
|
||||
<SSHKey
|
||||
v-model:value="sshKey"
|
||||
class="mb-20"
|
||||
@@ -891,7 +788,6 @@ export default {
|
||||
>
|
||||
<Network
|
||||
v-model:value="networkRows"
|
||||
v-model:network-boot-first="networkBootFirst"
|
||||
:mode="mode"
|
||||
:is-single="isSingle"
|
||||
/>
|
||||
@@ -1069,6 +965,18 @@ export default {
|
||||
:mode="mode"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="col span-6">
|
||||
<LabeledSelect
|
||||
v-model:value="osType"
|
||||
label-key="harvester.virtualMachine.osType"
|
||||
:options="OS"
|
||||
:disabled="!isCreate"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row mb-20">
|
||||
<div class="col span-6">
|
||||
<LabeledSelect
|
||||
v-model:value="maintenanceStrategy"
|
||||
@@ -1078,9 +986,6 @@ export default {
|
||||
:mode="mode"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row mb-20">
|
||||
<div class="col span-6">
|
||||
<Reserved
|
||||
:reserved-memory="reservedMemory"
|
||||
@@ -1090,6 +995,16 @@ export default {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row mb-20">
|
||||
<div class="col span-6">
|
||||
<CpuModel
|
||||
v-model:value="cpuModel"
|
||||
:mode="mode"
|
||||
@update:value="updateCpuModel"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row mb-20">
|
||||
<a
|
||||
v-if="showAdvanced"
|
||||
@@ -1146,16 +1061,6 @@ export default {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<VMPerformanceOptions
|
||||
v-model:block-multi-queue="blockMultiQueue"
|
||||
v-model:io-threads-policy="ioThreadsPolicy"
|
||||
v-model:io-thread-count="ioThreadCount"
|
||||
:has-virtio-disk="hasVirtioDisk"
|
||||
:has-dedicated-iothread="hasDedicatedIOThread"
|
||||
:mode="mode"
|
||||
class="mb-20"
|
||||
/>
|
||||
|
||||
<CloudConfig
|
||||
ref="yamlEditor"
|
||||
:user-script="userScript"
|
||||
@@ -1166,19 +1071,7 @@ export default {
|
||||
@updateUserData="updateUserData"
|
||||
@updateNetworkData="updateNetworkData"
|
||||
@updateDataTemplateId="updateDataTemplateId"
|
||||
>
|
||||
<template #after-user-data>
|
||||
<Checkbox
|
||||
v-model:value="installAgent"
|
||||
class="check mb-20"
|
||||
type="checkbox"
|
||||
:disabled="isWindows"
|
||||
label-key="harvester.virtualMachine.installAgent"
|
||||
:mode="mode"
|
||||
@update:value="updateAgent"
|
||||
/>
|
||||
</template>
|
||||
</CloudConfig>
|
||||
/>
|
||||
|
||||
<WindowsSysprep
|
||||
v-if="isWindows"
|
||||
@@ -1187,6 +1080,95 @@ export default {
|
||||
:mode="mode"
|
||||
:namespace="value.metadata.namespace"
|
||||
/>
|
||||
|
||||
<Checkbox
|
||||
v-if="value.cpuPinningFeatureEnabled"
|
||||
v-model:value="cpuPinning"
|
||||
:disabled="!enableCpuPinningCheckbox"
|
||||
class="check"
|
||||
type="checkbox"
|
||||
tooltip-key="harvester.virtualMachine.cpuPinning.tooltip"
|
||||
label-key="harvester.virtualMachine.cpuPinning.label"
|
||||
:mode="mode"
|
||||
/>
|
||||
|
||||
<Checkbox
|
||||
v-model:value="installUSBTablet"
|
||||
class="check mt-20"
|
||||
type="checkbox"
|
||||
tooltip-key="harvester.virtualMachine.usbTip"
|
||||
label-key="harvester.virtualMachine.enableUsb"
|
||||
:mode="mode"
|
||||
/>
|
||||
|
||||
<Checkbox
|
||||
v-model:value="installAgent"
|
||||
class="check"
|
||||
type="checkbox"
|
||||
:disabled="isWindows"
|
||||
label-key="harvester.virtualMachine.installAgent"
|
||||
:mode="mode"
|
||||
@update:value="updateAgent"
|
||||
/>
|
||||
|
||||
<Checkbox
|
||||
v-model:value="tpmEnabled"
|
||||
class="check"
|
||||
type="checkbox"
|
||||
label-key="harvester.virtualMachine.advancedOptions.tpm"
|
||||
:mode="mode"
|
||||
/>
|
||||
|
||||
<Checkbox
|
||||
v-if="value.tpmPersistentStateFeatureEnabled && tpmEnabled"
|
||||
v-model:value="tpmPersistentStateEnabled"
|
||||
class="check"
|
||||
type="checkbox"
|
||||
:label="t('harvester.virtualMachine.advancedOptions.tpmPersistentState')"
|
||||
:mode="mode"
|
||||
/>
|
||||
|
||||
<Checkbox
|
||||
v-model:value="efiEnabled"
|
||||
class="check"
|
||||
type="checkbox"
|
||||
:label="t('harvester.virtualMachine.advancedOptions.efiEnabled')"
|
||||
:mode="mode"
|
||||
/>
|
||||
|
||||
<Checkbox
|
||||
v-if="value.efiPersistentStateFeatureEnabled && efiEnabled"
|
||||
v-model:value="efiPersistentStateEnabled"
|
||||
class="check"
|
||||
type="checkbox"
|
||||
:label="t('harvester.virtualMachine.advancedOptions.efiPersistentState')"
|
||||
:mode="mode"
|
||||
/>
|
||||
|
||||
<Checkbox
|
||||
v-if="efiEnabled"
|
||||
v-model:value="secureBoot"
|
||||
class="check"
|
||||
type="checkbox"
|
||||
:label="t('harvester.virtualMachine.advancedOptions.secureBoot')"
|
||||
:mode="mode"
|
||||
/>
|
||||
|
||||
<Banner
|
||||
v-if="showCpuPinningBanner"
|
||||
color="warning"
|
||||
>
|
||||
<MessageLink
|
||||
v-if="mode === 'create'"
|
||||
:to="to"
|
||||
prefix-label="harvester.virtualMachine.advancedOptions.cpuManager.prefix"
|
||||
middle-label="harvester.virtualMachine.advancedOptions.cpuManager.middle"
|
||||
suffix-label="harvester.virtualMachine.advancedOptions.cpuManager.suffix"
|
||||
/>
|
||||
<span v-if="mode==='edit'">
|
||||
{{ t('harvester.virtualMachine.cpuPinning.restartVMMessage') }}
|
||||
</span>
|
||||
</Banner>
|
||||
</Tab>
|
||||
</Tabbed>
|
||||
|
||||
|
||||
@@ -100,7 +100,8 @@ export default {
|
||||
},
|
||||
|
||||
vmiIp() {
|
||||
const resource = this.$store.getters[`${ this.inStore }/byId`](HCI.VMI, this.value);
|
||||
const vmiResources = this.$store.getters[`${ this.inStore }/all`](HCI.VMI);
|
||||
const resource = vmiResources.find((VMI) => VMI.id === this.value) || null;
|
||||
const networksName = this.row.networksName || [];
|
||||
const vmiNetworks = resource?.spec?.networks || [];
|
||||
|
||||
|
||||
@@ -20,9 +20,7 @@ export default {
|
||||
|
||||
computed: {
|
||||
vmiResource() {
|
||||
const inStore = this.$store.getters['currentProduct'].inStore;
|
||||
|
||||
return this.$store.getters[`${ inStore }/byId`](HCI.VMI, this.vmResource?.id) || null;
|
||||
return this.$store.getters['harvester/byId'](HCI.VMI, this.vmResource?.id) || null;
|
||||
},
|
||||
migrationState() {
|
||||
return this.vmiResource?.migrationState?.status || '';
|
||||
|
||||
@@ -6,9 +6,6 @@ import harvesterCommonStore from './store/harvester-common';
|
||||
import harvesterStore from './store/harvester-store';
|
||||
import customValidators from './validators';
|
||||
import { PRODUCT_NAME } from './config/harvester';
|
||||
import {
|
||||
hostResolvesL10nGlobals, resolveL10nGlobals, standaloneProductName, PRODUCT_NAME_GLOBAL
|
||||
} from './utils/l10n-globals';
|
||||
import { defineAsyncComponent } from 'vue';
|
||||
import './styles/vue-flow.scss';
|
||||
|
||||
@@ -20,15 +17,6 @@ export default function (plugin: IPlugin) {
|
||||
// Auto-import model, detail, edit from the folders
|
||||
importTypes(plugin);
|
||||
|
||||
if (isSingleVirtualCluster) {
|
||||
// Standalone: the server-flavor setting picks the product name, see config/harvester-cluster
|
||||
plugin.register('l10n-global', PRODUCT_NAME_GLOBAL, standaloneProductName);
|
||||
} else if (!hostResolvesL10nGlobals(plugin.environment?.version)) {
|
||||
// Hosts older than Rancher 2.16 would show `[[Harvester]]` literally, so resolve the tokens here.
|
||||
// Mutating the module in place also updates the copy that importTypes registered.
|
||||
resolveL10nGlobals(require('./l10n/en-us.yaml'));
|
||||
}
|
||||
|
||||
// Provide plugin metadata from package.json
|
||||
plugin.metadata = require('./package.json');
|
||||
|
||||
|
||||
+70
-269
@@ -25,14 +25,13 @@ generic:
|
||||
|
||||
unsupported:
|
||||
serverVersion: 'Current version: <code>{serverVersion}</code>'
|
||||
description: '[[Harvester]] ui only supports [[Harvester]] cluster version greater or equal to 1.3.0.'
|
||||
learnMore: Learn more about [[Harvester]] from the <a target="_blank" href="https://harvesterhci.io/" rel="noopener noreferrer nofollow">[[Harvester]] Web Site</a> or read the <a target="_blank" href="https://docs.harvesterhci.io/" rel="noopener noreferrer nofollow">[[Harvester]] Docs</a>
|
||||
description: Harvester ui only supports Harvester cluster version greater or equal to 1.3.0.
|
||||
learnMore: Learn more about Harvester from the <a target="_blank" href="https://harvesterhci.io/" rel="noopener noreferrer nofollow">Harvester Web Site</a> or read the <a target="_blank" href="https://docs.harvesterhci.io/" rel="noopener noreferrer nofollow">Harvester Docs</a>
|
||||
|
||||
nav:
|
||||
group:
|
||||
networks: Networks
|
||||
backupAndSnapshot: Backup and Snapshots
|
||||
hardwareDevices: Hardware Devices
|
||||
Monitoring: Monitoring
|
||||
Logging: Logging
|
||||
'Monitoring and Logging': Monitoring and Logging
|
||||
@@ -88,10 +87,10 @@ harvester:
|
||||
primeLabel: '{vendor}'
|
||||
primeEmptyLabel: ''
|
||||
logos:
|
||||
tip: 'Upload a logo to replace the [[Harvester]] logo in the top-level navigation header. Image height should be 21 pixels with a max width of 200 pixels. Max file size is 20KB. Accepted formats: JPEG, PNG, SVG.'
|
||||
tip: 'Upload a logo to replace the Harvester logo in the top-level navigation header. Image height should be 21 pixels with a max width of 200 pixels. Max file size is 20KB. Accepted formats: JPEG, PNG, SVG.'
|
||||
favicon:
|
||||
tip: 'Upload an icon to replace the [[Harvester]] favicon in the browser tab. Max file size is 20KB'
|
||||
productLabel: '[[Harvester]]'
|
||||
tip: 'Upload an icon to replace the Harvester favicon in the browser tab. Max file size is 20KB'
|
||||
productLabel: 'Harvester'
|
||||
modal:
|
||||
backup:
|
||||
success: 'Backup { backUpName } has been initiated.'
|
||||
@@ -183,7 +182,7 @@ harvester:
|
||||
delete: Delete
|
||||
bundle:
|
||||
title: Generate a Support Bundle
|
||||
titleDescription: Collect system-related logs in [[Harvester]] to assist with troubleshooting and support.
|
||||
titleDescription: Collect system-related logs in Harvester to assist with troubleshooting and support.
|
||||
tip: Each field below specifies an aspect of the support bundle. For detailed explanations, please refer to the <a href="{doc}" target="_blank">documentation</a>.
|
||||
url: Issue URL
|
||||
description: Description
|
||||
@@ -287,7 +286,6 @@ harvester:
|
||||
createTemplate: Generate Template
|
||||
enableMaintenance: Enable Maintenance Mode
|
||||
disableMaintenance: Disable Maintenance Mode
|
||||
clearMaintenance: Clear Maintenance Mode Error
|
||||
enableCPUManager: Enable CPU Manager
|
||||
disableCPUManager: Disable CPU Manager
|
||||
cordon: Cordon
|
||||
@@ -337,7 +335,7 @@ harvester:
|
||||
attachedVM: Attached Virtual Machine
|
||||
cpuManager: CPU<br>Manager
|
||||
diskState: Disk
|
||||
routeConnectivityTooltip: Connectivity between the VM network and the management network, which the [[Harvester]] nodes are connected to.
|
||||
routeConnectivityTooltip: Connectivity between the VM network and the management network, which the Harvester nodes are connected to.
|
||||
fingerprint: Fingerprint
|
||||
value: Value
|
||||
actions: Actions
|
||||
@@ -502,7 +500,7 @@ harvester:
|
||||
aclEmptyError: The fields in subnet access control list rule can not be empty.
|
||||
dashboard:
|
||||
label: Dashboard
|
||||
header: "[[Harvester]] Cluster: {cluster}"
|
||||
header: "Harvester Cluster: {cluster}"
|
||||
hardwareResourceGauge:
|
||||
cpu: CPU
|
||||
memory: Memory
|
||||
@@ -513,58 +511,6 @@ harvester:
|
||||
label: Events
|
||||
vmMetrics:
|
||||
label: Virtual Machine Metrics
|
||||
healthSummary:
|
||||
component: Component
|
||||
severity: Severity
|
||||
errorCount: Errors
|
||||
warningCount: Warnings
|
||||
expandAll: Expand All
|
||||
collapseAll: Collapse All
|
||||
componentHealth:
|
||||
label: Components
|
||||
errors: '{count, plural, =1 {1 error} other {# errors}}'
|
||||
component: Component
|
||||
check: Check
|
||||
severity: Severity
|
||||
message: Message
|
||||
affectedCount: Affected Resources
|
||||
noAffectedResources: No affected resources
|
||||
noIssues: No issues detected
|
||||
checksNotLoaded: Unable to load the checks
|
||||
showIgnored: 'Show ignored ({counts})'
|
||||
ignoredChecks: '{count, plural, =1 {1 check} other {# checks}}'
|
||||
ignoredResources: '{count, plural, =1 {1 resource} other {# resources}}'
|
||||
loadFailed:
|
||||
healthSummaries: 'Unable to load the health summary: {error}'
|
||||
componentHealths: 'Unable to load the checks: {error}'
|
||||
ignoreRules: 'Unable to load the ignore rules: {error}'
|
||||
ignore:
|
||||
create: Create Ignore Rule
|
||||
view: View Ignore Rule
|
||||
edit: Edit Ignore Rule
|
||||
delete: Delete Ignore Rule
|
||||
ignored: Ignored
|
||||
plusIgnored: '+ {n} ignored'
|
||||
scope: Scope
|
||||
scopeResources: Selected resources
|
||||
scopeCheck: Entire check
|
||||
resources: Resources
|
||||
duration: Ignore for
|
||||
days7: 7 days
|
||||
days30: 30 days
|
||||
forever: Forever
|
||||
expiresOn: 'Expires on {date}'
|
||||
expiredOn: 'Expired on {date}'
|
||||
neverExpires: Never expires
|
||||
willExpireOn: 'Will expire on {date}'
|
||||
willNeverExpire: Will never expire
|
||||
staysExpired: 'This rule expired on {date} and stays expired unless you choose how long to ignore for.'
|
||||
reason: Reason
|
||||
reasonPlaceholder: Why is it ignored? (optional)
|
||||
created: The ignore rule of {name} is created
|
||||
updated: The ignore rule of {name} is updated
|
||||
attemptingToDelete: You are attempting to delete the ignore rule of
|
||||
reportedAgain: What it ignores will be reported again.
|
||||
|
||||
version: Version
|
||||
host:
|
||||
@@ -740,7 +686,6 @@ harvester:
|
||||
virtualMachine:
|
||||
label: Virtual Machines
|
||||
osType: OS Type
|
||||
osTypeTooltip: Selecting an image with an OS label on the Volumes tab may change the OS Type selection.
|
||||
cpuModel:
|
||||
label: CPU Model
|
||||
fetchError: 'Failed to load CPU model configuration: {error}'
|
||||
@@ -812,10 +757,6 @@ harvester:
|
||||
tooltip: Enable CPU Pinning brings better performance and reduce latency for the virtual machine
|
||||
restartVMMessage: Changing the CPU Pinning setting requires a virtual machine reboot for the change to take effect
|
||||
migrationMessage: This virtual machine can only be migrated to a target node that has CPU Manager enabled, as CPU Pinning is configured.
|
||||
cpuManager:
|
||||
prefix: You must enable CPU Manager for at least one node in
|
||||
middle: 'host page'
|
||||
suffix: to enable CPU Pinning for VM
|
||||
restartNow: |-
|
||||
{restart, select,
|
||||
true {Restart}
|
||||
@@ -825,9 +766,13 @@ harvester:
|
||||
genericLoginError: Authentication failed. Please re-log in and try again.
|
||||
installAgent: Install guest agent
|
||||
enableUsb: Enable USB Tablet
|
||||
systemOptions:
|
||||
advancedOptions:
|
||||
tpm: Enable TPM
|
||||
tpmPersistentState: TPM Persistent State
|
||||
cpuManager:
|
||||
prefix: You must enable CPU Manager for at least one node in
|
||||
middle: 'host page'
|
||||
suffix: to enable CPU Pinning for VM
|
||||
efiEnabled: Booting in EFI mode
|
||||
efiPersistentState: EFI Persistent State
|
||||
secureBoot: Secure Boot
|
||||
@@ -855,51 +800,6 @@ harvester:
|
||||
setFirst: Set as root volume
|
||||
saveVolume: Update Volume
|
||||
encryption: Encryption
|
||||
performance:
|
||||
profile:
|
||||
label: Storage Performance Profile
|
||||
tip: '"High Performance" switches the disk to the virtio bus, disables the host cache, uses native AIO and gives the disk a dedicated I/O thread. Choose "Custom" to set each option yourself.'
|
||||
default: Default
|
||||
highPerformance: High Performance
|
||||
custom: Custom
|
||||
highProfileTip: This disk will use the virtio bus, no host cache, native AIO and a dedicated I/O thread.
|
||||
cacheMode:
|
||||
label: Cache Mode
|
||||
tip: 'How the host caches disk I/O. "None" is best for high-throughput guests on block storage, "WriteBack" favors performance and "WriteThrough" favors durability.'
|
||||
default: Default (hypervisor)
|
||||
none: None (no host cache)
|
||||
writeback: WriteBack
|
||||
writethrough: WriteThrough
|
||||
filesystemWarning: "\"None\" (O_DIRECT) requires storage that supports direct I/O. It is recommended only for Block volume mode; on Filesystem volumes the VM may fail to start."
|
||||
ioMode:
|
||||
label: I/O Mode
|
||||
tip: 'How QEMU submits I/O. "Native" (Linux AIO) has the lowest overhead and needs cache mode "None". "Threads" uses a host thread pool.'
|
||||
default: Default (hypervisor)
|
||||
native: Native (AIO)
|
||||
threads: Threads
|
||||
nativeRequiresNoCacheTip: Native I/O mode needs the host cache disabled, so cache mode is set to None.
|
||||
dedicatedIOThread:
|
||||
label: Dedicated I/O Thread
|
||||
tip: Give this disk its own I/O thread instead of sharing one. Useful for disks with heavy I/O.
|
||||
busTip: 'This disk uses the {bus} bus. A dedicated I/O thread needs the virtio bus.'
|
||||
diskPerformance:
|
||||
title: Storage Performance
|
||||
description: These options apply to all volumes of the virtual machine.
|
||||
blockMultiQueue:
|
||||
label: Virtio Block Multi-Queue
|
||||
tip: Spread disk I/O over one queue per vCPU so that it is processed on multiple CPUs.
|
||||
noVirtioTip: Add at least one disk on the virtio bus to enable Block Multi-Queue.
|
||||
ioThreadsPolicy:
|
||||
label: I/O Threads Policy
|
||||
tip: '"Shared" uses one I/O thread for all disks. "Auto" spreads disks over a pool of threads. "Supplemental Pool" uses a fixed number of threads.'
|
||||
default: "Disabled (default)"
|
||||
shared: Shared
|
||||
auto: Auto
|
||||
supplementalPool: Supplemental Pool
|
||||
autoEnabledTip: A volume asks for a dedicated I/O thread, so the Shared policy will be used.
|
||||
ioThreadCount:
|
||||
label: I/O Thread Count
|
||||
tip: Number of I/O threads in the supplemental pool.
|
||||
shareable:
|
||||
label: Shareable
|
||||
tip: Allow multiple virtual machines to attach and write to this volume simultaneously.
|
||||
@@ -921,12 +821,6 @@ harvester:
|
||||
title: Network
|
||||
addNetwork: Add Network
|
||||
addPort: Add Port
|
||||
networkBoot:
|
||||
label: Enable network boot (PXE)
|
||||
tip: Adds this interface to the VM boot order so the guest firmware can boot from the network. Requires a DHCP/TFTP (PXE) server reachable on the selected network; the management network does not provide one.
|
||||
order: Network boot order
|
||||
first: Before volumes
|
||||
last: After volumes
|
||||
cloudConfig:
|
||||
title: Cloud Configuration
|
||||
createTemplateTitle: 'Create {name}'
|
||||
@@ -938,12 +832,10 @@ harvester:
|
||||
label: User Data Template
|
||||
title: "User Data:"
|
||||
tip: "You can specify user data to configure an instance or run a configuration script during launch. If you launch more than one instance at a time, the user data is available to all the instances in that reservation. <a href='https://cloudinit.readthedocs.io/en/latest/topics/examples.html' target='_blank'>Learn more</a>"
|
||||
invalidYaml: 'Invalid User Data YAML syntax'
|
||||
network:
|
||||
label: Network Data Template
|
||||
title: "Network Data:"
|
||||
tip: "The network-data configuration allows you to customize the instance's networking interfaces by assigning subnet configuration, virtual device creation (bonds, bridges, VLANs) routes and DNS configuration. <a href='https://cloudinit.readthedocs.io/en/latest/reference/network-config-format-v1.html' target='_blank'>Learn more</a>"
|
||||
invalidYaml: 'Invalid Network Data YAML syntax'
|
||||
sysprep:
|
||||
title: Windows Unattended & Sysprep Configuration
|
||||
description: "Configure Windows automated installation using autounattend.xml. The configuration will be stored in a Kubernetes Secret and mounted as a CD-ROM during installation. <a href='https://docs.microsoft.com/en-us/windows-hardware/manufacture/desktop/automate-windows-setup' target='_blank'>Learn more</a>"
|
||||
@@ -989,7 +881,7 @@ harvester:
|
||||
displayNamePlaceholder: Virtual machine alias name
|
||||
displayName: Display Name
|
||||
filesystem:
|
||||
description: '[[Harvester]] supports filesystem volumes for VM via virtiofs.'
|
||||
description: Harvester supports filesystem volumes for VM via virtiofs.
|
||||
type: Filesystem Type
|
||||
volume: Volume
|
||||
resource: Resource
|
||||
@@ -1061,104 +953,17 @@ harvester:
|
||||
from: Generated from
|
||||
down: No events in the past hour
|
||||
console:
|
||||
notRunning:
|
||||
title: This virtual machine is not running
|
||||
detail: Start it to use its console.
|
||||
startingTitle: This virtual machine is starting
|
||||
startingDetail: The console connects once it is running.
|
||||
shortcutKeys: Shortcut keys
|
||||
softReboot: Soft reboot
|
||||
view: View
|
||||
shortcutMenu:
|
||||
yourShortcuts: Your shortcuts
|
||||
holdModifiers: Hold modifiers
|
||||
holdHint: 'The next key you pick is sent as {combo}+key.'
|
||||
keys: Keys
|
||||
printScreen: Print Screen
|
||||
functionKeys: Function keys
|
||||
manage: Manage custom shortcuts…
|
||||
blockedDisconnected: Keys can be sent once the console is connected.
|
||||
hint: Clicking the console captures your keyboard. To send a shortcut, use the Shortcut keys menu.
|
||||
hintViewOnly: '"View only" mode is on. In this mode, your mouse and keyboard are not sent to the VM.'
|
||||
viewOnly: View only
|
||||
connection:
|
||||
menuLabel: Connection
|
||||
description: Connected to {name}. If the screen stops updating, reconnecting usually fixes it.
|
||||
customKeys:
|
||||
title: Custom shortcuts
|
||||
description: Save key combinations you send often. They appear at the top of the Shortcut keys menu.
|
||||
new: New shortcut
|
||||
combination: Key combination
|
||||
reserved: Combinations your browser or OS reserves, like Ctrl+Alt+Del or Ctrl+W, can’t be recorded. Send them from the Shortcut keys menu instead, by holding Ctrl or Alt there.
|
||||
duplicate: This key combination is already saved.
|
||||
name: Name (optional)
|
||||
clear: Clear
|
||||
add: Add shortcut
|
||||
saved: 'Saved shortcuts ({count})'
|
||||
delete: 'Delete {name}'
|
||||
done: Done
|
||||
saveError: Unable to save the custom shortcuts
|
||||
recorder:
|
||||
empty: Click here, then press a key combination
|
||||
recording: Press a key combination…
|
||||
recordingStatus: Recording
|
||||
again: Click to record again
|
||||
viewOptions:
|
||||
scaling: Scaling
|
||||
automatic: Automatic
|
||||
manual: Manual
|
||||
automaticHelp: The screen scales to fit the window.
|
||||
manualHelp: You set the zoom. Scroll to see parts of the screen that do not fit.
|
||||
zoom: Zoom level
|
||||
zoomIn: Zoom in
|
||||
zoomOut: Zoom out
|
||||
levelOf: '{value} of {max}'
|
||||
qualityLevel:
|
||||
label: JPEG quality
|
||||
help: Higher quality looks sharper and uses more bandwidth.
|
||||
compressionLevel:
|
||||
label: Compression
|
||||
help: Higher compression saves bandwidth but uses more CPU.
|
||||
reset: Reset to defaults
|
||||
fullscreen:
|
||||
enter: Full screen
|
||||
exit: Exit full screen
|
||||
ctrlAltDel: Ctrl+Alt+Del
|
||||
confirm:
|
||||
ctrlAltDel:
|
||||
title: 'Send Ctrl+Alt+Del to {name}?'
|
||||
message: The key combination goes straight to the guest operating system. On many systems, including most Linux distributions, this restarts the VM immediately. Unsaved work in the VM will be lost.
|
||||
button: Send Ctrl+Alt+Del
|
||||
softReboot:
|
||||
title: 'Soft reboot {name}?'
|
||||
message: The guest operating system is asked to shut down and restart. Unsaved work in the VM will be lost.
|
||||
button: Soft reboot
|
||||
takeOver:
|
||||
label: Take over
|
||||
title: Take over this console?
|
||||
confirm: The other VNC session connected to this virtual machine will be disconnected.
|
||||
overlay:
|
||||
connecting: 'Connecting to {name}…'
|
||||
attempt: 'Attempt {retryTimes} of {maximumRetryTimes}.'
|
||||
reconnectNow: Reconnect now
|
||||
failure:
|
||||
inUse: This console is in use
|
||||
unavailable: Unable to connect
|
||||
dropped: Connection lost
|
||||
error: Connection failed
|
||||
failureDetail:
|
||||
inUse: Another VNC session is connected to this virtual machine. Retry once it is released, or take over the console to disconnect the other session.
|
||||
unavailable: The console is not available. Check that the virtual machine is running, then retry.
|
||||
dropped: The console stopped receiving data from the virtual machine. The VM itself may still be running, or another VNC session may have opened this console.
|
||||
status:
|
||||
connecting: Connecting…
|
||||
connected: Connected
|
||||
disconnected: Disconnected
|
||||
notRunning: Not running
|
||||
failed: Connection failed
|
||||
reconnecting: 'Reconnecting {retryTimes} of {maximumRetryTimes}'
|
||||
credentialsRequired: This console requires credentials that the dashboard cannot provide.
|
||||
inUse: Another VNC session may be using this console. Retrying until it is released.
|
||||
down: This virtual machine is down. Please start it to access its console.
|
||||
shortcutKeys: Shortcut Keys
|
||||
customShortcutKeys: Custom Shortcut Keys
|
||||
management: Management Shortcut Keys
|
||||
record:
|
||||
start: Record
|
||||
recording: Recording
|
||||
stop: Stop Recording
|
||||
tips: Press the record button to capture your keyboard inputs.
|
||||
send: Send
|
||||
preferredKeys: Preferred Custom Shortcut Keys
|
||||
terminationGracePeriodSeconds:
|
||||
label: Termination Grace Period
|
||||
affinity:
|
||||
@@ -1192,8 +997,6 @@ harvester:
|
||||
createWithDataVolumeTooltip: Create Volume with Kubevirt/Containerized Data Importer way. It can fill accessMode/volumeMode automatically.
|
||||
showAdvanced: Show Advanced Options
|
||||
hideAdvanced: Hide Advanced Options
|
||||
performance:
|
||||
pvcTip: These high-performance options are saved as defaults on the volume and applied when it is attached to a virtual machine as a disk.
|
||||
source: Source
|
||||
kind: Kind
|
||||
sourceOptions:
|
||||
@@ -1285,8 +1088,8 @@ harvester:
|
||||
selectExisting: Select Existing Image
|
||||
createRepository: Creating Upgrade Repository
|
||||
succeeded: Succeeded
|
||||
releaseTip: Please read the upgrade documentation carefully. You can view details on the <a href="{url}" target="_blank">[[Harvester]] Release Notes</a>.
|
||||
checkReady: I have read and understood the upgrade instructions related to this [[Harvester]] version.
|
||||
releaseTip: Please read the upgrade documentation carefully. You can view details on the <a href="{url}" target="_blank">Harvester Release Notes</a>.
|
||||
checkReady: I have read and understood the upgrade instructions related to this Harvester version.
|
||||
pending: Pending
|
||||
upload:
|
||||
duplicatedFile: The file you are trying to upload already exists.
|
||||
@@ -1295,7 +1098,7 @@ harvester:
|
||||
os: OS
|
||||
kubernetes: Kubernetes
|
||||
monitoringChart: Monitoring Chart
|
||||
harvesterChart: '[[Harvester]] Chart'
|
||||
harvesterChart: Harvester Chart
|
||||
success: Success
|
||||
fail: Fail
|
||||
ongoing: On-going
|
||||
@@ -1335,7 +1138,7 @@ harvester:
|
||||
maxFailure:
|
||||
label: Max Failure
|
||||
count: Count
|
||||
tooltip: Max number of consecutive failed backups that could be tolerated. If reach this threshold, [[Harvester]] controller will suspend the schedule job. This value should less than retain count
|
||||
tooltip: Max number of consecutive failed backups that could be tolerated. If reach this threshold, Harvester controller will suspend the schedule job. This value should less than retain count
|
||||
virtualMachine:
|
||||
title: Virtual Machine Name
|
||||
placeholder: Select a virtual machine
|
||||
@@ -1349,7 +1152,7 @@ harvester:
|
||||
title: Restore Virtual Machine
|
||||
refreshInterval:
|
||||
label: Refresh Interval
|
||||
tip: The interval for the backup target to sync data to [[Harvester]] cluster. Set to 0 to disable refresh mechanism.
|
||||
tip: The interval for the backup target to sync data to harvester cluster. Set to 0 to disable refresh mechanism.
|
||||
backupTargetTip: The endpoint used to access the backupstore. NFS and S3 are supported.
|
||||
message:
|
||||
noSetting:
|
||||
@@ -1368,7 +1171,7 @@ harvester:
|
||||
actionLabel: Test connection
|
||||
waitingLabel: Testing connection...
|
||||
successLabel: Connection tested
|
||||
successMessage: '[[Harvester]] can successfully connect to the endpoint {endpoint}'
|
||||
successMessage: 'Harvester can successfully connect to the endpoint {endpoint}'
|
||||
restore:
|
||||
backup: Backup
|
||||
deletePreviousVolumes: Delete Previous Volumes
|
||||
@@ -1579,7 +1382,7 @@ harvester:
|
||||
placeholder: Select a provider network
|
||||
networkPolicy:
|
||||
label: Policies
|
||||
banner: The network policies must be used for VMs attached to overlay networks. Please read the <a href="{url}" target="_blank">[[Harvester]] documentation</a> on how network policies work.
|
||||
banner: The network policies must be used for VMs attached to overlay networks. Please read the <a href="{url}" target="_blank">harvester document</a> how the network policy works.
|
||||
network:
|
||||
label: Virtual Machine Networks
|
||||
tabs:
|
||||
@@ -1688,7 +1491,7 @@ harvester:
|
||||
autoRotateRKE2Certs:
|
||||
expiringInHours: Expiring in
|
||||
httpProxy:
|
||||
warning: 'WARNING: <br/> If you configure "http-proxy" and "https-proxy", you must also put [[Harvester]] node's CIDR into "no-proxy", otherwise the [[Harvester]] cluster will be broken.'
|
||||
warning: 'WARNING: <br/> If you configure "http-proxy" and "https-proxy", you must also put Harvester node's CIDR into "no-proxy", otherwise the Harvester cluster will be broken.'
|
||||
supportBundleImage:
|
||||
imagePullPolicy: Pull Policy
|
||||
repo: Repository
|
||||
@@ -1740,7 +1543,7 @@ harvester:
|
||||
strategyType: Strategy Type
|
||||
concurrency: Concurrency
|
||||
harvesterMonitoring:
|
||||
label: '[[Harvester]] Monitoring'
|
||||
label: Harvester Monitoring
|
||||
section:
|
||||
prometheus: Prometheus
|
||||
prometheusNodeExporter: Prometheus Node Exporter
|
||||
@@ -1755,10 +1558,10 @@ harvester:
|
||||
url: URL
|
||||
insecureSkipTLSVerify: Insecure Skip TLS Verify
|
||||
tip:
|
||||
prefix: '[[Harvester]] secures cluster registration via TLS by default. If opt out "Insecure Skip TLS Verify", you must provide custom CA certificates using the'
|
||||
prefix: Harvester secures cluster registration via TLS by default. If opt out "Insecure Skip TLS Verify", you must provide custom CA certificates using the
|
||||
middle: 'additional-ca'
|
||||
suffix: setting.
|
||||
message: To completely unset the imported [[Harvester]] cluster, please also remove it on the Rancher Dashboard UI via the <code> Virtualization Management </code> page.
|
||||
message: To completely unset the imported Harvester cluster, please also remove it on the Rancher Dashboard UI via the <code> Virtualization Management </code> page.
|
||||
ntpServers:
|
||||
isNotIPV4: The address you entered is not IPv4 or host. Please enter a valid IPv4 address or a host address.
|
||||
isDuplicate: There are duplicate NTP server configurations.
|
||||
@@ -1788,19 +1591,19 @@ harvester:
|
||||
networkData: Network Data
|
||||
|
||||
support:
|
||||
title: '[[Harvester]] Support'
|
||||
title: Harvester Support
|
||||
kubeconfig:
|
||||
title: Download KubeConfig
|
||||
titleDescription: Download kubeconfig for debugging.
|
||||
internal:
|
||||
rancher:
|
||||
title: Access Embedded Rancher UI
|
||||
titleDescription: You can only use the embedded Rancher UI for debugging and validation purposes. For more information about how [[Harvester]] integrates with Rancher, see the <a target="_blank" href="{url}" rel="noopener noreferrer nofollow">documentation</a>.
|
||||
titleDescription: You can only use the embedded Rancher UI for debugging and validation purposes. For more information about how Harvester integrates with Rancher, see the <a target="_blank" href="{url}" rel="noopener noreferrer nofollow">documentation</a>.
|
||||
longhorn:
|
||||
title: Access Embedded Longhorn UI
|
||||
titleDescription: We only support to use the embedded Longhorn UI for debugging and validation purpose.
|
||||
community:
|
||||
learnMore: Find out more about [[Harvester]] support
|
||||
learnMore: Find out more about SUSE Harvester support
|
||||
pricing: Contact us for pricing
|
||||
|
||||
namespace:
|
||||
@@ -2020,16 +1823,16 @@ harvester:
|
||||
|
||||
addons:
|
||||
descriptions:
|
||||
'harvester-system/vm-import-controller': vm-import-controller is an add-on to help migrate virtual machine workloads from other source clusters to an existing [[Harvester]] cluster.
|
||||
'harvester-system/pcidevices-controller': pcidevices-controller is an add-on to help discover PCI devices for nodes in your cluster and allow users to prepare devices for PCI Passthrough, for use with [[Harvester]] virtual machine and guest clusters.
|
||||
'cattle-logging-system/rancher-logging': rancher-logging is an add-on to collect versatile logs, events, and audits from the [[Harvester]] cluster and route them to many kinds of servers based on flows.
|
||||
'harvester-system/vm-import-controller': vm-import-controller is an add-on to help migrate virtual machine workloads from other source clusters to an existing Harvester cluster.
|
||||
'harvester-system/pcidevices-controller': pcidevices-controller is an add-on to help discover PCI devices for nodes in your cluster and allow users to prepare devices for PCI Passthrough, for use with Harvester virtual machine and guest clusters.
|
||||
'cattle-logging-system/rancher-logging': rancher-logging is an add-on to collect versatile logs, events, and audits from the Harvester cluster and route them to many kinds of servers based on flows.
|
||||
'harvester-system/rancher-vcluster': rancher-vcluster deploys a virtual cluster (vcluster) with Rancher installed.
|
||||
'cattle-monitoring-system/rancher-monitoring': rancher-monitoring is an add-on that collects [[Harvester]] cluster and virtual machine metrics and allows you to view the metrics on an embedded dashboard and send alert(s) to remote servers.
|
||||
'vm-import-controller': vm-import-controller is an add-on to help migrate virtual machine workloads from other source clusters to an existing [[Harvester]] cluster.
|
||||
'pcidevices-controller': pcidevices-controller is an add-on to help discover PCI devices for nodes in your cluster and allow users to prepare devices for PCI Passthrough, for use with [[Harvester]] virtual machines and guest clusters.
|
||||
'nvidia-driver-toolkit': 'nvidia-driver-toolkit is an add-on to enable vGPU devices and assign them to [[Harvester]] virtual machines.'
|
||||
'rancher-logging': rancher-logging is an add-on to collect versatile logs, events, and audits from the [[Harvester]] cluster and route them to many kinds of servers based on flows.
|
||||
'rancher-monitoring': rancher-monitoring is an add-on to collect [[Harvester]] cluster and virtual machine metrics, view them on the embedded dashboard, and send alert(s) to remote servers.
|
||||
'cattle-monitoring-system/rancher-monitoring': rancher-monitoring is an add-on that collects Harvester cluster and virtual machine metrics and allows you to view the metrics on an embedded dashboard and send alert(s) to remote servers.
|
||||
'vm-import-controller': vm-import-controller is an add-on to help migrate virtual machine workloads from other source clusters to an existing Harvester cluster.
|
||||
'pcidevices-controller': pcidevices-controller is an add-on to help discover PCI devices for nodes in your cluster and allow users to prepare devices for PCI Passthrough, for use with Harvester virtual machines and guest clusters.
|
||||
'nvidia-driver-toolkit': 'nvidia-driver-toolkit is an add-on to enable vGPU devices and assign them to Harvester virtual machines.'
|
||||
'rancher-logging': rancher-logging is an add-on to collect versatile logs, events, and audits from the Harvester cluster and route them to many kinds of servers based on flows.
|
||||
'rancher-monitoring': rancher-monitoring is an add-on to collect Harvester cluster and virtual machine metrics, view them on the embedded dashboard, and send alert(s) to remote servers.
|
||||
'rancher-vcluster': rancher-vcluster deploys a virtual cluster (vcluster) with Rancher installed.
|
||||
'k3k': k3k is an add-on to deploy the k3k controller.
|
||||
'rancher-k3k': rancher-k3k deploys a k3k virtual cluster with Rancher installed.
|
||||
@@ -2098,7 +1901,7 @@ harvester:
|
||||
providerSelect: Provider
|
||||
createNew: Create new provider
|
||||
requirementsTitle: Requirements
|
||||
requirementsText: "To migrate virtual machines from VMware, you will need a vCenter Server running version 6.5 or higher with a user account that has at least read permissions, and the source environment must be network-accessible from [[Harvester]] Node."
|
||||
requirementsText: "To migrate virtual machines from VMware, you will need a vCenter Server running version 6.5 or higher with a user account that has at least read permissions, and the source environment must be network-accessible from Harvester Node."
|
||||
name: Name
|
||||
urlLabel: vCenter/ESXi URL
|
||||
urlPlaceholder: "https://vcenter.example.com/sdk"
|
||||
@@ -2151,7 +1954,7 @@ harvester:
|
||||
datastore: Datastore
|
||||
dashboard:
|
||||
title: Virtual Machine Migration Overview
|
||||
description: "Migrate virtual machines from VMware vSphere to [[Harvester]] using cold migration for data consistency. Create a migration plan to select VMs, map networks and storage, and prepare a migration to [[Harvester]]."
|
||||
description: "Migrate virtual machines from VMware vSphere to Harvester using cold migration for data consistency. Create a migration plan to select VMs, map networks and storage, and prepare a migration to Harvester."
|
||||
createPlan: Create Migration
|
||||
tableTitle: Migrations
|
||||
columns:
|
||||
@@ -2171,22 +1974,22 @@ harvester:
|
||||
checkMigratedVm: Click to check migrated VM details
|
||||
configureMappings:
|
||||
title: Set Mappings
|
||||
description: Map VMware networks and datastores to [[Harvester]] and Longhorn target resources
|
||||
description: Map VMware networks and datastores to Harvester and Longhorn target resources
|
||||
save: Save Mappings and Continue
|
||||
noTemplate: Start from scratch
|
||||
removeMap: Remove mapping
|
||||
networkMapping:
|
||||
title: Network Mapping
|
||||
description: Map VMware port groups to [[Harvester]] networks
|
||||
placeholder: Choose a [[Harvester]] network
|
||||
description: Map VMware port groups to Harvester networks
|
||||
placeholder: Choose a Harvester network
|
||||
template: Use existing network mapping as template
|
||||
options:
|
||||
podNetworking: Management Network
|
||||
ignored: Ignored (No NIC will be created)
|
||||
storageMapping:
|
||||
title: Storage Mapping
|
||||
description: Map VMware datastores to [[Harvester]] storage classes
|
||||
placeholder: Choose a [[Harvester]] Storage Class
|
||||
description: Map VMware datastores to Harvester storage classes
|
||||
placeholder: Choose a Harvester Storage Class
|
||||
template: Use existing storage mapping as template
|
||||
storageDefaults:
|
||||
title: 'Storage defaults — {name}'
|
||||
@@ -2505,7 +2308,7 @@ harvester:
|
||||
vGpuDevices: vGPU Devices
|
||||
showMore: Show More
|
||||
parentSriov: Filter By Parent SR-IOV GPU
|
||||
noPermission: Please contact your system administrator to add [[Harvester]] add-ons first.
|
||||
noPermission: Please contact your system administrator to add Harvester add-ons first.
|
||||
goSetting:
|
||||
prefix: The nvidia-driver-toolkit add-on is not enabled, click
|
||||
middle: here
|
||||
@@ -2541,7 +2344,7 @@ harvester:
|
||||
|
||||
vgpu:
|
||||
label: vGPU Devices
|
||||
noPermission: Please contact system administrator to add [[Harvester]] add-ons first.
|
||||
noPermission: Please contact system administrator to add Harvester add-ons first.
|
||||
detachWarning:
|
||||
title: Cannot Disable vGPU
|
||||
message: Please detach the device from the VM and save it first before disabling this vGPU device.
|
||||
@@ -2562,7 +2365,7 @@ harvester:
|
||||
|
||||
usb:
|
||||
label: USB Devices
|
||||
noPermission: Please contact system admin to add [[Harvester]] add-ons first
|
||||
noPermission: Please contact system admin to add Harvester add-ons first
|
||||
goSetting:
|
||||
prefix: The pcidevices-controller add-on is not enabled, click
|
||||
middle: here
|
||||
@@ -2623,7 +2426,7 @@ typeDescription:
|
||||
# Should fit on one line.
|
||||
# If you link to anything external, it MUST have
|
||||
# target="_blank" rel="noopener noreferrer nofollow"
|
||||
harvester: "Branding allows administrators to globally re-brand the UI by customizing the [[Harvester]] product name, logos and color scheme."
|
||||
harvester: "Branding allows administrators to globally re-brand the UI by customizing the Harvester product name, logos and color scheme."
|
||||
|
||||
advancedSettings:
|
||||
tags:
|
||||
@@ -2638,19 +2441,18 @@ advancedSettings:
|
||||
descriptions:
|
||||
'harv-vlan': Default Network Interface name of the VLAN network.
|
||||
'harv-backup-target': Custom backup target to store virtual machine backups.
|
||||
'branding': Branding allows administrators to globally re-brand the UI by customizing the [[Harvester]] product name, logos, and color scheme.
|
||||
'branding': Branding allows administrators to globally re-brand the UI by customizing the Harvester product name, logos, and color scheme.
|
||||
'harv-csi-driver-config': Configure additional information for CSI drivers.
|
||||
'harv-csi-online-expand-validation': Allow online volume expansion for specific CSI drivers.
|
||||
'harv-containerd-registry': Containerd Registry Configuration to connect private registries.
|
||||
'harv-log-level': Configure [[Harvester]] server log level. Defaults to Info.
|
||||
'harv-server-version': '[[Harvester]] server version.'
|
||||
'harv-server-flavor': "Indicates the [[Harvester]] edition: Prime or Community."
|
||||
'harv-upgrade-checker-enabled': Specifies whether to enable [[Harvester]] upgrade check or not. Default is True.
|
||||
'harv-upgrade-checker-url': Default [[Harvester]] upgrade check url. Only used when the <code>upgrade-checker-enabled</code> is equal to True.
|
||||
'harv-ui-source': Configure how to load the UI source. The `External` option is used to load the UI from a ui-index URL, while the `Bundled` option loads the UI from the local [[Harvester]] server.
|
||||
'harv-log-level': Configure Harvester server log level. Defaults to Info.
|
||||
'harv-server-version': Harvester server version.
|
||||
'harv-upgrade-checker-enabled': Specifies whether to enable Harvester upgrade check or not. Default is True.
|
||||
'harv-upgrade-checker-url': Default Harvester upgrade check url. Only used when the <code>upgrade-checker-enabled</code> is equal to True.
|
||||
'harv-ui-source': Configure how to load the UI source. The `External` option is used to load the UI from a ui-index URL, while the `Bundled` option loads the UI from the local Harvester server.
|
||||
'harv-ui-index': 'HTML index location for the UI.'
|
||||
'harv-cluster-registration-url': Registration URL for multi-cluster management.
|
||||
'harv-http-proxy': 'HTTP proxy for [[Harvester]] to access external services.'
|
||||
'harv-http-proxy': 'HTTP proxy for Harvester to access external services.'
|
||||
'harv-additional-ca': 'Custom CA root certificates for TLS validation.'
|
||||
'harv-overcommit-config': 'Resource overcommit configuration.'
|
||||
'harv-support-bundle-timeout': 'Support bundle timeout configuration in minutes, use 0 to disable the timeout.'
|
||||
@@ -2662,13 +2464,13 @@ advancedSettings:
|
||||
'harv-storage-network': 'Longhorn storage-network setting.'
|
||||
'harv-rwx-network': 'Configure RWX network behavior for shared or dedicated storage network usage.'
|
||||
'harv-support-bundle-namespaces': Select additional namespaces to include in the support bundle.
|
||||
'harv-auto-disk-provision-paths': Specify the disks(using glob pattern) that [[Harvester]] will automatically add as virtual machine storage.
|
||||
'harv-auto-disk-provision-paths': Specify the disks(using glob pattern) that Harvester will automatically add as virtual machine storage.
|
||||
'harv-support-bundle-image': Support bundle image configuration. Find different versions in <a href="https://hub.docker.com/r/rancher/support-bundle-kit/tags" target="_blank">rancher/support-bundle-kit</a>.
|
||||
'harv-release-download-url': This setting allows you to configure the <code>upgrade release download</code> URL address. [[Harvester]] will get the ISO URL and checksum value from the (<code>$URL</code>/<code>$VERSION</code>/version.yaml) file hosted by the configured URL.
|
||||
'harv-release-download-url': This setting allows you to configure the <code>upgrade release download</code> URL address. Harvester will get the ISO URL and checksum value from the (<code>$URL</code>/<code>$VERSION</code>/version.yaml) file hosted by the configured URL.
|
||||
'harv-default-vm-termination-grace-period-seconds': Configure the virtual machine termination grace period for virtual machine stop.
|
||||
'harv-ntp-servers': Configure NTP server. You can configure multiple IPv4 addresses or host addresses.
|
||||
'harv-auto-rotate-rke2-certs': The certificate rotation mechanism relies on Rancher. [[Harvester]] will automatically update certificates generation to trigger rotation.
|
||||
'harv-kubeconfig-default-token-ttl-minutes': 'TTL (in minutes) applied on [[Harvester]] administration kubeconfig files. Default is 0, which means to never expire.'
|
||||
'harv-auto-rotate-rke2-certs': The certificate rotation mechanism relies on Rancher. Harvester will automatically update certificates generation to trigger rotation.
|
||||
'harv-kubeconfig-default-token-ttl-minutes': 'TTL (in minutes) applied on Harvester administration kubeconfig files. Default is 0, which means to never expire.'
|
||||
'harv-longhorn-v2-data-engine-enabled': 'Enable the Longhorn V2 data engine. Default is false. <ul><li>Changing this setting will restart RKE2 on all nodes. This will not affect running VM workloads.</li><li>If you see "not enough hugepages-2Mi capacity" errors when enabling this setting, wait a minute for the error to clear. If the error remains, reboot the affected node.</li></ul>'
|
||||
'harv-longhorn-v2-data-engine-hugepage-enabled': 'Enable hugepages when using the Longhorn V2 data engine. Default is true. Disabling hugepages reduces memory pressure on low-spec nodes and increases deployment flexibility. However, performance may be lower compared to running with hugepages.'
|
||||
'harv-longhorn-v2-data-engine-memory-size': 'Configure the amount of memory allocated to the SPDK target daemon when using the Longhorn V2 data engine. Default is 2048 MiB.'
|
||||
@@ -2680,7 +2482,6 @@ advancedSettings:
|
||||
'harv-kubevirt-migration': 'Configure cluster-wide KubeVirt live migration parameters.'
|
||||
'harv-instance-manager-resources': 'Configure resource percentage reservations for Longhorn instance manager V1 and V2. Valid instance manager CPU range between 0 - 40.'
|
||||
'harv-cluster-pod-security-standard': 'Enforce Kubernetes Pod Security Standards (PSS) at the cluster level.'
|
||||
'harv-maintenance-mode-drain-timeout': 'Maintenance mode drain timeout in minutes. Use 0 to disable the timeout.'
|
||||
|
||||
typeLabel:
|
||||
kubevirt.io.virtualmachine: |-
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
import { MANAGEMENT } from '@shell/config/types';
|
||||
import SettingsPage from '../harvesterhci.io.setting.vue';
|
||||
import { HCI } from '../../types';
|
||||
import { HCI_SETTING } from '../../config/settings';
|
||||
|
||||
describe('list: harvesterhci.io.setting', () => {
|
||||
async function fetchPage({ visibleSettings = [], isSingleProduct = false } = {}) {
|
||||
const dispatch = jest.fn(() => Promise.resolve([]));
|
||||
const page = {
|
||||
initSettings: [],
|
||||
$store: {
|
||||
dispatch,
|
||||
getters: {
|
||||
isSingleProduct,
|
||||
currentProduct: { inStore: 'harvester' },
|
||||
'harvester/visibleSettings': visibleSettings,
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
await SettingsPage.fetch.call(page);
|
||||
|
||||
return { page, dispatch };
|
||||
}
|
||||
|
||||
const visible = (id, config = {}) => ({
|
||||
id, config, data: { id }
|
||||
});
|
||||
|
||||
it('should list the visible settings sorted by name, a setting with an alias under its alias', async() => {
|
||||
const { page } = await fetchPage({ visibleSettings: [visible('z-setting'), visible(HCI_SETTING.UI_PL, { alias: 'branding' })] });
|
||||
|
||||
expect(page.initSettings.map(({ id }) => id)).toStrictEqual(['branding', 'z-setting']);
|
||||
});
|
||||
|
||||
it('should keep the config and the resource of a setting', async() => {
|
||||
const { page } = await fetchPage({ visibleSettings: [visible('a-setting', { kind: 'json', canReset: true })] });
|
||||
|
||||
expect(page.initSettings[0]).toMatchObject({
|
||||
id: 'a-setting', kind: 'json', canReset: true, data: { id: 'a-setting' }, hide: true, canHide: true, hasActions: true
|
||||
});
|
||||
});
|
||||
|
||||
it('should only allow actions on the server version when it is read only', async() => {
|
||||
const { page } = await fetchPage({
|
||||
visibleSettings: [
|
||||
visible('a-setting', { readOnly: true }),
|
||||
visible(HCI_SETTING.SERVER_VERSION, { readOnly: true }),
|
||||
]
|
||||
});
|
||||
|
||||
expect(page.initSettings.map(({ hasActions }) => hasActions)).toStrictEqual([false, true]);
|
||||
});
|
||||
|
||||
it('should load the settings of the management store only in a single product', async() => {
|
||||
const { dispatch: multiCluster } = await fetchPage();
|
||||
const { dispatch: singleProduct } = await fetchPage({ isSingleProduct: true });
|
||||
|
||||
expect(multiCluster.mock.calls).toStrictEqual([['harvester/findAll', { type: HCI.SETTING }]]);
|
||||
expect(singleProduct.mock.calls).toStrictEqual([
|
||||
['harvester/findAll', { type: HCI.SETTING }],
|
||||
['management/findAll', { type: MANAGEMENT.SETTING }],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,54 +0,0 @@
|
||||
import { mount } from '@vue/test-utils';
|
||||
import HarvesterVPC from '../kubeovn.io.vpc.vue';
|
||||
|
||||
// A table that renders the page's group header for each of the given groups
|
||||
function resourceTable(groups) {
|
||||
return {
|
||||
data: () => ({ groups }),
|
||||
template: '<div><div v-for="group in groups" :key="group.key" class="group"><slot name="group-by" :group="group" /></div></div>',
|
||||
};
|
||||
}
|
||||
|
||||
function mountList(groups) {
|
||||
return mount(HarvesterVPC, {
|
||||
props: { schema: { id: 'kubeovn.io.vpc' } },
|
||||
data: () => ({ enabledKubeOvnAddon: true }),
|
||||
global: {
|
||||
stubs: {
|
||||
ResourceTable: resourceTable(groups),
|
||||
Masthead: true,
|
||||
Loading: true,
|
||||
'router-link': { template: '<a><slot /></a>' },
|
||||
},
|
||||
mocks: {
|
||||
$fetchState: { pending: false },
|
||||
t: (key) => ({ 'harvester.vpc.label': 'Virtual Private Cloud', 'generic.none': 'None' }[key] || key),
|
||||
$store: {
|
||||
getters: {
|
||||
currentProduct: { inStore: 'harvester' },
|
||||
'harvester/all': () => [],
|
||||
'harvester/schemaFor': () => ({ collectionMethods: ['POST'] }),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
describe('list: kubeovn.io.vpc', () => {
|
||||
it('should label a group of subnets without a VPC as None and offer no VPC actions', () => {
|
||||
const wrapper = mountList([{ key: '' }]);
|
||||
const group = wrapper.find('.group');
|
||||
|
||||
expect(group.find('.group-tab').text()).toBe('Virtual Private Cloud: None');
|
||||
expect(group.find('.right').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('should label a VPC group with its name and offer the VPC actions', () => {
|
||||
const wrapper = mountList([{ key: 'ovn-cluster' }]);
|
||||
const group = wrapper.find('.group');
|
||||
|
||||
expect(group.find('.group-tab').text()).toBe('Virtual Private Cloud: ovn-cluster');
|
||||
expect(group.findAll('.right a, .right button')).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
@@ -24,10 +24,8 @@ import { allDashboardsExist } from '@shell/utils/grafana';
|
||||
import { isEmpty } from '@shell/utils/object';
|
||||
import { HCI } from '../types';
|
||||
import HarvesterUpgrade from '../components/HarvesterUpgrade';
|
||||
import HealthSummaryTable from '../components/health/HealthSummaryTable';
|
||||
import { PRODUCT_NAME as HARVESTER_PRODUCT } from '../config/harvester';
|
||||
import { UNIT_SUFFIX } from '../utils/unit';
|
||||
import { totalErrorCount } from '../utils/component-health';
|
||||
|
||||
dayjs.extend(utc);
|
||||
dayjs.extend(minMax);
|
||||
@@ -127,7 +125,6 @@ export default {
|
||||
DashboardMetrics,
|
||||
Banner,
|
||||
MessageLink,
|
||||
HealthSummaryTable,
|
||||
},
|
||||
|
||||
async fetch() {
|
||||
@@ -240,20 +237,6 @@ export default {
|
||||
computed: {
|
||||
...mapGetters(['currentCluster']),
|
||||
|
||||
// the health resources only exist while the resource health addon is installed
|
||||
componentHealthEnabled() {
|
||||
const inStore = this.$store.getters['currentProduct'].inStore;
|
||||
|
||||
return this.$store.getters['harvester-common/getFeatureEnabled']('componentHealth') &&
|
||||
!!this.$store.getters[`${ inStore }/schemaFor`](HCI.HEALTH_SUMMARY);
|
||||
},
|
||||
|
||||
componentErrorCount() {
|
||||
const inStore = this.$store.getters['currentProduct'].inStore;
|
||||
|
||||
return totalErrorCount(this.$store.getters[`${ inStore }/all`](HCI.HEALTH_SUMMARY));
|
||||
},
|
||||
|
||||
accessibleResources() {
|
||||
const inStore = this.$store.getters['currentProduct'].inStore;
|
||||
|
||||
@@ -838,16 +821,6 @@ export default {
|
||||
</template>
|
||||
</SortableTable>
|
||||
</Tab>
|
||||
<Tab
|
||||
v-if="componentHealthEnabled"
|
||||
name="components"
|
||||
:label="t('harvester.dashboard.sections.componentHealth.label')"
|
||||
:weight="95"
|
||||
:display-alert-icon="componentErrorCount > 0"
|
||||
:error-icon-tooltip="t('harvester.dashboard.sections.componentHealth.errors', { count: componentErrorCount })"
|
||||
>
|
||||
<HealthSummaryTable />
|
||||
</Tab>
|
||||
</Tabbed>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -7,7 +7,7 @@ import { allHash } from '@shell/utils/promise';
|
||||
import Tabbed from '@shell/components/Tabbed/index.vue';
|
||||
import Tab from '@shell/components/Tabbed/Tab.vue';
|
||||
import Settings from '@pkg/harvester/components/SettingList.vue';
|
||||
import { HCI_SETTING } from '../config/settings';
|
||||
import { HCI_ALLOWED_SETTINGS, HCI_SINGLE_CLUSTER_ALLOWED_SETTING, HCI_SETTING } from '../config/settings';
|
||||
import { HCI } from '../types';
|
||||
|
||||
export default {
|
||||
@@ -29,19 +29,47 @@ export default {
|
||||
hash.settings = this.$store.dispatch('management/findAll', { type: MANAGEMENT.SETTING });
|
||||
}
|
||||
|
||||
await allHash(hash);
|
||||
const rows = await allHash(hash);
|
||||
|
||||
const initSettings = this.$store.getters[`${ inStore }/visibleSettings`].map(({ id, config, data }) => {
|
||||
let allRows = [];
|
||||
|
||||
allRows.push(...rows.harvesterSettings);
|
||||
|
||||
if (isSingleProduct) {
|
||||
allRows = [...rows.settings, ...allRows];
|
||||
}
|
||||
|
||||
// Map settings from array to object keyed by id
|
||||
const settingsMap = allRows.reduce((res, s) => {
|
||||
res[s.id] = s;
|
||||
|
||||
return res;
|
||||
}, {});
|
||||
|
||||
const initSettings = [];
|
||||
let SETTINGS = HCI_ALLOWED_SETTINGS;
|
||||
|
||||
if (this.isStandaloneHarvester) {
|
||||
SETTINGS = {
|
||||
...SETTINGS,
|
||||
...HCI_SINGLE_CLUSTER_ALLOWED_SETTING,
|
||||
};
|
||||
}
|
||||
|
||||
Object.keys(SETTINGS).forEach((setting) => {
|
||||
if (!settingsMap[setting]) {
|
||||
return;
|
||||
}
|
||||
const realSetting = SETTINGS[setting]?.alias || setting;
|
||||
const s = {
|
||||
...config,
|
||||
id: config.alias || id,
|
||||
data,
|
||||
...SETTINGS[setting],
|
||||
id: realSetting,
|
||||
data: settingsMap[setting],
|
||||
};
|
||||
|
||||
s.hide = s.canHide = (s.kind === 'json' || s.kind === 'multiline' || s.customFormatter === 'json' || s.data.customFormatter === 'json');
|
||||
s.hasActions = s.id === HCI_SETTING.SERVER_VERSION ? true : !s.readOnly;
|
||||
|
||||
return s;
|
||||
initSettings.push(s);
|
||||
});
|
||||
|
||||
this.initSettings = initSettings.sort((a, b) => {
|
||||
@@ -62,6 +90,7 @@ export default {
|
||||
|
||||
computed: {
|
||||
...mapGetters({ t: 'i18n/t' }),
|
||||
...mapGetters(['isStandaloneHarvester']),
|
||||
|
||||
settings() {
|
||||
return this.initSettings.map((setting) => {
|
||||
|
||||
@@ -139,8 +139,7 @@ export default {
|
||||
},
|
||||
methods: {
|
||||
groupLabel(group) {
|
||||
// Kube-OVN sets a subnet's VPC (ovn-cluster when none is given), so an empty one is a subnet it hasn't processed
|
||||
return `${ this.t('harvester.vpc.label') }: ${ group.key || this.t('generic.none') }`;
|
||||
return `${ this.t('harvester.vpc.label') }: ${ group.key }`;
|
||||
},
|
||||
|
||||
slotName(vpc) {
|
||||
@@ -227,10 +226,7 @@ export default {
|
||||
{{ groupLabel(group) }}
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
v-if="group.key"
|
||||
class="right"
|
||||
>
|
||||
<div class="right">
|
||||
<router-link
|
||||
v-if="isSubnetCreatable"
|
||||
class="btn btn-sm role-secondary mr-5"
|
||||
|
||||
@@ -151,8 +151,7 @@ export default {
|
||||
},
|
||||
|
||||
rows() {
|
||||
const vmIds = new Set(this.allVMs.map((VM) => VM.id));
|
||||
const matchVMIs = this.allVMIs.filter((VMI) => !vmIds.has(VMI.id));
|
||||
const matchVMIs = this.allVMIs.filter((VMI) => !this.allVMs.find((VM) => VM.id === VMI.id));
|
||||
|
||||
return [...this.allVMs, ...matchVMIs];
|
||||
},
|
||||
@@ -161,11 +160,7 @@ export default {
|
||||
* We want to show the progress bar only for Backup's restore; snapshot's restore is immediate.
|
||||
*/
|
||||
hasBackUpRestoreInProgress() {
|
||||
return this.rows.some((r) => {
|
||||
const restore = r.restoreResource;
|
||||
|
||||
return restore && !restore.fromSnapshot && !restore.isComplete;
|
||||
});
|
||||
return !!this.rows.find((r) => r.restoreResource && !r.restoreResource.fromSnapshot && !r.restoreResource.isComplete);
|
||||
},
|
||||
|
||||
vmRestartRequiredNames() {
|
||||
|
||||
@@ -1,140 +0,0 @@
|
||||
import VM_MIXIN from '../index';
|
||||
import impl from '../impl';
|
||||
|
||||
const USER_ERROR = 'harvester.virtualMachine.cloudConfig.user.invalidYaml';
|
||||
const NETWORK_ERROR = 'harvester.virtualMachine.cloudConfig.network.invalidYaml';
|
||||
const CLOUD_CONFIG = '#cloud-config\npackage_update: true\npackages:\n - qemu-guest-agent\n';
|
||||
const YAML_SCRIPT = '#!/bin/bash\napt-get update\napt-get install -y nginx\n';
|
||||
|
||||
function validate({
|
||||
userScript, networkScript, isEdit = false, savedCloudInit = {}
|
||||
}) {
|
||||
const form = {
|
||||
userScript,
|
||||
networkScript,
|
||||
isEdit,
|
||||
savedCloudInit,
|
||||
errors: [],
|
||||
t: (key) => key,
|
||||
};
|
||||
|
||||
VM_MIXIN.methods.validateCloudInit.call(form);
|
||||
|
||||
return form.errors;
|
||||
}
|
||||
|
||||
function userDataFor(userScript) {
|
||||
const form = {
|
||||
userScript,
|
||||
sshKey: [],
|
||||
$store: { getters: { 'harvester/byId': () => undefined } },
|
||||
...impl.methods,
|
||||
...VM_MIXIN.methods,
|
||||
};
|
||||
|
||||
return form.getUserData({ osType: 'linux', installAgent: false });
|
||||
}
|
||||
|
||||
describe('mixin: harvester-vm', () => {
|
||||
describe('validateCloudInit', () => {
|
||||
it.each([
|
||||
['a word after the mapping', `${ CLOUD_CONFIG }some words\n`],
|
||||
['only words', '#cloud-config\nsome words\n'],
|
||||
['only words and no header', 'some words\n'],
|
||||
['a list', '#cloud-config\n- a\n- b\n'],
|
||||
['bad indentation', '#cloud-config\nusers:\n - name: a\n bad: b\n'],
|
||||
['an unclosed quote', '#cloud-config\npassword: "abc\n'],
|
||||
])('should block cloud-config user data with %s', (_, userScript) => {
|
||||
expect(validate({ userScript })).toStrictEqual([USER_ERROR]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['undefined', undefined],
|
||||
['empty', ''],
|
||||
['only the header', '#cloud-config\n'],
|
||||
['a valid cloud-config', CLOUD_CONFIG],
|
||||
['a mapping without the header', 'password: test\n'],
|
||||
])('should allow user data that is %s', (_, userScript) => {
|
||||
expect(validate({ userScript })).toStrictEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['a script that is not valid YAML', '#!/bin/bash\napt-get update\n# start it\nsystemctl enable --now nginx\n'],
|
||||
['a script that parses as YAML', YAML_SCRIPT],
|
||||
['a MIME message with a cloud-config part', 'Content-Type: multipart/mixed; boundary="b"\nMIME-Version: 1.0\n\n--b\nContent-Type: text/cloud-config\n\n#cloud-config\npackages:\n - nginx\n--b--\n'],
|
||||
['a Jinja template', '## template: jinja\n#cloud-config\n{% if v1.region == "us" %}\npackages:\n - a\n{% endif %}\n'],
|
||||
['a Cloudbase-Init PowerShell script', '#ps1_sysnative\n# enable RDP\nWrite-Host "done: ok"\n'],
|
||||
['a Cloudbase-Init batch script', 'rem cmd\nnet user admin Passw0rd /add\n'],
|
||||
['a cloud-config archive', '#cloud-config-archive\n- type: text/x-shellscript\n content: |\n #!/bin/sh\n'],
|
||||
])('should not parse user data that is %s', (_, userScript) => {
|
||||
expect(validate({ userScript })).toStrictEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['words', 'some words\n'],
|
||||
['a list', '- a\n- b\n'],
|
||||
['bad indentation', 'network:\n version: 1\n bad: x\n'],
|
||||
])('should block network data with %s', (_, networkScript) => {
|
||||
expect(validate({ networkScript })).toStrictEqual([NETWORK_ERROR]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['undefined', undefined],
|
||||
['empty', ''],
|
||||
['only whitespace', ' \n'],
|
||||
['only a comment', '# nothing yet\n'],
|
||||
['a valid config', 'network:\n version: 1\n config:\n - type: physical\n name: eth0\n'],
|
||||
])('should allow network data that is %s', (_, networkScript) => {
|
||||
expect(validate({ networkScript })).toStrictEqual([]);
|
||||
});
|
||||
|
||||
it('should report both fields when both are invalid', () => {
|
||||
const errors = validate({ userScript: '#cloud-config\nsome words\n', networkScript: 'some words\n' });
|
||||
|
||||
expect(errors).toStrictEqual([USER_ERROR, NETWORK_ERROR]);
|
||||
});
|
||||
|
||||
it('should save an edited VM with the cloud-init it already has', () => {
|
||||
const savedCloudInit = {
|
||||
userScript: '#cloud-config\n#!/bin/bash\napt-get update apt-get install -y nginx\n',
|
||||
networkScript: 'some words\n',
|
||||
};
|
||||
|
||||
const errors = validate({
|
||||
...savedCloudInit, isEdit: true, savedCloudInit
|
||||
});
|
||||
|
||||
expect(errors).toStrictEqual([]);
|
||||
});
|
||||
|
||||
it('should check cloud-init changed while editing', () => {
|
||||
const savedCloudInit = { userScript: CLOUD_CONFIG, networkScript: '' };
|
||||
const errors = validate({
|
||||
userScript: '#cloud-config\nsome words\n', networkScript: 'some words\n', isEdit: true, savedCloudInit
|
||||
});
|
||||
|
||||
expect(errors).toStrictEqual([USER_ERROR, NETWORK_ERROR]);
|
||||
});
|
||||
|
||||
it('should check cloud-init a new VM takes from a template', () => {
|
||||
const savedCloudInit = { userScript: '#cloud-config\nsome words\n' };
|
||||
|
||||
expect(validate({ ...savedCloudInit, savedCloudInit })).toStrictEqual([USER_ERROR]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getUserData', () => {
|
||||
it.each([
|
||||
['a script that parses as YAML', YAML_SCRIPT],
|
||||
['a Cloudbase-Init batch script', 'rem cmd\nnet user admin Passw0rd /add\n'],
|
||||
['a Cloudbase-Init PowerShell script', '#ps1_sysnative\nWrite-Host done\n'],
|
||||
['a cloud-config archive', '#cloud-config-archive\n- type: text/x-shellscript\n content: echo hi\n'],
|
||||
])('should save %s as typed', (_, userScript) => {
|
||||
expect(userDataFor(userScript)).toStrictEqual(userScript);
|
||||
});
|
||||
|
||||
it('should add the header to cloud-config typed without one', () => {
|
||||
expect(userDataFor('password: test\n')).toBe('#cloud-config\npassword: test\n');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -35,18 +35,6 @@ export const SSH_EXISTING_TYPE = {
|
||||
EXISTING_ONLY_CLOUD: 'EXISTING_CLOUD',
|
||||
};
|
||||
|
||||
// Cloud-init and Cloudbase-Init run user data starting with one of these as a script, MIME or another format, not as cloud-config.
|
||||
const OTHER_USER_DATA_FORMATS = [
|
||||
'#!', '#include', '#cloud-boothook', '#part-handler', '#cloud-config-archive', '#cloud-config-jsonp', '## template:',
|
||||
'#ps1', 'rem cmd', '<script>', '<powershell>', 'content-type:', 'mime-version:'
|
||||
];
|
||||
|
||||
export function isCloudConfig(userScript) {
|
||||
const start = (userScript || '').trimStart().toLowerCase();
|
||||
|
||||
return !OTHER_USER_DATA_FORMATS.some((format) => start.startsWith(format));
|
||||
}
|
||||
|
||||
export default {
|
||||
methods: {
|
||||
hasCloudConfigComment(userScript) {
|
||||
|
||||
@@ -2,8 +2,6 @@ import YAML from 'yaml';
|
||||
import jsyaml from 'js-yaml';
|
||||
import isEqual from 'lodash/isEqual';
|
||||
import isEmpty from 'lodash/isEmpty';
|
||||
import isNil from 'lodash/isNil';
|
||||
import isPlainObject from 'lodash/isPlainObject';
|
||||
import difference from 'lodash/difference';
|
||||
import { sortBy } from '@shell/utils/sort';
|
||||
import { set } from '@shell/utils/object';
|
||||
@@ -25,7 +23,7 @@ import {
|
||||
import { HCI_SETTING } from '../../config/settings';
|
||||
import { HCI } from '../../types';
|
||||
import { parseVolumeClaimTemplates, EMPTY_IMAGE } from '../../utils/vm';
|
||||
import impl, { isCloudConfig, QGA_JSON, USB_TABLET } from './impl';
|
||||
import impl, { QGA_JSON, USB_TABLET } from './impl';
|
||||
import { GIBIBYTE } from '../../utils/unit';
|
||||
import { VOLUME_MODE, ACCESS_MODE, FILESYSTEM_SOURCE_TYPE } from '@pkg/harvester/config/types';
|
||||
|
||||
@@ -159,12 +157,9 @@ export default {
|
||||
installUSBTablet: true,
|
||||
networkScript: '',
|
||||
userScript: '',
|
||||
// The cloud-init the form loaded, so editing a VM never blocks saving it unchanged.
|
||||
savedCloudInit: {},
|
||||
imageId: '',
|
||||
diskRows: [],
|
||||
networkRows: [],
|
||||
networkBootFirst: true,
|
||||
filesystemRows: [],
|
||||
machineType: '',
|
||||
machineTypes: [],
|
||||
@@ -200,10 +195,6 @@ export default {
|
||||
cpuPinning: false,
|
||||
cpuModel: '',
|
||||
sysprep: { secretName: '', xmlContent: '' },
|
||||
// KubeVirt high-performance VM-level features
|
||||
blockMultiQueue: false,
|
||||
ioThreadsPolicy: '',
|
||||
ioThreadCount: 2,
|
||||
};
|
||||
},
|
||||
|
||||
@@ -294,14 +285,6 @@ export default {
|
||||
return this.osType === 'windows';
|
||||
},
|
||||
|
||||
hasVirtioDisk() {
|
||||
return (this.diskRows || []).some((R) => R.type === 'disk' && R.bus === 'virtio');
|
||||
},
|
||||
|
||||
hasDedicatedIOThread() {
|
||||
return (this.diskRows || []).some((R) => R.dedicatedIOThread);
|
||||
},
|
||||
|
||||
needNewSecret() {
|
||||
// When creating a template it is always necessary to create a new secret.
|
||||
return this.isCreate || this.showYaml ? false : this.resourceType === HCI.VM_VERSION;
|
||||
@@ -397,7 +380,6 @@ export default {
|
||||
const diskRows = this.getDiskRows(vm, volumeBackups);
|
||||
|
||||
const networkRows = this.getNetworkRows(vm, { fromTemplate, init });
|
||||
const networkBootFirst = this.isNetworkBootFirst(spec);
|
||||
const hasCreateVolumes = this.getHasCreatedVolumes(spec) || [];
|
||||
|
||||
let { userData = undefined, networkData = undefined } = this.getCloudInitNoCloud(spec);
|
||||
@@ -427,10 +409,6 @@ export default {
|
||||
const cpuPinning = this.isCpuPinning(spec);
|
||||
const cpuModel = spec.template.spec.domain.cpu?.model || '';
|
||||
|
||||
const blockMultiQueue = spec.template.spec.domain?.devices?.blockMultiQueue || false;
|
||||
const ioThreadsPolicy = spec.template.spec.domain?.ioThreadsPolicy || '';
|
||||
const ioThreadCount = spec.template.spec.domain?.ioThreads?.supplementalPoolThreadCount || 2;
|
||||
|
||||
const secretRef = this.getSecret(spec);
|
||||
const accessCredentials = this.getAccessCredentials(spec);
|
||||
|
||||
@@ -446,7 +424,6 @@ export default {
|
||||
this['accessCredentials'] = accessCredentials;
|
||||
this['userScript'] = userData;
|
||||
this['networkScript'] = networkData;
|
||||
this['savedCloudInit'] = { userScript: userData, networkScript: networkData };
|
||||
|
||||
this['sshKey'] = sshKey;
|
||||
this['osType'] = osType;
|
||||
@@ -470,13 +447,8 @@ export default {
|
||||
this['cpuPinning'] = cpuPinning;
|
||||
this['cpuModel'] = cpuModel;
|
||||
|
||||
this['blockMultiQueue'] = blockMultiQueue;
|
||||
this['ioThreadsPolicy'] = ioThreadsPolicy;
|
||||
this['ioThreadCount'] = ioThreadCount;
|
||||
|
||||
this['hasCreateVolumes'] = hasCreateVolumes;
|
||||
this['networkRows'] = networkRows;
|
||||
this['networkBootFirst'] = networkBootFirst;
|
||||
this['imageId'] = imageId;
|
||||
|
||||
this['diskRows'] = diskRows;
|
||||
@@ -531,20 +503,17 @@ export default {
|
||||
}
|
||||
|
||||
out.push({
|
||||
id: randomStr(5),
|
||||
source: SOURCE_TYPE.IMAGE,
|
||||
name: 'disk-0',
|
||||
accessMode: READ_WRITE_MANY, // root disk only support LHv1 volume, should be RWX
|
||||
id: randomStr(5),
|
||||
source: SOURCE_TYPE.IMAGE,
|
||||
name: 'disk-0',
|
||||
accessMode: READ_WRITE_MANY, // root disk only support LHv1 volume, should be RWX
|
||||
bus,
|
||||
volumeName: '',
|
||||
volumeName: '',
|
||||
size,
|
||||
type,
|
||||
storageClassName: '',
|
||||
image: this.imageId,
|
||||
volumeMode: VOLUME_MODE.BLOCK,
|
||||
cache: '',
|
||||
io: '',
|
||||
dedicatedIOThread: false,
|
||||
storageClassName: '',
|
||||
image: this.imageId,
|
||||
volumeMode: VOLUME_MODE.BLOCK,
|
||||
isEncrypted,
|
||||
volumeBackups,
|
||||
});
|
||||
@@ -634,25 +603,22 @@ export default {
|
||||
const volumeBackups = volBackups?.find((vBackup) => vBackup.volumeName === DISK.name) || null;
|
||||
|
||||
return {
|
||||
id: randomStr(5),
|
||||
id: randomStr(5),
|
||||
bootOrder,
|
||||
source,
|
||||
name: DISK.name,
|
||||
name: DISK.name,
|
||||
realName,
|
||||
bus,
|
||||
volumeName,
|
||||
container,
|
||||
accessMode,
|
||||
size: `${ formatSize }${ GIBIBYTE }`,
|
||||
volumeMode: volumeMode || this.customVolumeMode,
|
||||
size: `${ formatSize }${ GIBIBYTE }`,
|
||||
volumeMode: volumeMode || this.customVolumeMode,
|
||||
image,
|
||||
type,
|
||||
storageClassName,
|
||||
hotpluggable,
|
||||
cache: DISK?.cache || '',
|
||||
io: DISK?.io || '',
|
||||
dedicatedIOThread: DISK?.dedicatedIOThread || false,
|
||||
shareable: DISK.shareable || false,
|
||||
shareable: DISK.shareable || false,
|
||||
volumeStatus,
|
||||
dataSource,
|
||||
namespace,
|
||||
@@ -692,29 +658,12 @@ export default {
|
||||
model: I.model,
|
||||
networkName: isPod ? MANAGEMENT_NETWORK : network?.multus?.networkName,
|
||||
staticIp: annotations[`${ staticIpPrefix }${ I.name }`] || '',
|
||||
networkBoot: !!I.bootOrder,
|
||||
};
|
||||
});
|
||||
|
||||
return out;
|
||||
},
|
||||
|
||||
/**
|
||||
* Network boot devices are placed either before or after all volumes in the boot sequence.
|
||||
* Derive which one from an existing spec, so a round trip through the form keeps it.
|
||||
*/
|
||||
isNetworkBootFirst(spec) {
|
||||
const devices = spec?.template?.spec?.domain?.devices || {};
|
||||
const nicOrders = (devices.interfaces || []).map((I) => I.bootOrder).filter(Boolean);
|
||||
const diskOrders = (devices.disks || []).map((D) => D.bootOrder).filter(Boolean);
|
||||
|
||||
if (nicOrders.length === 0 || diskOrders.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return Math.min(...nicOrders) < Math.min(...diskOrders);
|
||||
},
|
||||
|
||||
parseVM() {
|
||||
this.userData = this.getUserData({ osType: this.osType, installAgent: this.installAgent });
|
||||
this.parseOther();
|
||||
@@ -927,10 +876,9 @@ export default {
|
||||
const disks = [];
|
||||
const volumes = [];
|
||||
const volumeClaimTemplates = [];
|
||||
const bootOrderOffset = this.networkBootFirst ? this.networkRows.filter((R) => R.networkBoot).length : 0;
|
||||
|
||||
disk.forEach( (R, index) => {
|
||||
const _disk = this.parseDisk(R, index + bootOrderOffset);
|
||||
const _disk = this.parseDisk(R, index);
|
||||
|
||||
disks.push(_disk);
|
||||
|
||||
@@ -1025,25 +973,9 @@ export default {
|
||||
// `shareable` is an attachment-level opt-in, remove the field
|
||||
// inherited from the old spec when the disk row no longer requests it
|
||||
mergedDisks.forEach((disk) => {
|
||||
const parsed = disks.find((D) => D.name === disk.name);
|
||||
|
||||
if (disk.shareable && !parsed?.shareable) {
|
||||
if (disk.shareable && !disks.find((D) => D.name === disk.name)?.shareable) {
|
||||
delete disk.shareable;
|
||||
}
|
||||
|
||||
// High-performance fields are only serialized when requested (see
|
||||
// parseDisk). When editing, mergeDeviceList would otherwise keep the
|
||||
// previous spec's cache/io/dedicatedIOThread even after the row is
|
||||
// switched back to "Default" or the dedicated I/O thread is unchecked,
|
||||
// silently preserving stale values — strip them so the disk matches
|
||||
// what the row actually requests.
|
||||
if (parsed) {
|
||||
['cache', 'io', 'dedicatedIOThread'].forEach((field) => {
|
||||
if (!parsed[field] && field in disk) {
|
||||
delete disk[field];
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
let spec = {
|
||||
@@ -1080,35 +1012,6 @@ export default {
|
||||
delete spec.template.spec.volumes;
|
||||
}
|
||||
|
||||
// KubeVirt high-performance VM-level features (I/O threads & block multi-queue).
|
||||
const domainRef = spec.template.spec.domain;
|
||||
const hasDedicatedIOThread = mergedDisks.some((D) => D.dedicatedIOThread);
|
||||
// If any disk requests a dedicated I/O thread, KubeVirt requires a policy;
|
||||
// default it to "shared" so the dedicated thread is honored.
|
||||
let ioThreadsPolicy = this.ioThreadsPolicy;
|
||||
|
||||
if (hasDedicatedIOThread && !ioThreadsPolicy) {
|
||||
ioThreadsPolicy = 'shared';
|
||||
}
|
||||
|
||||
if (ioThreadsPolicy) {
|
||||
domainRef.ioThreadsPolicy = ioThreadsPolicy;
|
||||
} else {
|
||||
delete domainRef.ioThreadsPolicy;
|
||||
}
|
||||
|
||||
if (ioThreadsPolicy === 'supplementalPool') {
|
||||
domainRef.ioThreads = { supplementalPoolThreadCount: Number(this.ioThreadCount) || 1 };
|
||||
} else {
|
||||
delete domainRef.ioThreads;
|
||||
}
|
||||
|
||||
if (this.blockMultiQueue) {
|
||||
domainRef.devices.blockMultiQueue = true;
|
||||
} else {
|
||||
delete domainRef.devices.blockMultiQueue;
|
||||
}
|
||||
|
||||
if (this.resourceType === HCI.VM) {
|
||||
if (!this.isSingle) {
|
||||
spec = this.multiVMScheduler(spec);
|
||||
@@ -1188,11 +1091,9 @@ export default {
|
||||
const networks = [];
|
||||
const interfaces = [];
|
||||
|
||||
let bootOrder = this.networkBootFirst ? 1 : this.diskRows.length + 1;
|
||||
|
||||
networkRow.forEach( (R) => {
|
||||
const _network = this.parseNetwork(R);
|
||||
const _interface = this.parseInterface(R, R.networkBoot ? bootOrder++ : undefined);
|
||||
const _interface = this.parseInterface(R);
|
||||
|
||||
networks.push(_network);
|
||||
interfaces.push(_interface);
|
||||
@@ -1296,11 +1197,6 @@ export default {
|
||||
* @param config
|
||||
*/
|
||||
getUserData(config) {
|
||||
// Scripts, MIME and the other formats are saved as typed: only cloud-config gets the SSH keys, the guest agent and the header.
|
||||
if (!isCloudConfig(this.userScript)) {
|
||||
return this.userScript;
|
||||
}
|
||||
|
||||
try {
|
||||
// https://github.com/eemeli/yaml/issues/136
|
||||
let userDataDoc = this.userScript ? YAML.parseDocument(this.userScript) : YAML.parseDocument({});
|
||||
@@ -1363,19 +1259,6 @@ export default {
|
||||
|
||||
if (R.type === HARD_DISK) {
|
||||
out.disk = { bus: R.bus };
|
||||
|
||||
// KubeVirt high-performance per-disk features. `cache`, `io` and
|
||||
// `dedicatedIOThread` live at the Disk level (siblings of `disk`), not
|
||||
// inside the DiskTarget. See disks_and_volumes.md#high-performance-features.
|
||||
if (R.cache) {
|
||||
out.cache = R.cache;
|
||||
}
|
||||
if (R.io) {
|
||||
out.io = R.io;
|
||||
}
|
||||
if (R.dedicatedIOThread) {
|
||||
out.dedicatedIOThread = true;
|
||||
}
|
||||
} else if (R.type === CD_ROM) {
|
||||
out.cdrom = { bus: R.bus };
|
||||
}
|
||||
@@ -1453,7 +1336,7 @@ export default {
|
||||
return arr.map( (id) => this.getSSHValue(id)).filter( (O) => O !== undefined);
|
||||
},
|
||||
|
||||
parseInterface(R, bootOrder) {
|
||||
parseInterface(R) {
|
||||
const _interface = {};
|
||||
const type = R.type;
|
||||
|
||||
@@ -1463,10 +1346,6 @@ export default {
|
||||
_interface.macAddress = R.macAddress;
|
||||
}
|
||||
|
||||
if (bootOrder) {
|
||||
_interface.bootOrder = bootOrder;
|
||||
}
|
||||
|
||||
_interface.model = R.model;
|
||||
_interface.name = R.name;
|
||||
|
||||
@@ -1493,30 +1372,6 @@ export default {
|
||||
this.networkScript = value;
|
||||
},
|
||||
|
||||
validateCloudInit() {
|
||||
const isYamlMapping = (text) => {
|
||||
try {
|
||||
const doc = jsyaml.load(text);
|
||||
|
||||
return isNil(doc) || isPlainObject(doc);
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// Editing only checks what changed, so a VM can still be saved with the cloud-init it already has.
|
||||
const isChanged = (key) => !this.isEdit || this[key] !== this.savedCloudInit[key];
|
||||
|
||||
// Scripts, MIME and the other formats are valid without being YAML. Anything else is saved as cloud-config.
|
||||
if (this.userScript && isChanged('userScript') && isCloudConfig(this.userScript) && !isYamlMapping(this.userScript)) {
|
||||
this.errors.push(this.t('harvester.virtualMachine.cloudConfig.user.invalidYaml'));
|
||||
}
|
||||
|
||||
if (this.networkScript && isChanged('networkScript') && !isYamlMapping(this.networkScript)) {
|
||||
this.errors.push(this.t('harvester.virtualMachine.cloudConfig.network.invalidYaml'));
|
||||
}
|
||||
},
|
||||
|
||||
mergeSSHAuthorizedKeys(yaml) {
|
||||
try {
|
||||
const sshAuthorizedKeys = YAML.parseDocument(yaml)
|
||||
@@ -1998,11 +1853,6 @@ export default {
|
||||
delete merged['bridge'];
|
||||
}
|
||||
|
||||
// boot order is owned by the form, don't inherit a stale one from the old spec
|
||||
if (!iface.bootOrder) {
|
||||
delete merged.bootOrder;
|
||||
}
|
||||
|
||||
return merged;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,398 +0,0 @@
|
||||
import { reactive } from 'vue';
|
||||
import VirtVm from '../kubevirt.io.virtualmachine';
|
||||
import { POD, PVC } from '@shell/config/types';
|
||||
import { HCI } from '../../types';
|
||||
|
||||
// The Steve base model and the shell resource class pull in most of the dashboard, none of that is needed here
|
||||
jest.mock('../harvester', () => ({ __esModule: true, default: class {} }));
|
||||
jest.mock('@shell/plugins/dashboard-store/resource-class', () => ({
|
||||
colorForState: (state) => (state === 'Running' ? 'text-success' : 'text-info'),
|
||||
stateSort: (color, display) => `${ color.replace(/^text-/, '') } ${ display }`,
|
||||
}));
|
||||
|
||||
const VM_ID = 'ns1/vm1';
|
||||
|
||||
// Creates a VM model with mocked store getters. Like the real store, `all` returns the same array that is mutated in place.
|
||||
// Reads from the global `$rootGetters` are recorded in `globalReads`.
|
||||
function createVm({
|
||||
vm = {}, vmi, pods = [], pvcs = [], restores = [], backups = [], claims = ['disk-pvc'], printableStatus
|
||||
} = {}) {
|
||||
const lists = reactive({
|
||||
[POD]: pods,
|
||||
[PVC]: pvcs,
|
||||
[HCI.RESTORE]: restores,
|
||||
[HCI.BACKUP]: backups,
|
||||
});
|
||||
const byId = { [HCI.VMI]: vmi ? [vmi] : [] };
|
||||
|
||||
const getters = {
|
||||
all: (type) => lists[type] || [],
|
||||
byId: (type, id) => (byId[type] || lists[type] || []).find((x) => x.id === id),
|
||||
schemaFor: () => undefined,
|
||||
};
|
||||
const globalReads = [];
|
||||
const rootGetters = new Proxy({ 'harvester-common/getFeatureEnabled': () => false }, {
|
||||
get(target, key) {
|
||||
globalReads.push(key);
|
||||
|
||||
return target[key];
|
||||
}
|
||||
});
|
||||
|
||||
const obj = Object.create(VirtVm.prototype);
|
||||
|
||||
Object.assign(obj, {
|
||||
id: VM_ID,
|
||||
type: HCI.VM,
|
||||
metadata: {
|
||||
name: 'vm1', namespace: 'ns1', annotations: {}
|
||||
},
|
||||
spec: {
|
||||
runStrategy: 'Always',
|
||||
template: {
|
||||
spec: {
|
||||
domain: { cpu: { cores: 1 }, resources: { limits: { memory: '1Gi' } } },
|
||||
volumes: claims.map((c) => ({ name: c, persistentVolumeClaim: { claimName: c } })),
|
||||
}
|
||||
}
|
||||
},
|
||||
status: {
|
||||
created: true, ready: true, printableStatus: printableStatus || 'Running', conditions: []
|
||||
},
|
||||
...vm,
|
||||
});
|
||||
Object.defineProperty(obj, '$rootGetters', { value: rootGetters });
|
||||
Object.defineProperty(obj, '$getters', { value: getters });
|
||||
Object.defineProperty(obj, 't', { value: (k) => k });
|
||||
|
||||
return {
|
||||
vm: obj, lists, globalReads
|
||||
};
|
||||
}
|
||||
|
||||
const readyVmi = (extra = {}) => ({
|
||||
id: VM_ID,
|
||||
metadata: { name: 'vm1', namespace: 'ns1' },
|
||||
status: {
|
||||
phase: 'Running',
|
||||
conditions: [{ type: 'Ready', status: 'True' }],
|
||||
...extra
|
||||
}
|
||||
});
|
||||
|
||||
const pvc = (name, encrypted, ns = 'ns1') => ({
|
||||
id: `${ ns }/${ name }`,
|
||||
metadata: { name, namespace: ns },
|
||||
isEncrypted: encrypted,
|
||||
});
|
||||
|
||||
describe('class VirtVm', () => {
|
||||
describe('restoreResource', () => {
|
||||
it('should distinguish snapshots from backups and follow backup updates', () => {
|
||||
const { vm, lists } = createVm({
|
||||
vm: {
|
||||
metadata: {
|
||||
namespace: 'ns1', name: 'vm1', annotations: { 'restore.harvesterhci.io/name': 'r1' }
|
||||
}
|
||||
},
|
||||
restores: [{
|
||||
id: 'ns1/r1', isComplete: false, spec: { virtualMachineBackupNamespace: 'ns1', virtualMachineBackupName: 'b1' }
|
||||
}],
|
||||
backups: [
|
||||
{ id: 'ns2/b1', spec: { type: 'snapshot' } },
|
||||
{ id: 'ns1/b1', spec: { type: 'backup' } },
|
||||
],
|
||||
});
|
||||
|
||||
expect(vm.restoreResource.fromSnapshot).toBe(false);
|
||||
expect(vm.restoreState).toBe(false);
|
||||
|
||||
lists[HCI.BACKUP][1].spec.type = 'snapshot';
|
||||
expect(vm.restoreResource.fromSnapshot).toBe(true);
|
||||
|
||||
lists[HCI.BACKUP].splice(1, 1);
|
||||
expect(vm.restoreResource.fromSnapshot).toBe(false);
|
||||
|
||||
lists[HCI.RESTORE][0].isComplete = true;
|
||||
expect(vm.restoreState).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('encryptedVolumeType', () => {
|
||||
it('should be none without volumes', () => {
|
||||
const { vm } = createVm({ claims: [] });
|
||||
|
||||
expect(vm.encryptedVolumeType).toBe('none');
|
||||
});
|
||||
|
||||
it('should be none if no PVC is encrypted', () => {
|
||||
const { vm } = createVm({ pvcs: [pvc('disk-pvc', false)] });
|
||||
|
||||
expect(vm.encryptedVolumeType).toBe('none');
|
||||
});
|
||||
|
||||
it('should be all if every PVC is encrypted', () => {
|
||||
const { vm } = createVm({
|
||||
claims: ['a', 'b'],
|
||||
pvcs: [pvc('a', true), pvc('b', true), pvc('other', false)]
|
||||
});
|
||||
|
||||
expect(vm.encryptedVolumeType).toBe('all');
|
||||
});
|
||||
|
||||
it('should be partial if some PVCs are encrypted', () => {
|
||||
const { vm } = createVm({
|
||||
claims: ['a', 'b'],
|
||||
pvcs: [pvc('a', true), pvc('b', false)]
|
||||
});
|
||||
|
||||
expect(vm.encryptedVolumeType).toBe('partial');
|
||||
});
|
||||
|
||||
it('should follow PVCs that are added to the store later', () => {
|
||||
const { vm, lists } = createVm({ claims: ['a'], pvcs: [] });
|
||||
|
||||
expect(vm.encryptedVolumeType).toBe('none');
|
||||
|
||||
lists[PVC].push(pvc('a', true));
|
||||
|
||||
expect(vm.encryptedVolumeType).toBe('all');
|
||||
});
|
||||
});
|
||||
|
||||
describe('actualState', () => {
|
||||
it('should be Off if the VM is halted', () => {
|
||||
const { vm } = createVm({
|
||||
vm: {
|
||||
spec: { runStrategy: 'Halted', template: { spec: { volumes: [], domain: {} } } },
|
||||
status: { created: false, conditions: [] }
|
||||
}
|
||||
});
|
||||
|
||||
expect(vm.actualState).toBe('Off');
|
||||
});
|
||||
|
||||
it('should be Running if the VMI is running and ready', () => {
|
||||
const { vm } = createVm({ vmi: readyVmi() });
|
||||
|
||||
expect(vm.actualState).toBe('Running');
|
||||
});
|
||||
|
||||
it('should be Not Ready if the VMI is running but not ready', () => {
|
||||
const { vm } = createVm({ vmi: readyVmi({ conditions: [{ type: 'Ready', status: 'False' }] }) });
|
||||
|
||||
expect(vm.actualState).toBe('Not Ready');
|
||||
});
|
||||
|
||||
it('should be Paused if the VMI has the Paused condition', () => {
|
||||
const { vm } = createVm({ vmi: readyVmi({ conditions: [{ type: 'Ready', status: 'True' }, { type: 'Paused', status: 'True' }] }) });
|
||||
|
||||
expect(vm.actualState).toBe('Paused');
|
||||
});
|
||||
|
||||
it('should be Stopping if the VM is not expected to run anymore but the VMI exists', () => {
|
||||
const { vm } = createVm({
|
||||
vm: { spec: { runStrategy: 'Halted', template: { spec: { volumes: [], domain: {} } } } },
|
||||
vmi: readyVmi()
|
||||
});
|
||||
|
||||
expect(vm.actualState).toBe('Stopping');
|
||||
});
|
||||
|
||||
it('should be Starting while the launcher pod is not ready', () => {
|
||||
const { vm } = createVm({
|
||||
vmi: readyVmi({ phase: 'Scheduling', conditions: [] }),
|
||||
pods: [{
|
||||
metadata: { namespace: 'ns1', ownerReferences: [{ name: 'vm1' }] },
|
||||
getPodStatus: { status: 'POD_NOT_SCHEDULABLE' }
|
||||
}]
|
||||
});
|
||||
|
||||
expect(vm.actualState).toBe('Starting');
|
||||
});
|
||||
|
||||
it('should be Unschedulable if the VM is starting and has an unschedulable condition', () => {
|
||||
const { vm } = createVm({
|
||||
vmi: readyVmi({ phase: 'Pending', conditions: [] }),
|
||||
vm: { status: { created: true, conditions: [{ reason: 'Unschedulable', message: 'no node' }] } }
|
||||
});
|
||||
|
||||
expect(vm.actualState).toBe('Unschedulable');
|
||||
expect(vm.isUnschedulable.message).toBe('no node');
|
||||
});
|
||||
|
||||
it('should not be Unschedulable without an unschedulable condition', () => {
|
||||
const { vm } = createVm({ vmi: readyVmi() });
|
||||
|
||||
expect(vm.isUnschedulable).toBeNull();
|
||||
expect(vm.actualState).toBe('Running');
|
||||
});
|
||||
|
||||
it('should not be Unschedulable if the VM is neither starting nor stopping', () => {
|
||||
const { vm } = createVm({
|
||||
vm: {
|
||||
spec: { runStrategy: 'Halted', template: { spec: { volumes: [], domain: {} } } },
|
||||
status: { created: false, conditions: [{ reason: 'Unschedulable' }] }
|
||||
}
|
||||
});
|
||||
|
||||
expect(vm.isUnschedulable).toBeNull();
|
||||
expect(vm.actualState).toBe('Off');
|
||||
});
|
||||
|
||||
it('should be Terminating if the VM is being deleted', () => {
|
||||
const { vm } = createVm({
|
||||
vmi: readyVmi(),
|
||||
vm: {
|
||||
metadata: {
|
||||
name: 'vm1', namespace: 'ns1', annotations: {}, deletionTimestamp: 'now'
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
expect(vm.actualState).toBe('Terminating');
|
||||
});
|
||||
|
||||
it('should be VM error if the VM has a failure condition', () => {
|
||||
const { vm } = createVm({ vm: { status: { created: true, conditions: [{ type: 'Failure', message: 'boom' }] } } });
|
||||
|
||||
expect(vm.actualState).toBe('VM error');
|
||||
});
|
||||
|
||||
it('should be Restoring while a restore is in progress', () => {
|
||||
const { vm } = createVm({
|
||||
vmi: readyVmi(),
|
||||
vm: {
|
||||
metadata: {
|
||||
name: 'vm1', namespace: 'ns1', annotations: { 'restore.harvesterhci.io/name': 'r1' }
|
||||
}
|
||||
},
|
||||
restores: [{ id: 'ns1/r1', isComplete: false }]
|
||||
});
|
||||
|
||||
expect(vm.actualState).toBe('Restoring');
|
||||
});
|
||||
|
||||
it('should not be Restoring if the restore of the annotation does not exist', () => {
|
||||
const { vm } = createVm({
|
||||
vmi: readyVmi(),
|
||||
vm: {
|
||||
metadata: {
|
||||
name: 'vm1', namespace: 'ns1', annotations: { 'restore.harvesterhci.io/name': 'other' }
|
||||
}
|
||||
},
|
||||
restores: [{ id: 'ns1/r1', isComplete: false }]
|
||||
});
|
||||
|
||||
expect(vm.actualState).toBe('Running');
|
||||
});
|
||||
});
|
||||
|
||||
describe('stateSort', () => {
|
||||
it('should be built from the same state as stateDisplay and stateColor', () => {
|
||||
const { vm } = createVm({ vmi: readyVmi() });
|
||||
|
||||
expect(vm.stateSort).toBe(`${ vm.stateColor.replace(/^text-/, '') } ${ vm.stateDisplay }`);
|
||||
});
|
||||
|
||||
it('should evaluate the state only once', () => {
|
||||
const { vm } = createVm({ vmi: readyVmi() });
|
||||
const spy = jest.spyOn(vm, 'actualState', 'get');
|
||||
|
||||
expect(vm.stateSort).toBe('success Running');
|
||||
expect(spy).toHaveBeenCalledTimes(1);
|
||||
|
||||
spy.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
describe('podResource', () => {
|
||||
it('should find the launcher pod by owner name', () => {
|
||||
const pod = { metadata: { namespace: 'ns1', ownerReferences: [{ name: 'vm1' }] } };
|
||||
const { vm } = createVm({ vmi: readyVmi(), pods: [pod] });
|
||||
|
||||
expect(vm.podResource).toStrictEqual(pod);
|
||||
});
|
||||
|
||||
it('should return the last pod if several pods have the same owner', () => {
|
||||
// e.g. the source and the target pod while the VM migrates
|
||||
const source = {
|
||||
metadata: {
|
||||
name: 'launcher-source', namespace: 'ns1', ownerReferences: [{ name: 'vm1' }]
|
||||
}
|
||||
};
|
||||
const target = {
|
||||
metadata: {
|
||||
name: 'launcher-target', namespace: 'ns1', ownerReferences: [{ name: 'vm1' }]
|
||||
}
|
||||
};
|
||||
const { vm } = createVm({ vmi: readyVmi(), pods: [source, target] });
|
||||
|
||||
expect(vm.podResource.metadata.name).toBe('launcher-target');
|
||||
});
|
||||
|
||||
it('should find pods that are added to the store later', () => {
|
||||
const { vm, lists } = createVm({ vmi: readyVmi(), pods: [] });
|
||||
|
||||
expect(vm.podResource).toBeUndefined();
|
||||
|
||||
const pod = { metadata: { namespace: 'ns1', ownerReferences: [{ name: 'vm1' }] } };
|
||||
|
||||
lists[POD].push(pod);
|
||||
|
||||
expect(vm.podResource).toStrictEqual(pod);
|
||||
});
|
||||
|
||||
it('should not return a pod of a VM with the same name in another namespace', () => {
|
||||
const other = { metadata: { namespace: 'ns2', ownerReferences: [{ name: 'vm1' }] } };
|
||||
const mine = { metadata: { namespace: 'ns1', ownerReferences: [{ name: 'vm1' }] } };
|
||||
const { vm } = createVm({ vmi: readyVmi(), pods: [mine, other] });
|
||||
|
||||
expect(vm.podResource).toStrictEqual(mine);
|
||||
});
|
||||
|
||||
it('should not return pods that were removed from the store', () => {
|
||||
const pod = { metadata: { namespace: 'ns1', ownerReferences: [{ name: 'vm1' }] } };
|
||||
const { vm, lists } = createVm({ vmi: readyVmi(), pods: [pod] });
|
||||
|
||||
expect(vm.podResource).toStrictEqual(pod);
|
||||
|
||||
lists[POD].splice(0, 1);
|
||||
|
||||
expect(vm.podResource).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('store', () => {
|
||||
it('should read the data of the VM from the store the VM lives in, not from a fixed one', () => {
|
||||
// The VM model is used with the `harvester` store (Harvester product) and the `cluster` store (Rancher explorer)
|
||||
const pod = { metadata: { namespace: 'ns1', ownerReferences: [{ name: 'vm1' }] } };
|
||||
const { vm, globalReads } = createVm({
|
||||
vmi: readyVmi(),
|
||||
pods: [pod],
|
||||
pvcs: [pvc('disk-pvc', false)],
|
||||
restores: [{ id: 'ns1/r1', isComplete: true }],
|
||||
vm: {
|
||||
metadata: {
|
||||
name: 'vm1', namespace: 'ns1', annotations: { 'restore.harvesterhci.io/name': 'r1' }
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
expect(vm.vmi.id).toBe(VM_ID);
|
||||
expect(vm.podResource).toStrictEqual(pod);
|
||||
expect(vm.volumes).toHaveLength(1);
|
||||
expect(vm.restoreResource.id).toBe('ns1/r1');
|
||||
expect(vm.actualState).toBe('Running');
|
||||
expect(globalReads.filter((key) => /^(harvester|cluster)\//.test(key))).toStrictEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isRestartRequired', () => {
|
||||
it('should reflect the RestartRequired condition', () => {
|
||||
const { vm } = createVm({ vm: { status: { conditions: [{ type: 'RestartRequired', status: 'True' }] } } });
|
||||
|
||||
expect(vm.isRestartRequired).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,95 +0,0 @@
|
||||
import { reactive } from 'vue';
|
||||
import VirtVmInstance from '../kubevirt.io.virtualmachineinstance';
|
||||
import { HCI } from '../../types';
|
||||
import { HCI as HCI_ANNOTATIONS } from '../../config/labels-annotations';
|
||||
|
||||
jest.mock('../harvester', () => ({ __esModule: true, default: class {} }));
|
||||
jest.mock('@shell/plugins/dashboard-store/resource-class', () => ({ colorForState: () => 'text-info' }));
|
||||
|
||||
function migration(namespace, timestamp, phase = 'Running') {
|
||||
return {
|
||||
metadata: { namespace, creationTimestamp: timestamp },
|
||||
spec: { vmiName: 'vm1' },
|
||||
status: { phase },
|
||||
};
|
||||
}
|
||||
|
||||
function createVmi(migrations) {
|
||||
const list = reactive(migrations);
|
||||
const vmi = Object.create(VirtVmInstance.prototype);
|
||||
|
||||
Object.assign(vmi, {
|
||||
metadata: {
|
||||
namespace: 'ns1',
|
||||
name: 'vm1',
|
||||
annotations: { [HCI_ANNOTATIONS.MIGRATION_STATE]: 'Migrating' },
|
||||
},
|
||||
$getters: { all: (type) => type === HCI.VMIM ? list : [] },
|
||||
});
|
||||
|
||||
return { vmi, list };
|
||||
}
|
||||
|
||||
describe('class VirtVmInstance', () => {
|
||||
it('should select the newest migration in the VMI namespace regardless of list order', () => {
|
||||
const { vmi } = createVmi([
|
||||
migration('ns1', '2026-01-03T00:00:00Z'),
|
||||
migration('ns2', '2026-01-04T00:00:00Z', 'Failed'),
|
||||
migration('ns1', '2026-01-01T00:00:00Z', 'Failed'),
|
||||
]);
|
||||
|
||||
expect(vmi.vmimResource.metadata.creationTimestamp).toBe('2026-01-03T00:00:00Z');
|
||||
expect(vmi.migrationState.status).toBe('Migrating');
|
||||
});
|
||||
|
||||
it('should follow additions, timestamp changes, phase changes and removals in the same list', () => {
|
||||
const { vmi, list } = createVmi([]);
|
||||
|
||||
expect(vmi.vmimResource).toStrictEqual([]);
|
||||
expect(vmi.migrationState).toBeNull();
|
||||
|
||||
list.push(migration('ns1', '2026-01-01T00:00:00Z'));
|
||||
expect(vmi.migrationState.status).toBe('Migrating');
|
||||
|
||||
list.push(migration('ns1', '2026-01-02T00:00:00Z', 'Failed'));
|
||||
expect(vmi.migrationState.status).toBe('Failed');
|
||||
|
||||
list[0].metadata.creationTimestamp = '2026-01-03T00:00:00Z';
|
||||
expect(vmi.vmimResource).toBe(list[0]);
|
||||
expect(vmi.migrationState.status).toBe('Migrating');
|
||||
|
||||
list[0].status.phase = 'Failed';
|
||||
expect(vmi.migrationState.status).toBe('Failed');
|
||||
|
||||
list.splice(0, 2);
|
||||
expect(vmi.migrationState).toBeNull();
|
||||
});
|
||||
|
||||
it('should follow a migration reassigned to another VMI or namespace', () => {
|
||||
const { vmi, list } = createVmi([migration('ns1', '2026-01-01T00:00:00Z')]);
|
||||
|
||||
expect(vmi.migrationState.status).toBe('Migrating');
|
||||
|
||||
list[0].spec.vmiName = 'vm2';
|
||||
expect(vmi.migrationState).toBeNull();
|
||||
|
||||
list[0].spec.vmiName = 'vm1';
|
||||
list[0].metadata.namespace = 'ns2';
|
||||
expect(vmi.migrationState).toBeNull();
|
||||
});
|
||||
|
||||
it('should invalidate the index when the store replaces properties on an existing migration', () => {
|
||||
const { vmi, list } = createVmi([migration('ns1', '2026-01-01T00:00:00Z')]);
|
||||
|
||||
expect(vmi.migrationState.status).toBe('Migrating');
|
||||
|
||||
const existing = list[0];
|
||||
|
||||
for (const key of Object.keys(existing)) {
|
||||
delete existing[key];
|
||||
}
|
||||
Object.assign(existing, migration('ns2', '2026-01-02T00:00:00Z', 'Failed'));
|
||||
|
||||
expect(vmi.migrationState).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -23,13 +23,6 @@ const ALLOW_SYSTEM_LABEL_KEYS = [
|
||||
|
||||
const HEALTHY = 'healthy';
|
||||
const WARNING = 'warning';
|
||||
const MAINTENANCE_MODE = 'MaintenanceMode';
|
||||
const MAINTENANCE_ERROR = 'Error';
|
||||
const MAINTENANCE_ENTERING_REASONS = ['Validating', 'Draining', 'Evacuating'];
|
||||
const MAINTENANCE_COMPLETED = 'Completed';
|
||||
// Legacy `harvesterhci.io/maintain-status` annotation values (clusters < v1.10)
|
||||
const LEGACY_MAINTENANCE_RUNNING = 'running';
|
||||
const LEGACY_MAINTENANCE_COMPLETED = 'completed';
|
||||
|
||||
export default class HciNode extends HarvesterResource {
|
||||
get _availableActions() {
|
||||
@@ -65,14 +58,6 @@ export default class HciNode extends HarvesterResource {
|
||||
total: 1
|
||||
};
|
||||
|
||||
const clearMaintenance = {
|
||||
action: 'clearMaintenanceMode',
|
||||
enabled: this.hasAction('clearMaintenanceMode'),
|
||||
icon: 'icon icon-fw icon-close',
|
||||
label: this.t('harvester.action.clearMaintenance'),
|
||||
total: 1
|
||||
};
|
||||
|
||||
const enableCPUManager = {
|
||||
action: 'enableCPUManager',
|
||||
enabled: this.cpuPinningFeatureEnabled && this.hasAction('enableCPUManager') && !this.isCPUManagerEnableInProgress && !this.isCPUManagerEnabled && !this.isEtcd, // witness node doesn't have CPU manager
|
||||
@@ -118,7 +103,6 @@ export default class HciNode extends HarvesterResource {
|
||||
uncordon,
|
||||
enableMaintenance,
|
||||
disableMaintenance,
|
||||
clearMaintenance,
|
||||
enableCPUManager,
|
||||
disableCPUManager,
|
||||
shutDown,
|
||||
@@ -214,10 +198,6 @@ export default class HciNode extends HarvesterResource {
|
||||
}
|
||||
|
||||
get stateDisplay() {
|
||||
if (this.isMaintenanceModeError) {
|
||||
return super.stateDisplay;
|
||||
}
|
||||
|
||||
if (this.isEnteringMaintenance) {
|
||||
return 'Entering maintenance mode';
|
||||
}
|
||||
@@ -266,10 +246,6 @@ export default class HciNode extends HarvesterResource {
|
||||
}
|
||||
|
||||
get stateDescription() {
|
||||
if (this.isMaintenanceModeError) {
|
||||
return super.stateDescription;
|
||||
}
|
||||
|
||||
const currentIP = this.metadata?.annotations?.[HCI_ANNOTATIONS.CURRENT_IP];
|
||||
const initIP = this.metadata?.annotations?.[HCI_ANNOTATIONS.INIT_IP];
|
||||
|
||||
@@ -349,11 +325,7 @@ export default class HciNode extends HarvesterResource {
|
||||
}
|
||||
|
||||
disableMaintenanceMode() {
|
||||
this.doActionGrowl('disableMaintenanceMode', {});
|
||||
}
|
||||
|
||||
clearMaintenanceMode() {
|
||||
this.doActionGrowl('clearMaintenanceMode', {});
|
||||
this.doAction('disableMaintenanceMode', {});
|
||||
}
|
||||
|
||||
enableCPUManager() {
|
||||
@@ -371,32 +343,11 @@ export default class HciNode extends HarvesterResource {
|
||||
);
|
||||
}
|
||||
|
||||
get maintenanceModeCondition() {
|
||||
return (this.status?.conditions || []).find(
|
||||
(c) => c.type === MAINTENANCE_MODE
|
||||
);
|
||||
}
|
||||
|
||||
get maintenanceModeConditionsEnabled() {
|
||||
return this.$rootGetters['harvester-common/getFeatureEnabled']('maintenanceModeConditions');
|
||||
}
|
||||
|
||||
// Clusters < v1.10 only expose the `harvesterhci.io/maintain-status` annotation
|
||||
get legacyMaintenanceStatus() {
|
||||
return this.metadata?.annotations?.[HCI_ANNOTATIONS.MAINTENANCE_STATUS];
|
||||
}
|
||||
|
||||
get isMaintenanceModeError() {
|
||||
return this.maintenanceModeConditionsEnabled && this.maintenanceModeCondition?.reason === MAINTENANCE_ERROR;
|
||||
}
|
||||
|
||||
get isMigratable() {
|
||||
const states = ['in-progress', 'unavailable'];
|
||||
|
||||
const engaged = this.maintenanceModeConditionsEnabled ? this.maintenanceModeCondition?.status === 'True' : !!this.legacyMaintenanceStatus;
|
||||
|
||||
return (
|
||||
!engaged &&
|
||||
!this.metadata?.annotations?.[HCI_ANNOTATIONS.MAINTENANCE_STATUS] &&
|
||||
!this.isUnSchedulable &&
|
||||
!states.includes(this.state)
|
||||
);
|
||||
@@ -411,26 +362,17 @@ export default class HciNode extends HarvesterResource {
|
||||
}
|
||||
|
||||
get isEnteringMaintenance() {
|
||||
if (!this.maintenanceModeConditionsEnabled) {
|
||||
return this.legacyMaintenanceStatus === LEGACY_MAINTENANCE_RUNNING;
|
||||
}
|
||||
|
||||
const cond = this.maintenanceModeCondition;
|
||||
|
||||
return (
|
||||
cond?.status === 'True' &&
|
||||
MAINTENANCE_ENTERING_REASONS.includes(cond?.reason)
|
||||
this.metadata?.annotations?.[HCI_ANNOTATIONS.MAINTENANCE_STATUS] ===
|
||||
'running'
|
||||
);
|
||||
}
|
||||
|
||||
get isMaintenance() {
|
||||
if (!this.maintenanceModeConditionsEnabled) {
|
||||
return this.legacyMaintenanceStatus === LEGACY_MAINTENANCE_COMPLETED;
|
||||
}
|
||||
|
||||
const cond = this.maintenanceModeCondition;
|
||||
|
||||
return cond?.status === 'True' && cond?.reason === MAINTENANCE_COMPLETED;
|
||||
return (
|
||||
this.metadata?.annotations?.[HCI_ANNOTATIONS.MAINTENANCE_STATUS] ===
|
||||
'completed'
|
||||
);
|
||||
}
|
||||
|
||||
get cpuPinningFeatureEnabled() {
|
||||
|
||||
@@ -326,7 +326,7 @@ export default class HciPv extends HarvesterResource {
|
||||
}
|
||||
|
||||
get relatedPV() {
|
||||
return this.$rootGetters['harvester/byId'](PV, this.spec?.volumeName);
|
||||
return this.$rootGetters['harvester/all'](PV).find((pv) => pv.metadata?.name === this.spec?.volumeName);
|
||||
}
|
||||
|
||||
get volumeProvider() {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { load } from 'js-yaml';
|
||||
import { omitBy, pickBy } from 'lodash';
|
||||
import { PRODUCT_NAME as HARVESTER_PRODUCT } from '../config/harvester';
|
||||
import { colorForState, stateSort } from '@shell/plugins/dashboard-store/resource-class';
|
||||
import { colorForState } from '@shell/plugins/dashboard-store/resource-class';
|
||||
import { POD, NODE, PVC } from '@shell/config/types';
|
||||
import { findBy } from '@shell/utils/array';
|
||||
import { parseSi } from '@shell/utils/units';
|
||||
@@ -14,7 +14,6 @@ import { BACKUP_TYPE } from '../config/types';
|
||||
import { HCI } from '../types';
|
||||
import HarvesterResource from './harvester';
|
||||
import { getVmCPUMemoryValues } from '../utils/cpuMemory';
|
||||
import { sharedComputed } from '../utils/shared-computed';
|
||||
import { isBackupTargetSettingUnavailable } from '../utils/setting';
|
||||
|
||||
export const OFF = 'Off';
|
||||
@@ -82,48 +81,42 @@ const VMIPhase = {
|
||||
Unknown: 'Unknown'
|
||||
};
|
||||
|
||||
// Index of the pods (namespace/ownerName -> pod), shared by all rows. `podList` must be the store list, not a copy.
|
||||
// If several pods have the same owner (e.g. while a VM migrates), the last one wins.
|
||||
function getPodOwnerIndex(podList) {
|
||||
return sharedComputed(podList, 'podOwnerIndex', (pods) => {
|
||||
const map = new Map(); // namespace/ownerName -> pod
|
||||
let productInStore;
|
||||
|
||||
for (const pod of pods) {
|
||||
const refName = pod.metadata?.ownerReferences?.[0]?.name;
|
||||
let _podOwnerMap = null;
|
||||
let _podOwnerMapSource = null;
|
||||
|
||||
if (refName) {
|
||||
map.set(`${ pod.metadata.namespace }/${ refName }`, pod);
|
||||
}
|
||||
}
|
||||
|
||||
return map;
|
||||
});
|
||||
}
|
||||
|
||||
// `getters` are the getters of the store of the VM (`this.$getters`)
|
||||
function getPodByOwnerName(getters, namespace, ownerName) {
|
||||
const podList = getters['all'](POD);
|
||||
function getPodByOwnerName(rootGetters, inStore, ownerName) {
|
||||
const podList = rootGetters[`${ inStore }/all`](POD);
|
||||
|
||||
if (!Array.isArray(podList)) {
|
||||
return undefined;
|
||||
}
|
||||
// if not equals (usually means the pod list has been updated), we need to rebuild the map, otherwise we can reuse the map for better performance
|
||||
if (_podOwnerMapSource !== podList) {
|
||||
_podOwnerMap = new Map(); // use Map to store ownerReference name and pod mapping
|
||||
for (const pod of podList) {
|
||||
const refName = pod.metadata?.ownerReferences?.[0]?.name;
|
||||
|
||||
return getPodOwnerIndex(podList).get(`${ namespace }/${ ownerName }`);
|
||||
}
|
||||
|
||||
// A VM only uses PVCs of its own namespace, so look them up by id instead of scanning all PVCs
|
||||
function getPvcsByNames(getters, namespace, names) {
|
||||
const out = [];
|
||||
|
||||
for (const name of new Set(names)) {
|
||||
const pvc = getters['byId'](PVC, `${ namespace }/${ name }`);
|
||||
|
||||
if (pvc) {
|
||||
out.push(pvc);
|
||||
if (refName) {
|
||||
_podOwnerMap.set(refName, pod);
|
||||
}
|
||||
}
|
||||
_podOwnerMapSource = podList;
|
||||
}
|
||||
|
||||
return out;
|
||||
return _podOwnerMap.get(ownerName);
|
||||
}
|
||||
|
||||
function getPvcsByNames(rootGetters, inStore, names) {
|
||||
const pvcList = rootGetters[`${ inStore }/all`](PVC);
|
||||
|
||||
if (!Array.isArray(pvcList)) {
|
||||
return [];
|
||||
}
|
||||
const uniqueNames = new Set(names);
|
||||
|
||||
return pvcList.filter((pvc) => uniqueNames.has(pvc.metadata?.name));
|
||||
}
|
||||
|
||||
const IgnoreMessages = ['pod has unbound immediate PersistentVolumeClaims'];
|
||||
@@ -142,8 +135,7 @@ export default class VirtVm extends HarvesterResource {
|
||||
clone.action = 'goToCloneVM';
|
||||
}
|
||||
|
||||
const scheduleSchema = this.$getters?.['schemaFor']?.(HCI.SCHEDULE_VM_BACKUP);
|
||||
const canCreateVMSSchedule = !!scheduleSchema && sharedComputed(scheduleSchema, 'canPost', (schema) => !!schema.collectionMethods?.find((x) => ['post'].includes(x.toLowerCase())));
|
||||
const canCreateVMSSchedule = !!this.$getters?.['schemaFor']?.(HCI.SCHEDULE_VM_BACKUP)?.collectionMethods?.find((x) => ['post'].includes(x.toLowerCase()));
|
||||
|
||||
return [
|
||||
{
|
||||
@@ -296,6 +288,14 @@ export default class VirtVm extends HarvesterResource {
|
||||
];
|
||||
}
|
||||
|
||||
get productInStore() {
|
||||
if (!productInStore) {
|
||||
productInStore = this.$rootGetters['currentProduct'].inStore;
|
||||
}
|
||||
|
||||
return productInStore;
|
||||
}
|
||||
|
||||
applyDefaults(resources = this, realMode) {
|
||||
const spec = {
|
||||
runStrategy: 'RerunOnFailure',
|
||||
@@ -729,13 +729,14 @@ export default class VirtVm extends HarvesterResource {
|
||||
}
|
||||
|
||||
get podResource() {
|
||||
const vmiResource = this.$getters['byId'](HCI.VMI, this.id);
|
||||
const inStore = this.productInStore;
|
||||
const vmiResource = this.$rootGetters[`${ inStore }/byId`](HCI.VMI, this.id);
|
||||
|
||||
if (!vmiResource?.metadata?.name) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return getPodByOwnerName(this.$getters, vmiResource.metadata.namespace, vmiResource.metadata.name);
|
||||
return getPodByOwnerName(this.$rootGetters, inStore, vmiResource.metadata.name);
|
||||
}
|
||||
|
||||
get isPaused() {
|
||||
@@ -763,7 +764,8 @@ export default class VirtVm extends HarvesterResource {
|
||||
}
|
||||
|
||||
get nsResourceQuota() {
|
||||
const allResQuotas = this.$getters['all'](HCI.RESOURCE_QUOTA);
|
||||
const inStore = this.productInStore;
|
||||
const allResQuotas = this.$rootGetters[`${ inStore }/all`](HCI.RESOURCE_QUOTA);
|
||||
|
||||
return allResQuotas.find( (RQ) => RQ.namespace === this.metadata.namespace);
|
||||
}
|
||||
@@ -773,13 +775,15 @@ export default class VirtVm extends HarvesterResource {
|
||||
}
|
||||
|
||||
get vmi() {
|
||||
return this.$getters['byId'](HCI.VMI, this.id);
|
||||
const inStore = this.productInStore;
|
||||
|
||||
return this.$rootGetters[`${ inStore }/byId`](HCI.VMI, this.id);
|
||||
}
|
||||
|
||||
get volumes() {
|
||||
const volumeClaimNames = this.spec.template.spec.volumes?.map((v) => v.persistentVolumeClaim?.claimName).filter((v) => !!v) || [];
|
||||
|
||||
return getPvcsByNames(this.$getters, this.metadata.namespace, volumeClaimNames);
|
||||
return getPvcsByNames(this.$rootGetters, this.productInStore, volumeClaimNames);
|
||||
}
|
||||
|
||||
get lvmVolumes() {
|
||||
@@ -803,15 +807,13 @@ export default class VirtVm extends HarvesterResource {
|
||||
}
|
||||
|
||||
get encryptedVolumeType() {
|
||||
const volumes = this.volumes;
|
||||
|
||||
if (!volumes || volumes.length === 0) {
|
||||
if (!this.volumes || this.volumes.length === 0) {
|
||||
return 'none';
|
||||
}
|
||||
|
||||
if (volumes.every((vol) => vol.isEncrypted)) {
|
||||
if (this.volumes.every((vol) => vol.isEncrypted)) {
|
||||
return 'all';
|
||||
} else if (volumes.some((vol) => vol.isEncrypted)) {
|
||||
} else if (this.volumes.some((vol) => vol.isEncrypted)) {
|
||||
return 'partial';
|
||||
} else {
|
||||
return 'none';
|
||||
@@ -916,14 +918,15 @@ export default class VirtVm extends HarvesterResource {
|
||||
}
|
||||
|
||||
get isUnschedulable() {
|
||||
// Check the cheap condition first
|
||||
const condition = this.status?.conditions?.find((c) => c.reason === UNSCHEDULABLE);
|
||||
if (this.isStopping || this.isStarting) {
|
||||
const condition = this.status?.conditions?.find((c) => c.reason === UNSCHEDULABLE);
|
||||
|
||||
if (condition && (this.isStopping || this.isStarting)) {
|
||||
return {
|
||||
status: UNSCHEDULABLE,
|
||||
message: condition.message || 'VM is unschedulable',
|
||||
};
|
||||
if (!!condition) {
|
||||
return {
|
||||
status: UNSCHEDULABLE,
|
||||
message: condition.message || 'VM is unschedulable',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
@@ -968,14 +971,16 @@ export default class VirtVm extends HarvesterResource {
|
||||
`metadata.annotations."${ HCI_ANNOTATIONS.RESTORE_NAME }"`
|
||||
) }`;
|
||||
|
||||
const res = this.$getters['byId'](HCI.RESTORE, id);
|
||||
const inStore = this.productInStore;
|
||||
|
||||
const res = this.$rootGetters[`${ inStore }/byId`](HCI.RESTORE, id);
|
||||
|
||||
if (res) {
|
||||
const backupId = `${ res.spec?.virtualMachineBackupNamespace }/${ res.spec?.virtualMachineBackupName }`;
|
||||
const backup = this.$getters['byId'](HCI.BACKUP, backupId);
|
||||
const allBackups = this.$rootGetters[`${ inStore }/all`](HCI.BACKUP);
|
||||
|
||||
// Snapshots and backups are told apart by spec.type
|
||||
res.fromSnapshot = !!backup && backup.spec?.type !== BACKUP_TYPE.BACKUP;
|
||||
res.fromSnapshot = !!allBackups
|
||||
.filter((b) => b.spec?.type !== BACKUP_TYPE.BACKUP)
|
||||
.find((s) => s.id === `${ res.spec?.virtualMachineBackupNamespace }/${ res.spec?.virtualMachineBackupName }`);
|
||||
}
|
||||
|
||||
return res;
|
||||
@@ -1000,13 +1005,11 @@ export default class VirtVm extends HarvesterResource {
|
||||
}
|
||||
|
||||
get restoreState() {
|
||||
const restore = this.restoreResource;
|
||||
|
||||
if (!restore) {
|
||||
if (!this.restoreResource) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return restore.isComplete;
|
||||
return this.restoreResource?.isComplete;
|
||||
}
|
||||
|
||||
get actualState() {
|
||||
@@ -1107,13 +1110,6 @@ export default class VirtVm extends HarvesterResource {
|
||||
return colorForState(state);
|
||||
}
|
||||
|
||||
// Evaluate actualState once, the base implementation does it in stateColor and stateDisplay
|
||||
get stateSort() {
|
||||
const state = this.actualState;
|
||||
|
||||
return stateSort(colorForState(state), state);
|
||||
}
|
||||
|
||||
get networkIps() {
|
||||
let networkData = '';
|
||||
const out = [];
|
||||
@@ -1164,6 +1160,7 @@ export default class VirtVm extends HarvesterResource {
|
||||
|
||||
get rootImageId() {
|
||||
let imageId = '';
|
||||
const inStore = this.productInStore;
|
||||
|
||||
const volumes = this.spec.template.spec.volumes || [];
|
||||
|
||||
@@ -1173,7 +1170,7 @@ export default class VirtVm extends HarvesterResource {
|
||||
});
|
||||
|
||||
if (!isNoExistingVolume) {
|
||||
const existingVolume = this.$getters['byId'](PVC, `${ this.metadata.namespace }/${ firstVolumeName }`);
|
||||
const existingVolume = this.$rootGetters[`${ inStore }/byId`](PVC, `${ this.metadata.namespace }/${ firstVolumeName }`);
|
||||
|
||||
if (existingVolume) {
|
||||
return existingVolume?.metadata?.annotations?.[
|
||||
@@ -1369,12 +1366,7 @@ export default class VirtVm extends HarvesterResource {
|
||||
get isBackupTargetUnavailable() {
|
||||
const backupTargetSetting = this.$rootGetters['harvester/byId'](HCI.SETTING, 'backup-target');
|
||||
|
||||
// sharedComputed needs an object as key
|
||||
if (!backupTargetSetting) {
|
||||
return isBackupTargetSettingUnavailable(backupTargetSetting);
|
||||
}
|
||||
|
||||
return sharedComputed(backupTargetSetting, 'unavailable', isBackupTargetSettingUnavailable);
|
||||
return isBackupTargetSettingUnavailable(backupTargetSetting);
|
||||
}
|
||||
|
||||
setInstanceLabels(val) {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user