mirror of
https://github.com/harvester/harvester-ui-extension.git
synced 2026-11-16 13:56:08 +08:00
Compare commits
237
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f1c50d008d | ||
|
|
c731fd059e | ||
|
|
376b74b9c1 | ||
|
|
1e0cea8986 | ||
|
|
af80479bd9 | ||
|
|
4caecb48a7 | ||
|
|
8d1d370197 | ||
|
|
df9992146c | ||
|
|
acbc120dc1 | ||
|
|
59c63c8d9e | ||
|
|
4a4f2c96bb | ||
|
|
d7bc112a64 | ||
|
|
08e81b0628 | ||
|
|
4599159bff | ||
|
|
ef40cf5d8d | ||
|
|
d57dbd4c8e | ||
|
|
4c68d057c1 | ||
|
|
b4b2017c61 | ||
|
|
9f0d927c9c | ||
|
|
18a53f5baf | ||
|
|
f872bb5abf | ||
|
|
cd015d57e7 | ||
|
|
635254afdc | ||
|
|
3c464e9d10 | ||
|
|
d412ee2aa6 | ||
|
|
580b2892cb | ||
|
|
965c7d9b72 | ||
|
|
01e3867da1 | ||
|
|
fd52218350 | ||
|
|
1839bf387e | ||
|
|
3e9a0a4377 | ||
|
|
a2898a2554 | ||
|
|
d11a045aed | ||
|
|
ae2a2f6d28 | ||
|
|
cf68c3976a | ||
|
|
33f8300c0e | ||
|
|
b26e34a2bd | ||
|
|
01fd3e5e61 | ||
|
|
d5df7ba602 | ||
|
|
607aa106e1 | ||
|
|
49e2be6ff4 | ||
|
|
9ee81f4054 | ||
|
|
f8fa82f614 | ||
|
|
a6c60de2cb | ||
|
|
843b388ede | ||
|
|
f2e8cce29f | ||
|
|
31682dd165 | ||
|
|
9fac43d5e5 | ||
|
|
cd6ea6e402 | ||
|
|
3bfe57dc54 | ||
|
|
089573f193 | ||
|
|
5d0c4f0c5a | ||
|
|
57bb1e8562 | ||
|
|
30ff129691 | ||
|
|
9175f16bfc | ||
|
|
7c5e0f93d1 | ||
|
|
8a7d3dffbe | ||
|
|
b7810c5970 | ||
|
|
72dedd46d1 | ||
|
|
24f716ab20 | ||
|
|
38ad0fe1a7 | ||
|
|
c84d262099 | ||
|
|
dbb53eae00 | ||
|
|
4afacd754a | ||
|
|
10d159e2c7 | ||
|
|
de755a662a | ||
|
|
f1200f4508 | ||
|
|
0ca2b0591a | ||
|
|
44f003309c | ||
|
|
7c1596c965 | ||
|
|
a5130986a8 | ||
|
|
e4ae7cec5e | ||
|
|
2c7b59daed | ||
|
|
224e34315b | ||
|
|
9f56f9eccc | ||
|
|
dd76956972 | ||
|
|
d92a53d9a7 | ||
|
|
afc3f0d87f | ||
|
|
a607b604f8 | ||
|
|
4d7b0f7350 | ||
|
|
c570b5870b | ||
|
|
af36163b29 | ||
|
|
b3dbc2f0d3 | ||
|
|
fed86d4c24 | ||
|
|
d18ebfb26b | ||
|
|
477206d8d0 | ||
|
|
fd0836d489 | ||
|
|
2e3536abc6 | ||
|
|
45c0dce61b | ||
|
|
6b8b1f68eb | ||
|
|
bb645c00db | ||
|
|
ed8c6e81ca | ||
|
|
ed692b579d | ||
|
|
f02074a25e | ||
|
|
a8f8f0d288 | ||
|
|
9fa9b3837b | ||
|
|
4b3bdf8a59 | ||
|
|
7bdf40d737 | ||
|
|
a1e7345437 | ||
|
|
9322a77b20 | ||
|
|
ed7d7ffd2e | ||
|
|
2ef8e2e0aa | ||
|
|
a0ea6beedb | ||
|
|
85a723e20c | ||
|
|
bbe6b1bdf0 | ||
|
|
81a572e5b5 | ||
|
|
1a727f0001 | ||
|
|
91862244e1 | ||
|
|
c7b0e9ee7a | ||
|
|
d9337ff188 | ||
|
|
c16922c228 | ||
|
|
bbade7e50c | ||
|
|
193bf092d5 | ||
|
|
308b6ddbd7 | ||
|
|
c850b78da2 | ||
|
|
0fe9557eb8 | ||
|
|
b6953d73f7 | ||
|
|
8a89a9c502 | ||
|
|
d5f17bfdf1 | ||
|
|
9d0bb6e1f4 | ||
|
|
2ec37d81d9 | ||
|
|
e50bff8b5e | ||
|
|
e898181834 | ||
|
|
a0f877a23e | ||
|
|
a805490930 | ||
|
|
887a122358 | ||
|
|
1f48e8aea7 | ||
|
|
b2c1a3b068 | ||
|
|
df1566f394 | ||
|
|
0a3b122316 | ||
|
|
d497613cc4 | ||
|
|
91494f5832 | ||
|
|
c61d30a607 | ||
|
|
9428a07850 | ||
|
|
28603d3ab3 | ||
|
|
f863b881a9 | ||
|
|
083ab9f3e9 | ||
|
|
5d52c368a1 | ||
|
|
d72f379ab1 | ||
|
|
2931248fdb | ||
|
|
7166a5b1bb | ||
|
|
00c884cda0 | ||
|
|
1c65b71e35 | ||
|
|
3e4bc31a9d | ||
|
|
bc4bbd9a40 | ||
|
|
a6666ef384 | ||
|
|
92588c9adc | ||
|
|
832df26efc | ||
|
|
f7869cb241 | ||
|
|
27c0124682 | ||
|
|
6c69579c41 | ||
|
|
145b534c5d | ||
|
|
ce017a0e40 | ||
|
|
72a6f77fd2 | ||
|
|
275b15ad62 | ||
|
|
06c9a8b3d9 | ||
|
|
36b1406738 | ||
|
|
06b13a9cc5 | ||
|
|
2a3cd32447 | ||
|
|
40dc31226b | ||
|
|
def9e1a24e | ||
|
|
da25b28f7f | ||
|
|
10abbd0452 | ||
|
|
8a7cc69a69 | ||
|
|
c188f3367d | ||
|
|
26d85a7760 | ||
|
|
6eb845b46b | ||
|
|
8c20ddb440 | ||
|
|
a92f27d80c | ||
|
|
f523a161b6 | ||
|
|
ad2273b5ba | ||
|
|
171939e66b | ||
|
|
18bfbbaac1 | ||
|
|
e79f493cb6 | ||
|
|
e84c0fe886 | ||
|
|
bbfeb55af9 | ||
|
|
e7446e7e23 | ||
|
|
adacaf65fa | ||
|
|
7c761b2829 | ||
|
|
cc8532ff99 | ||
|
|
ede281a42d | ||
|
|
d34279d98f | ||
|
|
efd93c5e52 | ||
|
|
8d338b5f72 | ||
|
|
f59c81da31 | ||
|
|
cf6d44601e | ||
|
|
89b43060df | ||
|
|
7194d52000 | ||
|
|
a8ea0645e4 | ||
|
|
713173b0e4 | ||
|
|
6ed13bcec1 | ||
|
|
02519820d7 | ||
|
|
2604101eb2 | ||
|
|
1cb16f0c74 | ||
|
|
752cf2e93a | ||
|
|
f4ea7b6ea0 | ||
|
|
a6405989e9 | ||
|
|
fb8a81fd0f | ||
|
|
3a5ead3c2c | ||
|
|
def4b64cd3 | ||
|
|
a191b845d8 | ||
|
|
32a57d791a | ||
|
|
2a7e51ef4c | ||
|
|
f726fb99e5 | ||
|
|
9c19ae1f9b | ||
|
|
6ece2d0284 | ||
|
|
aec424b007 | ||
|
|
ff80b91311 | ||
|
|
52252c16f7 | ||
|
|
19cf1e9302 | ||
|
|
ddb8e8106b | ||
|
|
9af5ff7b12 | ||
|
|
fff6153f15 | ||
|
|
1ecac7adf4 | ||
|
|
408818904a | ||
|
|
b96637e6d9 | ||
|
|
8bdaca777f | ||
|
|
d278687e75 | ||
|
|
3ea8edb824 | ||
|
|
e33302050b | ||
|
|
8fefb59802 | ||
|
|
872aec1c10 | ||
|
|
8814bd4cda | ||
|
|
72a17cd9c2 | ||
|
|
8d79b69748 | ||
|
|
47760a8426 | ||
|
|
e6fc641a29 | ||
|
|
90b85d2be7 | ||
|
|
ee9575f710 | ||
|
|
7d97e6821c | ||
|
|
42fc9d8fae | ||
|
|
0f03fc0805 | ||
|
|
6d4a7cd1b1 | ||
|
|
f69d445ef7 | ||
|
|
d358a0a618 | ||
|
|
47841e49b1 | ||
|
|
57c7f0f856 |
@@ -14,4 +14,3 @@ dist-pkg
|
||||
pkg/harvester/index.ts
|
||||
pkg/harvester/store/*
|
||||
scripts/pkgfile.js
|
||||
tmp
|
||||
|
||||
@@ -4,8 +4,7 @@ description: Setup node and install dependencies
|
||||
runs:
|
||||
using: 'composite'
|
||||
steps:
|
||||
- name: Setup Nodejs with yarn caching
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: '.nvmrc'
|
||||
cache: 'yarn'
|
||||
|
||||
@@ -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
|
||||
+18
-12
@@ -1,14 +1,20 @@
|
||||
pull_request_rules:
|
||||
- name: Ask to resolve conflict
|
||||
conditions:
|
||||
- conflict
|
||||
actions:
|
||||
comment:
|
||||
message: This pull request is now in conflict. Could you fix it @{{author}}? 🙏
|
||||
- name: Automatically open backport PR to release-harvester-v1.5
|
||||
conditions:
|
||||
- base=main
|
||||
- label="require backport 1.5"
|
||||
actions:
|
||||
backport:
|
||||
branches:
|
||||
- "release-harvester-v1.5"
|
||||
assignees:
|
||||
- "{{ author }}"
|
||||
labels:
|
||||
- "v1.5 backport PR"
|
||||
|
||||
commands_restrictions:
|
||||
backport:
|
||||
conditions:
|
||||
- or:
|
||||
- sender-permission>=write
|
||||
- sender=github-actions[bot]
|
||||
- name: Ask to resolve conflict
|
||||
conditions:
|
||||
- conflict
|
||||
actions:
|
||||
comment:
|
||||
message: This pull request is now in conflict. Could you fix it @{{author}}? 🙏
|
||||
@@ -1,23 +1,19 @@
|
||||
<!-- This template is for Devs to give QA details before moving the issue To-Test -->
|
||||
### Summary
|
||||
<!-- Give the fix root cause or feature requirement, at least list what this PR changes -->
|
||||
|
||||
### PR Checklists
|
||||
- Do we need to backport this PR change to the [Harvester Dashboard](https://github.com/harvester/dashboard)?
|
||||
- [ ] Yes, the relevant PR is at:
|
||||
- Are backend engineers aware of UI changes?
|
||||
- [ ] Yes, the backend owner is:
|
||||
|
||||
### PR Checklist
|
||||
<!-- Check Yes if there is backend PR related to this UI PR, tag the backend owner's Github account -->
|
||||
- Are backend engineers aware of UI changes ?
|
||||
- [ ] Yes, the backend owner is @
|
||||
- [ ] No, frontend-only.
|
||||
### Related Issue #
|
||||
<!-- Define findings related to the feature or bug issue. -->
|
||||
|
||||
### Related Issue
|
||||
<!-- Link the issue as harvester/harvester#<issue_number> -->
|
||||
harvester/harvester#<issue_number>
|
||||
### Test screenshot/video
|
||||
<!-- Attach screenshot or video of the changes and eventual comparison if you find it necessary -->
|
||||
|
||||
|
||||
### Test Steps
|
||||
<!-- Provide the test steps for reviewer to verify the issue -->
|
||||
1. Go to ... page
|
||||
|
||||
### Test screenshot or video
|
||||
<!-- Attach screenshot or video of the changes and eventual comparison -->
|
||||
### Extra technical notes summary
|
||||
<!-- Outline technical changes which may pass unobserved or may help to understand the process of solving the issue -->
|
||||
|
||||
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
# .github/release.yml
|
||||
changelog:
|
||||
categories:
|
||||
- title: Features
|
||||
labels:
|
||||
- feat
|
||||
- title: Bug Fixes
|
||||
labels:
|
||||
- fix
|
||||
- title: Dependencies
|
||||
labels:
|
||||
- deps
|
||||
- title: Performance
|
||||
labels:
|
||||
- perf
|
||||
- title: Documentation
|
||||
labels:
|
||||
- docs
|
||||
- title: Style
|
||||
labels:
|
||||
- style
|
||||
- title: Build & Continuous Integration
|
||||
labels:
|
||||
- build
|
||||
- ci
|
||||
- title: Security
|
||||
labels:
|
||||
- security
|
||||
- title: Tests
|
||||
labels:
|
||||
- test
|
||||
- title: Refactoring
|
||||
labels:
|
||||
- refactor
|
||||
- title: Chores
|
||||
labels:
|
||||
- chore
|
||||
- title: Others
|
||||
labels:
|
||||
- other
|
||||
@@ -1,57 +0,0 @@
|
||||
{
|
||||
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
|
||||
"extends": [
|
||||
"config:recommended",
|
||||
":semanticCommitTypeAll(deps)",
|
||||
":semanticCommitScopeDisabled"
|
||||
],
|
||||
"baseBranches": [
|
||||
"main",
|
||||
"release-harvester-v1.7",
|
||||
"release-harvester-v1.8"
|
||||
],
|
||||
"automergeMajor": false,
|
||||
"semanticCommits": "enabled",
|
||||
"semanticCommitType": "deps",
|
||||
"prHourlyLimit": 12,
|
||||
"digest": {
|
||||
"enabled": false
|
||||
},
|
||||
"timezone": "Asia/Taipei",
|
||||
"schedule": ["after 10am on sunday"],
|
||||
"postUpdateOptions": ["yarnDedupeFewer"],
|
||||
"packageRules": [
|
||||
{
|
||||
"matchUpdateTypes": ["digest"],
|
||||
"enabled": false
|
||||
},
|
||||
{
|
||||
"matchUpdateTypes": ["major"],
|
||||
"enabled": false
|
||||
},
|
||||
{
|
||||
"matchPackagePatterns": ["vue", "vue-router", "vuex"],
|
||||
"matchUpdateTypes": ["major"],
|
||||
"enabled": false
|
||||
},
|
||||
{
|
||||
"matchPackageNames": ["@rancher/shell"],
|
||||
"enabled": false
|
||||
},
|
||||
{
|
||||
"matchUpdateTypes": ["minor"],
|
||||
"groupName": "minor dependencies",
|
||||
"minimumReleaseAge": "7 days",
|
||||
"labels": ["minor-update"],
|
||||
"reviewers": ["a110605", "houhoucoop"]
|
||||
},
|
||||
{
|
||||
"matchUpdateTypes": ["patch"],
|
||||
"automerge": false,
|
||||
"minimumReleaseAge": "7 days",
|
||||
"groupName": "patch dependencies",
|
||||
"labels": ["patch-update"],
|
||||
"reviewers": ["a110605", "houhoucoop"]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
name: "PR Management Add PR Label Collect Data"
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, reopened, edited]
|
||||
branches:
|
||||
- main
|
||||
- 'release-harvester-v*'
|
||||
|
||||
jobs:
|
||||
collect:
|
||||
if: github.event.pull_request.draft == false
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
actions: write
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with:
|
||||
ref: ${{ github.base_ref }}
|
||||
|
||||
- name: Setup Nodejs and yarn install
|
||||
uses: ./.github/actions/setup
|
||||
|
||||
- name: Extract PR label
|
||||
run: |
|
||||
PR_LABEL=$(node ./scripts/extract-release-label.mjs "${{ github.event.pull_request.title }}")
|
||||
echo "PR_LABEL=$PR_LABEL"
|
||||
{
|
||||
echo "PR_NUMBER=${{ github.event.pull_request.number }}"
|
||||
echo "PR_LABEL=$PR_LABEL"
|
||||
} > pr-add-label-data.env
|
||||
|
||||
- name: Upload PR data artifact
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: pr-add-label-data
|
||||
path: pr-add-label-data.env
|
||||
@@ -1,33 +0,0 @@
|
||||
name: "PR Management Add PR Label"
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
workflows:
|
||||
- "PR Management Add PR Label Collect Data"
|
||||
types: [completed]
|
||||
|
||||
jobs:
|
||||
auto-assign-pr-label:
|
||||
runs-on: ubuntu-latest
|
||||
if: ${{ github.event.workflow_run.conclusion == 'success' }}
|
||||
permissions:
|
||||
actions: read
|
||||
pull-requests: write
|
||||
steps:
|
||||
- name: Download PR data artifact
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
|
||||
with:
|
||||
name: pr-add-label-data
|
||||
run-id: ${{ github.event.workflow_run.id }}
|
||||
github-token: ${{ github.token }}
|
||||
|
||||
- name: Load PR data
|
||||
run: |
|
||||
cat pr-add-label-data.env >> $GITHUB_ENV
|
||||
|
||||
- name: Set PR label
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
echo "PR_LABEL = $PR_LABEL"
|
||||
gh pr edit "$PR_NUMBER" --repo "${{ github.repository }}" --add-label "$PR_LABEL"
|
||||
@@ -1,28 +0,0 @@
|
||||
name: "PR Management Auto Assign Collect Data"
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, ready_for_review]
|
||||
branches:
|
||||
- main
|
||||
- 'release-harvester-v*'
|
||||
|
||||
jobs:
|
||||
collect:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
actions: write
|
||||
steps:
|
||||
- name: Save PR data to artifact
|
||||
run: |
|
||||
{
|
||||
echo "PR_NUMBER=${{ github.event.pull_request.number }}"
|
||||
echo "PR_AUTHOR=${{ github.event.pull_request.user.login }}"
|
||||
} > pr-auto-assign-data.env
|
||||
|
||||
- name: Upload PR data artifact
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: pr-auto-assign-data
|
||||
path: pr-auto-assign-data.env
|
||||
@@ -1,35 +0,0 @@
|
||||
name: "PR Management Auto Assign"
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
workflows:
|
||||
- "PR Management Auto Assign Collect Data"
|
||||
types: [completed]
|
||||
|
||||
jobs:
|
||||
auto-assign:
|
||||
runs-on: ubuntu-latest
|
||||
if: ${{ github.event.workflow_run.conclusion == 'success' }}
|
||||
env:
|
||||
REVIEWERS: "a110605,houhoucoop"
|
||||
permissions:
|
||||
actions: read
|
||||
pull-requests: write
|
||||
steps:
|
||||
- name: Download PR data artifact
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
|
||||
with:
|
||||
name: pr-auto-assign-data
|
||||
run-id: ${{ github.event.workflow_run.id }}
|
||||
github-token: ${{ github.token }}
|
||||
|
||||
- name: Load PR data
|
||||
run: |
|
||||
cat pr-auto-assign-data.env >> $GITHUB_ENV
|
||||
|
||||
- name: Auto assign PR author
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
echo "Assigning PR author: $PR_AUTHOR"
|
||||
gh pr edit "$PR_NUMBER" --repo "${{ github.repository }}" --add-assignee "$PR_AUTHOR" --add-reviewer "$REVIEWERS"
|
||||
@@ -1,30 +0,0 @@
|
||||
name: "PR Management Add Labels Collect Data"
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, reopened]
|
||||
branches:
|
||||
- main
|
||||
- 'release-harvester-v*'
|
||||
|
||||
jobs:
|
||||
collect:
|
||||
if: github.event.pull_request.draft == false
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
actions: write
|
||||
steps:
|
||||
- name: Save PR data to artifact
|
||||
run: |
|
||||
{
|
||||
echo "PR_NUMBER=${{ github.event.pull_request.number }}"
|
||||
echo "PR_BASE_REF=${{ github.event.pull_request.base.ref }}"
|
||||
echo "PR_USER_LOGIN=${{ github.event.pull_request.user.login }}"
|
||||
} > pr-backport-label-data.env
|
||||
|
||||
- name: Upload PR data artifact
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: pr-backport-label-data
|
||||
path: pr-backport-label-data.env
|
||||
@@ -1,83 +0,0 @@
|
||||
name: "PR Management Add Backport Labels"
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
workflows:
|
||||
- "PR Management Add Labels Collect Data"
|
||||
types: [completed]
|
||||
|
||||
jobs:
|
||||
add-require-backport-label:
|
||||
runs-on: ubuntu-latest
|
||||
if: ${{ github.event.workflow_run.conclusion == 'success' }}
|
||||
permissions:
|
||||
actions: read
|
||||
pull-requests: write
|
||||
steps:
|
||||
- name: Download PR data artifact
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
|
||||
with:
|
||||
name: pr-backport-label-data
|
||||
run-id: ${{ github.event.workflow_run.id }}
|
||||
github-token: ${{ github.token }}
|
||||
|
||||
- name: Load PR data
|
||||
run: |
|
||||
cat pr-backport-label-data.env >> $GITHUB_ENV
|
||||
|
||||
- name: Add require-backport label (main branch PRs)
|
||||
if: env.PR_BASE_REF == 'main'
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
repo="${{ github.repository }}"
|
||||
pr_number="$PR_NUMBER"
|
||||
|
||||
release_branches=$(gh api "repos/${repo}/branches" --paginate --jq '.[].name' | grep -E '^release-harvester-v[0-9]+\.[0-9]+$' || true)
|
||||
|
||||
if [[ -z "$release_branches" ]]; then
|
||||
echo "No release branches found, skipping."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
latest_branch=$(echo "$release_branches" | sort -Vr | head -n1)
|
||||
version="${latest_branch#release-harvester-v}"
|
||||
release_tag="v${version}.0"
|
||||
|
||||
tags=$(gh api "repos/${repo}/releases" --paginate --jq '.[].tag_name')
|
||||
if echo "$tags" | grep -Fxq "$release_tag"; then
|
||||
echo "Release $release_tag already published, skipping."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
label="require backport/v${version}"
|
||||
pr_labels=$(gh pr view "$pr_number" --repo "$repo" --json labels --jq '.labels[].name' || echo "")
|
||||
|
||||
if echo "$pr_labels" | grep -Fxq "$label"; then
|
||||
echo "Label '$label' already present, skipping."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "Adding label: $label"
|
||||
gh pr edit "$pr_number" --repo "$repo" --add-label "$label"
|
||||
|
||||
- name: Add backport label (release branch PRs opened by Mergify)
|
||||
if: startsWith(env.PR_BASE_REF, 'release-harvester-v')
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
IS_MERGIFY=$(echo "$PR_USER_LOGIN" | grep -iq 'mergify' && echo true || echo false)
|
||||
|
||||
if [[ "$IS_MERGIFY" != "true" ]]; then
|
||||
echo "PR author is not Mergify, skipping."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
version="${PR_BASE_REF#release-harvester-v}"
|
||||
label="backport/v${version}"
|
||||
echo "Adding label: $label"
|
||||
gh pr edit "$PR_NUMBER" --repo "${{ github.repository }}" --add-label "$label"
|
||||
@@ -1,28 +0,0 @@
|
||||
name: "PR Management Request Backport via Mergify Collect Data"
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [closed]
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
collect:
|
||||
if: github.event.pull_request.merged == true
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
actions: write
|
||||
steps:
|
||||
- name: Save PR data to artifact
|
||||
run: |
|
||||
labels_json='${{ toJson(github.event.pull_request.labels.*.name) }}'
|
||||
{
|
||||
echo "PR_NUMBER=${{ github.event.pull_request.number }}"
|
||||
echo "PR_LABELS=$(echo "$labels_json" | jq -r '[.[]] | join(",")')"
|
||||
} > pr-backport-request-data.env
|
||||
|
||||
- name: Upload PR data artifact
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: pr-backport-request-data
|
||||
path: pr-backport-request-data.env
|
||||
@@ -1,55 +0,0 @@
|
||||
name: "PR Management Request Backport via Mergify"
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
workflows:
|
||||
- "PR Management Request Backport via Mergify Collect Data"
|
||||
types: [completed]
|
||||
|
||||
jobs:
|
||||
comment-backport:
|
||||
runs-on: ubuntu-latest
|
||||
if: ${{ github.event.workflow_run.conclusion == 'success' }}
|
||||
permissions:
|
||||
actions: read
|
||||
pull-requests: write
|
||||
steps:
|
||||
- name: Download PR data artifact
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
|
||||
with:
|
||||
name: pr-backport-request-data
|
||||
run-id: ${{ github.event.workflow_run.id }}
|
||||
github-token: ${{ github.token }}
|
||||
|
||||
- name: Load PR data
|
||||
run: |
|
||||
cat pr-backport-request-data.env >> $GITHUB_ENV
|
||||
|
||||
- name: Post Mergify backport command
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
pr_number="$PR_NUMBER"
|
||||
repo="${{ github.repository }}"
|
||||
|
||||
labels=$(echo "$PR_LABELS" | tr ',' '\n')
|
||||
|
||||
echo "Labels on PR: $labels"
|
||||
|
||||
matches=$(echo "$labels" | grep -oE '^require backport/v[0-9]+\.[0-9]+$' || true)
|
||||
|
||||
if [[ -z "$matches" ]]; then
|
||||
echo "No back-port labels found — skipping."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
branches=$(echo "$matches" \
|
||||
| sed -E 's/^require backport\/v/release-harvester-v/' \
|
||||
| sort -u | tr '\n' ' ')
|
||||
branches=${branches%% }
|
||||
|
||||
cmd="@Mergifyio backport $branches"
|
||||
echo "Posting Mergify command: $cmd"
|
||||
gh pr comment "$pr_number" --repo "$repo" --body "$cmd"
|
||||
@@ -15,7 +15,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Check package version
|
||||
env:
|
||||
|
||||
@@ -25,12 +25,12 @@ jobs:
|
||||
name: Build & Upload Hosted
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
# Note - Cannot use the setup action here as it uses a different yarn install arg
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: '.nvmrc'
|
||||
cache: 'yarn'
|
||||
@@ -45,20 +45,19 @@ jobs:
|
||||
run: ./scripts/build-upload-gate
|
||||
|
||||
- name: Get gcs auth
|
||||
uses: rancher-eio/read-vault-secrets@d266f55186f80a893839f6e15662e67388e443e6 # v3
|
||||
uses: rancher-eio/read-vault-secrets@main
|
||||
with:
|
||||
secrets: |
|
||||
secret/data/github/repo/${{ github.repository }}/google-auth/harvester/credentials token | GOOGLE_AUTH ;
|
||||
|
||||
- name: Apply gcs auth
|
||||
# https://github.com/google-github-actions/auth
|
||||
uses: google-github-actions/auth@c200f3691d83b41bf9bbd8638997a462592937ed # v2
|
||||
|
||||
uses: 'google-github-actions/auth@v2'
|
||||
with:
|
||||
credentials_json: "${{ env.GOOGLE_AUTH }}"
|
||||
|
||||
- name: Upload build
|
||||
uses: google-github-actions/upload-cloud-storage@c0f6160ff80057923ff50e5e567695cea181ec23 # v2
|
||||
uses: 'google-github-actions/upload-cloud-storage@v2'
|
||||
# https://github.com/google-github-actions/upload-cloud-storage
|
||||
with:
|
||||
path: ${{steps.build-hosted.outputs.BUILD_HOSTED_DIR}}
|
||||
@@ -72,12 +71,12 @@ jobs:
|
||||
name: Build & Upload Embedded
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
# Note - Cannot use the setup action here as it uses a different yarn install arg
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: '.nvmrc'
|
||||
cache: 'yarn'
|
||||
@@ -90,19 +89,19 @@ jobs:
|
||||
DISABLED_EMBED_PKG: https://releases.rancher.com/harvester-ui/plugin/harvester-1.0.3.tar.gz
|
||||
|
||||
- name: Get gcs auth
|
||||
uses: rancher-eio/read-vault-secrets@d266f55186f80a893839f6e15662e67388e443e6 # v3
|
||||
uses: rancher-eio/read-vault-secrets@main
|
||||
with:
|
||||
secrets: |
|
||||
secret/data/github/repo/${{ github.repository }}/google-auth/harvester/credentials token | GOOGLE_AUTH ;
|
||||
|
||||
- name: Apply gcs auth
|
||||
# https://github.com/google-github-actions/auth
|
||||
uses: google-github-actions/auth@c200f3691d83b41bf9bbd8638997a462592937ed # v2
|
||||
uses: 'google-github-actions/auth@v2'
|
||||
with:
|
||||
credentials_json: "${{ env.GOOGLE_AUTH }}"
|
||||
|
||||
- name: Upload tar
|
||||
uses: google-github-actions/upload-cloud-storage@c0f6160ff80057923ff50e5e567695cea181ec23 # v2
|
||||
uses: 'google-github-actions/upload-cloud-storage@v2'
|
||||
with:
|
||||
path: ${{steps.build-embedded.outputs.BUILD_EMBEDED_TGZ}}
|
||||
destination: releases.rancher.com/harvester-ui/dashboard
|
||||
@@ -115,23 +114,16 @@ jobs:
|
||||
name: Build & Upload Plugin
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
# Note - Cannot use the setup action here as it uses a different yarn install arg
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: '.nvmrc'
|
||||
cache: 'yarn'
|
||||
|
||||
# Tag builds (RC, formal and sprint releases) ship the tag as the package
|
||||
# version. RC/formal tags already match package.json; sprint tags
|
||||
# (vX.Y.Z-dev-YYYYMMDD) only share its prefix, so pin it here for the build.
|
||||
- name: Pin package version to tag
|
||||
if: ${{ inputs.CI_BUILD_TAG != '' }}
|
||||
run: ./scripts/bump_version.sh "${{ inputs.CI_BUILD_TAG }}"
|
||||
|
||||
- id: ci-build-pkg
|
||||
name: Build pkg
|
||||
run: ./scripts/ci-build-pkg.sh harvester
|
||||
@@ -141,19 +133,19 @@ jobs:
|
||||
run: ./scripts/build-upload-gate
|
||||
|
||||
- name: Get gcs auth
|
||||
uses: rancher-eio/read-vault-secrets@d266f55186f80a893839f6e15662e67388e443e6 # v3
|
||||
uses: rancher-eio/read-vault-secrets@main
|
||||
with:
|
||||
secrets: |
|
||||
secret/data/github/repo/${{ github.repository }}/google-auth/harvester/credentials token | GOOGLE_AUTH ;
|
||||
|
||||
- name: Apply gcs auth
|
||||
# https://github.com/google-github-actions/auth
|
||||
uses: google-github-actions/auth@c200f3691d83b41bf9bbd8638997a462592937ed # v2
|
||||
uses: 'google-github-actions/auth@v2'
|
||||
with:
|
||||
credentials_json: "${{ env.GOOGLE_AUTH }}"
|
||||
|
||||
- name: Upload plugin tar
|
||||
uses: google-github-actions/upload-cloud-storage@c0f6160ff80057923ff50e5e567695cea181ec23 # v2
|
||||
uses: 'google-github-actions/upload-cloud-storage@v2'
|
||||
with:
|
||||
path: dist-pkg/${{steps.ci-build-pkg.outputs.PKG_TARBALL}}
|
||||
destination: releases.rancher.com/harvester-ui/plugin
|
||||
@@ -163,7 +155,7 @@ jobs:
|
||||
process_gcloudignore: false
|
||||
|
||||
- name: Upload plugin directory
|
||||
uses: google-github-actions/upload-cloud-storage@c0f6160ff80057923ff50e5e567695cea181ec23 # v2
|
||||
uses: 'google-github-actions/upload-cloud-storage@v2'
|
||||
with:
|
||||
path: dist-pkg/${{steps.ci-build-pkg.outputs.PKG_NAME}}
|
||||
destination: releases.rancher.com/harvester-ui/plugin/${{steps.ci-build-pkg.outputs.PKG_NAME}}
|
||||
|
||||
@@ -27,14 +27,14 @@ jobs:
|
||||
build-status: ${{ job.status }}
|
||||
steps:
|
||||
- name: Read Secrets
|
||||
uses: rancher-eio/read-vault-secrets@d266f55186f80a893839f6e15662e67388e443e6 # v3
|
||||
uses: rancher-eio/read-vault-secrets@main
|
||||
with:
|
||||
secrets: |
|
||||
secret/data/github/repo/${{ github.repository }}/dockerhub/rancher/credentials username | DOCKER_USERNAME ;
|
||||
secret/data/github/repo/${{ github.repository }}/dockerhub/rancher/credentials password | DOCKER_PASSWORD ;
|
||||
|
||||
- name: Checkout repository (normal flow)
|
||||
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Enable Corepack
|
||||
run: corepack enable
|
||||
@@ -45,26 +45,26 @@ jobs:
|
||||
git config user.email 'github-actions[bot]@users.noreply.github.com'
|
||||
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ env.DOCKER_USERNAME }}
|
||||
password: ${{ env.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Setup Helm
|
||||
uses: azure/setup-helm@5119fcb9089d432beecbf79bb2c7915207344b78 # v3
|
||||
uses: azure/setup-helm@v3
|
||||
with:
|
||||
version: v3.8.0
|
||||
|
||||
- name: Setup Nodejs with yarn install
|
||||
uses: ./.github/actions/setup
|
||||
- name: Setup Nodejs with yarn caching
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: yarn
|
||||
|
||||
# The catalog image is tagged with the package.json version. Sprint tags
|
||||
# (vX.Y.Z-dev-YYYYMMDD) only share its prefix, so pin it to the tag here.
|
||||
- name: Pin package version to tag
|
||||
if: ${{ github.ref_type == 'tag' }}
|
||||
run: ./scripts/bump_version.sh "${{ github.ref_name }}"
|
||||
- name: Install dependencies
|
||||
run: yarn
|
||||
|
||||
- name: Build and push UI image
|
||||
run: |
|
||||
publish="yarn publish-pkgs -cp -r ${{ inputs.registry_target }} -o ${{ inputs.registry_user }}"
|
||||
$publish
|
||||
$publish
|
||||
@@ -4,7 +4,6 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- 'release-harvester-v*'
|
||||
- 'main'
|
||||
|
||||
jobs:
|
||||
setup-target-branch:
|
||||
@@ -13,22 +12,19 @@ jobs:
|
||||
target_branch: ${{ steps.get-version.outputs.target_branch }}
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Determine target branch
|
||||
id: get-version
|
||||
run: |
|
||||
if [[ "${{ github.ref_name }}" == "main" ]]; then
|
||||
TARGET_BRANCH="main-head"
|
||||
elif [[ "${{ github.ref_name }}" =~ ^release-harvester-v([0-9]+\.[0-9]+)$ ]]; then
|
||||
if [[ "${{ github.ref_name }}" =~ ^release-harvester-v([0-9]+\.[0-9]+)$ ]]; then
|
||||
TARGET_BRANCH="v${BASH_REMATCH[1]}-head"
|
||||
echo "target_branch=${TARGET_BRANCH}" >> $GITHUB_ENV
|
||||
echo "target_branch=${TARGET_BRANCH}" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "Error: invalid branch format." && exit 1
|
||||
fi
|
||||
|
||||
echo "target_branch=${TARGET_BRANCH}" >> $GITHUB_ENV
|
||||
echo "target_branch=${TARGET_BRANCH}" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Ensure target branch exists
|
||||
run: |
|
||||
git fetch --all
|
||||
@@ -44,7 +40,7 @@ jobs:
|
||||
version: ${{ steps.get_version.outputs.version }}
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Extract version from package.json
|
||||
id: get_version
|
||||
@@ -62,13 +58,7 @@ jobs:
|
||||
contents: write
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
|
||||
- name: Setup Node from .nvmrc
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
node-version-file: '.nvmrc'
|
||||
cache: 'yarn'
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup environment
|
||||
run: |
|
||||
@@ -76,7 +66,7 @@ jobs:
|
||||
yarn install --frozen-lockfile
|
||||
|
||||
- name: Setup Helm
|
||||
uses: azure/setup-helm@5119fcb9089d432beecbf79bb2c7915207344b78 # v3
|
||||
uses: azure/setup-helm@v3
|
||||
with:
|
||||
version: v3.8.0
|
||||
|
||||
@@ -85,7 +75,7 @@ jobs:
|
||||
yarn publish-pkgs -s ${{ github.repository }} -b ${{ needs.setup-target-branch.outputs.target_branch }} -t harvester-${{ needs.extract-version.outputs.version }}
|
||||
|
||||
- name: Upload charts artifact
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: charts
|
||||
path: tmp
|
||||
@@ -100,7 +90,7 @@ jobs:
|
||||
contents: write
|
||||
steps:
|
||||
- name: Checkout release branch
|
||||
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: '${{ github.ref_name }}'
|
||||
|
||||
@@ -111,7 +101,7 @@ jobs:
|
||||
echo "LAST_COMMIT=${LAST_COMMIT}" >> $GITHUB_ENV
|
||||
|
||||
- name: Checkout target branch
|
||||
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: '${{ needs.setup-target-branch.outputs.target_branch }}'
|
||||
|
||||
@@ -127,7 +117,7 @@ jobs:
|
||||
git config user.email 'github-actions[bot]@users.noreply.github.com'
|
||||
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: charts
|
||||
|
||||
@@ -138,7 +128,7 @@ jobs:
|
||||
git push origin ${{ needs.setup-target-branch.outputs.target_branch }}
|
||||
|
||||
- name: Run Helm chart releaser
|
||||
uses: helm/chart-releaser-action@cae68fefc6b5f367a0275617c9f83181ba54714f # v1.7.0
|
||||
uses: helm/chart-releaser-action@v1.7.0
|
||||
with:
|
||||
charts_dir: ./charts
|
||||
env:
|
||||
|
||||
@@ -17,7 +17,7 @@ jobs:
|
||||
release_tag: ${{ steps.determine_tag.outputs.release_tag }}
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Determine release tag
|
||||
id: determine_tag
|
||||
@@ -33,7 +33,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
uses: actions/checkout@v4
|
||||
- name: Check package version
|
||||
env:
|
||||
TAG_VERSION: ${{ github.event.release.tag_name }}
|
||||
@@ -43,10 +43,12 @@ jobs:
|
||||
needs:
|
||||
- setup-release-tag
|
||||
- check-version
|
||||
uses: rancher/dashboard/.github/workflows/build-extension-charts.yml@9bf23dff6650116673346447bcf0b088e0edb27f # creators-pkg-v3.0.12
|
||||
uses: rancher/dashboard/.github/workflows/build-extension-charts.yml@master
|
||||
permissions:
|
||||
actions: write
|
||||
contents: write
|
||||
pull-requests: write
|
||||
deployments: write
|
||||
pages: write
|
||||
with:
|
||||
target_branch: gh-pages
|
||||
tagged_release: '${{ needs.setup-release-tag.outputs.release_tag }}'
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
name: Build Standalone on PR Merge
|
||||
|
||||
on:
|
||||
workflow_dispatch: # manually trigger on Github Actions only support PR branch pushed to harvester/harvester-ui-extension
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
@@ -30,35 +29,3 @@ jobs:
|
||||
id-token: write
|
||||
with:
|
||||
CI_BRANCH: ${{github.ref_name}}
|
||||
comment-on-pr:
|
||||
name: Comment build result on PR
|
||||
# Only for manual runs so the existing push / pull_request flows are untouched.
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
needs:
|
||||
- build
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
pull-requests: write
|
||||
steps:
|
||||
- name: Add build artifact comment to the PR opened from this branch
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
BRANCH: ${{ github.ref_name }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# Match scripts/version: sanitize the branch and map main -> latest.
|
||||
if [ "$BRANCH" = "main" ]; then
|
||||
DIR="latest"
|
||||
else
|
||||
DIR=$(printf '%s' "$BRANCH" | sed -E 's/[^a-zA-Z0-9.-]+/-/g')
|
||||
fi
|
||||
URL="https://releases.rancher.com/harvester-ui/dashboard/${DIR}/index.html"
|
||||
|
||||
PR=$(gh pr list --repo "$GITHUB_REPOSITORY" --state open --base main --head "$BRANCH" --json number --jq '.[0].number // empty')
|
||||
if [ -z "$PR" ]; then
|
||||
echo "No open PR found for branch $BRANCH, skipping comment."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
BODY=$(printf '🚀 **UI Artifact Build Status:** `SUCCESS` ✅\n> ui-index: %s\n> ui-source: external' "$URL")
|
||||
gh pr comment "$PR" --repo "$GITHUB_REPOSITORY" --body "$BODY"
|
||||
|
||||
@@ -9,7 +9,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
uses: actions/checkout@v4
|
||||
- name: Check package version
|
||||
env:
|
||||
TAG_VERSION: ${{github.ref_name}}
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
name: FOSSA Scanning
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["main", "release-harvester-v*"]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
|
||||
jobs:
|
||||
fossa-scanning:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
|
||||
# The FOSSA token is shared between all repos in Harvester's GH org. It can
|
||||
# be used directly and there is no need to request specific access to EIO.
|
||||
- name: Read FOSSA token
|
||||
uses: rancher-eio/read-vault-secrets@d266f55186f80a893839f6e15662e67388e443e6 # v3
|
||||
with:
|
||||
secrets: |
|
||||
secret/data/github/org/harvester/fossa/credentials token | FOSSA_API_KEY_PUSH_ONLY
|
||||
|
||||
- name: FOSSA scan
|
||||
uses: fossas/fossa-action@ff70fe9fe17cbd2040648f1c45e8ec4e4884dcf3 # v1.9.0
|
||||
with:
|
||||
api-key: ${{ env.FOSSA_API_KEY_PUSH_ONLY }}
|
||||
# Only runs the scan and do not provide/returns any results back to the
|
||||
# pipeline.
|
||||
run-tests: false
|
||||
@@ -1,13 +1,12 @@
|
||||
name: Tests
|
||||
|
||||
on:
|
||||
workflow_call: # This tells GH that the workflow is reusable
|
||||
workflow_call: # This tells GH that the workflow is reusable
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- 'release-*'
|
||||
pull_request:
|
||||
types: [opened, reopened, edited, synchronize]
|
||||
branches:
|
||||
- main
|
||||
- 'release-*'
|
||||
@@ -16,66 +15,9 @@ jobs:
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0 # Need full history for commit-lint
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Run tests
|
||||
uses: ./.github/actions/lint
|
||||
|
||||
- name: Validate PR title lint
|
||||
if: github.event_name == 'pull_request'
|
||||
shell: bash
|
||||
run: echo "${{ github.event.pull_request.title }}" | npx commitlint
|
||||
|
||||
- name: Validate commit messages
|
||||
shell: bash
|
||||
run: |
|
||||
echo "GITHUB_EVENT_NAME=$GITHUB_EVENT_NAME"
|
||||
echo "GITHUB_BASE_SHA=$GITHUB_BASE_SHA"
|
||||
echo "GITHUB_HEAD_SHA=$GITHUB_HEAD_SHA"
|
||||
echo "GITHUB_BEFORE=$GITHUB_BEFORE"
|
||||
echo "GITHUB_AFTER=$GITHUB_AFTER"
|
||||
|
||||
if [ "$GITHUB_EVENT_NAME" = "pull_request" ] && [ -n "$GITHUB_BASE_SHA" ] && [ -n "$GITHUB_HEAD_SHA" ]; then
|
||||
FROM="$GITHUB_BASE_SHA"
|
||||
TO="$GITHUB_HEAD_SHA"
|
||||
elif [ -n "$GITHUB_BEFORE" ] && [ -n "$GITHUB_AFTER" ]; then
|
||||
if [ "$GITHUB_BEFORE" = "0000000000000000000000000000000000000000" ]; then
|
||||
# first push to HEAD
|
||||
FROM=""
|
||||
TO="$GITHUB_AFTER"
|
||||
else
|
||||
FROM="$GITHUB_BEFORE"
|
||||
TO="$GITHUB_AFTER"
|
||||
fi
|
||||
else
|
||||
echo "No valid commit range found, skipping commitlint."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "FROM=$FROM"
|
||||
echo "TO=$TO"
|
||||
|
||||
if [ -z "$FROM" ]; then
|
||||
echo "Linting last commit $TO"
|
||||
npx commitlint --last --verbose
|
||||
|
||||
else
|
||||
echo "Linting commits from $FROM to $TO"
|
||||
npx commitlint --from "$FROM" --to "$TO" --verbose
|
||||
fi
|
||||
env:
|
||||
GITHUB_EVENT_NAME: ${{ github.event_name }}
|
||||
GITHUB_BASE_SHA: ${{ github.event.pull_request.base.sha }}
|
||||
GITHUB_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
|
||||
GITHUB_BEFORE: ${{ github.event.before }}
|
||||
GITHUB_AFTER: ${{ github.event.after }}
|
||||
|
||||
unit-tests:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
|
||||
- name: Run unit tests
|
||||
uses: ./.github/actions/test
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
npx --no -- commitlint --edit $1
|
||||
@@ -1 +0,0 @@
|
||||
yarn lint
|
||||
@@ -1,286 +0,0 @@
|
||||
> This `./AGENTS.md` file is generated by running `yarn agents:generate`. `CLAUDE.md` and `GEMINI.md` are symlinks to this file so Claude Code, GitHub Copilot and Gemini all read the same content.
|
||||
|
||||
|
||||
# Project Overview
|
||||
|
||||
The Harvester UI Extension is a Rancher extension that provides the user interface for Harvester within the Rancher Dashboard.
|
||||
|
||||
```
|
||||
Note: This extension is available starting from Rancher 2.10.0. Ensure your Rancher version is 2.10.0 or later to access Harvester integration.
|
||||
```
|
||||
|
||||
# Personas
|
||||
|
||||
## Software Developer
|
||||
|
||||
You are an expert Senior Software Engineer specializing in Vue.js and TypeScript. You have deep knowledge of Kubernetes and the Rancher ecosystem.
|
||||
- **Focus**: Writing clean, maintainable, and performant code.
|
||||
- **Priorities**: Adhering to the project's code style, ensuring type safety, and following best practices for component design.
|
||||
|
||||
|
||||
# Agents
|
||||
|
||||
## Boundaries
|
||||
|
||||
- ✅ **Always:**
|
||||
- Write to `.github`, `docs/`, `pkg/harvester`, `scripts/`.
|
||||
- Make commits in a new branch (for a PR).
|
||||
- Run `yarn lint:fix` before commits.
|
||||
- Use conventional commit format:
|
||||
```
|
||||
<type>: <description>
|
||||
```
|
||||
- Follow existing naming conventions (PascalCase for components, camelCase for functions).
|
||||
- After changing a Vue, JS, or TS file, make sure it's automatically formatted with ESLint.
|
||||
- After updating files in `docs/agents.md/`, run `yarn agents:generate` to update root `AGENTS.md`.
|
||||
- ⚠️ **Ask first:**
|
||||
- Adding dependencies
|
||||
- Upgrading dependencies
|
||||
- 🚫 **Never:**
|
||||
- Commit or log secrets, `.env`, `kubeconfig` or any API keys.
|
||||
- Edit `node_modules/`.
|
||||
- Commit directly to `main` (use PRs).
|
||||
- Skip git hooks with `--no-verify` flag.
|
||||
|
||||
## Tools
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- **Node.js**: `>= 24.0.0` (see `.nvmrc` for the pinned version: `24`)
|
||||
- **Package manager**: `yarn` (v1 classic)
|
||||
|
||||
### Common Commands
|
||||
|
||||
| Command | Description |
|
||||
|---------|-------------|
|
||||
| `yarn install --frozen-lockfile` | Install dependencies (CI-safe, no lockfile changes) |
|
||||
| `RANCHER_ENV=harvester API=https://<harvester-ip> yarn dev` | Start development server at `https://127.0.0.1:8005` |
|
||||
| `yarn build-pkg harvester` | Build the Harvester extension package |
|
||||
| `yarn serve-pkgs` | Serve the locally built extension for testing |
|
||||
| `yarn lint` | Run ESLint (zero warnings allowed) |
|
||||
| `yarn lint:fix` | Run ESLint with auto-fix |
|
||||
| `yarn test` | Run the unit tests (Jest) in watch mode |
|
||||
| `yarn test:ci` | Run the unit tests once, as CI does (silent) |
|
||||
| `yarn clean` | Clean build artifacts |
|
||||
| `yarn agents:generate` | Regenerate `AGENTS.md` from `docs/agents.md/` sources |
|
||||
|
||||
### Development
|
||||
|
||||
- **Start dev server**:
|
||||
```bash
|
||||
RANCHER_ENV=harvester API=https://your-harvester-ip yarn dev
|
||||
```
|
||||
- `API` should point to a running Harvester cluster (e.g., `https://x.x.x.x`).
|
||||
- The dashboard will be available at `https://127.0.0.1:8005`.
|
||||
|
||||
### Building
|
||||
|
||||
- **Build extension package**:
|
||||
```bash
|
||||
yarn build-pkg harvester
|
||||
```
|
||||
- **Serve locally built extension** (for integration testing with a Rancher instance):
|
||||
```bash
|
||||
yarn serve-pkgs
|
||||
```
|
||||
|
||||
### Linting
|
||||
|
||||
- **Check** (must pass with zero warnings):
|
||||
```bash
|
||||
yarn lint
|
||||
```
|
||||
- **Auto-fix**:
|
||||
```bash
|
||||
yarn lint:fix
|
||||
```
|
||||
- ESLint covers `.js`, `.ts`, and `.vue` files.
|
||||
- Always run `yarn lint:fix` before committing.
|
||||
|
||||
### Unit Tests
|
||||
|
||||
- **Run**:
|
||||
```bash
|
||||
yarn test
|
||||
```
|
||||
- `yarn test` starts Jest in watch mode (like in the Rancher dashboard) and only runs the tests related to changed files. It does not exit, so use `yarn test:ci` for a single run of all tests, e.g. in scripts.
|
||||
- CI runs `yarn test:ci` on every pull request.
|
||||
- See the Unit Tests section of the Contributors Guide for how the tests are set up.
|
||||
|
||||
### Commit Conventions
|
||||
|
||||
- Commits are validated by [commitlint](https://commitlint.js.org/) via a Husky `commit-msg` hook.
|
||||
- Follow [Conventional Commits](https://www.conventionalcommits.org/) format (configured in `commitlint.config.js`).
|
||||
|
||||
### Agent Documentation
|
||||
|
||||
- Source files live in `docs/agents.md/` (agents, contributors, personas subdirectories).
|
||||
- After editing any source file, regenerate the root `AGENTS.md`:
|
||||
```bash
|
||||
yarn agents:generate
|
||||
```
|
||||
|
||||
# Contributors Guide
|
||||
|
||||
## Getting Started
|
||||
|
||||
Please see the [Harvester UI Extension README](https://github.com/harvester/harvester-ui-extension).
|
||||
|
||||
To get started, follow the `Development Setup` section.
|
||||
|
||||
## Project Information
|
||||
|
||||
- **Tech Stack:**
|
||||
- `Vue.js`: Framework
|
||||
- `Linting`: ESLint
|
||||
- `CSS`: SCSS should be used
|
||||
- `TypeScript`: Primary language for logic.
|
||||
- **Code Style and Standards:**
|
||||
- `Language`: TypeScript is preferred for new code.
|
||||
- `Vue.js`:
|
||||
- Composition API components are preferred over Options API.
|
||||
- Large pages with lots of code and styles should be avoided by breaking the page up into smaller Vue components.
|
||||
- Order the Single File Component blocks as `<script>`, then `<template>`, then `<style>`.
|
||||
- The `<style>` tag should include `lang="scss" scoped`.
|
||||
- `Linting`: Follow the ESLint configuration in the root.
|
||||
|
||||
- **File Structure:**
|
||||
- `.github/`: CI/CD workflows and Renovate config.
|
||||
- `docs/`: Documentation source for `AGENTS.md` generation.
|
||||
- `scripts/`: Bash scripts for build, CI and doc generation.
|
||||
- `pkg/harvester/`: Main extension source. Files are named after K8s resource types (e.g., `kubevirt.io.virtualmachine`, `harvesterhci.io.volume`).
|
||||
- `index.ts`: Plugin entry point — registers the product and auto-imports models/detail/edit views.
|
||||
- `types.ts`: `HCI` constant mapping 60+ K8s resource types to string identifiers.
|
||||
- `components/`: Reusable Vue components (VNC/serial console, settings panels, upgrade banners, filters).
|
||||
- `config/`: Constants — settings keys, table column definitions, feature flags, type mappings, doc links.
|
||||
- `detail/`: Read-only detail views per resource type. Complex resources use subdirectories with tabs.
|
||||
- `dialog/`: Modal dialogs for operations (VM clone/migrate/restart, backup/restore, device passthrough, etc.).
|
||||
- `edit/`: Create/edit forms. Complex resources (e.g., VM) split into subcomponents (CpuMemory, Network, Volume, CloudConfig, etc.).
|
||||
- `formatters/`: Table cell formatters — state badges, usage bars, resource references.
|
||||
- `l10n/`: Localization (`en-us.yaml`).
|
||||
- `list/`: List (table) views per resource type, mirroring `detail/` and `edit/` naming.
|
||||
- `mixins/`: Shared Vue mixins — VM helpers (`harvester-vm/`) and disk helpers (`harvester-disk.js`).
|
||||
- `models/`: Model classes extending `SteveModel` with computed properties and actions. Base class: `harvester.js`.
|
||||
- `pages/`: Route-level pages — dashboard, support, console, members, brand, alertmanager.
|
||||
- `promptRemove/`: Custom delete-confirmation dialogs (VM, backup).
|
||||
- `routing/`: Vue Router config — all product routes (CRUD, console, support, upgrade, etc.).
|
||||
- `store/`: Vuex modules — `harvester-common.js` for shared state; `harvester-store/` for VM/resource creation actions with Steve integration.
|
||||
- `styles/`: Global SCSS files.
|
||||
- `utils/`: Helpers — VM volume templates, CPU/memory calc, cron parsing, regex validators, feature flags.
|
||||
- `validators/`: Form validation functions per resource type, pushing i18n error messages.
|
||||
|
||||
|
||||
|
||||
## Harvester UI Extension Development Guide
|
||||
|
||||
### Backward Compatibility
|
||||
|
||||
The Harvester UI Extension supports earlier cluster versions (e.g., UI Ext v1.8.0 works with clusters v1.7.0 and v1.6.0). It uses Feature Flags defined in `pkg/harvester/config/` to ensure the UI matches the cluster's specific version.
|
||||
|
||||
### Implementation Steps for New Features
|
||||
|
||||
To add a feature in a new release, follow these steps:
|
||||
|
||||
1. **Register**: Add a unique `[Feature Name]` to the corresponding release array in the configuration.
|
||||
2. **Check**: Use the following getter to verify if the feature is enabled for the current version:
|
||||
|
||||
```js
|
||||
computed: {
|
||||
newFeatureEnabled() {
|
||||
return this.$store.getters['harvester-common/getFeatureEnabled']('[Feature Name]');
|
||||
},
|
||||
},
|
||||
```
|
||||
|
||||
3. **Render**: Use the result of the check to conditionally render the UI components.
|
||||
|
||||
|
||||
## E2E Tests (Cypress)
|
||||
|
||||
See https://github.com/harvester/harvester-ui-tests
|
||||
|
||||
## Unit Tests (Jest)
|
||||
|
||||
Unit and component tests run with [Jest](https://jestjs.io/). The setup follows the Rancher dashboard and the Rancher extension template ([rancher/ui-plugin-examples](https://github.com/rancher/ui-plugin-examples)), so both stay aligned.
|
||||
|
||||
- Run the tests in watch mode with `yarn test`, all tests once with `yarn test:ci`, a single file with `yarn test <path>`. CI runs `yarn test:ci` on every pull request.
|
||||
- Test files live next to the code in `__tests__` folders and are named `<name>.test.js` or `<name>.test.ts`.
|
||||
- Configuration:
|
||||
- `jest.config.js`: environment, module aliases (`@shell`, `@components`, `@pkg`) and transforms.
|
||||
- `jest.setup.js`: global mocks (`t`, `$store`, common directives) and browser APIs that jsdom does not provide.
|
||||
- `vue3JestRegisterTs.js`: makes TypeScript available to the Vue compiler, otherwise `.vue` files with typed props fail to compile.
|
||||
- Components are tested with the Vue Test Utils 2 API: use `props` and `global.mocks`, not the Vue 2 options `propsData` and `mocks`.
|
||||
- Models and utils can be tested without mounting anything, see `pkg/harvester/models/__tests__` for examples.
|
||||
|
||||
## Node Dependencies
|
||||
|
||||
Dependencies are managed via `package.json` and `yarn`
|
||||
|
||||
- To install dependencies use `yarn install`. This will fail if dependencies and versions listed in `package.json` are out of step with the `yarn.lock` file
|
||||
- To add a dependency use `yarn run add:no-lock ...` instead of `yarn add`
|
||||
- To upgrade a dependency use `yarn run upgrade:no-lock ...` instead of `yarn upgrade`
|
||||
|
||||
|
||||
Renovate automatically updates dependencies and opens upgrade PRs after 10:00 AM on Sundays (`Asia/Taipei`).
|
||||
For the Renovate config, see `.github/renovate.json`.
|
||||
|
||||
|
||||
## Milestone guidance
|
||||
|
||||
- All issues must first be resolved in the `main` branch
|
||||
- If backports are needed they can be made via the backport bot
|
||||
- pull requests
|
||||
- comment `@Mergifyio backport <target branch>` e.g. `@Mergifyio backport release-harvester-v1.8`
|
||||
- All backported pull requests must link to a backported issue
|
||||
|
||||
|
||||
## Creating a branch
|
||||
|
||||
### To resolve an issue
|
||||
- Checkout the branch matching the milestone of the issue `git checkout ${targetMilestoneBranch}`. Replace `${targetMilestoneBranch}` with the target milestone of the issue. For example
|
||||
- `main` for the latest unreleased minor version
|
||||
- `release-harvester-v.X` for release minor versions
|
||||
- `release-harvester-v1.6`
|
||||
- `release-harvester-v1.7`
|
||||
- `release-harvester-v1.8`
|
||||
- Ensure you have the latest of that branch `git pull --rebase`
|
||||
- Checkout the branch to commit the changes to `git checkout issue-${issueNumber}`. Replace `${issueNumber}` with the issue number.
|
||||
|
||||
## Creating a commit
|
||||
|
||||
- This project uses commit-lint with [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) to ensure consistent and meaningful commit messages.
|
||||
|
||||
### Commit Message Format
|
||||
All commit messages must follow the conventional commit format:
|
||||
```
|
||||
<type>: <description>
|
||||
|
||||
[optional body]
|
||||
|
||||
[optional footer(s)]
|
||||
```
|
||||
|
||||
### Supported Types
|
||||
- feat: New features
|
||||
- fix: Bug fixes
|
||||
- docs: Documentation changes
|
||||
- style: Code style changes (formatting, missing semicolons, etc.)
|
||||
- refactor: Code refactoring
|
||||
- perf: Performance improvements
|
||||
- test: Adding or updating tests
|
||||
- build: Build system or external dependencies
|
||||
- ci: CI/CD changes
|
||||
- chore: Other changes that don't modify src or test files
|
||||
- revert: Reverts a previous commit
|
||||
- wip: Work in progress
|
||||
- deps: Dependency updates
|
||||
- security: Security fixes
|
||||
|
||||
## Creating a Pull Request
|
||||
|
||||
- Pull requests must come from forks
|
||||
- Description should always have commit supported type prefix. E.g `fix: XXX`, `feat: OOO`
|
||||
- A Pull Request will only be merged once
|
||||
- ALL CI gates have passed
|
||||
- At least one harvester/harvester-ui-extension code owners reviews and approves the PR
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
@a110605
|
||||
@houhoucoop
|
||||
@@ -1,189 +1,63 @@
|
||||
# harvester-ui-extension
|
||||
|
||||
The Harvester UI Extension is a Rancher extension that provides the user interface for [Harvester](https://harvesterhci.io) within the [Rancher Dashboard](https://github.com/rancher/dashboard).
|
||||
|
||||
> **Note:**
|
||||
> This extension is available starting from **Rancher 2.10.0**. Ensure your Rancher version is **2.10.0 or later** to access Harvester integration.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Installation](#installation)
|
||||
- [Development Setup](#development-setup)
|
||||
- [Commit Message Guidelines](#commit-message-guidelines)
|
||||
- [Branch Structure](#branch-structure)
|
||||
- [Testing Guidelines](#testing-guidelines)
|
||||
- [Release](#release)
|
||||
- [Contributing](#contributing)
|
||||
- [License](#license)
|
||||
|
||||
Rancher Extension used in [rancher/dashboard](https://github.com/rancher/dashboard) for [Harvester](https://harvesterhci.io) Dashboard UI.
|
||||
|
||||
`
|
||||
From Rancher 2.10.0, Harvester integration is provided by this new Harvester UI Extension.
|
||||
`
|
||||
|
||||
## Installation
|
||||
|
||||
For Harvester UI extension installation instructions, please refer to the page **Rancher Integration** -> **Harvester UI Extension** in [official Harvester documentation](https://docs.harvesterhci.io).
|
||||
To install the Harvester UI Extension in Rancher 2.10.0 and newer, please refer to [installation](https://docs.harvesterhci.io/v1.5/rancher/harvester-ui-extension#installation-on-rancher-210) on harvester doc.
|
||||
|
||||
## Running for Development
|
||||
|
||||
## Development Setup
|
||||
This is what you probably want to get started.
|
||||
|
||||
### Prerequisite
|
||||
|
||||
Nodejs version >= 20
|
||||
|
||||
Ensure **Node.js v24 or later** is installed for development and debugging.
|
||||
|
||||
### Standalone Mode
|
||||
|
||||
Run the extension standalone with hot reload at `https://localhost:8005`.
|
||||
For development, serve with hot reload at https://localhost:8005
|
||||
|
||||
```bash
|
||||
# Install dependencies
|
||||
yarn install
|
||||
|
||||
# Start the development server
|
||||
# Use RANCHER_ENV to specify the endpoint for your Harvester API
|
||||
RANCHER_ENV=harvester API=https://your-harvester-ip yarn dev
|
||||
|
||||
# Example with specific server version
|
||||
RANCHER_ENV=harvester VUE_APP_SERVER_VERSION=v1.5.0 API=https://192.168.1.123 yarn dev
|
||||
```
|
||||
# Use VUE_APP_SERVER_VERSION to specify the Harvester server version
|
||||
# in case your are running a dev build of Harvester
|
||||
RANCHER_ENV=harvester VUE_APP_SERVER_VERSION=your-harvester-server-version API=https://your-harvester-ip yarn dev
|
||||
|
||||
You may also define environment variables in a `.env` file:
|
||||
# or put your env variables into a .env file
|
||||
|
||||
```env
|
||||
RANCHER_ENV=harvester
|
||||
VUE_APP_SERVER_VERSION=v1.5.0
|
||||
API=https://192.168.1.123
|
||||
# Example
|
||||
RANCHER_ENV=harvester VUE_APP_SERVER_VERSION=v1.4.0 API=https://192.168.1.123 yarn dev
|
||||
```
|
||||
|
||||
### Rancher Integration Mode
|
||||
|
||||
To run as a Rancher extension, follow the [Rancher UI Extension Guide](https://extensions.rancher.io/extensions/next/extensions-getting-started#running-the-app).
|
||||
In this mode, you need to have Rancher and run Harvester UI Extension as Rancher extension, see more detail in [Rancher UI extension](https://extensions.rancher.io/extensions/next/extensions-getting-started#running-the-app).
|
||||
|
||||
```bash
|
||||
API=https://your-rancher-ip yarn dev
|
||||
|
||||
# Example
|
||||
API=https://192.168.1.123 yarn dev
|
||||
```
|
||||
|
||||
## Commit Message Guidelines
|
||||
|
||||
This project uses [commit-lint](https://commitlint.js.org/) with [Conventional Commits](https://www.conventionalcommits.org/) to ensure consistent and meaningful commit messages.
|
||||
|
||||
### Commit Message Format
|
||||
|
||||
All commit messages must follow the conventional commit format:
|
||||
|
||||
```
|
||||
<type>[optional scope]: <description>
|
||||
|
||||
[optional body]
|
||||
|
||||
[optional footer(s)]
|
||||
```
|
||||
|
||||
### Supported Types
|
||||
|
||||
- **feat**: New features
|
||||
- **fix**: Bug fixes
|
||||
- **docs**: Documentation changes
|
||||
- **style**: Code style changes (formatting, missing semicolons, etc.)
|
||||
- **refactor**: Code refactoring
|
||||
- **perf**: Performance improvements
|
||||
- **test**: Adding or updating tests
|
||||
- **build**: Build system or external dependencies
|
||||
- **ci**: CI/CD changes
|
||||
- **chore**: Other changes that don't modify src or test files
|
||||
- **revert**: Reverts a previous commit
|
||||
- **wip**: Work in progress
|
||||
- **deps**: Dependency updates
|
||||
- **security**: Security fixes
|
||||
|
||||
### Examples
|
||||
|
||||
```bash
|
||||
# Feature
|
||||
git commit -m "feat: add new virtual machine creation wizard"
|
||||
|
||||
# Bug fix
|
||||
git commit -m "fix: resolve memory leak in VM console"
|
||||
|
||||
# Documentation
|
||||
git commit -m "docs: update installation instructions"
|
||||
|
||||
# Breaking change
|
||||
git commit -m "feat!: change API endpoint structure
|
||||
|
||||
BREAKING CHANGE: The /api/v1/vms endpoint has been replaced with /api/v2/vms"
|
||||
```
|
||||
|
||||
### Git Hooks
|
||||
|
||||
The project uses [Husky](https://typicode.github.io/husky/) to automatically validate commit messages and run linting before commits:
|
||||
|
||||
- **pre-commit**: Runs ESLint to ensure code quality
|
||||
- **commit-msg**: Validates commit message format using commit-lint
|
||||
|
||||
These hooks are automatically installed when you run `yarn install`.
|
||||
|
||||
### Manual Validation
|
||||
|
||||
You can manually validate commit messages:
|
||||
|
||||
```bash
|
||||
# Validate the last commit
|
||||
yarn commitlint
|
||||
|
||||
# Validate a specific commit
|
||||
npx commitlint --from <commit-hash>
|
||||
|
||||
# Validate a range of commits
|
||||
npx commitlint --from <start-hash> --to <end-hash>
|
||||
```
|
||||
|
||||
## Branch Structure
|
||||
|
||||
- **`main`** – Main development branch
|
||||
- **`release-harvester-vX.Y`** – Stable release branches per version series
|
||||
- **`vX.Y-head`** – Testing branches for ongoing changes to extension builds in each release series
|
||||
|
||||
> **Note:**
|
||||
> The `vX.Y-head` branches are auto-generated and kept in sync with release branches. Use these for testing the latest changes in each version series.
|
||||
|
||||
## Testing Guidelines
|
||||
|
||||
### UI Extension Testing
|
||||
|
||||
To validate changes in a release series, switch to the appropriate `vX.Y-head` branch. For main branch testing, use `main-head`.
|
||||
|
||||
- Examples:
|
||||
- Test `1.0.x` series → `v1.0-head`
|
||||
- Test `1.5.x` series → `v1.5-head`
|
||||
|
||||
**Steps:**
|
||||
1. Navigate to **Rancher UI** → **Local** → **App** → **Repositories**
|
||||
2. Refresh the Harvester repository using the target `vX.Y-head` branch
|
||||
3. Go to the **Extensions** page and install the desired version
|
||||
|
||||
### Standalone Mode Testing
|
||||
|
||||
To test the standalone UI, configure Harvester to load the UI from an external source.
|
||||
|
||||
- Examples of `ui-index`:
|
||||
- Main branch → `https://releases.rancher.com/harvester-ui/dashboard/latest/index.html`
|
||||
- Release series `1.5.x` → `https://releases.rancher.com/harvester-ui/dashboard/release-harvester-v1.5/index.html`
|
||||
|
||||
**Steps:**
|
||||
1. Go to **Harvester UI** → **Advanced** → **Settings** → **UI**
|
||||
2. Set **ui-source** to `External`
|
||||
3. Set **ui-index** to the desired URL
|
||||
|
||||
|
||||
## Release
|
||||
|
||||
The Harvester UI Extension follows the [Harvester](https://github.com/harvester/harvester) release cycle. After RC1 is cut for a new Harvester version, we usually create and work from the corresponding release branch (for example, `release-harvester-v1.8`). The remaining RC builds and the final official release are published from that branch.
|
||||
|
||||
After Harvester releases a new version, update the Harvester entry in rancher/ui-plugin-charts [manifest.json](https://github.com/rancher/ui-plugin-charts/blob/aafd215debbc6cb3100e7ba4b0a542c932397acd/manifest.json#L133-L151). This ensures air-gapped users can pull the new Harvester UI Extension image.
|
||||
|
||||
## Contributing
|
||||
|
||||
If you want to contribute, start by reading this document, then visit our [Getting Started guide](https://extensions.rancher.io/extensions/next/extensions-getting-started) to learn how to develop and submit changes.
|
||||
For developers, after reading through the introduction on this page, head over to our [Getting Started](https://extensions.rancher.io/extensions/next/extensions-getting-started) guide to learn more.
|
||||
|
||||
## License
|
||||
|
||||
Copyright (c) 2014-2026 [SUSE, LLC.](https://www.suse.com/)
|
||||
License
|
||||
=======
|
||||
Copyright (c) 2014-2025 [SUSE, LLC.](https://www.suse.com/)
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
module.exports = {
|
||||
extends: ['@commitlint/config-conventional'],
|
||||
rules: {
|
||||
// Enforce conventional commit format
|
||||
'type-enum': [
|
||||
2,
|
||||
'always',
|
||||
[
|
||||
'feat', // New features
|
||||
'fix', // Bug fixes
|
||||
'docs', // Documentation changes
|
||||
'style', // Code style changes (formatting, missing semicolons, etc.)
|
||||
'refactor', // Code refactoring
|
||||
'perf', // Performance improvements
|
||||
'test', // Adding or updating tests
|
||||
'build', // Build system or external dependencies
|
||||
'ci', // CI/CD changes
|
||||
'chore', // Other changes that don't modify src or test files
|
||||
'revert', // Reverts a previous commit
|
||||
'wip', // Work in progress
|
||||
'deps', // Dependency updates
|
||||
'security', // Security fixes
|
||||
]
|
||||
],
|
||||
// Allows the scope to be empty. [0] means the rule is disabled.
|
||||
'scope-empty': [0, 'always'],
|
||||
// Allows any string for the scope.
|
||||
'scope-case': [2, 'always', 'kebab-case'],
|
||||
'type-case': [2, 'always', 'lower-case'],
|
||||
'type-empty': [2, 'never'],
|
||||
'subject-case': [0, 'never'],
|
||||
'subject-empty': [2, 'never'],
|
||||
'subject-full-stop': [2, 'never', '.'],
|
||||
'subject-max-length': [0, 'never'],
|
||||
'header-max-length': [0, 'always', 100],
|
||||
'body-leading-blank': [2, 'always'],
|
||||
'body-max-line-length': [0, 'always', 100],
|
||||
'footer-leading-blank': [2, 'always'],
|
||||
'footer-max-line-length': [0, 'always', 100],
|
||||
},
|
||||
// Ignore merge commits and revert commits
|
||||
ignores: [
|
||||
(commit) => commit.includes('Merge'),
|
||||
(commit) => commit.includes('Revert'),
|
||||
(commit) => commit.includes('merge'),
|
||||
(commit) => commit.includes('revert'),
|
||||
],
|
||||
};
|
||||
@@ -1,63 +0,0 @@
|
||||
# Agents.md
|
||||
|
||||
This folder contains files used to construct a single root `AGENTS.md`
|
||||
|
||||
We do this because
|
||||
- The single commonality between almost all AI tools is that they look for a root `AGENTS.md`
|
||||
- Having the information in a single place for all AI tools is better than duplicating and maintaining the information in multiple files for each AI tool
|
||||
|
||||
## Process
|
||||
1. Add files to or update files in `./docs/agents.md/agents`, `./docs/agents.md/personas`, `./docs/agents.md/contributors`.
|
||||
2. Each file must
|
||||
- Start markdown headers at the `##` level
|
||||
- End in a new line
|
||||
- Order contents in AGENTS.md by giving an optional number prefix
|
||||
3. Run `yarn agents:generate`.
|
||||
- Take the contents of `./docs/agents.md/template_agents.md`
|
||||
- Insert the contents of the agents, personas and contributors files
|
||||
- Output to `./AGENTS.md`
|
||||
4. Commit all changes, including root `./AGENTS.md` and any files that link to it
|
||||
|
||||
## Guidance
|
||||
|
||||
### Examples
|
||||
|
||||
When referencing code or configuration it's good to include an example
|
||||
|
||||
## Future Tasks
|
||||
- Add real world examples when referencing code
|
||||
- Create a GH workflow to monitor `agents.md` folder files in a PR, if changed run generate script and add new AGENTS.md to PR
|
||||
- Discuss
|
||||
- Three multi AI tool related questions
|
||||
- Questions
|
||||
- how AI specific patterns, like co-pilot instructions, can be expressed in a way to be adopted by or reduce duplication with the root agents.md
|
||||
- how AI tool specific metadata code can be included
|
||||
- multiple agents vs personas approach works
|
||||
- Proposal
|
||||
- Generic information applicable to all AI tools is added to the root `agents.md`
|
||||
- Agent, instruction or other AI specific files or patterns can be used in files specific to that AI tool. They must not contain duplicate information to the root `agents.md`
|
||||
- The root `agents.md` continues to be AI tool agnostic
|
||||
- How can folder specific agents be used
|
||||
- Proposal
|
||||
- `agents.md` are added to folders as long as most LLMs can make use of them and they do not duplicate information in the root `agents.md`
|
||||
|
||||
## Test Prompts
|
||||
|
||||
To validate LLMs are picking up information consider running the following prompts.
|
||||
|
||||
### Information
|
||||
|
||||
Can they provide correct information?
|
||||
|
||||
- `what's this project about?`
|
||||
- `can you tell me the process for fixing a github issue in this repo?`
|
||||
- `what makes a good software developer?`
|
||||
- `what should never be done in this project?`
|
||||
- `what are the folders in this project for?`
|
||||
- `what are the env vars i could use when running e2e tests?`
|
||||
|
||||
### Actions
|
||||
|
||||
Can they use the information in their actions?
|
||||
|
||||
Pending
|
||||
@@ -1,21 +0,0 @@
|
||||
## Boundaries
|
||||
|
||||
- ✅ **Always:**
|
||||
- Write to `.github`, `docs/`, `pkg/harvester`, `scripts/`.
|
||||
- Make commits in a new branch (for a PR).
|
||||
- Run `yarn lint:fix` before commits.
|
||||
- Use conventional commit format:
|
||||
```
|
||||
<type>: <description>
|
||||
```
|
||||
- Follow existing naming conventions (PascalCase for components, camelCase for functions).
|
||||
- After changing a Vue, JS, or TS file, make sure it's automatically formatted with ESLint.
|
||||
- After updating files in `docs/agents.md/`, run `yarn agents:generate` to update root `AGENTS.md`.
|
||||
- ⚠️ **Ask first:**
|
||||
- Adding dependencies
|
||||
- Upgrading dependencies
|
||||
- 🚫 **Never:**
|
||||
- Commit or log secrets, `.env`, `kubeconfig` or any API keys.
|
||||
- Edit `node_modules/`.
|
||||
- Commit directly to `main` (use PRs).
|
||||
- Skip git hooks with `--no-verify` flag.
|
||||
@@ -1,77 +0,0 @@
|
||||
## Tools
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- **Node.js**: `>= 24.0.0` (see `.nvmrc` for the pinned version: `24`)
|
||||
- **Package manager**: `yarn` (v1 classic)
|
||||
|
||||
### Common Commands
|
||||
|
||||
| Command | Description |
|
||||
|---------|-------------|
|
||||
| `yarn install --frozen-lockfile` | Install dependencies (CI-safe, no lockfile changes) |
|
||||
| `RANCHER_ENV=harvester API=https://<harvester-ip> yarn dev` | Start development server at `https://127.0.0.1:8005` |
|
||||
| `yarn build-pkg harvester` | Build the Harvester extension package |
|
||||
| `yarn serve-pkgs` | Serve the locally built extension for testing |
|
||||
| `yarn lint` | Run ESLint (zero warnings allowed) |
|
||||
| `yarn lint:fix` | Run ESLint with auto-fix |
|
||||
| `yarn test` | Run the unit tests (Jest) in watch mode |
|
||||
| `yarn test:ci` | Run the unit tests once, as CI does (silent) |
|
||||
| `yarn clean` | Clean build artifacts |
|
||||
| `yarn agents:generate` | Regenerate `AGENTS.md` from `docs/agents.md/` sources |
|
||||
|
||||
### Development
|
||||
|
||||
- **Start dev server**:
|
||||
```bash
|
||||
RANCHER_ENV=harvester API=https://your-harvester-ip yarn dev
|
||||
```
|
||||
- `API` should point to a running Harvester cluster (e.g., `https://x.x.x.x`).
|
||||
- The dashboard will be available at `https://127.0.0.1:8005`.
|
||||
|
||||
### Building
|
||||
|
||||
- **Build extension package**:
|
||||
```bash
|
||||
yarn build-pkg harvester
|
||||
```
|
||||
- **Serve locally built extension** (for integration testing with a Rancher instance):
|
||||
```bash
|
||||
yarn serve-pkgs
|
||||
```
|
||||
|
||||
### Linting
|
||||
|
||||
- **Check** (must pass with zero warnings):
|
||||
```bash
|
||||
yarn lint
|
||||
```
|
||||
- **Auto-fix**:
|
||||
```bash
|
||||
yarn lint:fix
|
||||
```
|
||||
- ESLint covers `.js`, `.ts`, and `.vue` files.
|
||||
- Always run `yarn lint:fix` before committing.
|
||||
|
||||
### Unit Tests
|
||||
|
||||
- **Run**:
|
||||
```bash
|
||||
yarn test
|
||||
```
|
||||
- `yarn test` starts Jest in watch mode (like in the Rancher dashboard) and only runs the tests related to changed files. It does not exit, so use `yarn test:ci` for a single run of all tests, e.g. in scripts.
|
||||
- CI runs `yarn test:ci` on every pull request.
|
||||
- See the Unit Tests section of the Contributors Guide for how the tests are set up.
|
||||
|
||||
### Commit Conventions
|
||||
|
||||
- Commits are validated by [commitlint](https://commitlint.js.org/) via a Husky `commit-msg` hook.
|
||||
- Follow [Conventional Commits](https://www.conventionalcommits.org/) format (configured in `commitlint.config.js`).
|
||||
|
||||
### Agent Documentation
|
||||
|
||||
- Source files live in `docs/agents.md/` (agents, contributors, personas subdirectories).
|
||||
- After editing any source file, regenerate the root `AGENTS.md`:
|
||||
```bash
|
||||
yarn agents:generate
|
||||
```
|
||||
@@ -1,72 +0,0 @@
|
||||
## Getting Started
|
||||
|
||||
Please see the [Harvester UI Extension README](https://github.com/harvester/harvester-ui-extension).
|
||||
|
||||
To get started, follow the `Development Setup` section.
|
||||
|
||||
## Project Information
|
||||
|
||||
- **Tech Stack:**
|
||||
- `Vue.js`: Framework
|
||||
- `Linting`: ESLint
|
||||
- `CSS`: SCSS should be used
|
||||
- `TypeScript`: Primary language for logic.
|
||||
- **Code Style and Standards:**
|
||||
- `Language`: TypeScript is preferred for new code.
|
||||
- `Vue.js`:
|
||||
- Composition API components are preferred over Options API.
|
||||
- Large pages with lots of code and styles should be avoided by breaking the page up into smaller Vue components.
|
||||
- Order the Single File Component blocks as `<script>`, then `<template>`, then `<style>`.
|
||||
- The `<style>` tag should include `lang="scss" scoped`.
|
||||
- `Linting`: Follow the ESLint configuration in the root.
|
||||
|
||||
- **File Structure:**
|
||||
- `.github/`: CI/CD workflows and Renovate config.
|
||||
- `docs/`: Documentation source for `AGENTS.md` generation.
|
||||
- `scripts/`: Bash scripts for build, CI and doc generation.
|
||||
- `pkg/harvester/`: Main extension source. Files are named after K8s resource types (e.g., `kubevirt.io.virtualmachine`, `harvesterhci.io.volume`).
|
||||
- `index.ts`: Plugin entry point — registers the product and auto-imports models/detail/edit views.
|
||||
- `types.ts`: `HCI` constant mapping 60+ K8s resource types to string identifiers.
|
||||
- `components/`: Reusable Vue components (VNC/serial console, settings panels, upgrade banners, filters).
|
||||
- `config/`: Constants — settings keys, table column definitions, feature flags, type mappings, doc links.
|
||||
- `detail/`: Read-only detail views per resource type. Complex resources use subdirectories with tabs.
|
||||
- `dialog/`: Modal dialogs for operations (VM clone/migrate/restart, backup/restore, device passthrough, etc.).
|
||||
- `edit/`: Create/edit forms. Complex resources (e.g., VM) split into subcomponents (CpuMemory, Network, Volume, CloudConfig, etc.).
|
||||
- `formatters/`: Table cell formatters — state badges, usage bars, resource references.
|
||||
- `l10n/`: Localization (`en-us.yaml`).
|
||||
- `list/`: List (table) views per resource type, mirroring `detail/` and `edit/` naming.
|
||||
- `mixins/`: Shared Vue mixins — VM helpers (`harvester-vm/`) and disk helpers (`harvester-disk.js`).
|
||||
- `models/`: Model classes extending `SteveModel` with computed properties and actions. Base class: `harvester.js`.
|
||||
- `pages/`: Route-level pages — dashboard, support, console, members, brand, alertmanager.
|
||||
- `promptRemove/`: Custom delete-confirmation dialogs (VM, backup).
|
||||
- `routing/`: Vue Router config — all product routes (CRUD, console, support, upgrade, etc.).
|
||||
- `store/`: Vuex modules — `harvester-common.js` for shared state; `harvester-store/` for VM/resource creation actions with Steve integration.
|
||||
- `styles/`: Global SCSS files.
|
||||
- `utils/`: Helpers — VM volume templates, CPU/memory calc, cron parsing, regex validators, feature flags.
|
||||
- `validators/`: Form validation functions per resource type, pushing i18n error messages.
|
||||
|
||||
|
||||
|
||||
## Harvester UI Extension Development Guide
|
||||
|
||||
### Backward Compatibility
|
||||
|
||||
The Harvester UI Extension supports earlier cluster versions (e.g., UI Ext v1.8.0 works with clusters v1.7.0 and v1.6.0). It uses Feature Flags defined in `pkg/harvester/config/` to ensure the UI matches the cluster's specific version.
|
||||
|
||||
### Implementation Steps for New Features
|
||||
|
||||
To add a feature in a new release, follow these steps:
|
||||
|
||||
1. **Register**: Add a unique `[Feature Name]` to the corresponding release array in the configuration.
|
||||
2. **Check**: Use the following getter to verify if the feature is enabled for the current version:
|
||||
|
||||
```js
|
||||
computed: {
|
||||
newFeatureEnabled() {
|
||||
return this.$store.getters['harvester-common/getFeatureEnabled']('[Feature Name]');
|
||||
},
|
||||
},
|
||||
```
|
||||
|
||||
3. **Render**: Use the result of the check to conditionally render the UI components.
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
## E2E Tests (Cypress)
|
||||
|
||||
See https://github.com/harvester/harvester-ui-tests
|
||||
@@ -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,12 +0,0 @@
|
||||
## Node Dependencies
|
||||
|
||||
Dependencies are managed via `package.json` and `yarn`
|
||||
|
||||
- To install dependencies use `yarn install`. This will fail if dependencies and versions listed in `package.json` are out of step with the `yarn.lock` file
|
||||
- To add a dependency use `yarn run add:no-lock ...` instead of `yarn add`
|
||||
- To upgrade a dependency use `yarn run upgrade:no-lock ...` instead of `yarn upgrade`
|
||||
|
||||
|
||||
Renovate automatically updates dependencies and opens upgrade PRs after 10:00 AM on Sundays (`Asia/Taipei`).
|
||||
For the Renovate config, see `.github/renovate.json`.
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
## Milestone guidance
|
||||
|
||||
- All issues must first be resolved in the `main` branch
|
||||
- If backports are needed they can be made via the backport bot
|
||||
- pull requests
|
||||
- comment `@Mergifyio backport <target branch>` e.g. `@Mergifyio backport release-harvester-v1.8`
|
||||
- All backported pull requests must link to a backported issue
|
||||
|
||||
|
||||
## Creating a branch
|
||||
|
||||
### To resolve an issue
|
||||
- Checkout the branch matching the milestone of the issue `git checkout ${targetMilestoneBranch}`. Replace `${targetMilestoneBranch}` with the target milestone of the issue. For example
|
||||
- `main` for the latest unreleased minor version
|
||||
- `release-harvester-v.X` for release minor versions
|
||||
- `release-harvester-v1.6`
|
||||
- `release-harvester-v1.7`
|
||||
- `release-harvester-v1.8`
|
||||
- Ensure you have the latest of that branch `git pull --rebase`
|
||||
- Checkout the branch to commit the changes to `git checkout issue-${issueNumber}`. Replace `${issueNumber}` with the issue number.
|
||||
|
||||
## Creating a commit
|
||||
|
||||
- This project uses commit-lint with [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) to ensure consistent and meaningful commit messages.
|
||||
|
||||
### Commit Message Format
|
||||
All commit messages must follow the conventional commit format:
|
||||
```
|
||||
<type>: <description>
|
||||
|
||||
[optional body]
|
||||
|
||||
[optional footer(s)]
|
||||
```
|
||||
|
||||
### Supported Types
|
||||
- feat: New features
|
||||
- fix: Bug fixes
|
||||
- docs: Documentation changes
|
||||
- style: Code style changes (formatting, missing semicolons, etc.)
|
||||
- refactor: Code refactoring
|
||||
- perf: Performance improvements
|
||||
- test: Adding or updating tests
|
||||
- build: Build system or external dependencies
|
||||
- ci: CI/CD changes
|
||||
- chore: Other changes that don't modify src or test files
|
||||
- revert: Reverts a previous commit
|
||||
- wip: Work in progress
|
||||
- deps: Dependency updates
|
||||
- security: Security fixes
|
||||
|
||||
## Creating a Pull Request
|
||||
|
||||
- Pull requests must come from forks
|
||||
- Description should always have commit supported type prefix. E.g `fix: XXX`, `feat: OOO`
|
||||
- A Pull Request will only be merged once
|
||||
- ALL CI gates have passed
|
||||
- At least one harvester/harvester-ui-extension code owners reviews and approves the PR
|
||||
@@ -1,5 +0,0 @@
|
||||
## Software Developer
|
||||
|
||||
You are an expert Senior Software Engineer specializing in Vue.js and TypeScript. You have deep knowledge of Kubernetes and the Rancher ecosystem.
|
||||
- **Focus**: Writing clean, maintainable, and performant code.
|
||||
- **Priorities**: Adhering to the project's code style, ensuring type safety, and following best practices for component design.
|
||||
@@ -1,22 +0,0 @@
|
||||
> This `./AGENTS.md` file is generated by running `yarn agents:generate`. `CLAUDE.md` and `GEMINI.md` are symlinks to this file so Claude Code, GitHub Copilot and Gemini all read the same content.
|
||||
|
||||
|
||||
# Project Overview
|
||||
|
||||
The Harvester UI Extension is a Rancher extension that provides the user interface for Harvester within the Rancher Dashboard.
|
||||
|
||||
```
|
||||
Note: This extension is available starting from Rancher 2.10.0. Ensure your Rancher version is 2.10.0 or later to access Harvester integration.
|
||||
```
|
||||
|
||||
# Personas
|
||||
|
||||
`<personas>`
|
||||
|
||||
# Agents
|
||||
|
||||
`<agents>`
|
||||
|
||||
# Contributors Guide
|
||||
|
||||
`<contributors>`
|
||||
@@ -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> "};
|
||||
});
|
||||
+16
-59
@@ -1,93 +1,50 @@
|
||||
{
|
||||
"name": "harvester-ui-extension",
|
||||
"version": "1.10.0-dev",
|
||||
"version": "1.5.2",
|
||||
"private": false,
|
||||
"engines": {
|
||||
"node": ">=24.0.0"
|
||||
"node": ">=20.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@babel/plugin-transform-class-static-block": "7.29.7",
|
||||
"@novnc/novnc": "1.7.0",
|
||||
"@rancher/shell": "3.0.14",
|
||||
"@vue-flow/background": "^1.3.0",
|
||||
"@vue-flow/controls": "^1.1.1",
|
||||
"@vue-flow/core": "^1.33.5",
|
||||
"@vue-flow/minimap": "^1.4.0",
|
||||
"@rancher/shell": "3.0.2-rc.6",
|
||||
"cache-loader": "^4.1.0",
|
||||
"color": "4.2.3",
|
||||
"ip": "2.0.1",
|
||||
"@xterm/xterm": "6.0.0",
|
||||
"@xterm/addon-fit": "0.11.0",
|
||||
"@xterm/addon-search": "0.16.0",
|
||||
"@xterm/addon-web-links": "0.12.0",
|
||||
"@xterm/addon-webgl": "0.19.0",
|
||||
"@xterm/addon-canvas": "0.7.0",
|
||||
"node-polyfill-webpack-plugin": "^3.0.0",
|
||||
"elkjs": "^0.11.0",
|
||||
"vue-draggable-next": "^2.2.1",
|
||||
"yaml": "^2.5.1"
|
||||
"yaml": "^2.5.1",
|
||||
"@babel/plugin-transform-class-static-block": "7.28.3"
|
||||
},
|
||||
"resolutions": {
|
||||
"@novnc/novnc": "1.7.0",
|
||||
"@tootallnate/once": "^2.0.1",
|
||||
"@types/lodash": "4.17.25",
|
||||
"@types/node": "25.3.3",
|
||||
"cookie": "0.7.2",
|
||||
"@types/node": "~20.19.0",
|
||||
"cronstrue": "2.59.0",
|
||||
"d3-color": "3.1.0",
|
||||
"**/diff2html/diff": "5.2.2",
|
||||
"ejs": "3.1.10",
|
||||
"follow-redirects": "1.16.0",
|
||||
"follow-redirects": "1.15.11",
|
||||
"glob": "7.2.3",
|
||||
"glob-parent": "6.0.2",
|
||||
"json5": "2.2.3",
|
||||
"markdown-it": "14.3.1",
|
||||
"@types/lodash": "4.17.20",
|
||||
"merge": "2.1.1",
|
||||
"node-forge": "1.4.3",
|
||||
"node-forge": "1.3.1",
|
||||
"nth-check": "2.1.1",
|
||||
"postcss": "8.5.26",
|
||||
"postcss-selector-parser": "7.1.6",
|
||||
"qs": "6.16.0",
|
||||
"roarr": "7.21.7",
|
||||
"semver": "7.5.4",
|
||||
"serialize-javascript": "7.0.5",
|
||||
"uuid": "11.1.1",
|
||||
"webpack-dev-server": "5.2.6",
|
||||
"ws": "8.21.0",
|
||||
"qs": "6.14.0",
|
||||
"roarr": "7.21.1",
|
||||
"semver": "7.7.2",
|
||||
"@vue/cli-service/html-webpack-plugin": "^5.0.0"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "NODE_ENV=dev ./node_modules/.bin/vue-cli-service serve",
|
||||
"build": "./node_modules/.bin/vue-cli-service build",
|
||||
"clean": "./node_modules/@rancher/shell/scripts/clean",
|
||||
"lint": "./node_modules/@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",
|
||||
"lint": "./node_modules/.bin/eslint --max-warnings 0 --ext .js,.ts,.vue .",
|
||||
"build-pkg": "./node_modules/@rancher/shell/scripts/build-pkg.sh",
|
||||
"serve-pkgs": "./node_modules/@rancher/shell/scripts/serve-pkgs",
|
||||
"publish-pkgs": "./node_modules/@rancher/shell/scripts/extension/publish",
|
||||
"parse-tag-name": "./node_modules/@rancher/shell/scripts/extension/parse-tag-name",
|
||||
"commitlint": "commitlint --edit",
|
||||
"prepare": "husky",
|
||||
"agents:generate": "./scripts/generate-agent-and-persona-mds.sh",
|
||||
"prelint": "npm --prefix node_modules/@rancher/shell/eslint-legacy install eslint-plugin-jest@^24 --no-save --no-audit --no-fund --legacy-peer-deps --loglevel=error",
|
||||
"prelint:fix": "npm --prefix node_modules/@rancher/shell/eslint-legacy install eslint-plugin-jest@^24 --no-save --no-audit --no-fund --legacy-peer-deps --loglevel=error"
|
||||
"parse-tag-name": "./node_modules/@rancher/shell/scripts/extension/parse-tag-name"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@commitlint/load": "^19.8.1",
|
||||
"@commitlint/cli": "^19.8.1",
|
||||
"@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.12",
|
||||
"@vue/test-utils": "2.4.6",
|
||||
"@vue/vue3-jest": "29.2.6",
|
||||
"babel-jest": "29.7.0",
|
||||
"babel-plugin-transform-require-context": "0.1.1",
|
||||
"jest": "29.7.0",
|
||||
"jest-environment-jsdom": "29.7.0",
|
||||
"ts-jest": "29.4.12"
|
||||
"eslint-plugin-promise": "^7.1.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,177 +0,0 @@
|
||||
# harvester-ui-extension
|
||||
|
||||
The Harvester UI Extension is a Rancher extension that provides the user interface for [Harvester](https://harvesterhci.io) within the [Rancher Dashboard](https://github.com/rancher/dashboard).
|
||||
|
||||
> **Note:**
|
||||
> This extension is available starting from **Rancher 2.10.0**. Ensure your Rancher version is **2.10.0 or later** to access Harvester integration.
|
||||
|
||||
## Installation
|
||||
|
||||
For Harvester UI extension installation instructions, please refer to the page **Rancher Integration** -> **Harvester UI Extension** in [official Harvester documentation](https://docs.harvesterhci.io).
|
||||
|
||||
## Development Setup
|
||||
|
||||
Ensure **Node.js v20 or later** is installed for development and debugging.
|
||||
|
||||
### Standalone Mode
|
||||
|
||||
Run the extension standalone with hot reload at `https://localhost:8005`.
|
||||
|
||||
```bash
|
||||
# Install dependencies
|
||||
yarn install
|
||||
|
||||
# Start the development server
|
||||
RANCHER_ENV=harvester API=https://your-harvester-ip yarn dev
|
||||
|
||||
# Example with specific server version
|
||||
RANCHER_ENV=harvester VUE_APP_SERVER_VERSION=v1.5.0 API=https://192.168.1.123 yarn dev
|
||||
```
|
||||
|
||||
You may also define environment variables in a `.env` file:
|
||||
|
||||
```env
|
||||
RANCHER_ENV=harvester
|
||||
VUE_APP_SERVER_VERSION=v1.5.0
|
||||
API=https://192.168.1.123
|
||||
```
|
||||
|
||||
### Rancher Integration Mode
|
||||
|
||||
To run as a Rancher extension, follow the [Rancher UI Extension Guide](https://extensions.rancher.io/extensions/next/extensions-getting-started#running-the-app).
|
||||
|
||||
```bash
|
||||
API=https://your-rancher-ip yarn dev
|
||||
```
|
||||
|
||||
## Commit Message Guidelines
|
||||
|
||||
This project uses [commit-lint](https://commitlint.js.org/) with [Conventional Commits](https://www.conventionalcommits.org/) to ensure consistent and meaningful commit messages.
|
||||
|
||||
### Commit Message Format
|
||||
|
||||
All commit messages must follow the conventional commit format:
|
||||
|
||||
```
|
||||
<type>[optional scope]: <description>
|
||||
|
||||
[optional body]
|
||||
|
||||
[optional footer(s)]
|
||||
```
|
||||
|
||||
### Supported Types
|
||||
|
||||
- **feat**: New features
|
||||
- **fix**: Bug fixes
|
||||
- **docs**: Documentation changes
|
||||
- **style**: Code style changes (formatting, missing semicolons, etc.)
|
||||
- **refactor**: Code refactoring
|
||||
- **perf**: Performance improvements
|
||||
- **test**: Adding or updating tests
|
||||
- **build**: Build system or external dependencies
|
||||
- **ci**: CI/CD changes
|
||||
- **chore**: Other changes that don't modify src or test files
|
||||
- **revert**: Reverts a previous commit
|
||||
- **wip**: Work in progress
|
||||
- **deps**: Dependency updates
|
||||
- **security**: Security fixes
|
||||
|
||||
### Examples
|
||||
|
||||
```bash
|
||||
# Feature
|
||||
git commit -m "feat: add new virtual machine creation wizard"
|
||||
|
||||
# Bug fix
|
||||
git commit -m "fix: resolve memory leak in VM console"
|
||||
|
||||
# Documentation
|
||||
git commit -m "docs: update installation instructions"
|
||||
|
||||
# Breaking change
|
||||
git commit -m "feat!: change API endpoint structure
|
||||
|
||||
BREAKING CHANGE: The /api/v1/vms endpoint has been replaced with /api/v2/vms"
|
||||
```
|
||||
|
||||
### Git Hooks
|
||||
|
||||
The project uses [Husky](https://typicode.github.io/husky/) to automatically validate commit messages and run linting before commits:
|
||||
|
||||
- **pre-commit**: Runs ESLint to ensure code quality
|
||||
- **commit-msg**: Validates commit message format using commit-lint
|
||||
|
||||
These hooks are automatically installed when you run `yarn install`.
|
||||
|
||||
### Manual Validation
|
||||
|
||||
You can manually validate commit messages:
|
||||
|
||||
```bash
|
||||
# Validate the last commit
|
||||
yarn commitlint
|
||||
|
||||
# Validate a specific commit
|
||||
npx commitlint --from <commit-hash>
|
||||
|
||||
# Validate a range of commits
|
||||
npx commitlint --from <start-hash> --to <end-hash>
|
||||
```
|
||||
|
||||
## Branch Structure
|
||||
|
||||
- **`main`** – Main development branch
|
||||
- **`release-harvester-vX.Y`** – Stable release branches per version series
|
||||
- **`vX.Y-head`** – Testing branches for ongoing changes to extension builds in each release series
|
||||
|
||||
> **Note:**
|
||||
> The `vX.Y-head` branches are auto-generated and kept in sync with release branches. Use these for testing the latest changes in each version series.
|
||||
|
||||
## Testing Guidelines
|
||||
|
||||
### UI Extension Testing
|
||||
|
||||
To validate changes in a release series, switch to the appropriate `vX.Y-head` branch. For main branch testing, use `main-head`.
|
||||
|
||||
- Examples:
|
||||
- Test `1.0.x` series → `v1.0-head`
|
||||
- Test `1.5.x` series → `v1.5-head`
|
||||
|
||||
**Steps:**
|
||||
1. Navigate to **Rancher UI** → **Local** → **App** → **Repositories**
|
||||
2. Refresh the Harvester repository using the target `vX.Y-head` branch
|
||||
3. Go to the **Extensions** page and install the desired version
|
||||
|
||||
### Standalone Mode Testing
|
||||
|
||||
To test the standalone UI, configure Harvester to load the UI from an external source.
|
||||
|
||||
- Examples of `ui-index`:
|
||||
- Main branch → `https://releases.rancher.com/harvester-ui/dashboard/latest/index.html`
|
||||
- Release series `1.5.x` → `https://releases.rancher.com/harvester-ui/dashboard/release-harvester-v1.5/index.html`
|
||||
|
||||
**Steps:**
|
||||
1. Go to **Harvester UI** → **Advanced** → **Settings** → **UI**
|
||||
2. Set **ui-source** to `External`
|
||||
3. Set **ui-index** to the desired URL
|
||||
|
||||
## Contributing
|
||||
|
||||
If you want to contribute, start by reading this document, then visit our [Getting Started guide](https://extensions.rancher.io/extensions/next/extensions-getting-started) to learn how to develop and submit changes.
|
||||
|
||||
## License
|
||||
|
||||
Copyright (c) 2014-2026 [SUSE, LLC.](https://www.suse.com/)
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
File diff suppressed because one or more lines are too long
|
Before Width: | Height: | Size: 5.8 KiB |
File diff suppressed because one or more lines are too long
|
Before Width: | Height: | Size: 5.8 KiB |
@@ -271,9 +271,4 @@ export default {
|
||||
.filter-label .v-popper__arrow-container {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.fixed-header-actions .middle .filter + .btn-group {
|
||||
display: inline-flex;
|
||||
vertical-align: middle;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -116,11 +116,6 @@ export default {
|
||||
.vm-schedule-dropdown .v-popper__arrow-container {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.fixed-header-actions .middle .vm-schedule-filter + .btn-group {
|
||||
display: inline-flex;
|
||||
vertical-align: middle;
|
||||
}
|
||||
</style>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
|
||||
@@ -1,186 +0,0 @@
|
||||
<script>
|
||||
import { Banner } from '@components/Banner';
|
||||
import MatchExpressions from '@shell/components/form/MatchExpressions';
|
||||
import ResourceTable from '@shell/components/ResourceTable';
|
||||
import { _EDIT } from '@shell/config/query-params';
|
||||
import { convert, simplify, matching as selectorMatching } from '@shell/utils/selector';
|
||||
import throttle from 'lodash/throttle';
|
||||
import { NODE } from '@shell/config/types';
|
||||
import { NAME, AGE } from '@shell/config/table-headers';
|
||||
|
||||
export default {
|
||||
name: 'HarvesterNodeSelector',
|
||||
|
||||
components: {
|
||||
Banner,
|
||||
MatchExpressions,
|
||||
ResourceTable,
|
||||
},
|
||||
|
||||
props: {
|
||||
mode: {
|
||||
type: String,
|
||||
default: _EDIT,
|
||||
},
|
||||
value: {
|
||||
type: Object,
|
||||
required: true,
|
||||
},
|
||||
},
|
||||
|
||||
async fetch() {
|
||||
this.updateMatchingResources();
|
||||
},
|
||||
|
||||
data() {
|
||||
const inStore = this.$store.getters['currentProduct'].inStore;
|
||||
|
||||
return {
|
||||
matchingResources: {
|
||||
matched: 0,
|
||||
matches: [],
|
||||
none: true,
|
||||
sample: null,
|
||||
total: 0,
|
||||
},
|
||||
tableHeaders: [
|
||||
NAME,
|
||||
{
|
||||
name: 'host-ip',
|
||||
labelKey: 'tableHeaders.hostIp',
|
||||
search: ['internalIp'],
|
||||
value: 'internalIp',
|
||||
sort: ['internalIp'],
|
||||
align: 'center',
|
||||
},
|
||||
{
|
||||
name: 'cpuManager',
|
||||
labelKey: 'harvester.tableHeaders.cpuManager',
|
||||
value: 'id',
|
||||
formatter: 'HarvesterCPUPinning',
|
||||
width: 150,
|
||||
align: 'center',
|
||||
},
|
||||
{
|
||||
name: 'diskState',
|
||||
labelKey: 'tableHeaders.diskState',
|
||||
value: 'diskState',
|
||||
formatter: 'HarvesterDiskState',
|
||||
width: 130,
|
||||
},
|
||||
AGE,
|
||||
],
|
||||
inStore,
|
||||
};
|
||||
},
|
||||
|
||||
watch: {
|
||||
value: {
|
||||
handler: 'updateMatchingResources',
|
||||
deep: true,
|
||||
},
|
||||
allResourcesInScope() {
|
||||
this.updateMatchingResources();
|
||||
},
|
||||
},
|
||||
|
||||
computed: {
|
||||
schema() {
|
||||
return this.$store.getters[`${ this.inStore }/schemaFor`](NODE);
|
||||
},
|
||||
|
||||
selectorExpressions: {
|
||||
get() {
|
||||
return convert(
|
||||
this.value.matchLabels || {},
|
||||
this.value.matchExpressions || []
|
||||
);
|
||||
},
|
||||
set(selectorExpressions) {
|
||||
const { matchLabels, matchExpressions } = simplify(selectorExpressions);
|
||||
|
||||
this.value['matchLabels'] = matchLabels;
|
||||
this.value['matchExpressions'] = matchExpressions;
|
||||
this.updateMatchingResources();
|
||||
},
|
||||
},
|
||||
|
||||
allNodes() {
|
||||
return this.$store.getters[`${ this.inStore }/all`](NODE) || [];
|
||||
},
|
||||
|
||||
allResourcesInScope() {
|
||||
return this.allNodes.length;
|
||||
},
|
||||
},
|
||||
|
||||
methods: {
|
||||
updateMatchingResources: throttle(function() {
|
||||
const expressions = this.selectorExpressions;
|
||||
const allNodes = this.allNodes;
|
||||
|
||||
// Empty expressions with no key = no match
|
||||
const hasValidExpression = expressions.length > 0 && expressions.every((e) => !!e.key);
|
||||
|
||||
if (!hasValidExpression) {
|
||||
this.matchingResources = {
|
||||
matched: 0,
|
||||
matches: [],
|
||||
none: true,
|
||||
sample: null,
|
||||
total: allNodes.length,
|
||||
};
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const matches = selectorMatching(allNodes, expressions, 'metadata.labels');
|
||||
|
||||
this.matchingResources = {
|
||||
matched: matches.length,
|
||||
matches,
|
||||
none: matches.length === 0,
|
||||
sample: matches[0]?.nameDisplay || null,
|
||||
total: allNodes.length,
|
||||
};
|
||||
}, 100, { trailing: true })
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<div class="row">
|
||||
<div class="col span-12">
|
||||
<MatchExpressions
|
||||
v-model:value="selectorExpressions"
|
||||
:mode="mode"
|
||||
:show-remove="false"
|
||||
:type="'node'"
|
||||
:target-resources="allResourcesInScope"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col span-12">
|
||||
<Banner :color="(matchingResources.none ? 'warning' : 'success')">
|
||||
<span v-clean-html="t('generic.selectors.matchingResources.matchesSome', matchingResources)" />
|
||||
</Banner>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col span-12">
|
||||
<ResourceTable
|
||||
:rows="matchingResources.matches"
|
||||
:headers="tableHeaders"
|
||||
key-field="id"
|
||||
:table-actions="false"
|
||||
:row-actions="false"
|
||||
:schema="schema"
|
||||
:groupable="false"
|
||||
:search="false"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -55,12 +55,8 @@ export default {
|
||||
!this.latestUpgrade.isUpgradeFailed;
|
||||
},
|
||||
|
||||
canUpgrade() {
|
||||
return this.versionOptions.length > 0 && !this.isUpgradeInProgress;
|
||||
},
|
||||
|
||||
versionOptions() {
|
||||
const versions = this.$store.getters['harvester/all'](HCI.VERSION) || [];
|
||||
const versions = this.$store.getters['harvester/all'](HCI.VERSION);
|
||||
|
||||
return versions.map((V) => V.metadata.name);
|
||||
},
|
||||
@@ -128,7 +124,6 @@ export default {
|
||||
|
||||
try {
|
||||
await proxyResource.save();
|
||||
proxyResource.notifyGeneratedName?.();
|
||||
|
||||
this.cancel();
|
||||
} catch (err) {
|
||||
@@ -159,23 +154,14 @@ export default {
|
||||
:cluster="currentCluster.nameDisplay"
|
||||
/>
|
||||
</h1>
|
||||
<span
|
||||
v-clean-tooltip="{
|
||||
content: canUpgrade ? t('harvester.upgradePage.upgradeAvailable') : t('harvester.upgradePage.upgradeUnavailable'),
|
||||
triggers: ['hover', 'focus', 'touch'],
|
||||
}"
|
||||
class="upgrade-btn-wrap"
|
||||
:tabindex="canUpgrade ? -1 : 0"
|
||||
<button
|
||||
v-if="versionOptions.length && !isUpgradeInProgress"
|
||||
type="button"
|
||||
class="btn bg-warning btn-sm"
|
||||
@click="open"
|
||||
>
|
||||
<button
|
||||
:disabled="!canUpgrade"
|
||||
type="button"
|
||||
class="btn bg-warning btn-sm"
|
||||
@click="open"
|
||||
>
|
||||
<t k="harvester.upgradePage.upgrade" />
|
||||
</button>
|
||||
</span>
|
||||
<t k="harvester.upgradePage.upgrade" />
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<ModalWithCard
|
||||
@@ -310,18 +296,6 @@ export default {
|
||||
line-height: 23px;
|
||||
}
|
||||
|
||||
.upgrade-btn-wrap {
|
||||
display: inline-flex;
|
||||
|
||||
button {
|
||||
color: #000 !important;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
color: #000 !important;
|
||||
}
|
||||
}
|
||||
|
||||
.currentVersion {
|
||||
margin-top: 10px;
|
||||
display: flex;
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
<script>
|
||||
import Collapse from '@shell/components/Collapse';
|
||||
import PercentageBar from '@shell/components/PercentageBar';
|
||||
import { HCI } from '../types';
|
||||
import { HCI as HCI_ANNOTATIONS } from '@pkg/harvester/config/labels-annotations';
|
||||
|
||||
export default {
|
||||
name: 'HarvesterUpgradeProgressList',
|
||||
@@ -27,45 +25,13 @@ export default {
|
||||
}
|
||||
},
|
||||
|
||||
async fetch() {
|
||||
await this.$store.dispatch('harvester/findAll', { type: HCI.UPGRADE });
|
||||
},
|
||||
|
||||
data() {
|
||||
return { open: true };
|
||||
},
|
||||
|
||||
computed: {
|
||||
showResumeButton() {
|
||||
return this.title === 'Upgrading Node';
|
||||
},
|
||||
latestUpgradeCR() {
|
||||
return this.$store.getters['harvester/all'](HCI.UPGRADE).find( (U) => U.isLatestUpgrade);
|
||||
},
|
||||
resumeUpgradePausedNodeEnabled() {
|
||||
return this.$store.getters['harvester-common/getFeatureEnabled']('resumeUpgradePausedNode');
|
||||
},
|
||||
},
|
||||
methods: {
|
||||
handleSwitch() {
|
||||
this.open = !this.open;
|
||||
},
|
||||
async resumeNodeUpgrade(nodeName) {
|
||||
if (!this.latestUpgradeCR || !nodeName) return;
|
||||
|
||||
try {
|
||||
const upgradePauseMapString = this.latestUpgradeCR.metadata.annotations[HCI_ANNOTATIONS.NODE_UPGRADE_PAUSE_MAP] || '{}';
|
||||
const upgradePauseMap = JSON.parse(upgradePauseMapString);
|
||||
|
||||
// update the upgrade CR annotation harvesterhci.io/node-upgrade-pause-map to unpause the node upgrade process
|
||||
upgradePauseMap[`${ nodeName }`] = 'unpause';
|
||||
this.latestUpgradeCR.setAnnotation(HCI_ANNOTATIONS.NODE_UPGRADE_PAUSE_MAP, JSON.stringify(upgradePauseMap));
|
||||
await this.latestUpgradeCR.save();
|
||||
} catch (e) {
|
||||
console.error(`unable to update harvester upgrade CR annotations: ${ this.latestUpgradeCR.id }.`, e); // eslint-disable-line no-console
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -97,28 +63,12 @@ export default {
|
||||
v-for="(item, i) in list"
|
||||
:key="i"
|
||||
>
|
||||
<div class="upgrade-node-header">
|
||||
<div class="upgrade-node-title">
|
||||
<p>
|
||||
{{ item.name }}
|
||||
</p>
|
||||
<span
|
||||
class="status"
|
||||
:class="{ [item.state]: true }"
|
||||
>
|
||||
{{ item.state }}
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
v-if="showResumeButton && resumeUpgradePausedNodeEnabled && item.state === 'Node-upgrade paused'"
|
||||
type="button"
|
||||
class="btn bg-info btn-sm"
|
||||
data-testid="add-item"
|
||||
@click="resumeNodeUpgrade(item.name)"
|
||||
>
|
||||
{{ t('action.resume') }}
|
||||
</button>
|
||||
</div>
|
||||
<p>
|
||||
{{ item.name }} <span
|
||||
class="status"
|
||||
:class="{ [item.state]: true }"
|
||||
>{{ item.state }}</span>
|
||||
</p>
|
||||
<PercentageBar
|
||||
:model-value="item.percent"
|
||||
preferred-direction="MORE"
|
||||
@@ -152,21 +102,10 @@ export default {
|
||||
}
|
||||
}
|
||||
.custom-content {
|
||||
.upgrade-node-title {
|
||||
flex: 1 0 80%;
|
||||
margin-right: 10px;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
}
|
||||
.upgrade-node-header {
|
||||
display:flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 14px;
|
||||
p {
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
margin-bottom: 14px;
|
||||
|
||||
.status {
|
||||
float: right;
|
||||
}
|
||||
@@ -178,8 +117,6 @@ export default {
|
||||
}
|
||||
.warning {
|
||||
color: var(--error);
|
||||
margin-bottom: 8px;
|
||||
margin-top: 4px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,59 +0,0 @@
|
||||
<script setup>
|
||||
defineProps({
|
||||
networkEntries: {
|
||||
type: Array,
|
||||
default: () => [],
|
||||
},
|
||||
storageEntries: {
|
||||
type: Array,
|
||||
default: () => [],
|
||||
},
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="mappings-cell">
|
||||
<div
|
||||
v-for="(entry, idx) in networkEntries"
|
||||
:key="'net-' + idx"
|
||||
class="mapping-entry"
|
||||
>
|
||||
<i
|
||||
class="icon icon-network"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span>{{ entry }}</span>
|
||||
</div>
|
||||
<div
|
||||
v-for="(entry, idx) in storageEntries"
|
||||
:key="'stor-' + idx"
|
||||
class="mapping-entry"
|
||||
>
|
||||
<i
|
||||
class="icon icon-datastore"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span>{{ entry }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.mappings-cell {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.mapping-entry {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
color: var(--muted);
|
||||
|
||||
.icon {
|
||||
font-size: 16px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -122,7 +122,7 @@ export default {
|
||||
return this.$store.getters['currentCluster'].isLocal;
|
||||
},
|
||||
canEditClusterMembers() {
|
||||
return this.schema?.collectionMethods.find((x) => x.toLowerCase() === 'post');
|
||||
return this.normanClusterRTBSchema?.collectionMethods.find((x) => x.toLowerCase() === 'post');
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script>
|
||||
import { allHash } from '@shell/utils/promise';
|
||||
import debounce from 'lodash/debounce';
|
||||
|
||||
import Socket, {
|
||||
EVENT_CONNECTED,
|
||||
EVENT_CONNECTING,
|
||||
@@ -21,98 +22,74 @@ export default {
|
||||
|
||||
data() {
|
||||
return {
|
||||
socket: null,
|
||||
terminal: null,
|
||||
textDecoder: null,
|
||||
fitAddon: null,
|
||||
searchAddon: null,
|
||||
webglAddon: null,
|
||||
onResize: null,
|
||||
isOpen: false,
|
||||
isOpening: false,
|
||||
backlog: [],
|
||||
firstTime: true,
|
||||
queue: [],
|
||||
isDraining: false,
|
||||
drainScheduled: false,
|
||||
drainTimer: null,
|
||||
showSearch: false,
|
||||
searchQuery: '',
|
||||
searchOptions: {
|
||||
caseSensitive: false,
|
||||
regex: false,
|
||||
wholeWord: false,
|
||||
incremental: true,
|
||||
decorations: {
|
||||
matchBackground: '#B45309',
|
||||
matchBorder: '#FDBA74',
|
||||
matchOverviewRuler: '#FDBA74',
|
||||
activeMatchBackground: '#EA580C',
|
||||
activeMatchBorder: '#FED7AA',
|
||||
activeMatchColorOverviewRuler: '#FED7AA',
|
||||
},
|
||||
},
|
||||
socket: null,
|
||||
terminal: null,
|
||||
fitAddon: null,
|
||||
searchAddon: null,
|
||||
webglAddon: null,
|
||||
isOpen: false,
|
||||
isOpening: false,
|
||||
backlog: [],
|
||||
firstTime: true,
|
||||
queue: []
|
||||
};
|
||||
},
|
||||
|
||||
computed: {
|
||||
serialConsoleUrl() {
|
||||
return this.value?.getSerialConsolePath || '';
|
||||
},
|
||||
|
||||
xtermConfig() {
|
||||
return {
|
||||
allowProposedApi: true,
|
||||
cursorBlink: true,
|
||||
cursorStyle: 'bar',
|
||||
cursorWidth: 2,
|
||||
scrollback: 5000,
|
||||
useStyle: true,
|
||||
fontFamily: 'JetBrains Mono, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',
|
||||
fontSize: 16,
|
||||
lineHeight: 1.3,
|
||||
fontSize: 12,
|
||||
};
|
||||
},
|
||||
},
|
||||
|
||||
watch: {
|
||||
queue: {
|
||||
handler: debounce(async function(neu) {
|
||||
if (neu.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const msg = await Promise.all(neu);
|
||||
|
||||
(msg || []).forEach((m) => {
|
||||
this.terminal.write(m);
|
||||
});
|
||||
|
||||
this.queue = [];
|
||||
}, 10),
|
||||
deep: true
|
||||
}
|
||||
},
|
||||
|
||||
beforeUnmount() {
|
||||
this.close();
|
||||
},
|
||||
|
||||
watch: {
|
||||
serialConsoleUrl() {
|
||||
if (this.terminal) {
|
||||
this.connect();
|
||||
}
|
||||
},
|
||||
},
|
||||
|
||||
async mounted() {
|
||||
this.textDecoder = new TextDecoder('utf-8');
|
||||
await this.setupTerminal();
|
||||
await this.connect();
|
||||
this.onResize = debounce(() => this.fit(), 100);
|
||||
window.addEventListener('resize', this.onResize);
|
||||
this.scheduleFit();
|
||||
},
|
||||
|
||||
methods: {
|
||||
async setupTerminal() {
|
||||
const docStyle = getComputedStyle(document.querySelector('body'));
|
||||
const xterm = await import(/* webpackChunkName: "xterm" */ '@xterm/xterm');
|
||||
const xterm = await import(/* webpackChunkName: "xterm" */ 'xterm');
|
||||
|
||||
const addons = await allHash({
|
||||
fit: import(/* webpackChunkName: "xterm" */ '@xterm/addon-fit'),
|
||||
webgl: import(/* webpackChunkName: "xterm" */ '@xterm/addon-webgl'),
|
||||
weblinks: import(/* webpackChunkName: "xterm" */ '@xterm/addon-web-links'),
|
||||
search: import(/* webpackChunkName: "xterm" */ '@xterm/addon-search'),
|
||||
canvas: import(/* webpackChunkName: "xterm" */ '@xterm/addon-canvas'),
|
||||
fit: import(/* webpackChunkName: "xterm" */ 'xterm-addon-fit'),
|
||||
webgl: import(/* webpackChunkName: "xterm" */ 'xterm-addon-webgl'),
|
||||
weblinks: import(/* webpackChunkName: "xterm" */ 'xterm-addon-web-links'),
|
||||
search: import(/* webpackChunkName: "xterm" */ 'xterm-addon-search'),
|
||||
});
|
||||
|
||||
const terminal = new xterm.Terminal({
|
||||
theme: {
|
||||
background: docStyle.getPropertyValue('--terminal-bg').trim(),
|
||||
cursor: docStyle.getPropertyValue('--terminal-text').trim(),
|
||||
cursor: docStyle.getPropertyValue('--terminal-cursor').trim(),
|
||||
foreground: docStyle.getPropertyValue('--terminal-text').trim()
|
||||
},
|
||||
...this.xtermConfig,
|
||||
@@ -120,48 +97,25 @@ export default {
|
||||
|
||||
this.fitAddon = new addons.fit.FitAddon();
|
||||
this.searchAddon = new addons.search.SearchAddon();
|
||||
|
||||
try {
|
||||
this.webglAddon = new addons.webgl.WebGlAddon();
|
||||
} catch (e) {
|
||||
// Some browsers (Safari) don't support the webgl renderer, so don't use it.
|
||||
this.webglAddon = null;
|
||||
}
|
||||
|
||||
terminal.loadAddon(this.fitAddon);
|
||||
terminal.loadAddon(this.searchAddon);
|
||||
terminal.loadAddon(new addons.weblinks.WebLinksAddon());
|
||||
terminal.open(this.$refs.xterm);
|
||||
|
||||
// The webgl renderer can fail without throwing: the context may be lost
|
||||
// mid-session, or it can attach but silently never paint, leaving the
|
||||
// terminal's helper textarea at 0x0. Detect both cases and fall back to the
|
||||
// canvas renderer so the terminal stays interactive.
|
||||
try {
|
||||
this.webglAddon = new addons.webgl.WebglAddon();
|
||||
|
||||
this.webglAddon.onContextLoss(() => {
|
||||
if (!this.isUnmounted && this.terminal) {
|
||||
this.fallbackToCanvas(terminal, addons);
|
||||
}
|
||||
});
|
||||
|
||||
if ( this.webglAddon ) {
|
||||
terminal.loadAddon(this.webglAddon);
|
||||
|
||||
// Detect the silent "attaches but never paints" failure after a render frame.
|
||||
requestAnimationFrame(() => {
|
||||
if (this.isUnmounted || !this.terminal) {
|
||||
return;
|
||||
}
|
||||
|
||||
const textarea = this.$refs.xterm?.querySelector('.xterm-helper-textarea');
|
||||
const hasPainted = textarea && textarea.getBoundingClientRect().height > 0;
|
||||
|
||||
if (this.webglAddon && !hasPainted) {
|
||||
this.fallbackToCanvas(terminal, addons);
|
||||
this.fit();
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
// Some browsers (e.g. Safari) don't support the webgl renderer, so don't use it.
|
||||
this.fallbackToCanvas(terminal, addons);
|
||||
}
|
||||
|
||||
this.fit();
|
||||
this.flush();
|
||||
this.scheduleDrainQueue();
|
||||
|
||||
terminal.onData((input) => {
|
||||
const msg = this.str2ab(input);
|
||||
@@ -169,132 +123,9 @@ export default {
|
||||
this.write(msg);
|
||||
});
|
||||
|
||||
terminal.attachCustomKeyEventHandler((event) => {
|
||||
const key = event.key?.toLowerCase();
|
||||
|
||||
if ((event.ctrlKey || event.metaKey) && key === 'f') {
|
||||
event.preventDefault();
|
||||
this.openSearch();
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if (key === 'escape' && this.showSearch) {
|
||||
event.preventDefault();
|
||||
this.closeSearch();
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
this.terminal = terminal;
|
||||
},
|
||||
|
||||
openSearch() {
|
||||
this.showSearch = true;
|
||||
|
||||
this.$nextTick(() => {
|
||||
const input = this.$refs.searchInput;
|
||||
|
||||
if (input) {
|
||||
input.focus();
|
||||
input.select();
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
closeSearch() {
|
||||
this.showSearch = false;
|
||||
this.searchQuery = '';
|
||||
this.clearSearchHighlights();
|
||||
this.terminal?.focus();
|
||||
},
|
||||
|
||||
clearSearchHighlights() {
|
||||
this.searchAddon?.clearActiveDecoration();
|
||||
this.searchAddon?.clearDecorations();
|
||||
this.terminal?.clearSelection();
|
||||
|
||||
// Disposing the search decorations doesn't repaint the webgl/canvas
|
||||
// layer, so force a refresh to remove the lingering highlight.
|
||||
if (this.terminal) {
|
||||
this.terminal.refresh(0, this.terminal.rows - 1);
|
||||
}
|
||||
},
|
||||
|
||||
findNext() {
|
||||
if (!this.searchAddon || !this.searchQuery) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.searchAddon.findNext(this.searchQuery, this.searchOptions);
|
||||
},
|
||||
|
||||
findPrevious() {
|
||||
if (!this.searchAddon || !this.searchQuery) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.searchAddon.findPrevious(this.searchQuery, this.searchOptions);
|
||||
},
|
||||
|
||||
onSearchInput() {
|
||||
if (!this.searchQuery) {
|
||||
this.clearSearchHighlights();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
this.findNext();
|
||||
},
|
||||
|
||||
onSearchKeydown(event) {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
|
||||
if (event.shiftKey) {
|
||||
this.findPrevious();
|
||||
} else {
|
||||
this.findNext();
|
||||
}
|
||||
}
|
||||
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
this.closeSearch();
|
||||
}
|
||||
},
|
||||
|
||||
scheduleFit() {
|
||||
this.$nextTick(() => {
|
||||
requestAnimationFrame(() => {
|
||||
this.fit();
|
||||
|
||||
// Re-fit after layout settles to avoid undersized rows on first paint.
|
||||
setTimeout(() => this.fit(), 120);
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
// Dispose the webgl renderer (if any) and switch to the canvas renderer.
|
||||
// Used when webgl fails to construct, loses its context, or silently never paints.
|
||||
fallbackToCanvas(terminal, addons) {
|
||||
if (this.isUnmounted) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.webglAddon?.dispose();
|
||||
this.webglAddon = null;
|
||||
|
||||
if (!this.canvasAddon) {
|
||||
this.canvasAddon = new addons.canvas.CanvasAddon();
|
||||
terminal.loadAddon(this.canvasAddon);
|
||||
}
|
||||
this.fit();
|
||||
},
|
||||
|
||||
str2ab(str) {
|
||||
const enc = new TextEncoder();
|
||||
|
||||
@@ -309,131 +140,12 @@ export default {
|
||||
}
|
||||
},
|
||||
|
||||
enqueueMessage(messagePromise) {
|
||||
this.queue.push(messagePromise);
|
||||
this.scheduleDrainQueue();
|
||||
},
|
||||
|
||||
scheduleDrainQueue() {
|
||||
if (this.drainScheduled || this.isDraining || !this.terminal) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.drainScheduled = true;
|
||||
|
||||
const shouldDrainImmediately = this.queue.length <= 3;
|
||||
|
||||
const runDrain = () => {
|
||||
this.drainScheduled = false;
|
||||
this.drainTimer = null;
|
||||
this.drainQueue();
|
||||
};
|
||||
|
||||
if (shouldDrainImmediately) {
|
||||
runDrain();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
this.drainTimer = requestAnimationFrame(runDrain);
|
||||
},
|
||||
|
||||
async decodeMessageData(data) {
|
||||
if (typeof data === 'string') {
|
||||
return data;
|
||||
}
|
||||
|
||||
if (!this.textDecoder) {
|
||||
this.textDecoder = new TextDecoder('utf-8');
|
||||
}
|
||||
|
||||
if (data instanceof Blob) {
|
||||
const buffer = await data.arrayBuffer();
|
||||
|
||||
return this.textDecoder.decode(new Uint8Array(buffer), { stream: true });
|
||||
}
|
||||
|
||||
if (data instanceof ArrayBuffer) {
|
||||
return this.textDecoder.decode(new Uint8Array(data), { stream: true });
|
||||
}
|
||||
|
||||
if (ArrayBuffer.isView(data)) {
|
||||
const view = data;
|
||||
const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
|
||||
|
||||
return this.textDecoder.decode(bytes, { stream: true });
|
||||
}
|
||||
|
||||
return String(data || '');
|
||||
},
|
||||
|
||||
async drainQueue() {
|
||||
if (this.isDraining || !this.terminal) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.isDraining = true;
|
||||
|
||||
try {
|
||||
while (this.queue.length > 0) {
|
||||
const pendingMessages = this.queue.splice(0, this.queue.length);
|
||||
const settledMessages = await Promise.allSettled(pendingMessages);
|
||||
const messages = settledMessages
|
||||
.filter((result) => result.status === 'fulfilled')
|
||||
.map((result) => result.value);
|
||||
const output = messages.filter(Boolean).join('');
|
||||
|
||||
if (output) {
|
||||
await this.writeOutputInChunks(output);
|
||||
}
|
||||
|
||||
if (this.queue.length > 0) {
|
||||
await this.nextFrame();
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
this.isDraining = false;
|
||||
|
||||
// If data arrived between the last while-check and releasing the lock,
|
||||
// immediately schedule another drain so output never gets stuck.
|
||||
if (this.queue.length > 0 && this.terminal) {
|
||||
this.scheduleDrainQueue();
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
async writeOutputInChunks(output) {
|
||||
if (!output) {
|
||||
return;
|
||||
}
|
||||
|
||||
const chunkSize = output.length > 20000 ? 16000 : output.length > 8000 ? 8000 : output.length;
|
||||
|
||||
if (chunkSize === output.length) {
|
||||
this.terminal.write(output);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
for (let index = 0; index < output.length; index += chunkSize) {
|
||||
this.terminal.write(output.slice(index, index + chunkSize));
|
||||
|
||||
if (index + chunkSize < output.length) {
|
||||
await this.nextFrame();
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
nextFrame() {
|
||||
return new Promise((resolve) => requestAnimationFrame(resolve));
|
||||
},
|
||||
|
||||
clear() {
|
||||
this.terminal.clear();
|
||||
},
|
||||
|
||||
getSocketUrl() {
|
||||
return this.serialConsoleUrl;
|
||||
return `${ this.value?.getSerialConsolePath }`;
|
||||
},
|
||||
|
||||
async connect() {
|
||||
@@ -469,7 +181,6 @@ export default {
|
||||
this.fit();
|
||||
this.flush();
|
||||
}
|
||||
this.scheduleFit();
|
||||
|
||||
if (this.firstTime) {
|
||||
this.socket.send(this.str2ab('\n'));
|
||||
@@ -484,7 +195,7 @@ export default {
|
||||
});
|
||||
|
||||
this.socket.addEventListener(EVENT_MESSAGE, (e) => {
|
||||
this.enqueueMessage(this.decodeMessageData(e.detail.data));
|
||||
this.queue.push(e.detail.data.text());
|
||||
});
|
||||
|
||||
this.socket.connect();
|
||||
@@ -507,19 +218,22 @@ export default {
|
||||
}
|
||||
|
||||
this.fitAddon.fit();
|
||||
|
||||
const { rows, cols } = this.fitAddon.proposeDimensions();
|
||||
|
||||
if ( !this.isOpen ) {
|
||||
return;
|
||||
}
|
||||
|
||||
const message = JSON.stringify({
|
||||
Width: cols,
|
||||
Height: rows
|
||||
});
|
||||
|
||||
this.socket.send(this.str2ab(message));
|
||||
},
|
||||
|
||||
close() {
|
||||
if (this.onResize) {
|
||||
window.removeEventListener('resize', this.onResize);
|
||||
this.onResize = null;
|
||||
}
|
||||
|
||||
if (this.drainTimer) {
|
||||
cancelAnimationFrame(this.drainTimer);
|
||||
this.drainTimer = null;
|
||||
}
|
||||
|
||||
if ( this.socket ) {
|
||||
this.socket.disconnect();
|
||||
}
|
||||
@@ -534,44 +248,6 @@ export default {
|
||||
|
||||
<template>
|
||||
<div class="harvester-shell-container">
|
||||
<div
|
||||
v-if="showSearch"
|
||||
class="shell-search"
|
||||
>
|
||||
<input
|
||||
ref="searchInput"
|
||||
v-model="searchQuery"
|
||||
type="text"
|
||||
class="shell-search-input"
|
||||
placeholder="Search in terminal"
|
||||
@input="onSearchInput"
|
||||
@keydown="onSearchKeydown"
|
||||
>
|
||||
<button
|
||||
class="btn role-secondary btn-sm shell-search-btn"
|
||||
type="button"
|
||||
title="Shift+Enter"
|
||||
@click="findPrevious"
|
||||
>
|
||||
Prev
|
||||
</button>
|
||||
<button
|
||||
class="btn role-secondary btn-sm shell-search-btn"
|
||||
type="button"
|
||||
title="Enter"
|
||||
@click="findNext"
|
||||
>
|
||||
Next
|
||||
</button>
|
||||
<button
|
||||
class="btn role-secondary btn-sm shell-search-btn"
|
||||
type="button"
|
||||
title="Esc"
|
||||
@click="closeSearch"
|
||||
>
|
||||
Close
|
||||
</button>
|
||||
</div>
|
||||
<div
|
||||
ref="xterm"
|
||||
class="shell-body"
|
||||
@@ -581,73 +257,18 @@ export default {
|
||||
</template>
|
||||
|
||||
<style lang="scss">
|
||||
@import '../../../../node_modules/@xterm/xterm/css/xterm.css';
|
||||
@import '../../../../node_modules/xterm/css/xterm.css';
|
||||
|
||||
body, #__nuxt, #__layout, MAIN {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.harvester-shell-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
position: relative;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
|
||||
.resize-observer {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.shell-search {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
justify-content: flex-end;
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
right: 10px;
|
||||
z-index: 5;
|
||||
padding: 8px;
|
||||
border-radius: 6px;
|
||||
border: 1px solid var(--border);
|
||||
background: color-mix(in srgb, var(--body-bg) 88%, transparent);
|
||||
}
|
||||
|
||||
.shell-search-input {
|
||||
min-width: 220px;
|
||||
max-width: 420px;
|
||||
flex: 0 1 320px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 4px;
|
||||
background: var(--body-bg);
|
||||
color: var(--body-text);
|
||||
padding: 6px 8px;
|
||||
}
|
||||
|
||||
.shell-search-btn {
|
||||
min-width: 64px;
|
||||
}
|
||||
|
||||
.shell-body {
|
||||
flex: 1 1 auto;
|
||||
.shell-body, .terminal.xterm {
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
min-height: 0;
|
||||
padding: 0 10px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.terminal.xterm,
|
||||
.terminal.xterm .xterm-viewport,
|
||||
.terminal.xterm .xterm-screen,
|
||||
.terminal.xterm .xterm-scrollable-element {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.terminal.xterm .xterm-scrollable-element {
|
||||
min-height: 100%;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,17 +1,14 @@
|
||||
<script>
|
||||
import { mapGetters } from 'vuex';
|
||||
import ActionMenu from '@shell/components/ActionMenuShell';
|
||||
import { Banner } from '@components/Banner';
|
||||
import AsyncButton from '@shell/components/AsyncButton';
|
||||
import { HCI_ALLOWED_SETTINGS, HCI_SINGLE_CLUSTER_ALLOWED_SETTING, HCI_SETTING } from '../config/settings';
|
||||
import { DOC } from '../config/doc-links';
|
||||
import { docLink } from '../utils/feature-flags';
|
||||
import { HCI_ALLOWED_SETTINGS, HCI_SETTING } from '../config/settings';
|
||||
|
||||
const CATEGORY = {
|
||||
ui: [
|
||||
'branding',
|
||||
HCI_SETTING.SERVER_FLAVOR,
|
||||
'ui-source',
|
||||
'ui-plugin-index',
|
||||
'ui-index',
|
||||
]
|
||||
};
|
||||
@@ -22,7 +19,6 @@ export default {
|
||||
components: {
|
||||
AsyncButton,
|
||||
Banner,
|
||||
ActionMenu
|
||||
},
|
||||
|
||||
props: {
|
||||
@@ -34,113 +30,36 @@ export default {
|
||||
category: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
|
||||
searchQuery: {
|
||||
type: String,
|
||||
default: ''
|
||||
}
|
||||
},
|
||||
|
||||
data() {
|
||||
const categorySettings = this.filterCategorySettings();
|
||||
const filteredSettings = this.filterSearchSettings(categorySettings, this.searchQuery);
|
||||
|
||||
return {
|
||||
HCI_SETTING,
|
||||
categorySettings,
|
||||
filteredSettings,
|
||||
originalHideMap: this.createHideMap(categorySettings)
|
||||
};
|
||||
},
|
||||
|
||||
computed: { ...mapGetters({ t: 'i18n/t', isHarvesterPrime: 'harvester-common/isHarvesterPrime' }) },
|
||||
computed: { ...mapGetters({ t: 'i18n/t' }) },
|
||||
|
||||
watch: {
|
||||
settings: {
|
||||
deep: true,
|
||||
handler() {
|
||||
this.categorySettings = this.filterCategorySettings();
|
||||
this.filteredSettings = this.filterSearchSettings(this.categorySettings, this.searchQuery);
|
||||
}
|
||||
},
|
||||
searchQuery: {
|
||||
immediate: true,
|
||||
handler(newQuery) {
|
||||
const filtered = this.filterSearchSettings(this.categorySettings, newQuery);
|
||||
|
||||
this.filteredSettings = newQuery ? this.openJsonSettings(filtered) : filtered.map((s) => ({ ...s, hide: this.originalHideMap[s.id] ?? false }));
|
||||
this['categorySettings'] = this.filterCategorySettings();
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
methods: {
|
||||
createHideMap(settings = []) {
|
||||
const map = settings.reduce((acc, s) => {
|
||||
acc[s.id] = s.hide ?? false;
|
||||
|
||||
return acc;
|
||||
}, {} );
|
||||
|
||||
return map;
|
||||
},
|
||||
filterSearchSettings(settings, searchKey) {
|
||||
if (!searchKey) {
|
||||
return this.filterCategorySettings();
|
||||
}
|
||||
const searchQuery = searchKey.toLowerCase();
|
||||
|
||||
return settings.filter((setting) => {
|
||||
const id = setting.id?.toLowerCase() || '';
|
||||
|
||||
// filter by id
|
||||
if (id.includes(searchQuery) ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
let description = this.t(setting.description, this.getDocLinkParams(setting) || {}, true)?.toLowerCase() || '';
|
||||
|
||||
// remove <a> tags from description
|
||||
if (description.includes('<a')) {
|
||||
description = description.replace(/<a[^>]*>(.*?)<\/a>/g, '$1');
|
||||
}
|
||||
// filter by description
|
||||
if (description.includes(searchQuery)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// filter by customized value
|
||||
if (setting.customized === true && setting.data?.value) {
|
||||
const value = setting.data.value?.toLowerCase() || '';
|
||||
|
||||
return value.includes(searchQuery);
|
||||
}
|
||||
|
||||
// filter by json value
|
||||
if (setting.kind === 'json' && setting.json) {
|
||||
try {
|
||||
const json = JSON.parse(setting.json);
|
||||
const jsonString = JSON.stringify(json).toLowerCase();
|
||||
|
||||
return jsonString.includes(searchQuery);
|
||||
} catch (e) {
|
||||
console.error(`${ setting.id }: wrong format`, e); // eslint-disable-line no-console
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// filter by default value
|
||||
if (setting.data?.default) {
|
||||
return setting.data?.default.includes(searchQuery);
|
||||
}
|
||||
|
||||
return false;
|
||||
});
|
||||
},
|
||||
|
||||
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,21 +70,29 @@ export default {
|
||||
}) || [];
|
||||
},
|
||||
|
||||
getFeatureEnabled(id) {
|
||||
return id ? this.$store.getters['harvester-common/getFeatureEnabled'](id) : true;
|
||||
},
|
||||
|
||||
showActionMenu(e, setting) {
|
||||
const actionElement = e.srcElement;
|
||||
|
||||
this.$store.commit(`action-menu/show`, {
|
||||
resources: setting.data,
|
||||
elem: actionElement
|
||||
});
|
||||
},
|
||||
|
||||
getSettingOption(id) {
|
||||
return HCI_ALLOWED_SETTINGS.find((setting) => setting.id === id);
|
||||
},
|
||||
|
||||
openJsonSettings(settings) {
|
||||
return settings.map((s) => s.hide ? { ...s, hide: false } : s);
|
||||
},
|
||||
|
||||
toggleHide(s) {
|
||||
const setting = this.filteredSettings.find((setting) => setting.id === s.id);
|
||||
|
||||
if (setting) {
|
||||
setting.hide = !setting.hide;
|
||||
this.originalHideMap[setting.id] = setting.hide;
|
||||
}
|
||||
this.categorySettings.find((setting) => {
|
||||
if (setting.id === s.id) {
|
||||
setting.hide = !setting.hide;
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
async testConnect(buttonDone, value) {
|
||||
@@ -191,19 +118,6 @@ export default {
|
||||
}
|
||||
buttonDone(false);
|
||||
}
|
||||
},
|
||||
|
||||
getDocLinkParams(setting) {
|
||||
const settingConfig = HCI_ALLOWED_SETTINGS[setting.id] || HCI_SINGLE_CLUSTER_ALLOWED_SETTING[setting.id];
|
||||
|
||||
if (settingConfig?.docPath) {
|
||||
const version = this.$store.getters['harvester-common/getServerVersion']();
|
||||
const url = docLink(DOC[settingConfig.docPath], version);
|
||||
|
||||
return { url };
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
},
|
||||
};
|
||||
@@ -212,7 +126,7 @@ export default {
|
||||
<template>
|
||||
<div>
|
||||
<div
|
||||
v-for="(setting, i) in filteredSettings"
|
||||
v-for="(setting, i) in categorySettings"
|
||||
:key="i"
|
||||
class="advanced-setting mb-20"
|
||||
>
|
||||
@@ -224,24 +138,17 @@ export default {
|
||||
v-if="setting.customized"
|
||||
class="modified"
|
||||
>
|
||||
{{ t('advancedSettings.tags.modified.label') }}
|
||||
Modified
|
||||
</span>
|
||||
<span
|
||||
v-if="setting.experimental"
|
||||
v-clean-tooltip="t('advancedSettings.tags.experimental.description')"
|
||||
v-clean-tooltip="t('advancedSettings.experimental')"
|
||||
class="experimental"
|
||||
>
|
||||
{{ t('advancedSettings.tags.experimental.label') }}
|
||||
</span>
|
||||
<span
|
||||
v-if="setting.preview"
|
||||
v-clean-tooltip="t('advancedSettings.tags.preview.description')"
|
||||
class="preview"
|
||||
>
|
||||
{{ t('advancedSettings.tags.preview.label') }}
|
||||
Experimental
|
||||
</span>
|
||||
</h1>
|
||||
<h2 v-clean-html="t(setting.description, getDocLinkParams(setting) || {}, true)">
|
||||
<h2 v-clean-html="t(setting.description, {}, true)">
|
||||
</h2>
|
||||
</div>
|
||||
<div
|
||||
@@ -249,12 +156,15 @@ export default {
|
||||
:id="setting.id"
|
||||
class="action"
|
||||
>
|
||||
<ActionMenu
|
||||
:resource="setting.data"
|
||||
:button-aria-label="t('advancedSettings.edit.label')"
|
||||
data-testid="action-button"
|
||||
button-role="tertiary"
|
||||
/>
|
||||
<button
|
||||
aria-haspopup="true"
|
||||
aria-expanded="false"
|
||||
type="button"
|
||||
class="btn btn-sm role-multi-action actions"
|
||||
@click="showActionMenu($event, setting)"
|
||||
>
|
||||
<i class="icon icon-actions" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div value>
|
||||
@@ -262,8 +172,7 @@ export default {
|
||||
v-if="!setting.hide"
|
||||
class="settings-value"
|
||||
>
|
||||
<pre v-if="setting.id === 'branding' && isHarvesterPrime">{{ $store.getters['harvester-common/privateLabel'] }}</pre>
|
||||
<pre v-else-if="setting.kind === 'json'">{{ setting.json }}</pre>
|
||||
<pre v-if="setting.kind === 'json'">{{ setting.json }}</pre>
|
||||
<pre v-else-if="setting.kind === 'multiline'">{{ setting.data.value || setting.data.default }}</pre>
|
||||
<pre v-else-if="setting.kind === 'enum'">{{ t(setting.enum) }}</pre>
|
||||
<pre v-else-if="setting.kind === 'custom' && setting.custom">{{ setting.custom }}</pre>
|
||||
@@ -312,12 +221,6 @@ export default {
|
||||
{{ setting.data.errMessage }}
|
||||
</Banner>
|
||||
</div>
|
||||
<div
|
||||
v-if="filteredSettings.length === 0"
|
||||
class="advanced-setting mb-20 no-search-match"
|
||||
>
|
||||
<p> {{ t('harvester.setting.noSearchMatch') }} </p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -353,21 +256,19 @@ export default {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.modified,
|
||||
.experimental,
|
||||
.preview {
|
||||
.modified {
|
||||
margin-left: 10px;
|
||||
border: 1px solid;
|
||||
border: 1px solid var(--primary);
|
||||
border-radius: 5px;
|
||||
padding: 2px 10px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.modified { border-color: var(--primary); }
|
||||
.experimental { border-color: var(--error); }
|
||||
.preview { border-color: var(--warning); }
|
||||
|
||||
.no-search-match {
|
||||
text-align: center;
|
||||
.experimental {
|
||||
margin-left: 10px;
|
||||
border: 1px solid var(--error);
|
||||
border-radius: 5px;
|
||||
padding: 2px 10px;
|
||||
font-size: 12px;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -55,21 +55,14 @@ export default {
|
||||
const host = window.location.host;
|
||||
const prefix = window.location.pathname.replace(this.$route.path, '');
|
||||
const params = this.$route?.params;
|
||||
const popupWidth = Math.max(800, screen.width - 200);
|
||||
const popupHeight = Math.max(600, screen.height - 200);
|
||||
const popupLeft = Math.max(0, window.screenX + Math.floor((window.outerWidth - popupWidth) / 2));
|
||||
const popupTop = Math.max(0, window.screenY + Math.floor((window.outerHeight - popupHeight) / 2));
|
||||
|
||||
const url = `https://${ host }${ prefix }/${ PRODUCT_NAME }/c/${ params.cluster }/console/${ uid }/${ type }`;
|
||||
|
||||
// Defer so v-select can finish closing the dropdown before the popup steals focus
|
||||
this.$nextTick(() => {
|
||||
window.open(
|
||||
url,
|
||||
'_blank',
|
||||
`toolbars=0,width=${ popupWidth },height=${ popupHeight },left=${ popupLeft },top=${ popupTop },noreferrer`
|
||||
);
|
||||
});
|
||||
window.open(
|
||||
url,
|
||||
'_blank',
|
||||
`toolbars=0,width=${ screen.width - 200 },height=${ screen.height - 200 },left=0,top=0,noreferrer`
|
||||
);
|
||||
},
|
||||
|
||||
isEmpty(o) {
|
||||
|
||||
@@ -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,80 @@ 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());
|
||||
},
|
||||
|
||||
// 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.softrebootVM();
|
||||
},
|
||||
|
||||
showKeysModal() {
|
||||
@@ -403,527 +267,108 @@ 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"
|
||||
/>
|
||||
<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>
|
||||
|
||||
<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>
|
||||
<template #popper>
|
||||
<div>
|
||||
<button
|
||||
class="btn btn-sm bg-primary"
|
||||
@click="showKeysModal"
|
||||
>
|
||||
{{ t("harvester.virtualMachine.detail.console.management") }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="console-toolbar__group">
|
||||
<NovncShortcutKeysMenu
|
||||
v-bind="shortcutMenuProps"
|
||||
@send-keys="sendKeys"
|
||||
@send-shortcut="sendCustomKeys"
|
||||
@manage="showKeysModal"
|
||||
@ctrl-alt-del="ctrlAltDelete"
|
||||
/>
|
||||
</div>
|
||||
<hr>
|
||||
|
||||
<span
|
||||
class="console-toolbar__divider"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
|
||||
<div class="console-toolbar__group">
|
||||
<RcButton
|
||||
variant="tertiary"
|
||||
data-testid="vnc-ctrl-alt-del"
|
||||
:disabled="!canSendKeys"
|
||||
@click="ctrlAltDelete"
|
||||
>
|
||||
<template #before>
|
||||
<NovncIcon type="power" />
|
||||
</template>
|
||||
{{ t("harvester.virtualMachine.detail.console.ctrlAltDel") }}
|
||||
</RcButton>
|
||||
|
||||
<RcButton
|
||||
v-if="hasSoftRebootAction"
|
||||
variant="tertiary"
|
||||
left-icon="refresh-alt"
|
||||
data-testid="vnc-soft-reboot"
|
||||
:disabled="!!settings.viewOnly"
|
||||
@click="softReboot"
|
||||
>
|
||||
{{ t("harvester.virtualMachine.detail.console.softReboot") }}
|
||||
</RcButton>
|
||||
</div>
|
||||
|
||||
<span class="console-toolbar__spacer" />
|
||||
|
||||
<div class="console-toolbar__group">
|
||||
<v-dropdown
|
||||
placement="bottom-end"
|
||||
trigger="click"
|
||||
:container="false"
|
||||
@hide="onViewHide"
|
||||
>
|
||||
<RcButton
|
||||
ref="viewButton"
|
||||
variant="tertiary"
|
||||
left-icon="show"
|
||||
right-icon="chevron-down"
|
||||
data-testid="vnc-view"
|
||||
<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);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
<style lang="scss">
|
||||
.vm-console .v-popper__arrow-container {
|
||||
display: none;
|
||||
}
|
||||
.vm-console .v-popper__popper{
|
||||
margin-top: 8px;
|
||||
}
|
||||
.vm-console .v-popper__inner{
|
||||
overflow-y: visible;
|
||||
.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"
|
||||
/>
|
||||
|
||||
@@ -1,196 +0,0 @@
|
||||
<script>
|
||||
import { RadioGroup } from '@components/Form/Radio';
|
||||
import LabeledSelect from '@shell/components/form/LabeledSelect';
|
||||
import { NAMESPACE } from '@shell/config/types';
|
||||
import CreateEditView from '@shell/mixins/create-edit-view';
|
||||
|
||||
export default {
|
||||
name: 'HarvesterClusterPodSecurityStandard',
|
||||
|
||||
components: {
|
||||
RadioGroup,
|
||||
LabeledSelect,
|
||||
},
|
||||
|
||||
mixins: [CreateEditView],
|
||||
|
||||
props: {
|
||||
value: {
|
||||
type: Object,
|
||||
default: () => ({}),
|
||||
},
|
||||
},
|
||||
|
||||
async fetch() {
|
||||
const inStore = this.$store.getters['currentProduct'].inStore;
|
||||
|
||||
await this.$store.dispatch(`${ inStore }/findAll`, { type: NAMESPACE });
|
||||
},
|
||||
|
||||
data() {
|
||||
let enabled = false;
|
||||
let whitelistedNamespaces = [];
|
||||
let privilegedNamespaces = [];
|
||||
let restrictedNamespaces = [];
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(this.value.value || this.value.default || '{}');
|
||||
|
||||
enabled = !!parsed.enabled;
|
||||
whitelistedNamespaces = parsed.whitelistedNamespacesList ? parsed.whitelistedNamespacesList.split(',') : [];
|
||||
privilegedNamespaces = parsed.privilegedNamespacesList ? parsed.privilegedNamespacesList.split(',') : [];
|
||||
restrictedNamespaces = parsed.restrictedNamespacesList ? parsed.restrictedNamespacesList.split(',') : [];
|
||||
} catch (e) {
|
||||
enabled = false;
|
||||
whitelistedNamespaces = [];
|
||||
privilegedNamespaces = [];
|
||||
restrictedNamespaces = [];
|
||||
}
|
||||
|
||||
return {
|
||||
enabled,
|
||||
whitelistedNamespaces,
|
||||
privilegedNamespaces,
|
||||
restrictedNamespaces,
|
||||
};
|
||||
},
|
||||
|
||||
computed: {
|
||||
enabledOptions() {
|
||||
return [
|
||||
{ label: this.t('generic.enabled'), value: true },
|
||||
{ label: this.t('generic.disabled'), value: false },
|
||||
];
|
||||
},
|
||||
|
||||
allNamespaces() {
|
||||
const inStore = this.$store.getters['currentProduct'].inStore;
|
||||
|
||||
return this.$store.getters[`${ inStore }/all`](NAMESPACE).filter((ns) => !ns.isSystem).map((ns) => ns.id);
|
||||
},
|
||||
|
||||
whitelistedOptions() {
|
||||
const excluded = new Set([...this.privilegedNamespaces, ...this.restrictedNamespaces]);
|
||||
|
||||
return this.allNamespaces.filter((ns) => !excluded.has(ns));
|
||||
},
|
||||
|
||||
privilegedOptions() {
|
||||
const excluded = new Set([...this.whitelistedNamespaces, ...this.restrictedNamespaces]);
|
||||
|
||||
return this.allNamespaces.filter((ns) => !excluded.has(ns));
|
||||
},
|
||||
|
||||
restrictedOptions() {
|
||||
const excluded = new Set([...this.whitelistedNamespaces, ...this.privilegedNamespaces]);
|
||||
|
||||
return this.allNamespaces.filter((ns) => !excluded.has(ns));
|
||||
},
|
||||
},
|
||||
|
||||
methods: {
|
||||
useDefault() {
|
||||
try {
|
||||
const parsed = JSON.parse(this.value.default || '{}');
|
||||
|
||||
this.enabled = !!parsed.enabled;
|
||||
this.whitelistedNamespaces = parsed.whitelistedNamespacesList ? parsed.whitelistedNamespacesList.split(',') : [];
|
||||
this.privilegedNamespaces = parsed.privilegedNamespacesList ? parsed.privilegedNamespacesList.split(',') : [];
|
||||
this.restrictedNamespaces = parsed.restrictedNamespacesList ? parsed.restrictedNamespacesList.split(',') : [];
|
||||
} catch (e) {
|
||||
this.enabled = false;
|
||||
this.whitelistedNamespaces = [];
|
||||
this.privilegedNamespaces = [];
|
||||
this.restrictedNamespaces = [];
|
||||
}
|
||||
this.save();
|
||||
},
|
||||
|
||||
onUpdateEnabled() {
|
||||
if (!this.enabled) {
|
||||
this.whitelistedNamespaces = [];
|
||||
this.privilegedNamespaces = [];
|
||||
this.restrictedNamespaces = [];
|
||||
}
|
||||
this.save();
|
||||
},
|
||||
|
||||
updateWhitelisted(selected) {
|
||||
this.whitelistedNamespaces = selected;
|
||||
this.save();
|
||||
},
|
||||
|
||||
updatePrivileged(selected) {
|
||||
this.privilegedNamespaces = selected;
|
||||
this.save();
|
||||
},
|
||||
|
||||
updateRestricted(selected) {
|
||||
this.restrictedNamespaces = selected;
|
||||
this.save();
|
||||
},
|
||||
|
||||
save() {
|
||||
this.value.value = JSON.stringify({
|
||||
enabled: this.enabled,
|
||||
whitelistedNamespacesList: this.whitelistedNamespaces.join(','),
|
||||
privilegedNamespacesList: this.privilegedNamespaces.join(','),
|
||||
restrictedNamespacesList: this.restrictedNamespaces.join(','),
|
||||
});
|
||||
},
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<div class="row mb-20">
|
||||
<div class="col span-6">
|
||||
<RadioGroup
|
||||
v-model:value="enabled"
|
||||
name="enabled"
|
||||
:options="enabledOptions"
|
||||
@update:value="onUpdateEnabled"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<template v-if="enabled">
|
||||
<div class="row mb-20">
|
||||
<div class="col span-12">
|
||||
<LabeledSelect
|
||||
v-model:value="whitelistedNamespaces"
|
||||
:label="t('harvester.setting.clusterPodSecurityStandard.whitelistedNamespaces.label')"
|
||||
:options="whitelistedOptions"
|
||||
:multiple="true"
|
||||
:mode="mode"
|
||||
@update:value="updateWhitelisted"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row mb-20">
|
||||
<div class="col span-12">
|
||||
<LabeledSelect
|
||||
v-model:value="privilegedNamespaces"
|
||||
:label="t('harvester.setting.clusterPodSecurityStandard.privilegedNamespaces.label')"
|
||||
:options="privilegedOptions"
|
||||
:multiple="true"
|
||||
:mode="mode"
|
||||
@update:value="updatePrivileged"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row mb-20">
|
||||
<div class="col span-12">
|
||||
<LabeledSelect
|
||||
v-model:value="restrictedNamespaces"
|
||||
:label="t('harvester.setting.clusterPodSecurityStandard.restrictedNamespaces.label')"
|
||||
:options="restrictedOptions"
|
||||
:multiple="true"
|
||||
:mode="mode"
|
||||
@update:value="updateRestricted"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,123 +0,0 @@
|
||||
<script>
|
||||
import MessageLink from '@shell/components/MessageLink';
|
||||
import CreateEditView from '@shell/mixins/create-edit-view';
|
||||
import { LabeledInput } from '@components/Form/LabeledInput';
|
||||
import { HCI_SETTING } from '../../config/settings';
|
||||
import { Checkbox } from '@components/Form/Checkbox';
|
||||
import { Banner } from '@components/Banner';
|
||||
|
||||
export default {
|
||||
name: 'HarvesterEditClusterRegistrationURL',
|
||||
|
||||
components: {
|
||||
LabeledInput, MessageLink, Checkbox, Banner
|
||||
},
|
||||
|
||||
mixins: [CreateEditView],
|
||||
|
||||
data() {
|
||||
let parseDefaultValue = {};
|
||||
|
||||
try {
|
||||
parseDefaultValue = JSON.parse(this.value.value);
|
||||
} catch (error) {
|
||||
parseDefaultValue.url = this.value.value;
|
||||
parseDefaultValue.insecureSkipTLSVerify = true;
|
||||
}
|
||||
|
||||
return {
|
||||
parseDefaultValue,
|
||||
errors: []
|
||||
};
|
||||
},
|
||||
|
||||
computed: {
|
||||
toCA() {
|
||||
return `${ HCI_SETTING.ADDITIONAL_CA }?mode=edit`;
|
||||
},
|
||||
clusterRegistrationTLSVerifyEnabled() {
|
||||
return this.$store.getters['harvester-common/getFeatureEnabled']('clusterRegistrationTLSVerify');
|
||||
},
|
||||
registrationURL: {
|
||||
get() {
|
||||
return this.clusterRegistrationTLSVerifyEnabled ? this.parseDefaultValue.url : this.parseDefaultValue;
|
||||
},
|
||||
|
||||
set(value) {
|
||||
if (this.clusterRegistrationTLSVerifyEnabled) {
|
||||
this.parseDefaultValue.url = value;
|
||||
} else {
|
||||
this.parseDefaultValue = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
methods: {
|
||||
getDefaultValue() {
|
||||
if (this.clusterRegistrationTLSVerifyEnabled) {
|
||||
return { url: '', insecureSkipTLSVerify: false };
|
||||
} else {
|
||||
return '';
|
||||
}
|
||||
},
|
||||
|
||||
updateUrl() {
|
||||
this.update();
|
||||
},
|
||||
|
||||
update() {
|
||||
if (this.clusterRegistrationTLSVerifyEnabled) {
|
||||
this.value['value'] = JSON.stringify(this.parseDefaultValue);
|
||||
} else {
|
||||
this.value['value'] = this.parseDefaultValue;
|
||||
}
|
||||
},
|
||||
|
||||
useDefault() {
|
||||
this.parseDefaultValue = this.getDefaultValue();
|
||||
},
|
||||
|
||||
updateInsecureSkipTLSVerify(newValue) {
|
||||
const { url = '' } = this.parseDefaultValue;
|
||||
|
||||
this.parseDefaultValue = { url, insecureSkipTLSVerify: newValue };
|
||||
this.update();
|
||||
},
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="row"
|
||||
>
|
||||
<div class="col span-12">
|
||||
<Banner color="info">
|
||||
<MessageLink
|
||||
:to="toCA"
|
||||
target="_blank"
|
||||
prefix-label="harvester.setting.clusterRegistrationUrl.tip.prefix"
|
||||
middle-label="harvester.setting.clusterRegistrationUrl.tip.middle"
|
||||
suffix-label="harvester.setting.clusterRegistrationUrl.tip.suffix"
|
||||
/>
|
||||
</Banner>
|
||||
<LabeledInput
|
||||
v-model:value="registrationURL"
|
||||
class="mb-20"
|
||||
:mode="mode"
|
||||
:label="t('harvester.setting.clusterRegistrationUrl.url')"
|
||||
@update:value="updateUrl"
|
||||
/>
|
||||
<div v-if="clusterRegistrationTLSVerifyEnabled">
|
||||
<Checkbox
|
||||
v-model:value="parseDefaultValue.insecureSkipTLSVerify"
|
||||
class="check mb-5"
|
||||
type="checkbox"
|
||||
:label="t('harvester.setting.clusterRegistrationUrl.insecureSkipTLSVerify')"
|
||||
@update:value="updateInsecureSkipTLSVerify"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,294 +0,0 @@
|
||||
<script>
|
||||
import { _EDIT } from '@shell/config/query-params';
|
||||
import LabeledSelect from '@shell/components/form/LabeledSelect';
|
||||
import InfoBox from '@shell/components/InfoBox';
|
||||
import { Banner } from '@components/Banner';
|
||||
import { allHash } from '@shell/utils/promise';
|
||||
import { CSI_DRIVER } from '../../types';
|
||||
import { LONGHORN_DRIVER } from '@shell/config/types';
|
||||
|
||||
export default {
|
||||
name: 'CSIOnlineExpandValidation',
|
||||
|
||||
components: {
|
||||
Banner,
|
||||
InfoBox,
|
||||
LabeledSelect,
|
||||
},
|
||||
|
||||
props: {
|
||||
mode: {
|
||||
type: String,
|
||||
default: _EDIT,
|
||||
},
|
||||
value: {
|
||||
type: Object,
|
||||
default: () => ({}),
|
||||
},
|
||||
registerBeforeHook: {
|
||||
type: Function,
|
||||
required: true,
|
||||
},
|
||||
},
|
||||
|
||||
async fetch() {
|
||||
const inStore = this.$store.getters['currentProduct'].inStore;
|
||||
|
||||
try {
|
||||
await allHash({ csiDrivers: this.$store.dispatch(`${ inStore }/findAll`, { type: CSI_DRIVER }) });
|
||||
this.fetchError = null;
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch CSI drivers:', error); // eslint-disable-line no-console
|
||||
this.fetchError = this.t(
|
||||
'harvester.setting.csiOnlineExpandValidation.failedToLoadDrivers',
|
||||
{ error: error.message || error },
|
||||
true
|
||||
);
|
||||
}
|
||||
},
|
||||
|
||||
data() {
|
||||
return {
|
||||
configArr: [],
|
||||
parseError: null,
|
||||
fetchError: null,
|
||||
};
|
||||
},
|
||||
|
||||
created() {
|
||||
const initValue = this.value.value || this.value.default || '{}';
|
||||
|
||||
this.configArr = this.parseValue(initValue);
|
||||
this.registerBeforeHook?.(this.willSave, 'willSave');
|
||||
},
|
||||
|
||||
computed: {
|
||||
allErrors() {
|
||||
const errors = [];
|
||||
|
||||
if (this.fetchError) {
|
||||
errors.push(this.fetchError);
|
||||
}
|
||||
if (this.parseError) {
|
||||
errors.push(this.parseError);
|
||||
}
|
||||
|
||||
return errors;
|
||||
},
|
||||
|
||||
csiDrivers() {
|
||||
if (this.fetchError) return [];
|
||||
|
||||
const inStore = this.$store.getters['currentProduct'].inStore;
|
||||
|
||||
return this.$store.getters[`${ inStore }/all`](CSI_DRIVER) || [];
|
||||
},
|
||||
|
||||
provisioners() {
|
||||
const usedKeys = this.configArr.map(({ key }) => key);
|
||||
|
||||
return this.csiDrivers
|
||||
.filter(({ name }) => !usedKeys.includes(name))
|
||||
.map(({ name }) => name);
|
||||
},
|
||||
|
||||
provisionerValue() {
|
||||
return [
|
||||
{ label: 'True', value: true },
|
||||
{ label: 'False', value: false },
|
||||
];
|
||||
},
|
||||
|
||||
disableAdd() {
|
||||
return this.parseError || this.fetchError || this.configArr.length >= this.csiDrivers.length;
|
||||
},
|
||||
|
||||
disableConfigEditing() {
|
||||
return this.parseError || this.fetchError;
|
||||
}
|
||||
},
|
||||
|
||||
watch: {
|
||||
'value.value'(newVal, oldVal) {
|
||||
if (newVal !== oldVal) {
|
||||
this.configArr = this.parseValue(newVal || '{}');
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
methods: {
|
||||
_convertToBoolean(value) {
|
||||
if (typeof value === 'boolean') return value;
|
||||
|
||||
if (typeof value === 'string') {
|
||||
const lowerCaseValue = value.toLowerCase();
|
||||
|
||||
if (lowerCaseValue === 'true') return true;
|
||||
if (lowerCaseValue === 'false') return false;
|
||||
}
|
||||
|
||||
return false; // default to false for any other string or non-boolean type
|
||||
},
|
||||
parseValue(raw) {
|
||||
try {
|
||||
const json = JSON.parse(raw);
|
||||
|
||||
this.parseError = null;
|
||||
|
||||
return Object.entries(json).map(([key, value]) => ({
|
||||
key,
|
||||
value: this._convertToBoolean(value),
|
||||
}));
|
||||
} catch (e) {
|
||||
console.error('[CSIOnlineExpandValidation] JSON Parsing Error:', raw, e); // eslint-disable-line no-console
|
||||
this.parseError = this.t(
|
||||
'harvester.setting.csiOnlineExpandValidation.invalidJsonFormat',
|
||||
{ error: e.message },
|
||||
true
|
||||
);
|
||||
|
||||
return [];
|
||||
}
|
||||
},
|
||||
|
||||
stringifyConfig() {
|
||||
const obj = {};
|
||||
|
||||
this.configArr.forEach(({ key, value }) => {
|
||||
obj[key] = value;
|
||||
});
|
||||
|
||||
return this.configArr.length ? JSON.stringify(obj) : '';
|
||||
},
|
||||
|
||||
update() {
|
||||
this.value.value = this.stringifyConfig();
|
||||
},
|
||||
|
||||
willSave() {
|
||||
const errors = [];
|
||||
|
||||
this.configArr.forEach(({ key }) => {
|
||||
if (!key) {
|
||||
errors.push(
|
||||
this.t('validation.required', { key: this.t('harvester.setting.csiOnlineExpandValidation.provisioner') }, true)
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
this.value.value = this.stringifyConfig();
|
||||
|
||||
return errors.length ? Promise.reject(errors) : Promise.resolve();
|
||||
},
|
||||
|
||||
useDefault() {
|
||||
this.configArr = this.parseValue(this.value.default || '{}');
|
||||
this.update();
|
||||
},
|
||||
|
||||
disableEdit(driverKey) {
|
||||
return this.fetchError || driverKey === LONGHORN_DRIVER;
|
||||
},
|
||||
|
||||
add() {
|
||||
if (this.disableConfigEditing) return;
|
||||
|
||||
this.configArr.push({ key: '', value: true });
|
||||
},
|
||||
|
||||
remove(index) {
|
||||
if (this.disableConfigEditing) return;
|
||||
|
||||
this.configArr.splice(index, 1);
|
||||
this.update();
|
||||
},
|
||||
|
||||
onValueChange(idx, newVal) {
|
||||
if (this.disableConfigEditing) return;
|
||||
|
||||
const val = newVal === 'true' ? true : newVal === 'false' ? false : newVal;
|
||||
|
||||
this.configArr[idx].value = val;
|
||||
this.update();
|
||||
},
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<Banner
|
||||
v-for="(errorMsg, index) in allErrors"
|
||||
:key="index"
|
||||
color="error"
|
||||
>
|
||||
{{ errorMsg }}
|
||||
</Banner>
|
||||
<InfoBox
|
||||
v-for="(driver, idx) in configArr"
|
||||
:key="idx"
|
||||
class="box"
|
||||
>
|
||||
<button
|
||||
class="role-link btn btn-sm remove"
|
||||
type="button"
|
||||
:disabled="disableEdit(driver.key)"
|
||||
@click="remove(idx)"
|
||||
>
|
||||
<i class="icon icon-x" />
|
||||
</button>
|
||||
|
||||
<div class="row">
|
||||
<div class="col span-4">
|
||||
<LabeledSelect
|
||||
v-model:value="driver.key"
|
||||
label-key="harvester.setting.csiOnlineExpandValidation.provisioner"
|
||||
required
|
||||
searchable
|
||||
:mode="mode"
|
||||
:disabled="disableEdit(driver.key)"
|
||||
:options="provisioners"
|
||||
@update:value="update"
|
||||
@keydown.native.enter.prevent
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="col span-4">
|
||||
<LabeledSelect
|
||||
v-model:value="driver.value"
|
||||
:value="driver.value.toString()"
|
||||
label-key="harvester.setting.csiOnlineExpandValidation.value"
|
||||
required
|
||||
searchable
|
||||
:mode="mode"
|
||||
:disabled="disableEdit(driver.key)"
|
||||
:options="provisionerValue"
|
||||
@update:value="val => onValueChange(idx, val)"
|
||||
@keydown.native.enter.prevent
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</InfoBox>
|
||||
|
||||
<button
|
||||
class="btn btn-sm role-primary"
|
||||
:disabled="disableAdd"
|
||||
@click="add"
|
||||
>
|
||||
{{ t('generic.add') }}
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.box {
|
||||
position: relative;
|
||||
padding-top: 40px;
|
||||
}
|
||||
.remove {
|
||||
position: absolute;
|
||||
top: 10px;
|
||||
right: 10px;
|
||||
padding: 0;
|
||||
}
|
||||
</style>
|
||||
@@ -1,104 +0,0 @@
|
||||
<script>
|
||||
import UnitInput from '@shell/components/form/UnitInput';
|
||||
import { Banner } from '@components/Banner';
|
||||
|
||||
export default {
|
||||
name: 'HarvesterInstanceManagerResources',
|
||||
|
||||
components: {
|
||||
UnitInput,
|
||||
Banner,
|
||||
},
|
||||
|
||||
props: {
|
||||
value: {
|
||||
type: Object,
|
||||
default: () => ({
|
||||
value: '',
|
||||
default: '{}'
|
||||
})
|
||||
},
|
||||
},
|
||||
|
||||
data() {
|
||||
const resources = this.parseJSON(this.value?.value) || this.parseJSON(this.value?.default) || {};
|
||||
|
||||
return {
|
||||
resources,
|
||||
parseError: null,
|
||||
};
|
||||
},
|
||||
|
||||
methods: {
|
||||
parseJSON(string) {
|
||||
try {
|
||||
return JSON.parse(string);
|
||||
} catch (e) {
|
||||
this.parseError = this.t('harvester.setting.instanceManagerResources.parseError', { error: e.message });
|
||||
|
||||
return null;
|
||||
}
|
||||
},
|
||||
|
||||
update() {
|
||||
if (!this.value) return;
|
||||
|
||||
const cpu = { ...this.resources?.cpu };
|
||||
|
||||
if (cpu.v1 !== null && cpu.v1 !== undefined) cpu.v1 = String(cpu.v1);
|
||||
if (cpu.v2 !== null && cpu.v2 !== undefined) cpu.v2 = String(cpu.v2);
|
||||
|
||||
this.value.value = JSON.stringify({ ...this.resources, cpu });
|
||||
},
|
||||
|
||||
useDefault() {
|
||||
if (this.value?.default) {
|
||||
this.resources = this.parseJSON(this.value.default) || {};
|
||||
this.update();
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<Banner
|
||||
v-if="parseError"
|
||||
color="error"
|
||||
>
|
||||
{{ parseError }}
|
||||
</Banner>
|
||||
|
||||
<div class="row">
|
||||
<div class="col span-12">
|
||||
<UnitInput
|
||||
v-model:value="resources.cpu.v1"
|
||||
:label="t('harvester.setting.instanceManagerResources.v1')"
|
||||
suffix="%"
|
||||
:delay="0"
|
||||
type="number"
|
||||
min="0"
|
||||
max="100"
|
||||
required
|
||||
:mode="mode"
|
||||
class="mb-20"
|
||||
@update:value="update"
|
||||
/>
|
||||
<UnitInput
|
||||
v-model:value="resources.cpu.v2"
|
||||
:label="t('harvester.setting.instanceManagerResources.v2')"
|
||||
suffix="%"
|
||||
:delay="0"
|
||||
type="number"
|
||||
min="0"
|
||||
max="100"
|
||||
required
|
||||
:mode="mode"
|
||||
class="mb-20"
|
||||
@update:value="update"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,154 +0,0 @@
|
||||
<script>
|
||||
import { LabeledInput } from '@components/Form/LabeledInput';
|
||||
import { RadioGroup } from '@components/Form/Radio';
|
||||
import UnitInput from '@shell/components/form/UnitInput';
|
||||
import { MEBIBYTE } from '../../utils/unit';
|
||||
import { Banner } from '@components/Banner';
|
||||
|
||||
export default {
|
||||
name: 'KubevirtMigration',
|
||||
|
||||
components: {
|
||||
LabeledInput,
|
||||
UnitInput,
|
||||
RadioGroup,
|
||||
Banner
|
||||
},
|
||||
|
||||
props: {
|
||||
registerBeforeHook: {
|
||||
type: Function,
|
||||
required: true
|
||||
},
|
||||
value: {
|
||||
type: Object,
|
||||
default: () => ({
|
||||
value: '',
|
||||
default: '{}'
|
||||
})
|
||||
},
|
||||
},
|
||||
|
||||
data() {
|
||||
const migration = this.parseJSON(this.value?.value) || this.parseJSON(this.value?.default) || {};
|
||||
|
||||
return {
|
||||
MEBIBYTE,
|
||||
migration,
|
||||
parseError: null,
|
||||
};
|
||||
},
|
||||
|
||||
created() {
|
||||
this.registerBeforeHook?.(this.willSave, 'willSave');
|
||||
},
|
||||
|
||||
methods: {
|
||||
parseJSON(string) {
|
||||
try {
|
||||
return JSON.parse(string);
|
||||
} catch (e) {
|
||||
this.parseError = this.t('kubevirtMigration.parseError', { error: e.message });
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('Failed to parse JSON:', e.message);
|
||||
|
||||
return null;
|
||||
}
|
||||
},
|
||||
|
||||
updateValue() {
|
||||
if (this.value) {
|
||||
this.value.value = JSON.stringify(this.migration);
|
||||
}
|
||||
},
|
||||
|
||||
useDefault() {
|
||||
if (this.value?.default) {
|
||||
const defaultMigration = this.parseJSON(this.value.default) || {};
|
||||
|
||||
this.migration = defaultMigration;
|
||||
this.updateValue();
|
||||
}
|
||||
},
|
||||
|
||||
async willSave() {
|
||||
this.updateValue();
|
||||
|
||||
return Promise.resolve();
|
||||
},
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<Banner
|
||||
v-if="parseError"
|
||||
color="error"
|
||||
>
|
||||
{{ parseError }}
|
||||
</Banner>
|
||||
|
||||
<div class="migration-field">
|
||||
<LabeledInput
|
||||
v-model:value.number="migration.parallelMigrationsPerCluster"
|
||||
:label="t('harvester.setting.kubevirtMigration.parallelMigrationsPerCluster')"
|
||||
type="number"
|
||||
min="1"
|
||||
/>
|
||||
<LabeledInput
|
||||
v-model:value.number="migration.parallelOutboundMigrationsPerNode"
|
||||
:label="t('harvester.setting.kubevirtMigration.parallelOutboundMigrationsPerNode')"
|
||||
type="number"
|
||||
min="1"
|
||||
/>
|
||||
<UnitInput
|
||||
v-model:value="migration.bandwidthPerMigration"
|
||||
min="0"
|
||||
:label="t('harvester.setting.kubevirtMigration.bandwidthPerMigration')"
|
||||
:mode="mode"
|
||||
:suffix="MEBIBYTE"
|
||||
:tooltip="t('harvester.setting.kubevirtMigration.bandwidthPerMigrationTooltip', _, true)"
|
||||
/>
|
||||
<UnitInput
|
||||
v-model:value="migration.completionTimeoutPerGiB"
|
||||
:label="t('harvester.setting.kubevirtMigration.completionTimeoutPerGiB')"
|
||||
:mode="mode"
|
||||
:suffix="migration.completionTimeoutPerGiB === 1 ? 'Second' : 'Seconds'"
|
||||
min="10"
|
||||
/>
|
||||
<UnitInput
|
||||
v-model:value="migration.progressTimeout"
|
||||
:label="t('harvester.setting.kubevirtMigration.progressTimeout')"
|
||||
:mode="mode"
|
||||
:suffix="migration.progressTimeout === 1 ? 'Second' : 'Seconds'"
|
||||
min="10"
|
||||
/>
|
||||
<div
|
||||
v-for="field in ['allowAutoConverge','allowPostCopy','unsafeMigrationOverride','allowWorkloadDisruption','disableTLS','matchSELinuxLevelOnMigration']"
|
||||
:key="field"
|
||||
>
|
||||
<label
|
||||
class="mb-5"
|
||||
:for="field"
|
||||
>{{ t(`harvester.setting.kubevirtMigration.${field}`) }}</label>
|
||||
<RadioGroup
|
||||
:id="field"
|
||||
v-model:value="migration[field]"
|
||||
:options="[
|
||||
{ label: t('advancedSettings.edit.trueOption'), value: true },
|
||||
{ label: t('advancedSettings.edit.falseOption'), value: false },
|
||||
]"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.migration-field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
</style>
|
||||
@@ -1,221 +0,0 @@
|
||||
<script>
|
||||
import CreateEditView from '@shell/mixins/create-edit-view';
|
||||
import { RadioGroup } from '@components/Form/Radio';
|
||||
import { SECRET } from '@shell/config/types';
|
||||
import { exceptionToErrorsArray } from '@shell/utils/error';
|
||||
import FileSelector, { createOnSelected } from '@shell/components/form/FileSelector';
|
||||
import YamlEditor from '@shell/components/YamlEditor';
|
||||
|
||||
export default {
|
||||
name: 'HarvesterRancherCluster',
|
||||
|
||||
components: {
|
||||
RadioGroup,
|
||||
FileSelector,
|
||||
YamlEditor
|
||||
},
|
||||
|
||||
mixins: [CreateEditView],
|
||||
|
||||
props: {
|
||||
value: {
|
||||
type: Object,
|
||||
default: () => ({}),
|
||||
},
|
||||
registerBeforeHook: {
|
||||
type: Function,
|
||||
required: false,
|
||||
default: () => {},
|
||||
},
|
||||
},
|
||||
|
||||
data() {
|
||||
let parseDefaultValue = {};
|
||||
|
||||
try {
|
||||
const data = this.value.value || this.value.default || '{}';
|
||||
const parsed = JSON.parse(data);
|
||||
|
||||
parseDefaultValue = {
|
||||
kubeConfig: '',
|
||||
removeUpstreamClusterWhenNamespaceIsDeleted: parsed.removeUpstreamClusterWhenNamespaceIsDeleted || false
|
||||
};
|
||||
} catch (error) {
|
||||
parseDefaultValue = {
|
||||
kubeConfig: '',
|
||||
removeUpstreamClusterWhenNamespaceIsDeleted: false
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
parseDefaultValue,
|
||||
errors: [],
|
||||
existingSecret: null,
|
||||
};
|
||||
},
|
||||
|
||||
async created() {
|
||||
await this.checkExistingSecret();
|
||||
if (this.registerBeforeHook) {
|
||||
this.registerBeforeHook(this.willSave, 'willSave');
|
||||
}
|
||||
},
|
||||
|
||||
methods: {
|
||||
onKeySelected: createOnSelected('parseDefaultValue.kubeConfig'),
|
||||
|
||||
update() {
|
||||
if (this.parseDefaultValue.removeUpstreamClusterWhenNamespaceIsDeleted) {
|
||||
this.value['value'] = JSON.stringify({ removeUpstreamClusterWhenNamespaceIsDeleted: true });
|
||||
} else {
|
||||
this.value['value'] = this.value.default || '{}';
|
||||
}
|
||||
},
|
||||
|
||||
async checkExistingSecret() {
|
||||
const inStore = this.$store.getters['currentProduct'].inStore;
|
||||
|
||||
await this.$store.dispatch(`${ inStore }/findAll`, { type: SECRET });
|
||||
const secrets = this.$store.getters[`${ inStore }/all`](SECRET) || [];
|
||||
|
||||
this.existingSecret = secrets.find((secret) => secret.metadata.name === 'rancher-cluster-config' &&
|
||||
secret.metadata.namespace === 'harvester-system'
|
||||
);
|
||||
|
||||
// If the secret exists and has data, populate the kubeConfig
|
||||
if (this.existingSecret?.data?.kubeConfig) {
|
||||
const decodedContent = atob(this.existingSecret.data.kubeConfig);
|
||||
|
||||
this.parseDefaultValue.kubeConfig = decodedContent;
|
||||
this.$nextTick(() => {
|
||||
this.update();
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
async createOrUpdateRancherKubeConfigSecret() {
|
||||
this.errors = [];
|
||||
// Check if kubeConfig is provided
|
||||
if (!this.parseDefaultValue.kubeConfig) {
|
||||
this.errors.push(this.t('validation.required', { key: this.t('harvester.setting.rancherCluster.kubeConfig') }, true));
|
||||
|
||||
return Promise.reject(this.errors);
|
||||
}
|
||||
|
||||
try {
|
||||
let secret;
|
||||
|
||||
if (this.existingSecret) {
|
||||
secret = this.existingSecret;
|
||||
secret.setData('kubeConfig', this.parseDefaultValue.kubeConfig);
|
||||
} else {
|
||||
const inStore = this.$store.getters['currentProduct'].inStore;
|
||||
|
||||
secret = await this.$store.dispatch(`${ inStore }/create`, {
|
||||
apiVersion: 'v1',
|
||||
kind: 'Secret',
|
||||
metadata: {
|
||||
name: 'rancher-cluster-config',
|
||||
namespace: 'harvester-system'
|
||||
},
|
||||
type: 'secret',
|
||||
data: { kubeConfig: btoa(this.parseDefaultValue.kubeConfig) }
|
||||
});
|
||||
}
|
||||
await secret.save();
|
||||
|
||||
return Promise.resolve();
|
||||
} catch (err) {
|
||||
this.errors = exceptionToErrorsArray(err);
|
||||
|
||||
return Promise.reject(this.errors);
|
||||
}
|
||||
},
|
||||
|
||||
async deleteRancherKubeConfigSecret() {
|
||||
if (this.existingSecret) {
|
||||
this.existingSecret.remove();
|
||||
}
|
||||
},
|
||||
|
||||
async willSave() {
|
||||
// Only create or update secret if enabled
|
||||
if (this.parseDefaultValue.removeUpstreamClusterWhenNamespaceIsDeleted) {
|
||||
await this.createOrUpdateRancherKubeConfigSecret();
|
||||
} else {
|
||||
await this.deleteRancherKubeConfigSecret();
|
||||
}
|
||||
|
||||
return Promise.resolve();
|
||||
},
|
||||
|
||||
useDefault() {
|
||||
this.parseDefaultValue = {
|
||||
kubeConfig: '',
|
||||
removeUpstreamClusterWhenNamespaceIsDeleted: false
|
||||
};
|
||||
}
|
||||
},
|
||||
|
||||
watch: {
|
||||
'parseDefaultValue.removeUpstreamClusterWhenNamespaceIsDeleted'(val, oldVal) {
|
||||
if (val && !oldVal && this.existingSecret?.data?.kubeConfig) {
|
||||
// Populate kubeConfig with the existing secret value
|
||||
this.parseDefaultValue.kubeConfig = atob(this.existingSecret.data.kubeConfig);
|
||||
}
|
||||
},
|
||||
'parseDefaultValue.kubeConfig'(val) {
|
||||
this.$refs.yaml?.updateValue(val);
|
||||
}
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<div class="row mt-20">
|
||||
<div class="col span-12">
|
||||
<RadioGroup
|
||||
v-model:value="parseDefaultValue.removeUpstreamClusterWhenNamespaceIsDeleted"
|
||||
:label="t('harvester.setting.rancherCluster.removeUpstreamClusterWhenNamespaceIsDeleted')"
|
||||
name="removeUpstreamClusterWhenNamespaceIsDeleted"
|
||||
:options="[true, false]"
|
||||
:labels="[t('generic.enabled'), t('generic.disabled')]"
|
||||
@update:value="update"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
v-if="parseDefaultValue.removeUpstreamClusterWhenNamespaceIsDeleted"
|
||||
class="row mt-20"
|
||||
>
|
||||
<div class="col span-12">
|
||||
<FileSelector
|
||||
variant="primary"
|
||||
class="mb-10"
|
||||
:label="t('generic.readFromFile')"
|
||||
@selected="onKeySelected"
|
||||
/>
|
||||
<YamlEditor
|
||||
ref="yaml"
|
||||
v-model:value="parseDefaultValue.kubeConfig"
|
||||
class="yaml-editor"
|
||||
:editor-mode="mode === 'view' ? 'VIEW_CODE' : 'EDIT_CODE'"
|
||||
@update:value="update"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
$yaml-height: 540px;
|
||||
|
||||
:deep() .yaml-editor{
|
||||
flex: 1;
|
||||
min-height: $yaml-height;
|
||||
& .code-mirror .cm-editor {
|
||||
min-height: $yaml-height;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,371 +0,0 @@
|
||||
<script>
|
||||
import { LabeledInput } from '@components/Form/LabeledInput';
|
||||
import LabeledSelect from '@shell/components/form/LabeledSelect.vue';
|
||||
import { RadioGroup } from '@components/Form/Radio';
|
||||
import ArrayList from '@shell/components/form/ArrayList';
|
||||
import { isValidCIDR } from '@pkg/harvester/utils/regular';
|
||||
import { _EDIT } from '@shell/config/query-params';
|
||||
import { Banner } from '@components/Banner';
|
||||
import { allHash } from '@shell/utils/promise';
|
||||
import { HCI } from '../../types';
|
||||
import { NETWORK_TYPE } from '../../config/types';
|
||||
|
||||
const { L2VLAN, UNTAGGED } = NETWORK_TYPE;
|
||||
const SHARE_STORAGE_NETWORK = 'share-storage-network';
|
||||
const NETWORK = 'network';
|
||||
|
||||
const DEFAULT_DEDICATED_NETWORK = {
|
||||
vlan: '',
|
||||
clusterNetwork: '',
|
||||
range: '',
|
||||
exclude: [],
|
||||
};
|
||||
|
||||
export default {
|
||||
name: 'RwxNetworkSetting',
|
||||
|
||||
components: {
|
||||
RadioGroup,
|
||||
Banner,
|
||||
ArrayList,
|
||||
LabeledInput,
|
||||
LabeledSelect,
|
||||
},
|
||||
|
||||
props: {
|
||||
registerBeforeHook: {
|
||||
type: Function,
|
||||
required: true,
|
||||
},
|
||||
|
||||
mode: {
|
||||
type: String,
|
||||
default: _EDIT,
|
||||
},
|
||||
|
||||
value: {
|
||||
type: Object,
|
||||
default: () => {
|
||||
return {};
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
async fetch() {
|
||||
const inStore = this.$store.getters['currentProduct'].inStore;
|
||||
|
||||
await allHash({
|
||||
clusterNetworks: this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.CLUSTER_NETWORK }),
|
||||
vlanStatus: this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.VLAN_STATUS }),
|
||||
});
|
||||
},
|
||||
|
||||
data() {
|
||||
let enabled = false; // enabled / disabled options
|
||||
let shareStorageNetwork = false; // shareStorageNetwork / dedicatedRwxNetwork options
|
||||
let dedicatedNetwork = { ...DEFAULT_DEDICATED_NETWORK };
|
||||
let networkType = L2VLAN;
|
||||
let exclude = [];
|
||||
|
||||
try {
|
||||
const parsedValue = JSON.parse(this.value.value || this.value.default || '{}');
|
||||
const parsedNetwork = parsedValue?.[NETWORK] || parsedValue || {};
|
||||
|
||||
if (parsedValue && typeof parsedValue === 'object') {
|
||||
shareStorageNetwork = !!parsedValue[SHARE_STORAGE_NETWORK];
|
||||
networkType = 'vlan' in parsedNetwork ? L2VLAN : UNTAGGED;
|
||||
dedicatedNetwork = {
|
||||
vlan: parsedNetwork.vlan || '',
|
||||
clusterNetwork: parsedNetwork.clusterNetwork || '',
|
||||
range: parsedNetwork.range || '',
|
||||
};
|
||||
exclude = parsedNetwork?.exclude?.toString().split(',') || [];
|
||||
enabled = shareStorageNetwork || !!(parsedNetwork.vlan || parsedNetwork.clusterNetwork || parsedNetwork.range);
|
||||
}
|
||||
} catch (error) {
|
||||
enabled = false;
|
||||
shareStorageNetwork = false;
|
||||
dedicatedNetwork = { ...DEFAULT_DEDICATED_NETWORK };
|
||||
}
|
||||
|
||||
return {
|
||||
enabled,
|
||||
shareStorageNetwork,
|
||||
dedicatedNetwork,
|
||||
networkType,
|
||||
exclude,
|
||||
defaultAddValue: '',
|
||||
};
|
||||
},
|
||||
|
||||
created() {
|
||||
if (this.registerBeforeHook) {
|
||||
this.registerBeforeHook(this.willSave, 'willSave');
|
||||
}
|
||||
},
|
||||
|
||||
computed: {
|
||||
showDedicatedNetworkConfig() {
|
||||
return this.enabled && !this.shareStorageNetwork;
|
||||
},
|
||||
|
||||
showVlan() {
|
||||
return this.networkType === L2VLAN;
|
||||
},
|
||||
|
||||
networkTypes() {
|
||||
return [L2VLAN, UNTAGGED];
|
||||
},
|
||||
|
||||
clusterNetworkOptions() {
|
||||
const inStore = this.$store.getters['currentProduct'].inStore;
|
||||
const clusterNetworks = this.$store.getters[`${ inStore }/all`](HCI.CLUSTER_NETWORK) || [];
|
||||
const clusterNetworksOptions = this.networkType === UNTAGGED ? clusterNetworks.filter((network) => network.id !== 'mgmt') : clusterNetworks;
|
||||
|
||||
return clusterNetworksOptions.map((network) => {
|
||||
const disabled = !network.isReadyForStorageNetwork;
|
||||
|
||||
return {
|
||||
label: disabled ? `${ network.id } (${ this.t('generic.notReady') })` : network.id,
|
||||
value: network.id,
|
||||
disabled,
|
||||
};
|
||||
});
|
||||
},
|
||||
},
|
||||
|
||||
methods: {
|
||||
onUpdateEnabled() {
|
||||
if (!this.enabled) {
|
||||
this.shareStorageNetwork = false;
|
||||
this.dedicatedNetwork = { ...DEFAULT_DEDICATED_NETWORK };
|
||||
}
|
||||
|
||||
this.update();
|
||||
},
|
||||
|
||||
onUpdateNetworkType() {
|
||||
if (this.shareStorageNetwork) {
|
||||
this.dedicatedNetwork = { ...DEFAULT_DEDICATED_NETWORK };
|
||||
}
|
||||
|
||||
this.update();
|
||||
},
|
||||
|
||||
onUpdateDedicatedType(neu) {
|
||||
this.dedicatedNetwork.clusterNetwork = '';
|
||||
|
||||
if (neu === L2VLAN) {
|
||||
this.dedicatedNetwork.vlan = '';
|
||||
} else {
|
||||
delete this.dedicatedNetwork.vlan;
|
||||
}
|
||||
|
||||
this.update();
|
||||
},
|
||||
|
||||
inputVlan(neu) {
|
||||
if (neu === '') {
|
||||
this.dedicatedNetwork.vlan = '';
|
||||
this.update();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const newValue = Number(neu);
|
||||
|
||||
if (newValue > 4094) {
|
||||
this.dedicatedNetwork.vlan = 4094;
|
||||
} else if (newValue < 1) {
|
||||
this.dedicatedNetwork.vlan = 1;
|
||||
} else {
|
||||
this.dedicatedNetwork.vlan = newValue;
|
||||
}
|
||||
|
||||
this.update();
|
||||
},
|
||||
|
||||
useDefault() {
|
||||
this.enabled = false;
|
||||
this.shareStorageNetwork = false;
|
||||
this.dedicatedNetwork = { ...DEFAULT_DEDICATED_NETWORK };
|
||||
this.update();
|
||||
},
|
||||
|
||||
update() {
|
||||
const value = { [SHARE_STORAGE_NETWORK]: false };
|
||||
|
||||
if (this.enabled && this.shareStorageNetwork) {
|
||||
value[SHARE_STORAGE_NETWORK] = true;
|
||||
}
|
||||
|
||||
if (this.showDedicatedNetworkConfig) {
|
||||
value[NETWORK] = {};
|
||||
|
||||
if (this.showVlan) {
|
||||
value[NETWORK].vlan = this.dedicatedNetwork.vlan;
|
||||
}
|
||||
|
||||
value[NETWORK].clusterNetwork = this.dedicatedNetwork.clusterNetwork;
|
||||
value[NETWORK].range = this.dedicatedNetwork.range;
|
||||
|
||||
const excludeList = this.exclude.filter((ip) => ip);
|
||||
|
||||
if (Array.isArray(excludeList) && excludeList.length > 0) {
|
||||
value[NETWORK].exclude = excludeList;
|
||||
}
|
||||
}
|
||||
|
||||
this.value.value = JSON.stringify(value);
|
||||
},
|
||||
|
||||
willSave() {
|
||||
this.update();
|
||||
|
||||
if (!this.showDedicatedNetworkConfig) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
const errors = [];
|
||||
|
||||
if (this.showVlan && !this.dedicatedNetwork.vlan) {
|
||||
errors.push(this.t('validation.required', { key: this.t('harvester.setting.storageNetwork.vlan') }, true));
|
||||
}
|
||||
|
||||
if (!this.dedicatedNetwork.clusterNetwork) {
|
||||
errors.push(this.t('validation.required', { key: this.t('harvester.setting.storageNetwork.clusterNetwork') }, true));
|
||||
}
|
||||
|
||||
if (!this.dedicatedNetwork.range) {
|
||||
errors.push(this.t('validation.required', { key: this.t('harvester.setting.storageNetwork.range.label') }, true));
|
||||
} else if (!isValidCIDR(this.dedicatedNetwork.range)) {
|
||||
errors.push(this.t('harvester.setting.storageNetwork.range.invalid', null, true));
|
||||
}
|
||||
|
||||
if (this.exclude) {
|
||||
const hasInvalidCIDR = this.exclude.find((cidr) => {
|
||||
return cidr && !isValidCIDR(cidr);
|
||||
});
|
||||
|
||||
if (hasInvalidCIDR) {
|
||||
errors.push(this.t('harvester.setting.storageNetwork.exclude.invalid', null, true));
|
||||
}
|
||||
}
|
||||
|
||||
if (errors.length > 0) {
|
||||
return Promise.reject(errors);
|
||||
}
|
||||
|
||||
return Promise.resolve();
|
||||
},
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div :class="mode">
|
||||
<Banner color="warning">
|
||||
<t
|
||||
k="harvester.setting.rwxNetwork.warning"
|
||||
:raw="true"
|
||||
/>
|
||||
</Banner>
|
||||
<RadioGroup
|
||||
v-model:value="enabled"
|
||||
class="mb-20"
|
||||
name="rwx-network-enable"
|
||||
:options="[true,false]"
|
||||
:labels="[t('generic.enabled'), t('generic.disabled')]"
|
||||
@update:value="onUpdateEnabled"
|
||||
/>
|
||||
|
||||
<RadioGroup
|
||||
v-if="enabled"
|
||||
v-model:value="shareStorageNetwork"
|
||||
class="mb-20"
|
||||
name="rwx-network-type"
|
||||
:options="[true,false]"
|
||||
:labels="[t('harvester.setting.rwxNetwork.shareStorageNetwork'), t('harvester.setting.rwxNetwork.dedicatedRwxNetwork')]"
|
||||
@update:value="onUpdateNetworkType"
|
||||
/>
|
||||
<Banner
|
||||
v-if="shareStorageNetwork"
|
||||
class="mb-20"
|
||||
color="warning"
|
||||
>
|
||||
<t
|
||||
k="harvester.setting.rwxNetwork.shareStorageNetworkWarning"
|
||||
:raw="true"
|
||||
/>
|
||||
</Banner>
|
||||
<template v-if="showDedicatedNetworkConfig">
|
||||
<LabeledSelect
|
||||
v-model:value="networkType"
|
||||
class="mb-20"
|
||||
:options="networkTypes"
|
||||
:mode="mode"
|
||||
:label="t('harvester.fields.type')"
|
||||
required
|
||||
@update:value="onUpdateDedicatedType"
|
||||
/>
|
||||
|
||||
<LabeledInput
|
||||
v-if="showVlan"
|
||||
v-model:value.number="dedicatedNetwork.vlan"
|
||||
type="number"
|
||||
class="mb-20"
|
||||
:mode="mode"
|
||||
required
|
||||
placeholder="e.g. 1 - 4094"
|
||||
label-key="harvester.setting.storageNetwork.vlan"
|
||||
@update:value="inputVlan"
|
||||
/>
|
||||
|
||||
<LabeledSelect
|
||||
v-model:value="dedicatedNetwork.clusterNetwork"
|
||||
label-key="harvester.setting.storageNetwork.clusterNetwork"
|
||||
class="mb-20"
|
||||
required
|
||||
:options="clusterNetworkOptions"
|
||||
@update:value="update"
|
||||
/>
|
||||
|
||||
<LabeledInput
|
||||
v-model:value="dedicatedNetwork.range"
|
||||
class="mb-5"
|
||||
:mode="mode"
|
||||
required
|
||||
:placeholder="t('harvester.setting.storageNetwork.range.placeholder')"
|
||||
label-key="harvester.setting.storageNetwork.range.label"
|
||||
@update:value="update"
|
||||
/>
|
||||
|
||||
<ArrayList
|
||||
v-model:value="exclude"
|
||||
:show-header="true"
|
||||
:default-add-value="defaultAddValue"
|
||||
:mode="mode"
|
||||
:add-label="t('harvester.setting.storageNetwork.exclude.addIp')"
|
||||
class="mt-20"
|
||||
@update:value="update"
|
||||
>
|
||||
<template #column-headers>
|
||||
<div class="box mb-10">
|
||||
<div class="key">
|
||||
{{ t('harvester.setting.storageNetwork.exclude.label') }}
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<template #columns="scope">
|
||||
<div class="key">
|
||||
<input
|
||||
v-model="scope.row.value"
|
||||
:placeholder="t('harvester.setting.storageNetwork.exclude.placeholder')"
|
||||
@update:value="update"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</ArrayList>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
@@ -62,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';
|
||||
@@ -64,9 +64,6 @@ export default {
|
||||
|
||||
try {
|
||||
parsedDefaultValue = JSON.parse(this.value.value);
|
||||
if (typeof parsedDefaultValue.exclusiveVlan !== 'boolean') {
|
||||
parsedDefaultValue.exclusiveVlan = false;
|
||||
}
|
||||
networkType = 'vlan' in parsedDefaultValue ? L2VLAN : UNTAGGED; // backend doesn't provide networkType, so we check if vlan is provided instead
|
||||
openVlan = true;
|
||||
} catch (error) {
|
||||
@@ -75,8 +72,7 @@ export default {
|
||||
vlan: '',
|
||||
clusterNetwork: '',
|
||||
range: '',
|
||||
exclude: [],
|
||||
exclusiveVlan: false
|
||||
exclude: []
|
||||
};
|
||||
}
|
||||
const exclude = parsedDefaultValue?.exclude?.toString().split(',') || [];
|
||||
@@ -98,10 +94,6 @@ export default {
|
||||
},
|
||||
|
||||
computed: {
|
||||
showExclusiveVlan() {
|
||||
return this.networkType === L2VLAN &&
|
||||
Number(this.parsedDefaultValue.vlan) !== 1;
|
||||
},
|
||||
showVlan() {
|
||||
return this.networkType === L2VLAN;
|
||||
},
|
||||
@@ -140,18 +132,6 @@ export default {
|
||||
};
|
||||
});
|
||||
},
|
||||
exclusiveVlanOptions() {
|
||||
return [
|
||||
{
|
||||
label: this.t('generic.enabled'),
|
||||
value: true
|
||||
},
|
||||
{
|
||||
label: this.t('generic.disabled'),
|
||||
value: false
|
||||
}
|
||||
];
|
||||
},
|
||||
},
|
||||
|
||||
watch: {
|
||||
@@ -194,8 +174,7 @@ export default {
|
||||
vlan: '',
|
||||
clusterNetwork: '',
|
||||
range: '',
|
||||
exclude: [],
|
||||
exclusiveVlan: false
|
||||
exclude: []
|
||||
};
|
||||
},
|
||||
|
||||
@@ -301,15 +280,7 @@ export default {
|
||||
label-key="harvester.setting.storageNetwork.vlan"
|
||||
@update:value="inputVlan"
|
||||
/>
|
||||
<LabeledSelect
|
||||
v-if="showExclusiveVlan"
|
||||
v-model:value="parsedDefaultValue.exclusiveVlan"
|
||||
class="mb-20"
|
||||
:options="exclusiveVlanOptions"
|
||||
:mode="mode"
|
||||
label-key="harvester.setting.storageNetwork.exclusiveVlan"
|
||||
@update:value="update"
|
||||
/>
|
||||
|
||||
<LabeledSelect
|
||||
v-model:value="parsedDefaultValue.clusterNetwork"
|
||||
label-key="harvester.setting.storageNetwork.clusterNetwork"
|
||||
|
||||
@@ -3,9 +3,6 @@ import { NAMESPACE } from '@shell/config/types';
|
||||
import CreateEditView from '@shell/mixins/create-edit-view';
|
||||
import LabeledSelect from '@shell/components/form/LabeledSelect';
|
||||
|
||||
const SELECT_ALL = 'select_all';
|
||||
const UNSELECT_ALL = 'unselect_all';
|
||||
|
||||
export default {
|
||||
name: 'HarvesterBundleNamespaces',
|
||||
|
||||
@@ -14,92 +11,47 @@ export default {
|
||||
mixins: [CreateEditView],
|
||||
|
||||
async fetch() {
|
||||
this.loading = true;
|
||||
|
||||
await this.$store.dispatch('harvester/findAll', { type: NAMESPACE });
|
||||
|
||||
if (this.customSupportBundleFeatureEnabled) {
|
||||
try {
|
||||
const url = this.$store.getters['harvester-common/getHarvesterClusterUrl']('v1/harvester/namespaces?link=supportbundle');
|
||||
const response = await this.$store.dispatch('harvester/request', { url });
|
||||
|
||||
this.defaultNamespaces = response.data || [];
|
||||
} catch (error) {
|
||||
this.defaultNamespaces = [];
|
||||
}
|
||||
} else {
|
||||
this.defaultNamespaces = [];
|
||||
}
|
||||
|
||||
this.loading = false;
|
||||
},
|
||||
|
||||
data() {
|
||||
let namespaces = [];
|
||||
const namespacesStr = this.value?.value || this.value?.default || '';
|
||||
const namespaces = namespacesStr ? namespacesStr.split(',') : [];
|
||||
|
||||
return {
|
||||
namespaces,
|
||||
defaultNamespaces: [],
|
||||
loading: true
|
||||
};
|
||||
if (namespacesStr) {
|
||||
namespaces = namespacesStr.split(',');
|
||||
}
|
||||
|
||||
return { namespaces };
|
||||
},
|
||||
|
||||
computed: {
|
||||
customSupportBundleFeatureEnabled() {
|
||||
return this.$store.getters['harvester-common/getFeatureEnabled']('customSupportBundle');
|
||||
},
|
||||
|
||||
allNamespaces() {
|
||||
return this.$store.getters['harvester/all'](NAMESPACE).map((ns) => ns.id);
|
||||
},
|
||||
|
||||
filteredNamespaces() {
|
||||
if (!this.customSupportBundleFeatureEnabled) {
|
||||
return this.allNamespaces;
|
||||
}
|
||||
|
||||
const defaultIds = this.defaultNamespaces.map((ns) => ns.id);
|
||||
|
||||
return this.allNamespaces.filter((ns) => !defaultIds.includes(ns));
|
||||
},
|
||||
|
||||
namespaceOptions() {
|
||||
const mappedNamespaces = this.filteredNamespaces.map((ns) => ({ label: ns, value: ns }));
|
||||
|
||||
if (!this.customSupportBundleFeatureEnabled) {
|
||||
return mappedNamespaces;
|
||||
}
|
||||
|
||||
const allSelected =
|
||||
this.namespaces.length === this.filteredNamespaces.length &&
|
||||
this.filteredNamespaces.every((ns) => this.namespaces.includes(ns));
|
||||
|
||||
const controlOption = allSelected ? { label: this.t('harvester.modal.bundle.namespaces.unselectAll'), value: UNSELECT_ALL } : { label: this.t('harvester.modal.bundle.namespaces.selectAll'), value: SELECT_ALL };
|
||||
|
||||
return [controlOption, ...mappedNamespaces];
|
||||
return this.$store.getters['harvester/all'](NAMESPACE).map((N) => {
|
||||
return {
|
||||
label: N.id,
|
||||
value: N.id
|
||||
};
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
methods: {
|
||||
update(selected) {
|
||||
if (selected.includes(SELECT_ALL)) {
|
||||
this.namespaces = [...this.filteredNamespaces];
|
||||
} else if (selected.includes(UNSELECT_ALL)) {
|
||||
this.namespaces = [];
|
||||
} else {
|
||||
this.namespaces = selected.filter((val) => val !== SELECT_ALL && val !== UNSELECT_ALL);
|
||||
}
|
||||
update() {
|
||||
const namespaceStr = this.namespaces.join(',');
|
||||
|
||||
this.value.value = this.namespaces.join(',');
|
||||
this.value['value'] = namespaceStr;
|
||||
}
|
||||
},
|
||||
|
||||
watch: {
|
||||
'value.value'(newVal) {
|
||||
const raw = newVal || this.value.default || '';
|
||||
|
||||
this.namespaces = raw ? raw.split(',') : [];
|
||||
'value.value': {
|
||||
handler(neu) {
|
||||
if (neu === this.value.default || !neu) {
|
||||
this.namespaces = [];
|
||||
}
|
||||
},
|
||||
deep: true
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -110,7 +62,6 @@ export default {
|
||||
<div class="col span-12">
|
||||
<LabeledSelect
|
||||
v-model:value="namespaces"
|
||||
:loading="loading"
|
||||
:multiple="true"
|
||||
label-key="nameNsDescription.namespace.label"
|
||||
:mode="mode"
|
||||
|
||||
@@ -1,224 +0,0 @@
|
||||
<script>
|
||||
import CreateEditView from '@shell/mixins/create-edit-view';
|
||||
import { LabeledInput } from '@components/Form/LabeledInput';
|
||||
import LabeledSelect from '@shell/components/form/LabeledSelect';
|
||||
import { RadioGroup } from '@components/Form/Radio';
|
||||
import { mapGetters } from 'vuex';
|
||||
import { allHash } from '@shell/utils/promise';
|
||||
import { NODE } from '@shell/config/types';
|
||||
|
||||
export default {
|
||||
name: 'HarvesterUpgradeConfig',
|
||||
|
||||
components: {
|
||||
LabeledInput,
|
||||
LabeledSelect,
|
||||
RadioGroup
|
||||
},
|
||||
mixins: [CreateEditView],
|
||||
|
||||
async fetch() {
|
||||
const inStore = this.$store.getters['currentProduct'].inStore;
|
||||
const hash = { nodes: this.$store.dispatch(`${ inStore }/findAll`, { type: NODE }) };
|
||||
|
||||
await allHash(hash);
|
||||
},
|
||||
|
||||
data() {
|
||||
let parseDefaultValue = {};
|
||||
|
||||
try {
|
||||
parseDefaultValue = this.value.value ? JSON.parse(this.value.value) : JSON.parse(this.value.default);
|
||||
} catch (error) {
|
||||
parseDefaultValue = JSON.parse(this.value.default);
|
||||
}
|
||||
parseDefaultValue = this.normalizeValue(parseDefaultValue);
|
||||
|
||||
return {
|
||||
parseDefaultValue,
|
||||
errors: []
|
||||
};
|
||||
},
|
||||
|
||||
computed: {
|
||||
...mapGetters({ t: 'i18n/t' }),
|
||||
strategyOptions() {
|
||||
return [
|
||||
{ value: 'sequential', label: 'sequential' },
|
||||
{ value: 'skip', label: 'skip' },
|
||||
{ value: 'parallel', label: 'parallel' }
|
||||
];
|
||||
},
|
||||
nodeUpgradeOptions() {
|
||||
return [
|
||||
{ value: 'auto', label: 'auto' },
|
||||
{ value: 'manual', label: 'manual' }
|
||||
];
|
||||
},
|
||||
nodesOptions() {
|
||||
const inStore = this.$store.getters['currentProduct'].inStore;
|
||||
const nodes = this.$store.getters[`${ inStore }/all`](NODE);
|
||||
|
||||
return nodes.map((node) => ({ value: node.id, label: node.name }));
|
||||
},
|
||||
showPauseNodes() {
|
||||
return this.parseDefaultValue.nodeUpgradeOption?.strategy?.mode === 'manual';
|
||||
},
|
||||
resumeUpgradePausedNodeEnabled() {
|
||||
return this.$store.getters['harvester-common/getFeatureEnabled']('resumeUpgradePausedNode');
|
||||
},
|
||||
},
|
||||
|
||||
created() {
|
||||
this.update();
|
||||
},
|
||||
|
||||
methods: {
|
||||
normalizeValue(obj) {
|
||||
// handle nodeUpgradeOption.strategy
|
||||
if (obj?.nodeUpgradeOption?.strategy?.mode === 'auto') {
|
||||
delete obj.nodeUpgradeOption.strategy.pauseNodes;
|
||||
}
|
||||
|
||||
if (obj?.nodeUpgradeOption?.strategy?.mode === 'manual') {
|
||||
if (!Array.isArray(obj.nodeUpgradeOption.strategy.pauseNodes)) {
|
||||
obj.nodeUpgradeOption.strategy.pauseNodes = this.nodesOptions.map((node) => node.value);
|
||||
}
|
||||
}
|
||||
|
||||
// handle imagePreloadOption.strategy
|
||||
if (!obj.imagePreloadOption) {
|
||||
obj.imagePreloadOption = { strategy: { type: 'sequential' } };
|
||||
}
|
||||
if (!obj.imagePreloadOption.strategy) {
|
||||
obj.imagePreloadOption.strategy = { type: 'sequential' };
|
||||
}
|
||||
if (!obj.imagePreloadOption.strategy.type) {
|
||||
obj.imagePreloadOption.strategy.type = 'sequential';
|
||||
}
|
||||
// Only set concurrency if type is 'parallel'
|
||||
if (obj.imagePreloadOption.strategy.type === 'parallel') {
|
||||
if (typeof obj.imagePreloadOption.strategy.concurrency !== 'number') {
|
||||
obj.imagePreloadOption.strategy.concurrency = 0;
|
||||
}
|
||||
} else {
|
||||
delete obj.imagePreloadOption.strategy.concurrency;
|
||||
}
|
||||
if (typeof obj.restoreVM !== 'boolean') {
|
||||
obj.restoreVM = false;
|
||||
}
|
||||
|
||||
return obj;
|
||||
},
|
||||
update() {
|
||||
try {
|
||||
// Clone to avoid mutating the form state
|
||||
const valueToSave = JSON.parse(JSON.stringify(this.parseDefaultValue));
|
||||
|
||||
if (valueToSave.imagePreloadOption && valueToSave.imagePreloadOption.strategy) {
|
||||
if (valueToSave.imagePreloadOption.strategy.type !== 'parallel') {
|
||||
delete valueToSave.imagePreloadOption.strategy.concurrency;
|
||||
}
|
||||
}
|
||||
|
||||
this.value['value'] = JSON.stringify(valueToSave, null, 2);
|
||||
this.errors = [];
|
||||
} catch (e) {
|
||||
this.errors = ['Invalid JSON'];
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
watch: {
|
||||
value: {
|
||||
handler(neu) {
|
||||
let parseDefaultValue;
|
||||
|
||||
try {
|
||||
parseDefaultValue = JSON.parse(neu.value);
|
||||
} catch (err) {
|
||||
parseDefaultValue = JSON.parse(this.value.default);
|
||||
}
|
||||
parseDefaultValue = this.normalizeValue(parseDefaultValue);
|
||||
this['parseDefaultValue'] = parseDefaultValue;
|
||||
this.update();
|
||||
},
|
||||
deep: true
|
||||
},
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<div
|
||||
class="row"
|
||||
@input="update"
|
||||
>
|
||||
<div class="col span-12">
|
||||
<label class="mb-5"><b>{{ t('harvester.setting.upgrade.imagePreloadStrategy') }}</b></label>
|
||||
<LabeledSelect
|
||||
v-model:value="parseDefaultValue.imagePreloadOption.strategy.type"
|
||||
class="mb-20"
|
||||
:mode="mode"
|
||||
:label="t('harvester.setting.upgrade.strategyType')"
|
||||
:options="strategyOptions"
|
||||
@update:value="update"
|
||||
/>
|
||||
<LabeledInput
|
||||
v-if="parseDefaultValue.imagePreloadOption.strategy.type === 'parallel'"
|
||||
v-model:value.number="parseDefaultValue.imagePreloadOption.strategy.concurrency"
|
||||
class="mb-20"
|
||||
:mode="mode"
|
||||
:label="t('harvester.setting.upgrade.concurrency')"
|
||||
min="0"
|
||||
type="number"
|
||||
/>
|
||||
<label class="mb-5"><b>{{ t('harvester.setting.upgrade.restoreVM') }}</b></label>
|
||||
<RadioGroup
|
||||
v-model:value="parseDefaultValue.restoreVM"
|
||||
class="mb-20"
|
||||
name="restoreVM"
|
||||
:options="[true, false]"
|
||||
:labels="[t('generic.enabled'), t('generic.disabled')]"
|
||||
@update:value="update"
|
||||
/>
|
||||
<div v-if="resumeUpgradePausedNodeEnabled">
|
||||
<label class="mb-5"><b>{{ t('harvester.setting.upgrade.nodeUpgradeOption') }}</b></label>
|
||||
<LabeledSelect
|
||||
v-model:value="parseDefaultValue.nodeUpgradeOption.strategy.mode"
|
||||
class="mb-20 label-select"
|
||||
:mode="mode"
|
||||
:label="t('harvester.setting.upgrade.strategy')"
|
||||
:options="nodeUpgradeOptions"
|
||||
@update:value="update"
|
||||
/>
|
||||
<LabeledSelect
|
||||
v-if="showPauseNodes"
|
||||
v-model:value="parseDefaultValue.nodeUpgradeOption.strategy.pauseNodes"
|
||||
class="mb-20 label-select"
|
||||
:clearable="true"
|
||||
:multiple="true"
|
||||
:mode="mode"
|
||||
:label="t('harvester.setting.upgrade.pauseNodes')"
|
||||
:options="nodesOptions"
|
||||
@update:value="update"
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
v-if="errors.length"
|
||||
class="error"
|
||||
>
|
||||
{{ errors[0] }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.error {
|
||||
color: #d9534f;
|
||||
margin-top: 5px;
|
||||
}
|
||||
</style>
|
||||
@@ -69,15 +69,6 @@ export default {
|
||||
:mode="mode"
|
||||
label-key="harvester.setting.vmForceDeletionPolicy.period"
|
||||
/>
|
||||
|
||||
<LabeledInput
|
||||
v-if="parseDefaultValue.enable"
|
||||
v-model:value.number="parseDefaultValue.vmMigrationTimeout"
|
||||
class="mb-20"
|
||||
type="number"
|
||||
:mode="mode"
|
||||
label-key="harvester.setting.vmForceDeletionPolicy.vmMigrationTimeout"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -1,270 +0,0 @@
|
||||
<script>
|
||||
import { LabeledInput } from '@components/Form/LabeledInput';
|
||||
import LabeledSelect from '@shell/components/form/LabeledSelect.vue';
|
||||
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 { NODE } from '@shell/config/types';
|
||||
import { _EDIT } from '@shell/config/query-params';
|
||||
import { HCI } from '../../types';
|
||||
|
||||
const DEFAULT_NETWORK = {
|
||||
clusterNetwork: '',
|
||||
vlan: '',
|
||||
range: '',
|
||||
exclude: [],
|
||||
};
|
||||
|
||||
export default {
|
||||
name: 'VMMigrationNetwork',
|
||||
|
||||
components: {
|
||||
LabeledInput,
|
||||
LabeledSelect,
|
||||
RadioGroup,
|
||||
Banner,
|
||||
ArrayList,
|
||||
},
|
||||
|
||||
props: {
|
||||
registerBeforeHook: {
|
||||
type: Function,
|
||||
required: true,
|
||||
},
|
||||
mode: {
|
||||
type: String,
|
||||
default: _EDIT,
|
||||
},
|
||||
value: {
|
||||
type: Object,
|
||||
default: () => ({ value: '' }),
|
||||
},
|
||||
},
|
||||
|
||||
async fetch() {
|
||||
const inStore = this.$store.getters['currentProduct'].inStore;
|
||||
|
||||
try {
|
||||
await allHash({
|
||||
clusterNetworks: this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.CLUSTER_NETWORK }),
|
||||
vlanStatus: this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.VLAN_STATUS }),
|
||||
nodes: this.$store.dispatch(`${ inStore }/findAll`, { type: NODE }),
|
||||
});
|
||||
|
||||
this.fetchError = null;
|
||||
} catch (e) {
|
||||
console.error('Failed to fetch network data:', e); // eslint-disable-line no-console
|
||||
this.fetchError = this.t('harvester.setting.vmMigrationNetwork.fetchError', { error: e.message || e }, true);
|
||||
}
|
||||
},
|
||||
|
||||
data() {
|
||||
const { parsed, enabled, parseError } = this.parseInitialValue();
|
||||
|
||||
return {
|
||||
enabled,
|
||||
network: { ...DEFAULT_NETWORK, ...parsed },
|
||||
fetchError: null,
|
||||
parseError,
|
||||
};
|
||||
},
|
||||
|
||||
created() {
|
||||
this.registerBeforeHook?.(this.willSave, 'willSave');
|
||||
},
|
||||
|
||||
computed: {
|
||||
allErrors() {
|
||||
return [this.fetchError, this.parseError].filter(Boolean);
|
||||
},
|
||||
|
||||
clusterNetworkOptions() {
|
||||
const inStore = this.$store.getters['currentProduct'].inStore;
|
||||
const networks = this.$store.getters[`${ inStore }/all`](HCI.CLUSTER_NETWORK) || [];
|
||||
|
||||
return networks.map((net) => ({
|
||||
label: net.isReadyForStorageNetwork ? net.id : `${ net.id } (${ this.t('generic.notReady') })`,
|
||||
value: net.id,
|
||||
disabled: !net.isReadyForStorageNetwork,
|
||||
}));
|
||||
},
|
||||
|
||||
disableEdit() {
|
||||
return !!(this.fetchError || this.parseError);
|
||||
},
|
||||
},
|
||||
|
||||
methods: {
|
||||
parseInitialValue() {
|
||||
let parsed = {};
|
||||
let enabled = false;
|
||||
let parseError = null;
|
||||
|
||||
try {
|
||||
if (typeof this.value.value === 'string' && this.value.value.trim()) {
|
||||
parsed = JSON.parse(this.value.value);
|
||||
enabled = true;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('[VMMigrationNetwork] Failed to parse value:', e); // eslint-disable-line no-console
|
||||
parseError = this.t('harvester.setting.vmMigrationNetwork.parseError', { error: e.message }, true);
|
||||
}
|
||||
|
||||
if (!Array.isArray(parsed.exclude)) {
|
||||
parsed.exclude = [];
|
||||
}
|
||||
|
||||
return {
|
||||
parsed, enabled, parseError
|
||||
};
|
||||
},
|
||||
|
||||
clearErrors() {
|
||||
this.fetchError = null;
|
||||
this.parseError = null;
|
||||
},
|
||||
|
||||
inputVlan(val) {
|
||||
this.network.vlan = val ? Math.min(4094, Math.max(1, Number(val))) : '';
|
||||
this.update();
|
||||
},
|
||||
|
||||
useDefault() {
|
||||
this.network = { ...DEFAULT_NETWORK };
|
||||
this.value.value = '';
|
||||
this.enabled = false;
|
||||
this.clearErrors();
|
||||
},
|
||||
|
||||
update() {
|
||||
try {
|
||||
this.value.value = this.enabled ? JSON.stringify({
|
||||
...this.network,
|
||||
exclude: (this.network.exclude || []).filter((e) => !!e?.trim()),
|
||||
}) : '';
|
||||
} catch (e) {
|
||||
console.error('Failed to stringify network config:', e); // eslint-disable-line no-console
|
||||
this.value.value = '';
|
||||
}
|
||||
},
|
||||
|
||||
validateInputs() {
|
||||
const errors = [];
|
||||
|
||||
if (!this.network.clusterNetwork) {
|
||||
errors.push(this.t('validation.required', { key: this.t('harvester.setting.vmMigrationNetwork.clusterNetwork') }, true));
|
||||
}
|
||||
|
||||
if (!this.network.range) {
|
||||
errors.push(this.t('validation.required', { key: this.t('harvester.setting.vmMigrationNetwork.range.label') }, true));
|
||||
} else if (!isValidCIDR(this.network.range)) {
|
||||
errors.push(this.t('harvester.setting.vmMigrationNetwork.range.invalid', null, true));
|
||||
}
|
||||
|
||||
if (this.network.vlan === '') {
|
||||
errors.push(this.t('validation.required', { key: this.t('harvester.setting.vmMigrationNetwork.vlan') }, true));
|
||||
} else {
|
||||
const vlan = Number(this.network.vlan);
|
||||
|
||||
if (isNaN(vlan) || vlan < 1 || vlan > 4094) {
|
||||
errors.push(this.t('validation.between', {
|
||||
key: this.t('harvester.setting.vmMigrationNetwork.vlan'),
|
||||
min: 1,
|
||||
max: 4094,
|
||||
}, true));
|
||||
}
|
||||
}
|
||||
|
||||
for (const cidr of this.network.exclude || []) {
|
||||
if (cidr && !isValidCIDR(cidr)) {
|
||||
errors.push(this.t('harvester.setting.storageNetwork.exclude.invalid', { value: cidr }, true));
|
||||
}
|
||||
}
|
||||
|
||||
return errors;
|
||||
},
|
||||
|
||||
async willSave() {
|
||||
if (!this.enabled) {
|
||||
this.useDefault();
|
||||
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
this.update();
|
||||
|
||||
const errors = this.validateInputs();
|
||||
|
||||
return errors.length ? Promise.reject(errors) : Promise.resolve();
|
||||
},
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<Banner
|
||||
v-for="(errorMsg, index) in allErrors"
|
||||
:key="index"
|
||||
color="error"
|
||||
>
|
||||
{{ errorMsg }}
|
||||
</Banner>
|
||||
<RadioGroup
|
||||
v-model:value="enabled"
|
||||
class="mb-20"
|
||||
name="enableMigrationNetwork"
|
||||
:options="[true, false]"
|
||||
:labels="[t('generic.enabled'), t('generic.disabled')]"
|
||||
@update:value="update"
|
||||
/>
|
||||
<template v-if="enabled">
|
||||
<LabeledSelect
|
||||
v-model:value="network.clusterNetwork"
|
||||
required
|
||||
label-key="harvester.setting.vmMigrationNetwork.clusterNetwork"
|
||||
class="mb-20"
|
||||
:mode="mode"
|
||||
:options="clusterNetworkOptions"
|
||||
:disabled="disableEdit"
|
||||
@update:value="update"
|
||||
/>
|
||||
<LabeledInput
|
||||
v-model:value.number="network.vlan"
|
||||
required
|
||||
type="number"
|
||||
class="mb-20"
|
||||
:min="1"
|
||||
:max="4094"
|
||||
:mode="mode"
|
||||
placeholder="e.g. 1 - 4094"
|
||||
label-key="harvester.setting.vmMigrationNetwork.vlan"
|
||||
:disabled="disableEdit"
|
||||
@update:value="inputVlan"
|
||||
/>
|
||||
<LabeledInput
|
||||
v-model:value="network.range"
|
||||
required
|
||||
class="mb-5"
|
||||
:mode="mode"
|
||||
:placeholder="t('harvester.setting.vmMigrationNetwork.range.placeholder')"
|
||||
label-key="harvester.setting.vmMigrationNetwork.range.label"
|
||||
:disabled="disableEdit"
|
||||
@update:value="update"
|
||||
/>
|
||||
<ArrayList
|
||||
v-model:value="network.exclude"
|
||||
:show-header="true"
|
||||
:default-add-value="''"
|
||||
:mode="mode"
|
||||
:add-disabled="disableEdit"
|
||||
:add-label="t('harvester.setting.vmMigrationNetwork.exclude.addButton')"
|
||||
:value-label="t('harvester.setting.vmMigrationNetwork.exclude.label')"
|
||||
:value-placeholder="t('harvester.setting.storageNetwork.exclude.placeholder')"
|
||||
@update:value="update"
|
||||
/>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,649 +0,0 @@
|
||||
<script setup>
|
||||
import { ref, computed, watch, toRefs } from 'vue';
|
||||
import { useStore } from 'vuex';
|
||||
import Loading from '@shell/components/Loading';
|
||||
import { Banner } from '@components/Banner';
|
||||
import { STORAGE_CLASS, NETWORK_ATTACHMENT } from '@shell/config/types';
|
||||
import { useI18n } from '@shell/composables/useI18n';
|
||||
import { randomStr } from '@shell/utils/string';
|
||||
import { HCI } from '../../types';
|
||||
import { VOLUME_MODE, ACCESS_MODE } from '../../config/types';
|
||||
import { FORKLIFT_NAMESPACE } from '../../config/harvester-map';
|
||||
import { buildNetworkMapEntries, buildStorageMapEntries } from '../../utils/forklift';
|
||||
import { isInternalStorageClass } from '../../utils/storage-class';
|
||||
import MappingColumn from './MappingColumn.vue';
|
||||
import StorageDefaultsModal from './StorageDefaultsModal.vue';
|
||||
|
||||
const DEFAULT_VOLUME_MODE = VOLUME_MODE.FILE_SYSTEM;
|
||||
const DEFAULT_ACCESS_MODE = ACCESS_MODE?.READ_WRITE_MANY ?? 'ReadWriteMany';
|
||||
|
||||
const props = defineProps({
|
||||
providerName: { type: String, default: '' },
|
||||
provider: { type: Object, default: null },
|
||||
selectedVms: { type: Array, default: () => [] },
|
||||
stepData: { type: Object, required: true },
|
||||
useAllProviderData: { type: Boolean, default: false },
|
||||
existingNetworkMap: { type: Object, default: null },
|
||||
existingStorageMap: { type: Object, default: null },
|
||||
});
|
||||
|
||||
const emit = defineEmits(['ready']);
|
||||
|
||||
const store = useStore();
|
||||
const { t } = useI18n(store);
|
||||
|
||||
const vms = ref([]);
|
||||
const harvesterNetworks = ref([]);
|
||||
const storageClasses = ref([]);
|
||||
const allNetworkMaps = ref([]);
|
||||
const allStorageMaps = ref([]);
|
||||
const errors = ref([]);
|
||||
const loading = ref(true);
|
||||
|
||||
// Storage defaults edit modal state.
|
||||
const showStorageDefaultsModal = ref(false);
|
||||
const editingStorageEntry = ref(null);
|
||||
|
||||
const { networkEntries, storageEntries } = toRefs(props.stepData);
|
||||
|
||||
const NAMESPACE = FORKLIFT_NAMESPACE;
|
||||
|
||||
const harvesterNetworkOptions = computed(() => {
|
||||
const options = [
|
||||
{ label: t('harvester.addons.vmMigration.configureMappings.networkMapping.options.podNetworking'), value: 'pod' },
|
||||
{ label: t('harvester.addons.vmMigration.configureMappings.networkMapping.options.ignored'), value: 'ignored' },
|
||||
];
|
||||
|
||||
harvesterNetworks.value.forEach((net) => {
|
||||
const ns = net.metadata?.namespace || '';
|
||||
const name = net.metadata?.name || net.id;
|
||||
const fullName = ns ? `${ ns }/${ name }` : name;
|
||||
|
||||
options.push({ label: fullName, value: fullName });
|
||||
});
|
||||
|
||||
return options;
|
||||
});
|
||||
|
||||
const storageClassOptions = computed(() => {
|
||||
const options = storageClasses.value.filter((s) => !s.parameters?.backingImage).map((sc) => {
|
||||
const value = sc.name;
|
||||
let label = sc.isDefault ? `${ value } (${ t('generic.default') })` : value;
|
||||
let disabled = false;
|
||||
|
||||
if (isInternalStorageClass(value)) {
|
||||
label += ` (${ t('harvester.storage.internal.label') })`;
|
||||
disabled = true;
|
||||
}
|
||||
|
||||
return {
|
||||
label,
|
||||
value,
|
||||
disabled,
|
||||
};
|
||||
});
|
||||
|
||||
if (!options.find((o) => o.value === 'harvester-longhorn')) {
|
||||
options.unshift({ label: 'harvester-longhorn', value: 'harvester-longhorn' });
|
||||
}
|
||||
|
||||
return options;
|
||||
});
|
||||
|
||||
const applyNetworkMapTargets = (mapSpec) => {
|
||||
if (!mapSpec) {
|
||||
return;
|
||||
}
|
||||
|
||||
networkEntries.value.forEach((entry) => {
|
||||
const match = mapSpec.find(
|
||||
(m) => m.source?.id === entry.id || m.source?.name === entry.name
|
||||
);
|
||||
|
||||
if (match?.destination) {
|
||||
const dest = match.destination;
|
||||
|
||||
if (dest.type === 'pod') {
|
||||
entry.target = 'pod';
|
||||
} else if (dest.type === 'ignored') {
|
||||
entry.target = 'ignored';
|
||||
} else if (dest.type === 'multus' && dest.name) {
|
||||
entry.target = dest.namespace ? `${ dest.namespace }/${ dest.name }` : dest.name;
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const applyStorageMapTargets = (mapSpec, { markOverridden = false, captureInherited = false } = {}) => {
|
||||
if (!mapSpec) {
|
||||
return;
|
||||
}
|
||||
|
||||
storageEntries.value.forEach((entry) => {
|
||||
const match = mapSpec.find(
|
||||
(m) => m.source?.id === entry.id || m.source?.name === entry.name
|
||||
);
|
||||
|
||||
if (match?.destination?.storageClass) {
|
||||
entry.target = match.destination.storageClass;
|
||||
|
||||
if (captureInherited) {
|
||||
entry.inheritedFromProvider = true;
|
||||
}
|
||||
|
||||
if (match.destination.volumeMode) {
|
||||
entry.volumeMode = match.destination.volumeMode;
|
||||
|
||||
if (captureInherited) {
|
||||
entry.inheritedVolumeMode = match.destination.volumeMode;
|
||||
}
|
||||
}
|
||||
|
||||
if (match.destination.accessMode) {
|
||||
entry.accessModes = [match.destination.accessMode];
|
||||
|
||||
if (captureInherited) {
|
||||
entry.inheritedAccessModes = [match.destination.accessMode];
|
||||
}
|
||||
}
|
||||
|
||||
if (markOverridden) {
|
||||
entry.overridden = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const applyDefaultNetworkMap = () => {
|
||||
const defaultMap = allNetworkMaps.value.find(
|
||||
(nm) => nm.metadata.name === `${ props.providerName }-network-map-default`
|
||||
);
|
||||
|
||||
applyNetworkMapTargets(defaultMap?.spec?.map);
|
||||
};
|
||||
|
||||
const applyDefaultStorageMap = () => {
|
||||
const defaultMap = allStorageMaps.value.find(
|
||||
(sm) => sm.metadata.name === `${ props.providerName }-storage-map-default`
|
||||
);
|
||||
|
||||
applyStorageMapTargets(defaultMap?.spec?.map, { captureInherited: true });
|
||||
};
|
||||
|
||||
const allNetworksMapped = computed(() => networkEntries.value.length > 0 && networkEntries.value.every((e) => !!e.target));
|
||||
const allStorageMapped = computed(() => storageEntries.value.length > 0 && storageEntries.value.every((e) => !!e.target));
|
||||
|
||||
// The "Inherited from provider" hint only appears in the migration plan wizard
|
||||
// (where mappings inherit from the provider default), not on the provider creation page.
|
||||
const inheritedProviderName = computed(() => (props.useAllProviderData ? '' : props.providerName));
|
||||
|
||||
const openStorageDefaults = (entry) => {
|
||||
editingStorageEntry.value = entry;
|
||||
showStorageDefaultsModal.value = true;
|
||||
};
|
||||
|
||||
const closeStorageDefaults = () => {
|
||||
showStorageDefaultsModal.value = false;
|
||||
editingStorageEntry.value = null;
|
||||
};
|
||||
|
||||
const applyStorageDefaults = ({ volumeMode, accessModes }) => {
|
||||
if (editingStorageEntry.value) {
|
||||
editingStorageEntry.value.volumeMode = volumeMode;
|
||||
editingStorageEntry.value.accessModes = accessModes;
|
||||
|
||||
const inheritedVolumeMode = editingStorageEntry.value.inheritedVolumeMode;
|
||||
const inheritedAccessMode = editingStorageEntry.value.inheritedAccessModes?.[0];
|
||||
const selectedAccessMode = accessModes?.[0];
|
||||
|
||||
editingStorageEntry.value.overridden = volumeMode !== inheritedVolumeMode || selectedAccessMode !== inheritedAccessMode;
|
||||
}
|
||||
};
|
||||
|
||||
const canSave = computed(() => {
|
||||
if (props.useAllProviderData) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return networkEntries.value.length > 0 && storageEntries.value.length > 0 &&
|
||||
allNetworksMapped.value && allStorageMapped.value;
|
||||
});
|
||||
|
||||
watch(canSave, (val) => {
|
||||
emit('ready', val);
|
||||
});
|
||||
|
||||
// After restore, check if ready
|
||||
if (canSave.value) {
|
||||
emit('ready', true);
|
||||
}
|
||||
|
||||
const buildNetworkEntries = () => {
|
||||
const networkMap = {};
|
||||
|
||||
vms.value.forEach((vm) => {
|
||||
const vmName = vm.name || vm.id;
|
||||
|
||||
if (vm.networks && vm.networks.length > 0) {
|
||||
vm.networks.forEach((net) => {
|
||||
const netKey = net.id || net.name || 'default';
|
||||
|
||||
if (!networkMap[netKey]) {
|
||||
networkMap[netKey] = {
|
||||
name: net.name || t('harvester.addons.vmMigration.generic.unknown'),
|
||||
id: net.id || '',
|
||||
vlanId: net.vlanId || '',
|
||||
target: '',
|
||||
usedBy: [],
|
||||
_key: `net-${ netKey }`,
|
||||
};
|
||||
}
|
||||
|
||||
if (!networkMap[netKey].usedBy.includes(vmName)) {
|
||||
networkMap[netKey].usedBy.push(vmName);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
networkEntries.value = Object.values(networkMap);
|
||||
};
|
||||
|
||||
const buildStorageEntries = () => {
|
||||
const datastoreMap = {};
|
||||
|
||||
vms.value.forEach((vm) => {
|
||||
const vmName = vm.name || vm.id;
|
||||
|
||||
if (vm.disks && vm.disks.length > 0) {
|
||||
vm.disks.forEach((disk) => {
|
||||
const ds = disk.datastore;
|
||||
|
||||
if (ds && ds.id) {
|
||||
if (!datastoreMap[ds.id]) {
|
||||
datastoreMap[ds.id] = {
|
||||
name: ds.name || t('harvester.addons.vmMigration.generic.unknown'),
|
||||
id: ds.id,
|
||||
type: ds.type || '',
|
||||
capacity: 0,
|
||||
target: '',
|
||||
volumeMode: DEFAULT_VOLUME_MODE,
|
||||
accessModes: [DEFAULT_ACCESS_MODE],
|
||||
inheritedVolumeMode: DEFAULT_VOLUME_MODE,
|
||||
inheritedAccessModes: [DEFAULT_ACCESS_MODE],
|
||||
inheritedFromProvider: false,
|
||||
overridden: false,
|
||||
usedBy: [],
|
||||
_key: `stor-${ ds.id }`,
|
||||
};
|
||||
}
|
||||
|
||||
datastoreMap[ds.id].capacity += disk.capacity || 0;
|
||||
|
||||
if (!datastoreMap[ds.id].usedBy.includes(vmName)) {
|
||||
datastoreMap[ds.id].usedBy.push(vmName);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
storageEntries.value = Object.values(datastoreMap);
|
||||
};
|
||||
|
||||
const buildNetworkEntriesFromProvider = (networksData) => {
|
||||
networkEntries.value = (Array.isArray(networksData) ? networksData : []).map((net) => ({
|
||||
name: net.name || net.id,
|
||||
id: net.id || '',
|
||||
vlanId: net.vlanId || '',
|
||||
target: '',
|
||||
usedBy: [],
|
||||
_key: `net-${ net.id || net.name }`,
|
||||
}));
|
||||
};
|
||||
|
||||
const buildStorageEntriesFromProvider = (datastoresData) => {
|
||||
storageEntries.value = (Array.isArray(datastoresData) ? datastoresData : []).map((ds) => ({
|
||||
name: ds.name || ds.id,
|
||||
id: ds.id || '',
|
||||
type: ds.type || '',
|
||||
capacity: ds.capacity || 0,
|
||||
target: '',
|
||||
volumeMode: DEFAULT_VOLUME_MODE,
|
||||
accessModes: [DEFAULT_ACCESS_MODE],
|
||||
inheritedVolumeMode: DEFAULT_VOLUME_MODE,
|
||||
inheritedAccessModes: [DEFAULT_ACCESS_MODE],
|
||||
inheritedFromProvider: false,
|
||||
overridden: false,
|
||||
usedBy: [],
|
||||
_key: `stor-${ ds.id || ds.name }`,
|
||||
}));
|
||||
};
|
||||
|
||||
const formatStorageDetail = (entry) => {
|
||||
const parts = [];
|
||||
|
||||
if (entry.type) {
|
||||
parts.push(entry.type);
|
||||
}
|
||||
|
||||
if (entry.capacity) {
|
||||
const gb = entry.capacity / (1024 * 1024 * 1024);
|
||||
|
||||
if (gb >= 1024) {
|
||||
parts.push(t('harvester.addons.vmMigration.generic.memoryTb', { value: (gb / 1024).toFixed(1) }));
|
||||
} else {
|
||||
parts.push(t('harvester.addons.vmMigration.generic.memoryGb', { value: Math.round(gb) }));
|
||||
}
|
||||
}
|
||||
|
||||
return parts.join(' • ');
|
||||
};
|
||||
|
||||
const buildNetworkMapSpec = (providerRef) => ({
|
||||
map: buildNetworkMapEntries(networkEntries.value, NAMESPACE),
|
||||
provider: providerRef,
|
||||
});
|
||||
|
||||
const buildStorageMapSpec = (providerRef) => ({
|
||||
map: buildStorageMapEntries(storageEntries.value),
|
||||
provider: providerRef,
|
||||
});
|
||||
|
||||
const saveAndReturn = async() => {
|
||||
const inStore = store.getters['currentProduct'].inStore;
|
||||
|
||||
const providerRef = {
|
||||
source: {
|
||||
apiVersion: 'forklift.konveyor.io/v1beta1',
|
||||
kind: 'Provider',
|
||||
name: props.providerName,
|
||||
namespace: NAMESPACE,
|
||||
},
|
||||
destination: {
|
||||
apiVersion: 'forklift.konveyor.io/v1beta1',
|
||||
kind: 'Provider',
|
||||
name: 'host',
|
||||
namespace: NAMESPACE,
|
||||
},
|
||||
};
|
||||
|
||||
// Update existing maps in place (edit mode)
|
||||
if (props.existingNetworkMap && props.existingStorageMap) {
|
||||
props.existingNetworkMap.spec = buildNetworkMapSpec(providerRef);
|
||||
await props.existingNetworkMap.save();
|
||||
|
||||
props.existingStorageMap.spec = buildStorageMapSpec(providerRef);
|
||||
await props.existingStorageMap.save();
|
||||
|
||||
return {
|
||||
networkMapName: props.existingNetworkMap.metadata.name,
|
||||
storageMapName: props.existingStorageMap.metadata.name,
|
||||
};
|
||||
}
|
||||
|
||||
const providerOwnerRef = props.provider ? [{
|
||||
apiVersion: 'forklift.konveyor.io/v1beta1',
|
||||
kind: 'Provider',
|
||||
name: props.provider.metadata.name,
|
||||
uid: props.provider.metadata.uid,
|
||||
blockOwnerDeletion: true,
|
||||
}] : [];
|
||||
|
||||
const networkMap = await store.dispatch(`${ inStore }/create`, {
|
||||
type: HCI.FORKLIFT_NETWORK_MAP,
|
||||
metadata: {
|
||||
name: `${ props.providerName }-network-map-${ props.useAllProviderData ? 'default' : randomStr(5).toLowerCase() }`,
|
||||
namespace: NAMESPACE,
|
||||
ownerReferences: providerOwnerRef,
|
||||
},
|
||||
spec: buildNetworkMapSpec(providerRef),
|
||||
});
|
||||
|
||||
await networkMap.save();
|
||||
|
||||
const storageMap = await store.dispatch(`${ inStore }/create`, {
|
||||
type: HCI.FORKLIFT_STORAGE_MAP,
|
||||
metadata: {
|
||||
name: `${ props.providerName }-storage-map-${ props.useAllProviderData ? 'default' : randomStr(5).toLowerCase() }`,
|
||||
namespace: NAMESPACE,
|
||||
ownerReferences: providerOwnerRef,
|
||||
},
|
||||
spec: buildStorageMapSpec(providerRef),
|
||||
});
|
||||
|
||||
await storageMap.save();
|
||||
|
||||
return { networkMapName: networkMap.metadata.name, storageMapName: storageMap.metadata.name };
|
||||
};
|
||||
|
||||
defineExpose({ saveMappings: saveAndReturn });
|
||||
|
||||
const init = async() => {
|
||||
const inStore = store.getters['currentProduct'].inStore;
|
||||
|
||||
try {
|
||||
harvesterNetworks.value = await store.dispatch(`${ inStore }/findAll`, { type: NETWORK_ATTACHMENT });
|
||||
} catch (e) {
|
||||
harvesterNetworks.value = [];
|
||||
}
|
||||
|
||||
try {
|
||||
storageClasses.value = await store.dispatch(`${ inStore }/findAll`, { type: STORAGE_CLASS });
|
||||
} catch (e) {
|
||||
storageClasses.value = [];
|
||||
}
|
||||
|
||||
try {
|
||||
allNetworkMaps.value = await store.dispatch(`${ inStore }/findAll`, { type: HCI.FORKLIFT_NETWORK_MAP });
|
||||
} catch (e) {
|
||||
allNetworkMaps.value = [];
|
||||
}
|
||||
|
||||
try {
|
||||
allStorageMaps.value = await store.dispatch(`${ inStore }/findAll`, { type: HCI.FORKLIFT_STORAGE_MAP });
|
||||
} catch (e) {
|
||||
allStorageMaps.value = [];
|
||||
}
|
||||
|
||||
if (networkEntries.value.length === 0 || storageEntries.value.length === 0) {
|
||||
try {
|
||||
const providerUid = props.provider?.metadata?.uid;
|
||||
const providerType = props.provider?.spec?.type || 'vsphere';
|
||||
const baseUrl = store.getters['harvester-common/getHarvesterClusterUrl'](
|
||||
`v1/harvester/providers/${ providerType }/${ providerUid }`
|
||||
);
|
||||
|
||||
const [networksData, datastoresData] = await Promise.all([
|
||||
store.dispatch(`${ inStore }/request`, { url: `${ baseUrl }/networks` }).catch(() => []),
|
||||
store.dispatch(`${ inStore }/request`, { url: `${ baseUrl }/datastores?detail=1` }).catch(() => []),
|
||||
]);
|
||||
|
||||
if (props.useAllProviderData) {
|
||||
if (networkEntries.value.length === 0) {
|
||||
buildNetworkEntriesFromProvider(networksData);
|
||||
}
|
||||
if (storageEntries.value.length === 0) {
|
||||
buildStorageEntriesFromProvider(datastoresData);
|
||||
}
|
||||
} else {
|
||||
vms.value = props.selectedVms;
|
||||
|
||||
const networkNameMap = (Array.isArray(networksData) ? networksData : []).reduce((map, n) => {
|
||||
map[n.id] = n.name;
|
||||
|
||||
return map;
|
||||
}, {});
|
||||
const datastoreInfoMap = (Array.isArray(datastoresData) ? datastoresData : []).reduce((map, d) => {
|
||||
map[d.id] = { name: d.name, type: d.type || '' };
|
||||
|
||||
return map;
|
||||
}, {});
|
||||
|
||||
vms.value = vms.value.map((vm) => {
|
||||
const resolved = { ...vm };
|
||||
|
||||
if (resolved.networks) {
|
||||
resolved.networks = resolved.networks.map((n) => ({
|
||||
...n,
|
||||
name: n.name || networkNameMap[n.id] || n.id,
|
||||
}));
|
||||
}
|
||||
|
||||
if (resolved.disks) {
|
||||
resolved.disks = resolved.disks.map((d) => {
|
||||
const dsInfo = d.datastore ? datastoreInfoMap[d.datastore.id] : null;
|
||||
|
||||
return {
|
||||
...d,
|
||||
datastore: d.datastore ? {
|
||||
...d.datastore,
|
||||
name: d.datastore.name || dsInfo?.name || d.datastore.id,
|
||||
type: dsInfo?.type || '',
|
||||
} : d.datastore,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
return resolved;
|
||||
});
|
||||
|
||||
if (networkEntries.value.length === 0) {
|
||||
buildNetworkEntries();
|
||||
}
|
||||
if (storageEntries.value.length === 0) {
|
||||
buildStorageEntries();
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
errors.value = [e?.message || t('harvester.addons.vmMigration.errors.failedResolveDetails')];
|
||||
}
|
||||
}
|
||||
|
||||
const hasExistingNetworkTargets = networkEntries.value.some((e) => !!e.target);
|
||||
const hasExistingStorageTargets = storageEntries.value.some((e) => !!e.target);
|
||||
|
||||
if (!hasExistingNetworkTargets) {
|
||||
if (props.existingNetworkMap?.spec?.map) {
|
||||
applyNetworkMapTargets(props.existingNetworkMap.spec.map);
|
||||
} else {
|
||||
applyDefaultNetworkMap();
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasExistingStorageTargets) {
|
||||
if (props.existingStorageMap?.spec?.map) {
|
||||
applyStorageMapTargets(props.existingStorageMap.spec.map, { markOverridden: true });
|
||||
} else {
|
||||
applyDefaultStorageMap();
|
||||
}
|
||||
}
|
||||
|
||||
loading.value = false;
|
||||
};
|
||||
|
||||
init();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Loading v-if="loading" />
|
||||
<div
|
||||
v-else
|
||||
class="configure-mappings"
|
||||
>
|
||||
<Banner
|
||||
v-for="(err, i) in errors"
|
||||
:key="i"
|
||||
color="error"
|
||||
:label="err"
|
||||
/>
|
||||
<p class="text-deemphasized line-height-20">
|
||||
{{ t('harvester.addons.vmMigration.configureMappings.description') }}
|
||||
</p>
|
||||
<div class="mappings-columns">
|
||||
<MappingColumn
|
||||
:title="t('harvester.addons.vmMigration.configureMappings.networkMapping.title')"
|
||||
:description="t('harvester.addons.vmMigration.configureMappings.networkMapping.description')"
|
||||
:entries="networkEntries"
|
||||
:options="harvesterNetworkOptions"
|
||||
:placeholder="t('harvester.addons.vmMigration.configureMappings.networkMapping.placeholder')"
|
||||
:show-used-by="!useAllProviderData"
|
||||
:clearable="useAllProviderData"
|
||||
>
|
||||
<template #source-detail="{ entry }">
|
||||
<span class="source-detail text-deemphasized">{{ t('harvester.addons.vmMigration.generic.vlan', { id: entry.vlanId || '0' }) }}</span>
|
||||
</template>
|
||||
</MappingColumn>
|
||||
|
||||
<MappingColumn
|
||||
:title="t('harvester.addons.vmMigration.configureMappings.storageMapping.title')"
|
||||
:description="t('harvester.addons.vmMigration.configureMappings.storageMapping.description')"
|
||||
:entries="storageEntries"
|
||||
:options="storageClassOptions"
|
||||
:placeholder="t('harvester.addons.vmMigration.configureMappings.storageMapping.placeholder')"
|
||||
:show-used-by="!useAllProviderData"
|
||||
:clearable="useAllProviderData"
|
||||
:show-volume-settings="true"
|
||||
:inherited-provider-name="inheritedProviderName"
|
||||
@edit-defaults="openStorageDefaults"
|
||||
>
|
||||
<template #source-detail="{ entry }">
|
||||
<span
|
||||
v-if="entry.type || entry.capacity"
|
||||
class="source-detail text-deemphasized"
|
||||
>{{ formatStorageDetail(entry) }}</span>
|
||||
</template>
|
||||
</MappingColumn>
|
||||
</div>
|
||||
|
||||
<StorageDefaultsModal
|
||||
v-if="showStorageDefaultsModal && editingStorageEntry"
|
||||
:storage-class-name="editingStorageEntry.target"
|
||||
:provider-name="providerName"
|
||||
:show-inherited="!!inheritedProviderName"
|
||||
:volume-mode="editingStorageEntry.volumeMode"
|
||||
:access-modes="editingStorageEntry.accessModes"
|
||||
:inherited-volume-mode="editingStorageEntry.inheritedVolumeMode"
|
||||
:inherited-access-modes="editingStorageEntry.inheritedAccessModes"
|
||||
@apply="applyStorageDefaults"
|
||||
@close="closeStorageDefaults"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.mappings-columns {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 32px;
|
||||
|
||||
@media only screen and (min-width: map-get($breakpoints, '--viewport-7')) {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
|
||||
}
|
||||
|
||||
@media only screen and (min-width: map-get($breakpoints, '--viewport-9')) {
|
||||
gap: 48px;
|
||||
}
|
||||
|
||||
@media only screen and (min-width: map-get($breakpoints, '--viewport-12')) {
|
||||
gap: 64px;
|
||||
}
|
||||
}
|
||||
|
||||
.configure-mappings {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 24px;
|
||||
|
||||
.line-height-20 {
|
||||
line-height: 20px;
|
||||
}
|
||||
}
|
||||
|
||||
.source-detail {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
</style>
|
||||
@@ -1,573 +0,0 @@
|
||||
<script setup>
|
||||
import { ref, computed, watch, toRefs } from 'vue';
|
||||
import { useStore } from 'vuex';
|
||||
|
||||
import { LabeledInput } from '@components/Form/LabeledInput';
|
||||
import { Checkbox } from '@components/Form/Checkbox';
|
||||
import { Banner } from '@components/Banner';
|
||||
import Loading from '@shell/components/Loading';
|
||||
import AsyncButton from '@shell/components/AsyncButton';
|
||||
import LabeledSelect from '@shell/components/form/LabeledSelect';
|
||||
import { SECRET } from '@shell/config/types';
|
||||
import { randomStr } from '@shell/utils/string';
|
||||
import { useI18n } from '@shell/composables/useI18n';
|
||||
import { HCI } from '../../types';
|
||||
import { FORKLIFT_NAMESPACE } from '../../config/harvester-map';
|
||||
import { decodeSecretValue } from '../../utils/forklift';
|
||||
|
||||
const CREATE_NEW = '__create_new__';
|
||||
|
||||
const props = defineProps({
|
||||
stepData: { type: Object, required: true },
|
||||
createOnly: { type: Boolean, default: false },
|
||||
editMode: { type: Boolean, default: false },
|
||||
});
|
||||
|
||||
const emit = defineEmits(['complete', 'ready', 'form-valid', 'testing']);
|
||||
|
||||
const store = useStore();
|
||||
const { t } = useI18n(store);
|
||||
|
||||
const allProviders = ref([]);
|
||||
const allSecrets = ref([]);
|
||||
const errors = ref([]);
|
||||
const testBtnRef = ref(null);
|
||||
const loading = ref(true);
|
||||
const testing = ref(false);
|
||||
|
||||
const {
|
||||
selectedProvider,
|
||||
providerName,
|
||||
url,
|
||||
username,
|
||||
password,
|
||||
skipTlsVerify,
|
||||
vddkInitImage,
|
||||
testPassed,
|
||||
testResult,
|
||||
testError,
|
||||
createdProvider,
|
||||
createdSecret,
|
||||
} = toRefs(props.stepData);
|
||||
|
||||
const isExistingProvider = computed(() => selectedProvider.value !== CREATE_NEW);
|
||||
const isFormValid = computed(() => !!providerName.value && !!url.value && !!username.value && !!password.value);
|
||||
|
||||
const providerOptions = computed(() => {
|
||||
const options = [
|
||||
{ label: t('harvester.addons.vmMigration.configureProvider.createNew'), value: CREATE_NEW }
|
||||
];
|
||||
|
||||
allProviders.value.forEach((p) => {
|
||||
if (!p.spec?.url) {
|
||||
return;
|
||||
}
|
||||
|
||||
const secretRef = p.spec?.secret;
|
||||
|
||||
if (secretRef) {
|
||||
const secret = allSecrets.value.find(
|
||||
(s) => s.metadata.name === secretRef.name && s.metadata.namespace === secretRef.namespace
|
||||
);
|
||||
|
||||
if (!secret?.data?.user || !secret?.data?.password) {
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
options.push({
|
||||
label: p.metadata.name,
|
||||
value: p.metadata.name,
|
||||
});
|
||||
});
|
||||
|
||||
return options;
|
||||
});
|
||||
|
||||
// When the provider selection changes, populate or clear the fields
|
||||
watch(selectedProvider, (val) => {
|
||||
testPassed.value = false;
|
||||
testResult.value = null;
|
||||
testError.value = null;
|
||||
|
||||
if (val === CREATE_NEW) {
|
||||
providerName.value = '';
|
||||
url.value = '';
|
||||
username.value = '';
|
||||
password.value = '';
|
||||
skipTlsVerify.value = false;
|
||||
vddkInitImage.value = '';
|
||||
createdProvider.value = null;
|
||||
createdSecret.value = null;
|
||||
} else {
|
||||
const provider = allProviders.value.find(
|
||||
(p) => p.metadata.name === val && p.metadata.namespace === FORKLIFT_NAMESPACE
|
||||
);
|
||||
|
||||
if (provider) {
|
||||
providerName.value = provider.metadata.name;
|
||||
url.value = provider.spec?.url || '';
|
||||
vddkInitImage.value = provider.spec?.settings?.vddkInitImage || '';
|
||||
|
||||
const secretRef = provider.spec?.secret;
|
||||
|
||||
if (secretRef) {
|
||||
const secret = allSecrets.value.find(
|
||||
(s) => s.metadata.name === secretRef.name && s.metadata.namespace === secretRef.namespace
|
||||
);
|
||||
|
||||
if (secret?.data) {
|
||||
username.value = decodeSecretValue(secret.data.user);
|
||||
password.value = decodeSecretValue(secret.data.password);
|
||||
skipTlsVerify.value = decodeSecretValue(secret.data.insecureSkipVerify) === 'true';
|
||||
}
|
||||
}
|
||||
|
||||
createdProvider.value = provider;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Reset test state when any field changes (only for create new)
|
||||
watch([providerName, url, username, password], () => {
|
||||
if (!isExistingProvider.value) {
|
||||
testPassed.value = false;
|
||||
testResult.value = null;
|
||||
}
|
||||
});
|
||||
|
||||
// Emit ready/complete when testPassed changes
|
||||
watch(testPassed, (val) => {
|
||||
emit('ready', val);
|
||||
if (val) {
|
||||
emit('complete', { providerName: providerName.value, provider: createdProvider.value });
|
||||
}
|
||||
}, { immediate: true });
|
||||
|
||||
// Emit form-valid when form validity changes
|
||||
watch(isFormValid, (val) => {
|
||||
emit('form-valid', val);
|
||||
}, { immediate: true });
|
||||
|
||||
watch(testing, (val) => {
|
||||
emit('testing', val);
|
||||
}, { immediate: true });
|
||||
|
||||
const pollProviderReady = async(name) => {
|
||||
const inStore = store.getters['currentProduct'].inStore;
|
||||
const namespace = FORKLIFT_NAMESPACE;
|
||||
const maxAttempts = 15;
|
||||
let attempts = 0;
|
||||
|
||||
while (attempts < maxAttempts) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 2000));
|
||||
attempts++;
|
||||
|
||||
const refreshed = await store.dispatch(`${ inStore }/find`, {
|
||||
type: HCI.FORKLIFT_PROVIDER,
|
||||
id: `${ namespace }/${ name }`,
|
||||
opt: { force: true }
|
||||
});
|
||||
|
||||
const conditions = refreshed?.status?.conditions || [];
|
||||
const connectionCondition = conditions.find((c) => c.type === 'ConnectionTestSucceeded');
|
||||
const readyCondition = conditions.find((c) => c.type === 'Ready');
|
||||
|
||||
if (connectionCondition) {
|
||||
if (connectionCondition.status === 'True') {
|
||||
return { connected: true };
|
||||
}
|
||||
|
||||
return { connected: false, errorMsg: connectionCondition.message || t('harvester.addons.vmMigration.errors.connectionFailed') };
|
||||
}
|
||||
|
||||
if (readyCondition) {
|
||||
if (readyCondition.status === 'True') {
|
||||
return { connected: true };
|
||||
} else if (readyCondition.status === 'False') {
|
||||
return { connected: false, errorMsg: readyCondition.message || t('harvester.addons.vmMigration.errors.providerNotReady') };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { connected: false, errorMsg: '' };
|
||||
};
|
||||
|
||||
const handlePollResult = ({ connected, errorMsg }, buttonCb) => {
|
||||
if (connected) {
|
||||
testPassed.value = true;
|
||||
testResult.value = t('harvester.addons.vmMigration.configureProvider.testSuccess');
|
||||
testing.value = false;
|
||||
buttonCb(true);
|
||||
} else {
|
||||
testError.value = errorMsg || t('harvester.addons.vmMigration.configureProvider.testTimeout');
|
||||
testing.value = false;
|
||||
buttonCb(false);
|
||||
}
|
||||
};
|
||||
|
||||
const cleanupCreatedResources = async() => {
|
||||
if (createdProvider.value) {
|
||||
try {
|
||||
await createdProvider.value.remove();
|
||||
} catch (e) {}
|
||||
createdProvider.value = null;
|
||||
createdSecret.value = null;
|
||||
} else if (createdSecret.value) {
|
||||
try {
|
||||
await createdSecret.value.remove();
|
||||
} catch (e) {}
|
||||
createdSecret.value = null;
|
||||
}
|
||||
};
|
||||
|
||||
const testConnection = async(buttonCb) => {
|
||||
testResult.value = null;
|
||||
testError.value = null;
|
||||
testing.value = true;
|
||||
|
||||
if (!providerName.value || !url.value || !username.value || !password.value) {
|
||||
testError.value = t('harvester.addons.vmMigration.configureProvider.testMissingFields');
|
||||
testing.value = false;
|
||||
buttonCb(false);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const inStore = store.getters['currentProduct'].inStore;
|
||||
|
||||
// Edit mode: update existing provider URL + secret, then poll
|
||||
if (props.editMode && createdProvider.value) {
|
||||
try {
|
||||
createdProvider.value.spec.url = url.value;
|
||||
|
||||
const vddkImage = vddkInitImage.value?.trim();
|
||||
|
||||
if (vddkImage) {
|
||||
createdProvider.value.spec.settings = {
|
||||
...(createdProvider.value.spec.settings || {}),
|
||||
vddkInitImage: vddkImage,
|
||||
};
|
||||
} else if (createdProvider.value.spec.settings) {
|
||||
delete createdProvider.value.spec.settings.vddkInitImage;
|
||||
}
|
||||
|
||||
await createdProvider.value.save();
|
||||
|
||||
const secretRef = createdProvider.value.spec?.secret;
|
||||
|
||||
if (secretRef && createdSecret.value) {
|
||||
createdSecret.value.data = {
|
||||
user: btoa(username.value),
|
||||
password: btoa(password.value),
|
||||
insecureSkipVerify: btoa(String(skipTlsVerify.value)),
|
||||
url: btoa(url.value),
|
||||
};
|
||||
await createdSecret.value.save();
|
||||
}
|
||||
|
||||
handlePollResult(await pollProviderReady(providerName.value), buttonCb);
|
||||
} catch (err) {
|
||||
testError.value = err.message || t('harvester.addons.vmMigration.configureProvider.testFailed');
|
||||
testing.value = false;
|
||||
buttonCb(false);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// For existing providers, just poll for Ready/ConnectionTestSucceeded status
|
||||
if (isExistingProvider.value) {
|
||||
try {
|
||||
handlePollResult(await pollProviderReady(providerName.value), buttonCb);
|
||||
} catch (err) {
|
||||
testError.value = err.message || t('harvester.addons.vmMigration.configureProvider.testFailed');
|
||||
testing.value = false;
|
||||
buttonCb(false);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// For new providers, create provider + secret then poll
|
||||
try {
|
||||
await cleanupCreatedResources();
|
||||
|
||||
const namespace = FORKLIFT_NAMESPACE;
|
||||
const secretName = `${ providerName.value }-creds-${ randomStr(4).toLowerCase() }`;
|
||||
|
||||
const spec = {
|
||||
type: 'vsphere',
|
||||
url: url.value,
|
||||
secret: {
|
||||
name: secretName,
|
||||
namespace,
|
||||
},
|
||||
};
|
||||
|
||||
const vddkImage = vddkInitImage.value?.trim();
|
||||
|
||||
if (vddkImage) {
|
||||
spec.settings = { vddkInitImage: vddkImage };
|
||||
}
|
||||
|
||||
const provider = await store.dispatch(`${ inStore }/create`, {
|
||||
type: HCI.FORKLIFT_PROVIDER,
|
||||
metadata: {
|
||||
name: providerName.value,
|
||||
namespace,
|
||||
},
|
||||
spec,
|
||||
});
|
||||
|
||||
await provider.save();
|
||||
createdProvider.value = provider;
|
||||
|
||||
const newSecret = await store.dispatch(`${ inStore }/create`, {
|
||||
type: SECRET,
|
||||
metadata: {
|
||||
name: secretName,
|
||||
namespace,
|
||||
labels: { 'ui.forklift/created-for-resource-type': 'forklift.konveyor.io.provider' },
|
||||
ownerReferences: [
|
||||
{
|
||||
apiVersion: 'forklift.konveyor.io/v1beta1',
|
||||
kind: 'Provider',
|
||||
name: provider.metadata.name,
|
||||
uid: provider.metadata.uid,
|
||||
blockOwnerDeletion: true,
|
||||
},
|
||||
],
|
||||
}
|
||||
});
|
||||
|
||||
newSecret['_type'] = 'Opaque';
|
||||
newSecret['data'] = {
|
||||
user: btoa(username.value),
|
||||
password: btoa(password.value),
|
||||
insecureSkipVerify: btoa(String(skipTlsVerify.value)),
|
||||
url: btoa(url.value),
|
||||
};
|
||||
|
||||
await newSecret.save();
|
||||
createdSecret.value = newSecret;
|
||||
|
||||
const result = await pollProviderReady(providerName.value);
|
||||
|
||||
if (!result.connected) {
|
||||
await cleanupCreatedResources();
|
||||
}
|
||||
|
||||
handlePollResult(result, buttonCb);
|
||||
} catch (err) {
|
||||
await cleanupCreatedResources();
|
||||
testError.value = err.message || t('harvester.addons.vmMigration.configureProvider.testFailed');
|
||||
testing.value = false;
|
||||
buttonCb(false);
|
||||
}
|
||||
};
|
||||
|
||||
const init = async() => {
|
||||
const inStore = store.getters['currentProduct'].inStore;
|
||||
|
||||
try {
|
||||
allProviders.value = await store.dispatch(`${ inStore }/findAll`, { type: HCI.FORKLIFT_PROVIDER });
|
||||
|
||||
allSecrets.value = await store.dispatch(`${ inStore }/findAll`, {
|
||||
type: SECRET,
|
||||
opt: { labelSelector: `ui.forklift/created-for-resource-type=${ HCI.FORKLIFT_PROVIDER }` }
|
||||
});
|
||||
} catch (e) {
|
||||
errors.value = [e?.message || t('harvester.addons.vmMigration.errors.failedLoadProviders')];
|
||||
}
|
||||
|
||||
loading.value = false;
|
||||
};
|
||||
|
||||
init();
|
||||
|
||||
const clickTestButton = () => {
|
||||
testBtnRef.value?.$el?.click();
|
||||
};
|
||||
|
||||
defineExpose({ testConnection, clickTestButton });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Loading v-if="loading" />
|
||||
<div
|
||||
v-else
|
||||
class="configure-provider-step"
|
||||
>
|
||||
<p class="text-deemphasized line-height-20">
|
||||
{{ t('harvester.addons.vmMigration.configureProvider.description') }}
|
||||
</p>
|
||||
|
||||
<div class="configure-provider-step-content">
|
||||
<h3 class="table-title m-0">
|
||||
<b>{{ t('harvester.addons.vmMigration.configureProvider.connectionDetails') }}</b>
|
||||
</h3>
|
||||
|
||||
<Banner
|
||||
class="requirements-banner m-0"
|
||||
color="info"
|
||||
>
|
||||
<div class="requirements-banner-content">
|
||||
<span class="requirements-banner-title">{{ t('harvester.addons.vmMigration.configureProvider.requirementsTitle') }}</span>
|
||||
<br>
|
||||
<span>{{ t('harvester.addons.vmMigration.configureProvider.requirementsText') }}</span>
|
||||
</div>
|
||||
</Banner>
|
||||
|
||||
<div class="configure-provider-step-form">
|
||||
<div v-if="!createOnly && !editMode">
|
||||
<LabeledSelect
|
||||
v-model:value="selectedProvider"
|
||||
required
|
||||
:label="t('harvester.addons.vmMigration.configureProvider.providerSelect')"
|
||||
:options="providerOptions"
|
||||
:reduce="(opt) => opt.value"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="!isExistingProvider || editMode"
|
||||
>
|
||||
<LabeledInput
|
||||
v-model:value="providerName"
|
||||
:label="t('harvester.addons.vmMigration.configureProvider.name')"
|
||||
:disabled="editMode"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="col span-6">
|
||||
<LabeledInput
|
||||
v-model:value="url"
|
||||
:label="t('harvester.addons.vmMigration.configureProvider.urlLabel')"
|
||||
:placeholder="t('harvester.addons.vmMigration.configureProvider.urlPlaceholder')"
|
||||
:disabled="isExistingProvider && !editMode"
|
||||
required
|
||||
/>
|
||||
<p class="text-deemphasized mt-5">
|
||||
{{ t('harvester.addons.vmMigration.configureProvider.urlHint') }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="col span-6">
|
||||
<LabeledInput
|
||||
v-model:value="vddkInitImage"
|
||||
:label="t('harvester.addons.vmMigration.configureProvider.vddkImageLabel')"
|
||||
:placeholder="t('harvester.addons.vmMigration.configureProvider.vddkImagePlaceholder')"
|
||||
:tooltip="t('harvester.addons.vmMigration.configureProvider.vddkImageTooltip')"
|
||||
:disabled="isExistingProvider && !editMode"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="col span-6">
|
||||
<LabeledInput
|
||||
v-model:value="username"
|
||||
:label="t('harvester.addons.vmMigration.fields.username')"
|
||||
:disabled="isExistingProvider && !editMode"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div class="col span-6">
|
||||
<LabeledInput
|
||||
v-model:value="password"
|
||||
type="password"
|
||||
:label="t('harvester.addons.vmMigration.fields.password')"
|
||||
:disabled="isExistingProvider && !editMode"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Checkbox
|
||||
v-model:value="skipTlsVerify"
|
||||
:label="t('harvester.addons.vmMigration.configureProvider.skipSsl')"
|
||||
:disabled="isExistingProvider && !editMode"
|
||||
/>
|
||||
<p class="text-deemphasized ml-20">
|
||||
{{ t('harvester.addons.vmMigration.configureProvider.skipSslHint') }}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<AsyncButton
|
||||
ref="testBtnRef"
|
||||
mode="test"
|
||||
:disabled="!isFormValid"
|
||||
:action-label="t('harvester.addons.vmMigration.configureProvider.testConnection.action')"
|
||||
:waiting-label="t('harvester.addons.vmMigration.configureProvider.testConnection.waiting')"
|
||||
:success-label="t('harvester.addons.vmMigration.configureProvider.testConnection.success')"
|
||||
:error-label="t('harvester.addons.vmMigration.configureProvider.testConnection.error')"
|
||||
:action-color="'role-secondary'"
|
||||
:waiting-color="'role-disabled'"
|
||||
@click="testConnection"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Banner
|
||||
v-if="testResult"
|
||||
color="success"
|
||||
>
|
||||
{{ testResult }}
|
||||
</Banner>
|
||||
<Banner
|
||||
v-if="testError"
|
||||
color="error"
|
||||
>
|
||||
{{ testError }}
|
||||
</Banner>
|
||||
<Banner
|
||||
v-for="(err, i) in errors"
|
||||
:key="i"
|
||||
color="error"
|
||||
>
|
||||
{{ err }}
|
||||
</Banner>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.requirements-banner {
|
||||
font-weight: 400;
|
||||
|
||||
.requirements-banner-title {
|
||||
font-weight: 600;
|
||||
}
|
||||
}
|
||||
|
||||
.configure-provider-step {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 24px;
|
||||
|
||||
.line-height-20 {
|
||||
line-height: 20px;
|
||||
}
|
||||
|
||||
.configure-provider-step-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
|
||||
.configure-provider-step-form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 20px;
|
||||
}
|
||||
}
|
||||
|
||||
:deep(.checkbox-label) {
|
||||
color: var(--body-text);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,252 +0,0 @@
|
||||
<script setup>
|
||||
import { useStore } from 'vuex';
|
||||
import LabeledSelect from '@shell/components/form/LabeledSelect';
|
||||
import { RcItemCard } from '@components/RcItemCard';
|
||||
import { useI18n } from '@shell/composables/useI18n';
|
||||
import { VOLUME_MODE } from '../../config/types';
|
||||
|
||||
const store = useStore();
|
||||
const { t } = useI18n(store);
|
||||
|
||||
const props = defineProps({
|
||||
title: { type: String, required: true },
|
||||
description: { type: String, default: '' },
|
||||
entries: { type: Array, default: () => [] },
|
||||
options: { type: Array, default: () => [] },
|
||||
placeholder: { type: String, default: '' },
|
||||
showUsedBy: { type: Boolean, default: false },
|
||||
clearable: { type: Boolean, default: false },
|
||||
// Storage-specific: show the volume/access mode defaults row with an Edit action.
|
||||
showVolumeSettings: { type: Boolean, default: false },
|
||||
// When set, the defaults row shows an "Inherited from provider" hint (migration plan wizard only).
|
||||
inheritedProviderName: { type: String, default: '' },
|
||||
});
|
||||
|
||||
const emit = defineEmits(['edit-defaults']);
|
||||
|
||||
// Only offer "Remove Map" for entries that already have a target selected;
|
||||
// entries without a selection just show the regular options.
|
||||
const optionsFor = (entry) => {
|
||||
if (!props.clearable || !entry.target) {
|
||||
return props.options;
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
label: t('harvester.addons.vmMigration.configureMappings.removeMap'),
|
||||
value: null,
|
||||
kind: 'highlighted',
|
||||
},
|
||||
{
|
||||
label: 'divider',
|
||||
disabled: true,
|
||||
kind: 'divider',
|
||||
},
|
||||
...props.options,
|
||||
];
|
||||
};
|
||||
|
||||
const formatModes = (entry) => {
|
||||
const volumeMode = entry.volumeMode || VOLUME_MODE.FILE_SYSTEM;
|
||||
const accessModes = (entry.accessModes || []).join(', ');
|
||||
|
||||
return t('harvester.addons.vmMigration.storageDefaults.summary', { volumeMode, accessModes });
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="mapping-column">
|
||||
<div>
|
||||
<h3 class="mapping-section-title">
|
||||
{{ title }}
|
||||
</h3>
|
||||
<p
|
||||
v-if="description"
|
||||
class="text-deemphasized line-height-20"
|
||||
>
|
||||
{{ description }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<RcItemCard
|
||||
v-for="entry in entries"
|
||||
:id="entry._key"
|
||||
:key="entry._key"
|
||||
:variant="'small'"
|
||||
:header="{}"
|
||||
class="bg-light-gray"
|
||||
>
|
||||
<template #item-card-content>
|
||||
<div class="card-content-column">
|
||||
<div class="card-content-row">
|
||||
<div class="mapping-source">
|
||||
<span class="source-name">{{ entry.name }}</span>
|
||||
<slot
|
||||
name="source-detail"
|
||||
:entry="entry"
|
||||
/>
|
||||
</div>
|
||||
<div :class="['mapping-arrow', entry.target ? 'text-success' : 'text-deemphasized']">
|
||||
<i
|
||||
class="icon icon-right-arrow-alt"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</div>
|
||||
<div class="mapping-target">
|
||||
<LabeledSelect
|
||||
v-model:value="entry.target"
|
||||
:options="optionsFor(entry)"
|
||||
:placeholder="placeholder+'...'"
|
||||
:searchable="true"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
v-if="showVolumeSettings && entry.target"
|
||||
class="storage-defaults-row"
|
||||
>
|
||||
<div class="storage-defaults">
|
||||
<div class="storage-defaults-info">
|
||||
<span class="storage-defaults-summary">{{ formatModes(entry) }}</span>
|
||||
<span
|
||||
v-if="inheritedProviderName && entry.inheritedFromProvider && !entry.overridden"
|
||||
class="text-deemphasized storage-defaults-inherited"
|
||||
>
|
||||
{{ t('harvester.addons.vmMigration.storageDefaults.inherited', { provider: inheritedProviderName }) }}
|
||||
</span>
|
||||
</div>
|
||||
<a
|
||||
role="button"
|
||||
class="storage-defaults-edit"
|
||||
@click.prevent="emit('edit-defaults', entry)"
|
||||
>
|
||||
{{ t('harvester.addons.vmMigration.storageDefaults.edit') }}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="showUsedBy && entry.usedBy && entry.usedBy.length">
|
||||
<span class="used-by">
|
||||
{{ t('harvester.addons.vmMigration.generic.usedBy') }} <b>{{ entry.usedBy.join(', ') }}</b>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</RcItemCard>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.mapping-column {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
flex-direction: column;
|
||||
|
||||
:deep(.item-card-header) {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
.mapping-section-title {
|
||||
font-weight: 600;
|
||||
margin: 0 0 5px 0;
|
||||
line-height: 28px;
|
||||
}
|
||||
|
||||
.card-content-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.card-content-column {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.mapping-source {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 2;
|
||||
min-width: 100px;
|
||||
font-size: 14px;
|
||||
line-height: 20px;
|
||||
|
||||
.source-name {
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.source-detail {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.used-by {
|
||||
margin-top: 4px;
|
||||
font-size: 14px;
|
||||
line-height: 24px;
|
||||
}
|
||||
}
|
||||
|
||||
.mapping-arrow {
|
||||
font-size: 22px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.mapping-target {
|
||||
flex: 3;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.line-height-20 {
|
||||
line-height: 20px;
|
||||
}
|
||||
|
||||
.storage-defaults-row {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.storage-defaults {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding: 8px 12px;
|
||||
border-radius: 4px;
|
||||
background-color: var(--body-bg);
|
||||
|
||||
.storage-defaults-info {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.storage-defaults-summary {
|
||||
font-size: 13px;
|
||||
line-height: 20px;
|
||||
}
|
||||
|
||||
.storage-defaults-inherited {
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
}
|
||||
|
||||
.storage-defaults-edit {
|
||||
flex-shrink: 0;
|
||||
cursor: pointer;
|
||||
}
|
||||
}
|
||||
|
||||
.bg-light-gray {
|
||||
background-color: var(--category-active) !important;
|
||||
border: 0;
|
||||
}
|
||||
</style>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user