mirror of
https://github.com/lensapp/lens.git
synced 2025-05-20 05:10:56 +00:00
Merge branch 'master' into prometheus-cluster-metadata
This commit is contained in:
commit
88a392ff0c
@ -30,10 +30,9 @@ jobs:
|
||||
displayName: Install Node.js
|
||||
- task: Cache@2
|
||||
inputs:
|
||||
key: yarn | $(Agent.OS) | yarn.lock
|
||||
key: 'yarn | "$(Agent.OS)"" | yarn.lock'
|
||||
restoreKeys: |
|
||||
yarn | "$(Agent.OS)"
|
||||
yarn
|
||||
path: $(YARN_CACHE_FOLDER)
|
||||
displayName: Cache Yarn packages
|
||||
- script: make node_modules
|
||||
@ -70,10 +69,9 @@ jobs:
|
||||
displayName: Install Node.js
|
||||
- task: Cache@2
|
||||
inputs:
|
||||
key: yarn | $(Agent.OS) | yarn.lock
|
||||
key: 'yarn | "$(Agent.OS)" | yarn.lock'
|
||||
restoreKeys: |
|
||||
yarn | "$(Agent.OS)"
|
||||
yarn
|
||||
path: $(YARN_CACHE_FOLDER)
|
||||
displayName: Cache Yarn packages
|
||||
- script: make node_modules
|
||||
@ -116,10 +114,9 @@ jobs:
|
||||
displayName: Install Node.js
|
||||
- task: Cache@2
|
||||
inputs:
|
||||
key: yarn | $(Agent.OS) | yarn.lock
|
||||
key: 'yarn | "$(Agent.OS)" | yarn.lock'
|
||||
restoreKeys: |
|
||||
yarn | "$(Agent.OS)"
|
||||
yarn
|
||||
path: $(YARN_CACHE_FOLDER)
|
||||
displayName: Cache Yarn packages
|
||||
- script: make node_modules
|
||||
|
||||
32
.eslintrc.js
32
.eslintrc.js
@ -1,5 +1,8 @@
|
||||
module.exports = {
|
||||
ignorePatterns: ["src/extensions/npm/extensions/dist/**/*"],
|
||||
module.exports = {
|
||||
ignorePatterns: [
|
||||
"**/node_modules/**/*",
|
||||
"**/dist/**/*",
|
||||
],
|
||||
overrides: [
|
||||
{
|
||||
files: [
|
||||
@ -13,14 +16,17 @@ module.exports = {
|
||||
env: {
|
||||
node: true
|
||||
},
|
||||
parserOptions: {
|
||||
parserOptions: {
|
||||
ecmaVersion: 2018,
|
||||
sourceType: 'module',
|
||||
},
|
||||
rules: {
|
||||
"indent": ["error", 2],
|
||||
"indent": ["error", 2, {
|
||||
"SwitchCase": 1,
|
||||
}],
|
||||
"no-unused-vars": "off",
|
||||
"semi": ["error", "always"],
|
||||
"object-shorthand": "error",
|
||||
}
|
||||
},
|
||||
{
|
||||
@ -33,10 +39,10 @@ module.exports = {
|
||||
"__mocks__/*.ts",
|
||||
],
|
||||
parser: "@typescript-eslint/parser",
|
||||
extends: [
|
||||
extends: [
|
||||
'plugin:@typescript-eslint/recommended',
|
||||
],
|
||||
parserOptions: {
|
||||
parserOptions: {
|
||||
ecmaVersion: 2018,
|
||||
sourceType: 'module',
|
||||
},
|
||||
@ -48,9 +54,12 @@ module.exports = {
|
||||
"@typescript-eslint/ban-types": "off",
|
||||
"@typescript-eslint/ban-ts-comment": "off",
|
||||
"@typescript-eslint/no-empty-interface": "off",
|
||||
"indent": ["error", 2],
|
||||
"indent": ["error", 2, {
|
||||
"SwitchCase": 1,
|
||||
}],
|
||||
"semi": "off",
|
||||
"@typescript-eslint/semi": ["error"],
|
||||
"object-shorthand": "error",
|
||||
},
|
||||
},
|
||||
{
|
||||
@ -58,10 +67,10 @@ module.exports = {
|
||||
"src/renderer/**/*.tsx",
|
||||
],
|
||||
parser: "@typescript-eslint/parser",
|
||||
extends: [
|
||||
extends: [
|
||||
'plugin:@typescript-eslint/recommended',
|
||||
],
|
||||
parserOptions: {
|
||||
parserOptions: {
|
||||
ecmaVersion: 2018,
|
||||
sourceType: 'module',
|
||||
jsx: true,
|
||||
@ -78,9 +87,12 @@ module.exports = {
|
||||
"@typescript-eslint/explicit-module-boundary-types": "off",
|
||||
"@typescript-eslint/ban-types": "off",
|
||||
"@typescript-eslint/no-empty-function": "off",
|
||||
"indent": ["error", 2],
|
||||
"indent": ["error", 2, {
|
||||
"SwitchCase": 1,
|
||||
}],
|
||||
"semi": "off",
|
||||
"@typescript-eslint/semi": ["error"],
|
||||
"object-shorthand": "error",
|
||||
},
|
||||
}
|
||||
]
|
||||
|
||||
132
CODE_OF_CONDUCT.md
Normal file
132
CODE_OF_CONDUCT.md
Normal file
@ -0,0 +1,132 @@
|
||||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
We as members, contributors, and leaders pledge to make participation in our
|
||||
community a harassment-free experience for everyone, regardless of age, body
|
||||
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
||||
identity and expression, level of experience, education, socio-economic status,
|
||||
nationality, personal appearance, race, religion, or sexual identity
|
||||
and orientation.
|
||||
|
||||
We pledge to act and interact in ways that contribute to an open, welcoming,
|
||||
diverse, inclusive, and healthy community.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to a positive environment for our
|
||||
community include:
|
||||
|
||||
* Demonstrating empathy and kindness toward other people
|
||||
* Being respectful of differing opinions, viewpoints, and experiences
|
||||
* Giving and gracefully accepting constructive feedback
|
||||
* Accepting responsibility and apologizing to those affected by our mistakes,
|
||||
and learning from the experience
|
||||
* Focusing on what is best not just for us as individuals, but for the
|
||||
overall community
|
||||
|
||||
Examples of unacceptable behavior include:
|
||||
|
||||
* The use of sexualized language or imagery, and sexual attention or
|
||||
advances of any kind
|
||||
* Trolling, insulting or derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or email
|
||||
address, without their explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Enforcement Responsibilities
|
||||
|
||||
Community leaders are responsible for clarifying and enforcing our standards of
|
||||
acceptable behavior and will take appropriate and fair corrective action in
|
||||
response to any behavior that they deem inappropriate, threatening, offensive,
|
||||
or harmful.
|
||||
|
||||
Community leaders have the right and responsibility to remove, edit, or reject
|
||||
comments, commits, code, wiki edits, issues, and other contributions that are
|
||||
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
||||
decisions when appropriate.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies within all community spaces, and also applies when
|
||||
an individual is officially representing the community in public spaces.
|
||||
Examples of representing our community include using an official e-mail address,
|
||||
posting via an official social media account, or acting as an appointed
|
||||
representative at an online or offline event.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported to the community leaders responsible for enforcement at
|
||||
info@k8slens.dev.
|
||||
All complaints will be reviewed and investigated promptly and fairly.
|
||||
|
||||
All community leaders are obligated to respect the privacy and security of the
|
||||
reporter of any incident.
|
||||
|
||||
## Enforcement Guidelines
|
||||
|
||||
Community leaders will follow these Community Impact Guidelines in determining
|
||||
the consequences for any action they deem in violation of this Code of Conduct:
|
||||
|
||||
### 1. Correction
|
||||
|
||||
**Community Impact**: Use of inappropriate language or other behavior deemed
|
||||
unprofessional or unwelcome in the community.
|
||||
|
||||
**Consequence**: A private, written warning from community leaders, providing
|
||||
clarity around the nature of the violation and an explanation of why the
|
||||
behavior was inappropriate. A public apology may be requested.
|
||||
|
||||
### 2. Warning
|
||||
|
||||
**Community Impact**: A violation through a single incident or series
|
||||
of actions.
|
||||
|
||||
**Consequence**: A warning with consequences for continued behavior. No
|
||||
interaction with the people involved, including unsolicited interaction with
|
||||
those enforcing the Code of Conduct, for a specified period of time. This
|
||||
includes avoiding interactions in community spaces as well as external channels
|
||||
like social media. Violating these terms may lead to a temporary or
|
||||
permanent ban.
|
||||
|
||||
### 3. Temporary Ban
|
||||
|
||||
**Community Impact**: A serious violation of community standards, including
|
||||
sustained inappropriate behavior.
|
||||
|
||||
**Consequence**: A temporary ban from any sort of interaction or public
|
||||
communication with the community for a specified period of time. No public or
|
||||
private interaction with the people involved, including unsolicited interaction
|
||||
with those enforcing the Code of Conduct, is allowed during this period.
|
||||
Violating these terms may lead to a permanent ban.
|
||||
|
||||
### 4. Permanent Ban
|
||||
|
||||
**Community Impact**: Demonstrating a pattern of violation of community
|
||||
standards, including sustained inappropriate behavior, harassment of an
|
||||
individual, or aggression toward or disparagement of classes of individuals.
|
||||
|
||||
**Consequence**: A permanent ban from any sort of public interaction within
|
||||
the community.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
||||
version 2.0, available at
|
||||
[https://www.contributor-covenant.org/version/2/0/code_of_conduct.html][v2.0].
|
||||
|
||||
Community Impact Guidelines were inspired by
|
||||
[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
|
||||
|
||||
For answers to common questions about this code of conduct, see the FAQ at
|
||||
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available
|
||||
at [https://www.contributor-covenant.org/translations][translations].
|
||||
|
||||
[homepage]: https://www.contributor-covenant.org
|
||||
[v2.0]: https://www.contributor-covenant.org/version/2/0/code_of_conduct.html
|
||||
[Mozilla CoC]: https://github.com/mozilla/diversity
|
||||
[FAQ]: https://www.contributor-covenant.org/faq
|
||||
[translations]: https://www.contributor-covenant.org/translations
|
||||
3
CONTRIBUTING.md
Normal file
3
CONTRIBUTING.md
Normal file
@ -0,0 +1,3 @@
|
||||
# Contributing to Lens
|
||||
|
||||
See [Contributing to Lens](https://docs.k8slens.dev/latest/contributing/) documentation.
|
||||
4
Makefile
4
Makefile
@ -99,6 +99,10 @@ publish-npm: build-npm
|
||||
npm config set '//registry.npmjs.org/:_authToken' "${NPM_TOKEN}"
|
||||
cd src/extensions/npm/extensions && npm publish --access=public
|
||||
|
||||
.PHONY: docs
|
||||
docs:
|
||||
yarn mkdocs-serve-local
|
||||
|
||||
.PHONY: clean-extensions
|
||||
clean-extensions:
|
||||
ifeq "$(DETECTED_OS)" "Windows"
|
||||
|
||||
45
README.md
45
README.md
@ -1,7 +1,7 @@
|
||||
# Lens | The Kubernetes IDE
|
||||
|
||||
[](https://dev.azure.com/lensapp/lensapp/_build/latest?definitionId=1&branchName=master)
|
||||
[](https://github.com/lensapp/lens/releases)
|
||||
[](https://github.com/lensapp/lens/releases?label=Downloads)
|
||||
[](https://join.slack.com/t/k8slens/shared_invite/enQtOTc5NjAyNjYyOTk4LWU1NDQ0ZGFkOWJkNTRhYTc2YjVmZDdkM2FkNGM5MjhiYTRhMDU2NDQ1MzIyMDA4ZGZlNmExOTc0N2JmY2M3ZGI)
|
||||
|
||||
World’s most popular Kubernetes IDE provides a simplified, consistent entry point for developers, testers, integrators, and DevOps, to ship code faster at scale. Lens is the only IDE you’ll ever need to take control of your Kubernetes clusters. It is a standalone application for MacOS, Windows and Linux operating systems. Lens is an open source project and free!
|
||||
@ -25,49 +25,12 @@ World’s most popular Kubernetes IDE provides a simplified, consistent entry po
|
||||
|
||||
## Installation
|
||||
|
||||
Download a pre-built package from the [releases](https://github.com/lensapp/lens/releases) page. Lens can be also installed via [snapcraft](https://snapcraft.io/kontena-lens) (Linux only).
|
||||
|
||||
Alternatively on Mac:
|
||||
```
|
||||
brew cask install lens
|
||||
```
|
||||
See [Getting Started](https://docs.k8slens.dev/latest/getting-started/) page.
|
||||
|
||||
## Development
|
||||
|
||||
> Prerequisites: Nodejs v12, make, yarn
|
||||
|
||||
* `make dev` - builds and starts the app
|
||||
* `make test` - run tests
|
||||
|
||||
## Development (advanced)
|
||||
|
||||
Allows for faster separate re-runs of some of the more involved processes:
|
||||
|
||||
1. `yarn dev:main` compiles electron's main process app part
|
||||
1. `yarn dev:renderer` compiles electron's renderer app part
|
||||
1. `yarn dev:extension-types` compile declaration types for `@k8slens/extensions`
|
||||
1. `yarn dev-run` runs app in dev-mode and auto-restart when main process file has changed
|
||||
|
||||
## Development (documentation)
|
||||
|
||||
Run a local instance of `mkdocs serve` in a docker container for developing the Lens Documentation.
|
||||
|
||||
> Prerequisites: docker, yarn
|
||||
|
||||
* `yarn mkdocs-serve-local` - local build and serve of mkdocs with auto update enabled
|
||||
|
||||
Go to [localhost:8000](http://127.0.0.1:8000)
|
||||
|
||||
## Developer's ~~RTFM~~ recommended list:
|
||||
|
||||
- [TypeScript](https://www.typescriptlang.org/docs/home.html) (front-end/back-end)
|
||||
- [ReactJS](https://reactjs.org/docs/getting-started.html) (front-end, ui)
|
||||
- [MobX](https://mobx.js.org/) (app-state-management, back-end/front-end)
|
||||
- [ElectronJS](https://www.electronjs.org/docs) (chrome/node)
|
||||
- [NodeJS](https://nodejs.org/dist/latest-v12.x/docs/api/) (api docs)
|
||||
|
||||
|
||||
See [Development](https://docs.k8slens.dev/latest/contributing/development/) page.
|
||||
|
||||
## Contributing
|
||||
|
||||
Bug reports and pull requests are welcome on GitHub at https://github.com/lensapp/lens.
|
||||
See [Contributing](https://docs.k8slens.dev/latest/contributing/) page.
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
# Adding Clusters
|
||||
|
||||
Add clusters by clicking the **Add Cluster** button in the left-side menu.
|
||||
Add clusters by clicking the **Add Cluster** button in the left-side menu.
|
||||
|
||||
1. Click the **Add Cluster** button (indicated with a '+' icon).
|
||||
2. Enter the path to your kubeconfig file. You'll need to have a kubeconfig file for the cluster you want to add. You can either browse for the path from the file system or or enter it directly.
|
||||
@ -13,4 +13,10 @@ Selected [cluster contexts](https://kubernetes.io/docs/concepts/configuration/or
|
||||
|
||||
For more information on kubeconfig see [Kubernetes docs](https://kubernetes.io/docs/concepts/configuration/organize-cluster-access-kubeconfig/).
|
||||
|
||||
To see your currently-enabled config with `kubectl`, enter `kubectl config view --minify --raw` in your terminal.
|
||||
To see your currently-enabled config with `kubectl`, enter `kubectl config view --minify --raw` in your terminal.
|
||||
|
||||
When connecting to a cluster, make sure you have a valid and working kubeconfig for the cluster. Following lists known "gotchas" in some authentication types used in kubeconfig with Lens app.
|
||||
|
||||
## Exec auth plugins
|
||||
|
||||
When using [exec auth](https://kubernetes.io/docs/reference/access-authn-authz/authentication/#configuration) plugins make sure the paths that are used to call any binaries are full paths as Lens app might not be able to call binaries with relative paths. Make also sure that you pass all needed information either as arguments or env variables in the config, Lens app might not have all login shell env variables set automatically.
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 252 KiB After Width: | Height: | Size: 611 KiB |
@ -1,3 +1,40 @@
|
||||
# Development
|
||||
|
||||
TBD
|
||||
Thank you for taking the time to make a contribution to Lens. The following document is a set of guidelines and instructions for contributing to Lens.
|
||||
|
||||
When contributing to this repository, please consider first discussing the change you wish to make by opening an issue.
|
||||
|
||||
## Recommended Reading:
|
||||
|
||||
- [TypeScript](https://www.typescriptlang.org/docs/home.html) (front-end/back-end)
|
||||
- [ReactJS](https://reactjs.org/docs/getting-started.html) (front-end, ui)
|
||||
- [MobX](https://mobx.js.org/) (app-state-management, back-end/front-end)
|
||||
- [ElectronJS](https://www.electronjs.org/docs) (chrome/node)
|
||||
- [NodeJS](https://nodejs.org/dist/latest-v12.x/docs/api/) (api docs)
|
||||
|
||||
## Local Development Environment
|
||||
|
||||
> Prerequisites: Nodejs v12, make, yarn
|
||||
|
||||
* `make dev` - builds and starts the app
|
||||
* `make clean` - cleanup local environment build artifacts
|
||||
|
||||
|
||||
## Github Workflow
|
||||
|
||||
We Use [Github Flow](https://guides.github.com/introduction/flow/index.html), so all code changes are tracked via Pull Requests.
|
||||
A detailed guide on the recommended workflow can be found below:
|
||||
|
||||
* [Github Workflow](./github_workflow.md)
|
||||
|
||||
## Code Testing
|
||||
|
||||
All submitted PRs go through a set of tests and reviews. You can run most of these tests *before* a PR is submitted.
|
||||
In fact, we recommend it, because it will save on many possible review iterations and automated tests.
|
||||
The testing guidelines can be found here:
|
||||
|
||||
* [Contributor's Guide to Testing](./testing.md)
|
||||
|
||||
## License
|
||||
|
||||
By contributing, you agree that your contributions will be licensed as described in [LICENSE](https://github.com/lensapp/lens/blob/master/LICENSE).
|
||||
|
||||
@ -20,3 +20,14 @@ When you create a new pull request, we expect some requirements to be met.
|
||||
* When updating documentation, add `Update Documentation:` before the title. E.g. `Update Documentation: Getting Started`
|
||||
* If your Pull Request closes an issue, you must write `Closes #ISSUE_NUMBER` where the ISSUE_NUMBER is the number in the end of the link url or the relevent issue. This will link your pull request to the issue, and when it is merged, the issue will close.
|
||||
* For each pull request made, we run tests to check if there are any broken links, the markdown formatting is valid, and the linter is passing.
|
||||
|
||||
|
||||
## Testing Documentation Site Locally
|
||||
|
||||
Run a local instance of `mkdocs` in a docker container for developing the Lens Documentation.
|
||||
|
||||
> Prerequisites: docker, yarn
|
||||
|
||||
* `make docs` - local build and serve of mkdocs with auto update enabled
|
||||
|
||||
Go to [localhost:8000](http://127.0.0.1:8000).
|
||||
|
||||
148
docs/contributing/github_workflow.md
Normal file
148
docs/contributing/github_workflow.md
Normal file
@ -0,0 +1,148 @@
|
||||
# Github Workflow
|
||||
|
||||
<!-- TOC -->
|
||||
- [Fork The Project](#fork-the-project)
|
||||
- [Adding the Forked Remote](#adding-the-forked-remote)
|
||||
- [Create & Rebase Your Feature Branch](#create--rebase-your-feature-branch)
|
||||
- [Commit & Push](#commit--push)
|
||||
- [Open a Pull Request](#open-a-pull-request)
|
||||
- [Get a code review](#get-a-code-review)
|
||||
- [Squash commits](#squash-commits)
|
||||
- [Push Your Final Changes](#push-your-final-changes)
|
||||
|
||||
<!-- /TOC -->
|
||||
This guide assumes you have already cloned the upstream repo to your system via git clone.
|
||||
|
||||
## Fork The Project
|
||||
|
||||
1. Go to [http://github.com/lensapp/lens](http://github.com/lensapp/lens)
|
||||
2. On the top, right-hand side, click on "fork" and select your username for the fork destination.
|
||||
|
||||
## Adding the Forked Remote
|
||||
|
||||
```
|
||||
export GITHUB_USER={ your github's username }
|
||||
|
||||
cd $WORKDIR/lens
|
||||
git remote add $GITHUB_USER git@github.com:${GITHUB_USER}/lens.git
|
||||
|
||||
# Prevent push to Upstream
|
||||
git remote set-url --push origin no_push
|
||||
|
||||
# Set your fork remote as a default push target
|
||||
git push --set-upstream $GITHUB_USER master
|
||||
```
|
||||
|
||||
Your remotes should look something like this:
|
||||
|
||||
```
|
||||
➜ git remote -v
|
||||
origin https://github.com/lensapp/lens (fetch)
|
||||
origin no_push (push)
|
||||
my_fork git@github.com:{ github_username }/lens.git (fetch)
|
||||
my_fork git@github.com:{ github_username }/lens.git (push)
|
||||
```
|
||||
|
||||
## Create & Rebase Your Feature Branch
|
||||
|
||||
Create a feature branch:
|
||||
|
||||
```
|
||||
git branch -b my_feature_branch
|
||||
```
|
||||
|
||||
Rebase your branch:
|
||||
|
||||
```
|
||||
git fetch origin
|
||||
|
||||
git rebase origin/master
|
||||
Current branch my_feature_branch is up to date.
|
||||
```
|
||||
|
||||
Please don't use `git pull` instead of the above `fetch / rebase`. `git pull` does a merge, which leaves merge commits. These make the commit history messy and violate the principle that commits ought to be individually understandable and useful.
|
||||
|
||||
## Commit & Push
|
||||
|
||||
Commit and sign your changes:
|
||||
|
||||
```
|
||||
git commit -m "my commit title" --signoff
|
||||
```
|
||||
|
||||
You can go back and edit/build/test some more, then `commit --amend` in a few cycles.
|
||||
|
||||
When ready, push your changes to your fork's repository:
|
||||
|
||||
```
|
||||
git push --set-upstream my_fork my_feature_branch
|
||||
```
|
||||
|
||||
## Open a Pull Request
|
||||
|
||||
See [Github Docs](https://docs.github.com/en/free-pro-team@latest/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request-from-a-fork).
|
||||
|
||||
### Get a code review
|
||||
|
||||
Once your pull request has been opened it will be assigned to one or more reviewers, and will go through a series of smoke tests.
|
||||
|
||||
Commit changes made in response to review comments should be added to the same branch on your fork.
|
||||
|
||||
Very small PRs are easy to review. Very large PRs are very difficult to review.
|
||||
|
||||
### Squashing Commits
|
||||
Commits on your branch should represent meaningful milestones or units of work.
|
||||
Small commits that contain typo fixes, rebases, review feedbacks, etc should be squashed.
|
||||
|
||||
To do that, it's best to perform an [interactive rebase](https://git-scm.com/book/en/v2/Git-Tools-Rewriting-History):
|
||||
|
||||
#### Example
|
||||
If you PR has 3 commits, count backwards from your last commit using `HEAD~3`:
|
||||
```
|
||||
git rebase -i HEAD~3
|
||||
```
|
||||
Output would be similar to this:
|
||||
```
|
||||
pick f7f3f6d Changed some code
|
||||
pick 310154e fixed some typos
|
||||
pick a5f4a0d made some review changes
|
||||
|
||||
# Rebase 710f0f8..a5f4a0d onto 710f0f8
|
||||
#
|
||||
# Commands:
|
||||
# p, pick <commit> = use commit
|
||||
# r, reword <commit> = use commit, but edit the commit message
|
||||
# e, edit <commit> = use commit, but stop for amending
|
||||
# s, squash <commit> = use commit, but meld into previous commit
|
||||
# f, fixup <commit> = like "squash", but discard this commit's log message
|
||||
# x, exec <command> = run command (the rest of the line) using shell
|
||||
# b, break = stop here (continue rebase later with 'git rebase --continue')
|
||||
# d, drop <commit> = remove commit
|
||||
# l, label <label> = label current HEAD with a name
|
||||
# t, reset <label> = reset HEAD to a label
|
||||
# m, merge [-C <commit> | -c <commit>] <label> [# <oneline>]
|
||||
# . create a merge commit using the original merge commit's
|
||||
# . message (or the oneline, if no original merge commit was
|
||||
# . specified). Use -c <commit> to reword the commit message.
|
||||
#
|
||||
# These lines can be re-ordered; they are executed from top to bottom.
|
||||
#
|
||||
# However, if you remove everything, the rebase will be aborted.
|
||||
#
|
||||
# Note that empty commits are commented out
|
||||
```
|
||||
Use a command line text editor to change the word `pick` to `fixup` for the commits you want to squash, then save your changes and continue the rebase:
|
||||
|
||||
Per the output above, you can see that:
|
||||
```
|
||||
fixup <commit> = like "squash", but discard this commit's log message
|
||||
```
|
||||
Which means that when rebased, the commit message "fixed some typos" will be removed, and squashed with the parent commit.
|
||||
|
||||
### Push Your Final Changes
|
||||
|
||||
Once done, you can push the final commits to your branch:
|
||||
```
|
||||
git push --force
|
||||
```
|
||||
You can run multiple iteration of `rebase`/`push -f`, if needed.
|
||||
45
docs/contributing/testing.md
Normal file
45
docs/contributing/testing.md
Normal file
@ -0,0 +1,45 @@
|
||||
## Testing Your Code
|
||||
|
||||
Lens uses github actions to run automated tests on any PR, before merging.
|
||||
However, a PR will not be reviewed before all tests are green, so to save time and prevent your PR from going stale, it is best to test it before submitting the PR.
|
||||
|
||||
### Run Local Verifications
|
||||
|
||||
Please run the following style and formatting commands and fix/check-in any changes:
|
||||
|
||||
#### 1. Linting
|
||||
|
||||
We use [ESLing](https://eslint.org/) for style verification.
|
||||
In the repository's root directory, simply run:
|
||||
|
||||
```
|
||||
make lint
|
||||
```
|
||||
|
||||
#### 3. Pre-submit Flight Checks
|
||||
|
||||
In the repository root directory, make sure that:
|
||||
|
||||
* `make build` runs successfully.
|
||||
* `make test` runs successfully.
|
||||
* `make integration` runs successfully (some tests require minikube running).
|
||||
|
||||
Please note that this last test is prone to "flakiness", so it might fail on occasion. If it fails constantly, take a deeper look at your code to find the source of the problem.
|
||||
|
||||
If you find that all tests passed, you may open a pull request upstream.
|
||||
|
||||
### Opening A Pull Request
|
||||
|
||||
#### Draft Mode
|
||||
|
||||
You may open a pull request in [draft mode](https://github.blog/2019-02-14-introducing-draft-pull-requests).
|
||||
All automated tests will still run against the PR, but the PR will not be assigned for review.
|
||||
Once a PR is ready for review, transition it from Draft mode, and code owners will be notified.
|
||||
|
||||
#### Pre-Requisites for PR Merge
|
||||
|
||||
In order for a PR to be merged, the following conditions should exist:
|
||||
1. The PR has passed all the automated tests (style, build & conformance tests).
|
||||
2. PR commits have been signed with the `--signoff` option.
|
||||
3. PR was reviewed and approved by a code owner.
|
||||
4. PR is rebased against upstream's master branch.
|
||||
@ -101,7 +101,6 @@ export default class ExampleRendererExtension extends LensRendererExtension {
|
||||
globalPages = [
|
||||
{
|
||||
id: "example",
|
||||
routePath: "/example",
|
||||
components: {
|
||||
Page: ExamplePage,
|
||||
}
|
||||
@ -156,7 +155,7 @@ import { ExampleIcon, ExamplePage } from "./src/page"
|
||||
export default class ExampleExtension extends LensRendererExtension {
|
||||
clusterPages = [
|
||||
{
|
||||
routePath: "/extension-example", // optional
|
||||
id: "extension-example", // optional
|
||||
exact: true, // optional
|
||||
components: {
|
||||
Page: () => <ExamplePage extension={this}/>,
|
||||
|
||||
@ -85,7 +85,7 @@ import React from "react"
|
||||
export default class ExampleExtension extends LensRendererExtension {
|
||||
clusterPages = [
|
||||
{
|
||||
routePath: "/extension-example",
|
||||
id: "extension-example",
|
||||
components: {
|
||||
Page: () => <ExamplePage extension={this}/>,
|
||||
}
|
||||
@ -94,4 +94,4 @@ export default class ExampleExtension extends LensRendererExtension {
|
||||
}
|
||||
```
|
||||
|
||||
The Hello World sample extension uses the `Cluster Page` capability, which is just one of the Lens extension API's capabilities. The [Common Capabilities](../capabilities/common-capabilities.md) page will help you home in on the right capabilities to use with your own extensions.
|
||||
The Hello World sample extension uses the `Cluster Page` capability, which is just one of the Lens extension API's capabilities. The [Common Capabilities](../capabilities/common-capabilities.md) page will help you home in on the right capabilities to use with your own extensions.
|
||||
|
||||
@ -1,5 +1,11 @@
|
||||
# Your First Extension
|
||||
|
||||
We recommend to always use [Yeoman generator for Lens Extension](https://github.com/lensapp/generator-lens-ext) to start new extension project. [Read the generator guide here](../guides/generator.md).
|
||||
|
||||
If you want to setup the project manually, please continue reading.
|
||||
|
||||
## First Extension
|
||||
|
||||
In this topic, you'll learn the basics of building extensions by creating an extension that adds a "Hello World" page to a cluster menu.
|
||||
|
||||
## Install the Extension
|
||||
|
||||
65
docs/extensions/guides/generator.md
Normal file
65
docs/extensions/guides/generator.md
Normal file
@ -0,0 +1,65 @@
|
||||
# New Extension Project with Generator
|
||||
|
||||
The [Lens Extension Generator](https://github.com/lensapp/generator-lens-ext) scaffolds a project ready for development. Install Yeoman and Lens Extension Generator with:
|
||||
|
||||
```bash
|
||||
npm install -g yo generator-lens-ext
|
||||
```
|
||||
|
||||
Run the generator and fill out a few fields for a TypeScript project:
|
||||
|
||||
```bash
|
||||
yo lens-ext
|
||||
# ? What type of extension do you want to create? New Extension (TypeScript)
|
||||
# ? What's the name of your extension? my-first-lens-ext
|
||||
# ? What's the description of your extension? My hello world extension
|
||||
# ? What's your extension's publisher name? @my-org/my-first-lens-ext
|
||||
# ? Initialize a git repository? Yes
|
||||
# ? Install dependencies after initialization? Yes
|
||||
# ? Which package manager to use? yarn
|
||||
# ? symlink created extension folder to ~/.k8slens/extensions (mac/linux) or :User
|
||||
s\<user>\.k8slens\extensions (windows)? Yes
|
||||
```
|
||||
|
||||
Start webpack, which watches the `my-first-lens-ext` folder.
|
||||
|
||||
```bash
|
||||
cd my-first-lens-ext
|
||||
npm start # start the webpack server in watch mode
|
||||
```
|
||||
|
||||
Then, open Lens, you should see a Hello World item in the menu:
|
||||
|
||||

|
||||
|
||||
## Developing the Extension
|
||||
|
||||
Try to change `my-first-lens-ext/renderer.tsx` to "Hello Lens!":
|
||||
|
||||
```tsx
|
||||
clusterPageMenus = [
|
||||
{
|
||||
target: { pageId: "hello" },
|
||||
title: "Hello Lens",
|
||||
components: {
|
||||
Icon: ExampleIcon,
|
||||
}
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
Then, Reload Lens by CMD+R (Mac) / Ctrl+R (Linux/Windows), you should see the menu item text changes:
|
||||
|
||||

|
||||
|
||||
## Debugging the Extension
|
||||
|
||||
[Testing](../testing-and-publishing/testing.md)
|
||||
|
||||
## Next steps
|
||||
|
||||
You can take a closer look at [Common Capabilities](../capabilities/common-capabilities.md) of extension, how to [style](../capabilities/styling.md) the extension. Or the [Extension Anatomy](anatomy.md).
|
||||
|
||||
You are welcome to raise an [issue](https://github.com/lensapp/generator-lens-ext/issues) for Lens Extension Generator, if you find problems, or have feature requests.
|
||||
|
||||
The source code of the generator is hosted at [Github](https://github.com/lensapp/generator-lens-ext)
|
||||
BIN
docs/extensions/guides/images/hello-lens.png
Normal file
BIN
docs/extensions/guides/images/hello-lens.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 60 KiB |
BIN
docs/extensions/guides/images/hello-world.png
Normal file
BIN
docs/extensions/guides/images/hello-world.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 62 KiB |
@ -20,7 +20,7 @@ export default class ExampleExtensionMain extends LensMainExtension {
|
||||
}
|
||||
```
|
||||
|
||||
There are two methods that you can implement to facilitate running your custom code. `onActivate()` is called when your extension has been successfully enabled. By overriding `onActivate()` you can initiate your custom code. `onDeactivate()` is called when the extension is disabled (typically from the [Lens Extensions Page]()) and when implemented gives you a chance to clean up after your extension, if necessary. The example above simply logs messages when the extension is enabled and disabled. Note that to see standard output from the main process there must be a console connected to it. This is typically achieved by starting Lens from the command prompt.
|
||||
There are two methods that you can implement to facilitate running your custom code. `onActivate()` is called when your extension has been successfully enabled. By implementing `onActivate()` you can initiate your custom code. `onDeactivate()` is called when the extension is disabled (typically from the [Lens Extensions Page]()) and when implemented gives you a chance to clean up after your extension, if necessary. The example above simply logs messages when the extension is enabled and disabled. Note that to see standard output from the main process there must be a console connected to it. This is typically achieved by starting Lens from the command prompt.
|
||||
|
||||
The following example is a little more interesting in that it accesses some Lens state data and periodically logs the name of the currently active cluster in Lens.
|
||||
|
||||
|
||||
@ -1 +1,425 @@
|
||||
# Renderer Extension
|
||||
|
||||
The renderer extension api is the interface to Lens' renderer process (Lens runs in main and renderer processes). It allows you to access, configure, and customize Lens data, add custom Lens UI elements, and generally run custom code in Lens' renderer process. The custom Lens UI elements that can be added include global pages, cluster pages, cluster page menus, cluster features, app preferences, status bar items, KubeObject menu items, and KubeObject details items. These UI elements are based on React components.
|
||||
|
||||
## `LensRendererExtension` Class
|
||||
|
||||
To create a renderer extension simply extend the `LensRendererExtension` class:
|
||||
|
||||
``` typescript
|
||||
import { LensRendererExtension } from "@k8slens/extensions";
|
||||
|
||||
export default class ExampleExtensionMain extends LensRendererExtension {
|
||||
onActivate() {
|
||||
console.log('custom renderer process extension code started');
|
||||
}
|
||||
|
||||
onDeactivate() {
|
||||
console.log('custom renderer process extension de-activated');
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
There are two methods that you can implement to facilitate running your custom code. `onActivate()` is called when your extension has been successfully enabled. By implementing `onActivate()` you can initiate your custom code. `onDeactivate()` is called when the extension is disabled (typically from the [Lens Extensions Page]()) and when implemented gives you a chance to clean up after your extension, if necessary. The example above simply logs messages when the extension is enabled and disabled.
|
||||
|
||||
### `clusterPages`
|
||||
|
||||
Cluster pages appear as part of the cluster dashboard. They are accessible from the side bar, and are shown in the menu list after *Custom Resources*. It is conventional to use a cluster page to show information or provide functionality pertaining to the active cluster, along with custom data and functionality your extension may have. However, it is not limited to the active cluster. Also, your extension can gain access to the Kubernetes resources in the active cluster in a straightforward manner using the [`clusterStore`](../stores#clusterstore).
|
||||
|
||||
The following example adds a cluster page definition to a `LensRendererExtension` subclass:
|
||||
|
||||
``` typescript
|
||||
import { LensRendererExtension } from "@k8slens/extensions";
|
||||
import { ExampleIcon, ExamplePage } from "./page"
|
||||
import React from "react"
|
||||
|
||||
export default class ExampleExtension extends LensRendererExtension {
|
||||
clusterPages = [
|
||||
{
|
||||
id: "hello",
|
||||
components: {
|
||||
Page: () => <ExamplePage extension={this}/>,
|
||||
}
|
||||
}
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
Cluster pages are objects matching the `PageRegistration` interface. The `id` field identiifies the page, and at its simplest is just a string identifier, as shown in the example above. The 'id' field can also convey route path details, such as variable parameters provided to a page ([See example below]()). The `components` field matches the `PageComponents` interface for wich there is one field, `Page`. `Page` is of type ` React.ComponentType<any>`, which gives you great flexibility in defining the appearance and behaviour of your page. For the example above `ExamplePage` can be defined in `page.tsx`:
|
||||
|
||||
``` typescript
|
||||
import { LensRendererExtension } from "@k8slens/extensions";
|
||||
import React from "react"
|
||||
|
||||
export class ExamplePage extends React.Component<{ extension: LensRendererExtension }> {
|
||||
render() {
|
||||
return (
|
||||
<div>
|
||||
<p>Hello world!</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Note that the `ExamplePage` class defines a property named `extension`. This allows the `ExampleExtension` object to be passed in React-style in the cluster page definition, so that `ExamplePage` can access any `ExampleExtension` subclass data.
|
||||
|
||||
### `clusterPageMenus`
|
||||
|
||||
The above example code shows how to create a cluster page but not how to make it available to the Lens user. Cluster pages are typically made available through a menu item in the cluster dashboard sidebar. Expanding on the above example a cluster page menu is added to the `ExampleExtension` definition:
|
||||
|
||||
``` typescript
|
||||
import { LensRendererExtension } from "@k8slens/extensions";
|
||||
import { ExampleIcon, ExamplePage } from "./page"
|
||||
import React from "react"
|
||||
|
||||
export default class ExampleExtension extends LensRendererExtension {
|
||||
clusterPages = [
|
||||
{
|
||||
id: "hello",
|
||||
components: {
|
||||
Page: () => <ExamplePage extension={this}/>,
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
clusterPageMenus = [
|
||||
{
|
||||
target: { pageId: "hello" },
|
||||
title: "Hello World",
|
||||
components: {
|
||||
Icon: ExampleIcon,
|
||||
}
|
||||
},
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
Cluster page menus are objects matching the `ClusterPageMenuRegistration` interface. They define the appearance of the cluster page menu item in the cluster dashboard sidebar and the behaviour when the cluster page menu item is activated (typically by a mouse click). The example above uses the `target` field to set the behaviour as a link to the cluster page with `id` of `"hello"`. This is done by setting `target`'s `pageId` field to `"hello"`. The cluster page menu item's appearance is defined by setting the `title` field to the text that is to be displayed in the cluster dashboard sidebar. The `components` field is used to set an icon that appears to the left of the `title` text in the sidebar. Thus when the `"Hello World"` menu item is activated the cluster dashboard will show the contents of `ExamplePage`. This example requires the definition of another React-based component, `ExampleIcon`, which has been added to `page.tsx`:
|
||||
|
||||
``` typescript
|
||||
import { LensRendererExtension, Component } from "@k8slens/extensions";
|
||||
import React from "react"
|
||||
|
||||
export function ExampleIcon(props: Component.IconProps) {
|
||||
return <Component.Icon {...props} material="pages" tooltip={"Hi!"}/>
|
||||
}
|
||||
|
||||
export class ExamplePage extends React.Component<{ extension: LensRendererExtension }> {
|
||||
render() {
|
||||
return (
|
||||
<div>
|
||||
<p>Hello world!</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`ExampleIcon` introduces one of Lens' built-in components available to extension developers, the `Component.Icon`. Built in are the [Material Design](https://material.io) [icons](https://material.io/resources/icons/). One can be selected by name via the `material` field. `ExampleIcon` also sets a tooltip, shown when the Lens user hovers over the icon with a mouse, by setting the `tooltip` field.
|
||||
|
||||
A cluster page menu can also be used to define a foldout submenu in the cluster dashboard sidebar. This enables the grouping of cluster pages. The following example shows how to specify a submenu having two menu items:
|
||||
|
||||
``` typescript
|
||||
import { LensRendererExtension } from "@k8slens/extensions";
|
||||
import { ExampleIcon, ExamplePage } from "./page"
|
||||
import React from "react"
|
||||
|
||||
export default class ExampleExtension extends LensRendererExtension {
|
||||
clusterPages = [
|
||||
{
|
||||
id: "hello",
|
||||
components: {
|
||||
Page: () => <ExamplePage extension={this}/>,
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "bonjour",
|
||||
components: {
|
||||
Page: () => <ExemplePage extension={this}/>,
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
clusterPageMenus = [
|
||||
{
|
||||
id: "example",
|
||||
title: "Greetings",
|
||||
components: {
|
||||
Icon: ExampleIcon,
|
||||
}
|
||||
},
|
||||
{
|
||||
parentId: "example",
|
||||
target: { pageId: "hello" },
|
||||
title: "Hello World",
|
||||
components: {
|
||||
Icon: ExampleIcon,
|
||||
}
|
||||
},
|
||||
{
|
||||
parentId: "example",
|
||||
target: { pageId: "bonjour" },
|
||||
title: "Bonjour le monde",
|
||||
components: {
|
||||
Icon: ExempleIcon,
|
||||
}
|
||||
}
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
The above defines two cluster pages and three cluster page menu objects. The cluster page definitons are straightforward. The first cluster page menu object defines the parent of a foldout submenu. Setting the `id` field in a cluster page menu definition implies that it is defining a foldout submenu. Also note that the `target` field is not specified (it is ignored if the `id` field is specified). This cluster page menu object specifies the `title` and `components` fields, which are used in displaying the menu item in the cluster dashboard sidebar. Initially the submenu is hidden. Activating this menu item toggles on and off the appearance of the submenu below it. The remaining two cluster page menu objects define the contents of the submenu. A cluster page menu object is defined to be a submenu item by setting the `parentId` field to the id of the parent of a foldout submenu, `"example"` in this case
|
||||
|
||||
### `globalPages`
|
||||
|
||||
Global pages appear independently of the cluster dashboard and they fill the Lens UI space. A global page is typically triggered from the cluster menu using a [global page menu](#globalpagemenus). They can also be triggered by a [custom app menu selection](../main-extension#appmenus) from a Main Extension or a [custom status bar item](#statusbaritems). Global pages can appear even when there is no active cluster, unlike cluster pages. It is conventional to use a global page to show information and provide functionality relevant across clusters, along with custom data and functionality that your extension may have.
|
||||
|
||||
The following example defines a `LensRendererExtension` subclass with a single global page definition:
|
||||
|
||||
``` typescript
|
||||
import { LensRendererExtension } from '@k8slens/extensions';
|
||||
import { HelpPage } from './page';
|
||||
import React from 'react';
|
||||
|
||||
export default class HelpExtension extends LensRendererExtension {
|
||||
globalPages = [
|
||||
{
|
||||
id: "help",
|
||||
components: {
|
||||
Page: () => <HelpPage extension={this}/>,
|
||||
}
|
||||
}
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
Global pages are objects matching the `PageRegistration` interface. The `id` field identiifies the page, and at its simplest is just a string identifier, as shown in the example above. The 'id' field can also convey route path details, such as variable parameters provided to a page ([See example below]()). The `components` field matches the `PageComponents` interface for which there is one field, `Page`. `Page` is of type ` React.ComponentType<any>`, which gives you great flexibility in defining the appearance and behaviour of your page. For the example above `HelpPage` can be defined in `page.tsx`:
|
||||
|
||||
``` typescript
|
||||
import { LensRendererExtension } from "@k8slens/extensions";
|
||||
import React from "react"
|
||||
|
||||
export class HelpPage extends React.Component<{ extension: LensRendererExtension }> {
|
||||
render() {
|
||||
return (
|
||||
<div>
|
||||
<p>Help yourself</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Note that the `HelpPage` class defines a property named `extension`. This allows the `HelpExtension` object to be passed in React-style in the global page definition, so that `HelpPage` can access any `HelpExtension` subclass data.
|
||||
|
||||
This example code shows how to create a global page but not how to make it available to the Lens user. Global pages are typically made available through a number of ways. Menu items can be added to the Lens app menu system and set to open a global page when activated (See [`appMenus` in the Main Extension guide](../main-extension#appmenus)). Interactive elements can be placed on the status bar (the blue strip along the bottom of the Lens UI) and can be configured to link to a global page when activated (See [`statusBarItems`](#statusbaritems)). As well, global pages can be made accessible from the cluster menu, which is the vertical strip along the left side of the Lens UI showing the available cluster icons, and the Add Cluster icon. Global page menu icons that are defined using [`globalPageMenus`](#globalpagemenus) appear below the Add Cluster icon.
|
||||
|
||||
### `globalPageMenus`
|
||||
|
||||
Global page menus connect a global page to the cluster menu, which is the vertical strip along the left side of the Lens UI showing the available cluster icons, and the Add Cluster icon. Expanding on the example from [`globalPages`](#globalPages) a global page menu is added to the `HelpExtension` definition:
|
||||
|
||||
``` typescript
|
||||
import { LensRendererExtension } from "@k8slens/extensions";
|
||||
import { HelpIcon, HelpPage } from "./page"
|
||||
import React from "react"
|
||||
|
||||
export default class HelpExtension extends LensRendererExtension {
|
||||
clusterPages = [
|
||||
{
|
||||
id: "help",
|
||||
components: {
|
||||
Page: () => <HelpPage extension={this}/>,
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
globalPageMenus = [
|
||||
{
|
||||
target: { pageId: "help" },
|
||||
title: "Help",
|
||||
components: {
|
||||
Icon: HelpIcon,
|
||||
}
|
||||
},
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
Global page menus are objects matching the `PageMenuRegistration` interface. They define the appearance of the global page menu item in the cluster menu and the behaviour when the global page menu item is activated (typically by a mouse click). The example above uses the `target` field to set the behaviour as a link to the global page with `id` of `"help"`. This is done by setting `target`'s `pageId` field to `"help"`. The global page menu item's appearance is defined by setting the `title` field to the text that is to be displayed as a tooltip in the cluster menu. The `components` field is used to set an icon that appears in the cluster menu. Thus when the `"Help"` icon is activated the contents of `ExamplePage` will be shown. This example requires the definition of another React-based component, `HelpIcon`, which has been added to `page.tsx`:
|
||||
|
||||
``` typescript
|
||||
import { LensRendererExtension, Component } from "@k8slens/extensions";
|
||||
import React from "react"
|
||||
|
||||
export function HelpIcon(props: Component.IconProps) {
|
||||
return <Component.Icon {...props} material="help"/>
|
||||
}
|
||||
|
||||
export class HelpPage extends React.Component<{ extension: LensRendererExtension }> {
|
||||
render() {
|
||||
return (
|
||||
<div>
|
||||
<p>Help</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`HelpIcon` introduces one of Lens' built-in components available to extension developers, the `Component.Icon`. Built in are the [Material Design](https://material.io) [icons](https://material.io/resources/icons/). One can be selected by name via the `material` field.
|
||||
|
||||
|
||||
|
||||
|
||||
*********************************************************************
|
||||
WIP below!
|
||||
*********************************************************************
|
||||
|
||||
|
||||
|
||||
### `clusterFeatures`
|
||||
|
||||
Cluster features are Kubernetes resources that can applied and managed to the active cluster. They can be installed/uninstalled from the [cluster settings page]().
|
||||
The following example shows how to add a cluster feature:
|
||||
|
||||
``` typescript
|
||||
import { LensRendererExtension } from "@k8slens/extensions"
|
||||
import { MetricsFeature } from "./src/metrics-feature"
|
||||
import React from "react"
|
||||
|
||||
export default class ClusterMetricsFeatureExtension extends LensRendererExtension {
|
||||
clusterFeatures = [
|
||||
{
|
||||
title: "Metrics Stack",
|
||||
components: {
|
||||
Description: () => {
|
||||
return (
|
||||
<span>
|
||||
Enable timeseries data visualization (Prometheus stack) for your cluster.
|
||||
Install this only if you don't have existing Prometheus stack installed.
|
||||
You can see preview of manifests <a href="https://github.com/lensapp/lens/tree/master/extensions/lens-metrics/resources" target="_blank">here</a>.
|
||||
</span>
|
||||
)
|
||||
}
|
||||
},
|
||||
feature: new MetricsFeature()
|
||||
}
|
||||
];
|
||||
}
|
||||
```
|
||||
The `title` and `components.Description` fields appear on the cluster settings page. The cluster feature must extend the abstract class `ClusterFeature.Feature`, and specifically implement the following methods:
|
||||
|
||||
``` typescript
|
||||
abstract install(cluster: Cluster): Promise<void>;
|
||||
abstract upgrade(cluster: Cluster): Promise<void>;
|
||||
abstract uninstall(cluster: Cluster): Promise<void>;
|
||||
abstract updateStatus(cluster: Cluster): Promise<ClusterFeatureStatus>;
|
||||
```
|
||||
|
||||
### `appPreferences`
|
||||
|
||||
The Preferences page is essentially a global page. Extensions can add custom preferences to the Preferences page, thus providing a single location for users to configure global, for Lens and extensions alike.
|
||||
|
||||
``` typescript
|
||||
import React from "react"
|
||||
import { LensRendererExtension } from "@k8slens/extensions"
|
||||
import { myCustomPreferencesStore } from "./src/my-custom-preferences-store"
|
||||
import { MyCustomPreferenceHint, MyCustomPreferenceInput } from "./src/my-custom-preference"
|
||||
|
||||
|
||||
export default class ExampleRendererExtension extends LensRendererExtension {
|
||||
appPreferences = [
|
||||
{
|
||||
title: "My Custom Preference",
|
||||
components: {
|
||||
Hint: () => <MyCustomPreferenceHint/>,
|
||||
Input: () => <MyCustomPreferenceInput store={myCustomPreferencesStore}/>
|
||||
}
|
||||
}
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
### `statusBarItems`
|
||||
|
||||
The Status bar is the blue strip along the bottom of the Lens UI. Status bar items are `React.ReactNode` types, which can be used to convey status information, or act as a link to a global page.
|
||||
|
||||
The following example adds a status bar item definition, as well as a global page definition, to a `LensRendererExtension` subclass, and configures the status bar item to navigate to the global upon a mouse click:
|
||||
|
||||
``` typescript
|
||||
import { LensRendererExtension, Navigation } from '@k8slens/extensions';
|
||||
import { MyStatusBarIcon, MyPage } from './page';
|
||||
import React from 'react';
|
||||
|
||||
export default class ExtensionRenderer extends LensRendererExtension {
|
||||
globalPages = [
|
||||
{
|
||||
path: "/my-extension-path",
|
||||
hideInMenu: true,
|
||||
components: {
|
||||
Page: () => <MyPage extension={this} />,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
statusBarItems = [
|
||||
{
|
||||
item: (
|
||||
<div
|
||||
className="flex align-center gaps hover-highlight"
|
||||
onClick={() => Navigation.navigate(this.globalPages[0].path)}
|
||||
>
|
||||
<MyStatusBarIcon />
|
||||
<span>My Status Bar Item</span>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
### `kubeObjectMenuItems`
|
||||
|
||||
An extension can add custom menu items (including actions) for specified Kubernetes resource kinds/apiVersions. These menu items appear under the `...` for each listed resource, and on the title bar of the details page for a specific resource.
|
||||
|
||||
``` typescript
|
||||
import React from "react"
|
||||
import { LensRendererExtension } from "@k8slens/extensions";
|
||||
import { CustomMenuItem, CustomMenuItemProps } from "./src/custom-menu-item"
|
||||
|
||||
export default class ExampleExtension extends LensRendererExtension {
|
||||
kubeObjectMenuItems = [
|
||||
{
|
||||
kind: "Node",
|
||||
apiVersions: ["v1"],
|
||||
components: {
|
||||
MenuItem: (props: CustomMenuItemProps) => <CustomMenuItem {...props} />
|
||||
}
|
||||
}
|
||||
];
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### `kubeObjectDetailItems`
|
||||
|
||||
An extension can add custom details (content) for specified Kubernetes resource kinds/apiVersions. These custom details appear on the details page for a specific resource.
|
||||
|
||||
``` typescript
|
||||
import React from "react"
|
||||
import { LensRendererExtension } from "@k8slens/extensions";
|
||||
import { CustomKindDetails, CustomKindDetailsProps } from "./src/custom-kind-details"
|
||||
|
||||
export default class ExampleExtension extends LensRendererExtension {
|
||||
kubeObjectMenuItems = [
|
||||
{
|
||||
kind: "CustomKind",
|
||||
apiVersions: ["custom.acme.org/v1"],
|
||||
components: {
|
||||
Details: (props: CustomKindDetailsProps) => <CustomKindDetails {...props} />
|
||||
}
|
||||
}
|
||||
];
|
||||
}
|
||||
```
|
||||
16
docs/support/README.md
Normal file
16
docs/support/README.md
Normal file
@ -0,0 +1,16 @@
|
||||
# Support
|
||||
|
||||
Here you will find different ways of getting support for Lens IDE.
|
||||
|
||||
## Community Support
|
||||
|
||||
* [Community Slack](https://join.slack.com/t/k8slens/shared_invite/enQtOTc5NjAyNjYyOTk4LWU1NDQ0ZGFkOWJkNTRhYTc2YjVmZDdkM2FkNGM5MjhiYTRhMDU2NDQ1MzIyMDA4ZGZlNmExOTc0N2JmY2M3ZGI) - Request for support and help from the Lens community via Slack.
|
||||
* [Github Issues](https://github.com/lensapp/lens/issues) - Submit your issues and feature requests to Lens IDE via Github.
|
||||
|
||||
## Commercial Support & Services
|
||||
|
||||
If you are interested in paid support options, professional services or training, please see the offerings from the following vendors:
|
||||
|
||||
* [Mirantis](https://www.mirantis.com/software/lens/) offers commercial support for officially released versions of Lens IDE on MacOS, Windows and Linux operating systems. In addition, Mirantis offers professional services to create proprietary / custom Lens IDE extensions and custom `msi` packaging to meet enterprise IT policies for software distribution and configuration. Training is also available.
|
||||
|
||||
If you'd like to get your business listed in here, please contact us via email [info@k8slens.dev](mailto:info@k8slens.dev)
|
||||
@ -1,5 +1,5 @@
|
||||
{
|
||||
"name": "extension-example",
|
||||
"name": "example-extension",
|
||||
"version": "1.0.0",
|
||||
"description": "Example extension",
|
||||
"main": "dist/main.js",
|
||||
|
||||
@ -11,7 +11,7 @@ export class ExamplePage extends React.Component<{ extension: LensRendererExtens
|
||||
deactivate = () => {
|
||||
const { extension } = this.props;
|
||||
extension.disable();
|
||||
}
|
||||
};
|
||||
|
||||
render() {
|
||||
const doodleStyle = {
|
||||
|
||||
@ -6,13 +6,12 @@ export default class ExampleExtension extends LensRendererExtension {
|
||||
clusterPages = [
|
||||
{
|
||||
id: "example",
|
||||
routePath: "/extension-example",
|
||||
title: "Example Extension",
|
||||
components: {
|
||||
Page: () => <ExamplePage extension={this}/>,
|
||||
}
|
||||
}
|
||||
]
|
||||
];
|
||||
|
||||
clusterPageMenus = [
|
||||
{
|
||||
@ -22,5 +21,5 @@ export default class ExampleExtension extends LensRendererExtension {
|
||||
Icon: ExampleIcon,
|
||||
}
|
||||
}
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
@ -38,5 +38,5 @@ export default class EventResourceStatusRendererExtension extends LensRendererEx
|
||||
apiVersions: ["batch/v1"],
|
||||
resolve: (cronJob: K8sApi.CronJob) => resolveStatusForCronJobs(cronJob)
|
||||
},
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
@ -6,8 +6,8 @@ export default class LicenseLensMainExtension extends LensMainExtension {
|
||||
parentId: "help",
|
||||
label: "License",
|
||||
async click() {
|
||||
Util.openExternal("https://k8slens.dev/licenses/eula.md");
|
||||
Util.openExternal("https://k8slens.dev/licenses/eula");
|
||||
}
|
||||
}
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
@ -10,14 +10,14 @@ export default class ClusterMetricsFeatureExtension extends LensRendererExtensio
|
||||
Description: () => {
|
||||
return (
|
||||
<span>
|
||||
Enable timeseries data visualization (Prometheus stack) for your cluster.
|
||||
Install this only if you don't have existing Prometheus stack installed.
|
||||
You can see preview of manifests <a href="https://github.com/lensapp/lens/tree/master/extensions/lens-metrics/resources" target="_blank">here</a>.
|
||||
Enable timeseries data visualization (Prometheus stack) for your cluster.
|
||||
Install this only if you don't have existing Prometheus stack installed.
|
||||
You can see preview of manifests <a href="https://github.com/lensapp/lens/tree/master/extensions/lens-metrics/resources" target="_blank">here</a>.
|
||||
</span>
|
||||
);
|
||||
}
|
||||
},
|
||||
feature: new MetricsFeature()
|
||||
}
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
@ -25,10 +25,10 @@ export interface MetricsConfiguration {
|
||||
}
|
||||
|
||||
export class MetricsFeature extends ClusterFeature.Feature {
|
||||
name = "metrics"
|
||||
latestVersion = "v2.17.2-lens1"
|
||||
name = "metrics";
|
||||
latestVersion = "v2.17.2-lens1";
|
||||
|
||||
config: MetricsConfiguration = {
|
||||
templateContext: MetricsConfiguration = {
|
||||
persistence: {
|
||||
enabled: false,
|
||||
storageClass: null,
|
||||
@ -53,12 +53,12 @@ export class MetricsFeature extends ClusterFeature.Feature {
|
||||
// Check if there are storageclasses
|
||||
const storageClassApi = K8sApi.forCluster(cluster, K8sApi.StorageClass);
|
||||
const scs = await storageClassApi.list();
|
||||
this.config.persistence.enabled = scs.some(sc => (
|
||||
this.templateContext.persistence.enabled = scs.some(sc => (
|
||||
sc.metadata?.annotations?.['storageclass.kubernetes.io/is-default-class'] === 'true' ||
|
||||
sc.metadata?.annotations?.['storageclass.beta.kubernetes.io/is-default-class'] === 'true'
|
||||
));
|
||||
|
||||
super.applyResources(cluster, super.renderTemplates(path.join(__dirname, "../resources/")));
|
||||
super.applyResources(cluster, path.join(__dirname, "../resources/"));
|
||||
}
|
||||
|
||||
async upgrade(cluster: Store.Cluster): Promise<void> {
|
||||
|
||||
@ -11,5 +11,5 @@ export default class NodeMenuRendererExtension extends LensRendererExtension {
|
||||
MenuItem: (props: NodeMenuProps) => <NodeMenu {...props} />
|
||||
}
|
||||
}
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
@ -19,5 +19,5 @@ export default class PodMenuRendererExtension extends LensRendererExtension {
|
||||
MenuItem: (props: PodLogsMenuProps) => <PodLogsMenu {...props} />
|
||||
}
|
||||
}
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
@ -1,13 +0,0 @@
|
||||
import { LensMainExtension } from "@k8slens/extensions";
|
||||
|
||||
export default class SupportPageMainExtension extends LensMainExtension {
|
||||
appMenus = [
|
||||
{
|
||||
parentId: "help",
|
||||
label: "Support",
|
||||
click: () => {
|
||||
this.navigate();
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
8520
extensions/support-page/package-lock.json
generated
8520
extensions/support-page/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -1,29 +0,0 @@
|
||||
{
|
||||
"name": "lens-support-page",
|
||||
"version": "0.1.0",
|
||||
"description": "Lens support page",
|
||||
"main": "dist/main.js",
|
||||
"renderer": "dist/renderer.js",
|
||||
"scripts": {
|
||||
"build": "webpack -p",
|
||||
"dev": "webpack --watch",
|
||||
"test": "jest --passWithNoTests --env=jsdom src $@"
|
||||
},
|
||||
"dependencies": {},
|
||||
"devDependencies": {
|
||||
"@k8slens/extensions": "file:../../src/extensions/npm/extensions",
|
||||
"@types/react": "^16.9.53",
|
||||
"@types/react-router": "^5.1.8",
|
||||
"@types/webpack": "^4.41.17",
|
||||
"css-loader": "^5.0.0",
|
||||
"jest": "^26.6.3",
|
||||
"mobx": "^5.15.5",
|
||||
"react": "^16.13.1",
|
||||
"sass-loader": "^10.0.4",
|
||||
"style-loader": "^2.0.0",
|
||||
"ts-loader": "^8.0.4",
|
||||
"ts-node": "^9.0.0",
|
||||
"typescript": "^4.0.3",
|
||||
"webpack": "^4.44.2"
|
||||
}
|
||||
}
|
||||
@ -1,23 +0,0 @@
|
||||
import React from "react";
|
||||
import { Component, Interface, LensRendererExtension } from "@k8slens/extensions";
|
||||
import { SupportPage } from "./src/support";
|
||||
|
||||
export default class SupportPageRendererExtension extends LensRendererExtension {
|
||||
globalPages: Interface.PageRegistration[] = [
|
||||
{
|
||||
components: {
|
||||
Page: SupportPage,
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
statusBarItems: Interface.StatusBarRegistration[] = [
|
||||
{
|
||||
item: (
|
||||
<div className="SupportPageIcon flex align-center" onClick={() => this.navigate()}>
|
||||
<Component.Icon interactive material="help" smallest/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
]
|
||||
}
|
||||
@ -1,19 +0,0 @@
|
||||
.SupportPage {
|
||||
a[target=_blank] {
|
||||
text-decoration: none;
|
||||
border-bottom: 1px solid;
|
||||
|
||||
&:after {
|
||||
content: "launch";
|
||||
font: small "Material Icons";
|
||||
vertical-align: middle;
|
||||
margin-left: 2px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.SupportPageIcon {
|
||||
color: white;
|
||||
font-size: var(--font-size-small);
|
||||
padding-right: calc(var(--padding) / 2);
|
||||
}
|
||||
@ -1,29 +0,0 @@
|
||||
// TODO: support localization / figure out how to extract / consume i18n strings
|
||||
|
||||
import "./support.scss";
|
||||
import React from "react";
|
||||
import { observer } from "mobx-react";
|
||||
import { App, Component } from "@k8slens/extensions";
|
||||
|
||||
@observer
|
||||
export class SupportPage extends React.Component {
|
||||
render() {
|
||||
const { PageLayout } = Component;
|
||||
const { slackUrl, issuesTrackerUrl } = App;
|
||||
return (
|
||||
<PageLayout showOnTop className="SupportPage" header={<h2>Support</h2>}>
|
||||
<h2>Community Slack Channel</h2>
|
||||
<p>
|
||||
Ask a question, see what's being discussed, join the conversation <a href={slackUrl} target="_blank">here</a>
|
||||
</p>
|
||||
|
||||
<h2>Report an Issue</h2>
|
||||
<p>
|
||||
Review existing issues or open a new one <a href={issuesTrackerUrl} target="_blank">here</a>
|
||||
</p>
|
||||
|
||||
{/*<h2><Trans>Commercial Support</Trans></h2>*/}
|
||||
</PageLayout>
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -1,29 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"outDir": "dist",
|
||||
"baseUrl": ".",
|
||||
"module": "CommonJS",
|
||||
"target": "ES2017",
|
||||
"lib": ["ESNext", "DOM", "DOM.Iterable"],
|
||||
"moduleResolution": "Node",
|
||||
"sourceMap": false,
|
||||
"declaration": false,
|
||||
"strict": false,
|
||||
"noImplicitAny": true,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"experimentalDecorators": true,
|
||||
"jsx": "react",
|
||||
"paths": {
|
||||
"*": [
|
||||
"node_modules/*",
|
||||
"../../types/*"
|
||||
]
|
||||
}
|
||||
},
|
||||
"include": [
|
||||
"renderer.tsx",
|
||||
"src/**/*"
|
||||
]
|
||||
}
|
||||
@ -1,75 +0,0 @@
|
||||
import path from "path";
|
||||
|
||||
const outputPath = path.resolve(__dirname, 'dist');
|
||||
|
||||
const lensExternals = {
|
||||
"@k8slens/extensions": "var global.LensExtensions",
|
||||
"react": "var global.React",
|
||||
"mobx": "var global.Mobx",
|
||||
"mobx-react": "var global.MobxReact",
|
||||
};
|
||||
|
||||
export default [
|
||||
{
|
||||
entry: './main.ts',
|
||||
context: __dirname,
|
||||
target: "electron-main",
|
||||
mode: "production",
|
||||
module: {
|
||||
rules: [
|
||||
{
|
||||
test: /\.tsx?$/,
|
||||
use: 'ts-loader',
|
||||
exclude: /node_modules/,
|
||||
},
|
||||
],
|
||||
},
|
||||
externals: [
|
||||
lensExternals,
|
||||
],
|
||||
resolve: {
|
||||
extensions: ['.tsx', '.ts', '.js'],
|
||||
},
|
||||
output: {
|
||||
libraryTarget: "commonjs2",
|
||||
globalObject: "this",
|
||||
filename: 'main.js',
|
||||
path: outputPath,
|
||||
},
|
||||
},
|
||||
{
|
||||
entry: './renderer.tsx',
|
||||
context: __dirname,
|
||||
target: "electron-renderer",
|
||||
mode: "production",
|
||||
module: {
|
||||
rules: [
|
||||
{
|
||||
test: /\.tsx?$/,
|
||||
use: 'ts-loader',
|
||||
exclude: /node_modules/,
|
||||
},
|
||||
{
|
||||
test: /\.s?css$/,
|
||||
use: [
|
||||
"style-loader",
|
||||
"css-loader",
|
||||
"sass-loader",
|
||||
]
|
||||
}
|
||||
],
|
||||
},
|
||||
externals: [
|
||||
lensExternals,
|
||||
],
|
||||
resolve: {
|
||||
extensions: ['.tsx', '.ts', '.js'],
|
||||
},
|
||||
output: {
|
||||
libraryTarget: "commonjs2",
|
||||
globalObject: "this",
|
||||
filename: 'renderer.js',
|
||||
path: outputPath,
|
||||
},
|
||||
},
|
||||
];
|
||||
@ -8,6 +8,7 @@ export default class TelemetryMainExtension extends LensMainExtension {
|
||||
console.log("telemetry main extension activated");
|
||||
tracker.start();
|
||||
tracker.reportPeriodically();
|
||||
tracker.watchExtensions();
|
||||
await telemetryPreferencesStore.loadExtension(this);
|
||||
}
|
||||
|
||||
|
||||
@ -3,7 +3,7 @@ import { toJS } from "mobx";
|
||||
|
||||
export type TelemetryPreferencesModel = {
|
||||
enabled: boolean;
|
||||
}
|
||||
};
|
||||
|
||||
export class TelemetryPreferencesStore extends Store.ExtensionStore<TelemetryPreferencesModel> {
|
||||
enabled = true;
|
||||
|
||||
@ -3,23 +3,26 @@ import ua from "universal-analytics";
|
||||
import Analytics from "analytics-node";
|
||||
import { machineIdSync } from "node-machine-id";
|
||||
import { telemetryPreferencesStore } from "./telemetry-preferences-store";
|
||||
import { reaction, IReactionDisposer } from "mobx";
|
||||
import { comparer } from "mobx";
|
||||
|
||||
export class Tracker extends Util.Singleton {
|
||||
static readonly GA_ID = "UA-159377374-1"
|
||||
static readonly SEGMENT_KEY = "YENwswyhlOgz8P7EFKUtIZ2MfON7Yxqb"
|
||||
protected eventHandlers: Array<(ev: EventBus.AppEvent ) => void> = []
|
||||
protected started = false
|
||||
protected visitor: ua.Visitor
|
||||
protected analytics: Analytics
|
||||
static readonly GA_ID = "UA-159377374-1";
|
||||
static readonly SEGMENT_KEY = "YENwswyhlOgz8P7EFKUtIZ2MfON7Yxqb";
|
||||
protected eventHandlers: Array<(ev: EventBus.AppEvent ) => void> = [];
|
||||
protected started = false;
|
||||
protected visitor: ua.Visitor;
|
||||
protected analytics: Analytics;
|
||||
protected machineId: string = null;
|
||||
protected ip: string = null;
|
||||
protected appVersion: string;
|
||||
protected locale: string;
|
||||
protected userAgent: string;
|
||||
protected anonymousId: string;
|
||||
protected os: string
|
||||
protected os: string;
|
||||
protected disposers: IReactionDisposer[];
|
||||
|
||||
protected reportInterval: NodeJS.Timeout
|
||||
protected reportInterval: NodeJS.Timeout;
|
||||
|
||||
private constructor() {
|
||||
super();
|
||||
@ -35,6 +38,7 @@ export class Tracker extends Util.Singleton {
|
||||
this.analytics = new Analytics(Tracker.SEGMENT_KEY, { flushAt: 1 });
|
||||
this.visitor.set("dl", "https://telemetry.k8slens.dev");
|
||||
this.visitor.set("ua", this.userAgent);
|
||||
this.disposers = [];
|
||||
}
|
||||
|
||||
start() {
|
||||
@ -49,6 +53,21 @@ export class Tracker extends Util.Singleton {
|
||||
EventBus.appEventBus.addListener(handler);
|
||||
}
|
||||
|
||||
watchExtensions() {
|
||||
let previousExtensions = App.getEnabledExtensions();
|
||||
this.disposers.push(reaction(() => App.getEnabledExtensions(), (currentExtensions) => {
|
||||
const removedExtensions = previousExtensions.filter(x => !currentExtensions.includes(x));
|
||||
removedExtensions.forEach(ext => {
|
||||
this.event("extension", "disable", { extension: ext });
|
||||
});
|
||||
const newExtensions = currentExtensions.filter(x => !previousExtensions.includes(x));
|
||||
newExtensions.forEach(ext => {
|
||||
this.event("extension", "enable", { extension: ext });
|
||||
});
|
||||
previousExtensions = currentExtensions;
|
||||
}, { equals: comparer.structural }));
|
||||
}
|
||||
|
||||
reportPeriodically() {
|
||||
this.reportInterval = setInterval(() => {
|
||||
this.reportData();
|
||||
@ -66,6 +85,9 @@ export class Tracker extends Util.Singleton {
|
||||
if (this.reportInterval) {
|
||||
clearInterval(this.reportInterval);
|
||||
}
|
||||
this.disposers.forEach(disposer => {
|
||||
disposer();
|
||||
});
|
||||
}
|
||||
|
||||
protected async isTelemetryAllowed(): Promise<boolean> {
|
||||
@ -79,7 +101,8 @@ export class Tracker extends Util.Singleton {
|
||||
appVersion: App.version,
|
||||
os: this.os,
|
||||
clustersCount: clustersList.length,
|
||||
workspacesCount: Store.workspaceStore.enabledWorkspacesList.length
|
||||
workspacesCount: Store.workspaceStore.enabledWorkspacesList.length,
|
||||
extensions: App.getEnabledExtensions()
|
||||
});
|
||||
|
||||
clustersList.forEach((cluster) => {
|
||||
|
||||
@ -16,8 +16,8 @@ jest.setTimeout(60000);
|
||||
// FIXME (!): improve / simplify all css-selectors + use [data-test-id="some-id"] (already used in some tests below)
|
||||
describe("Lens integration tests", () => {
|
||||
const TEST_NAMESPACE = "integration-tests";
|
||||
|
||||
const BACKSPACE = "\uE003";
|
||||
|
||||
let app: Application;
|
||||
|
||||
const appStart = async () => {
|
||||
@ -35,12 +35,45 @@ describe("Lens integration tests", () => {
|
||||
await app.client.waitUntilTextExists("h1", "Welcome");
|
||||
};
|
||||
|
||||
const minikubeReady = (): boolean => {
|
||||
// determine if minikube is running
|
||||
{
|
||||
const { status } = spawnSync("minikube status", { shell: true });
|
||||
if (status !== 0) {
|
||||
console.warn("minikube not running");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Remove TEST_NAMESPACE if it already exists
|
||||
{
|
||||
const { status } = spawnSync(`minikube kubectl -- get namespace ${TEST_NAMESPACE}`, { shell: true });
|
||||
if (status === 0) {
|
||||
console.warn(`Removing existing ${TEST_NAMESPACE} namespace`);
|
||||
|
||||
const { status, stdout, stderr } = spawnSync(
|
||||
`minikube kubectl -- delete namespace ${TEST_NAMESPACE}`,
|
||||
{ shell: true },
|
||||
);
|
||||
if (status !== 0) {
|
||||
console.warn(`Error removing ${TEST_NAMESPACE} namespace: ${stderr.toString()}`);
|
||||
return false;
|
||||
}
|
||||
|
||||
console.log(stdout.toString());
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
const ready = minikubeReady();
|
||||
|
||||
describe("app start", () => {
|
||||
beforeAll(appStart, 20000);
|
||||
|
||||
afterAll(async () => {
|
||||
if (app && app.isRunning()) {
|
||||
return util.tearDown(app);
|
||||
if (app?.isRunning()) {
|
||||
await util.tearDown(app);
|
||||
}
|
||||
});
|
||||
|
||||
@ -61,7 +94,7 @@ describe("Lens integration tests", () => {
|
||||
});
|
||||
|
||||
it('ensures helm repos', async () => {
|
||||
await app.client.waitUntilTextExists("div.repos #message-stable", "stable"); // wait for the helm-cli to fetch the stable repo
|
||||
await app.client.waitUntilTextExists("div.repos #message-bitnami", "bitnami"); // wait for the helm-cli to fetch the bitnami repo
|
||||
await app.client.click("#HelmRepoSelect"); // click the repo select to activate the drop-down
|
||||
await app.client.waitUntilTextExists("div.Select__option", ""); // wait for at least one option to appear (any text)
|
||||
});
|
||||
@ -73,28 +106,50 @@ describe("Lens integration tests", () => {
|
||||
});
|
||||
});
|
||||
|
||||
const minikubeReady = (): boolean => {
|
||||
// determine if minikube is running
|
||||
let status = spawnSync("minikube status", { shell: true });
|
||||
if (status.status !== 0) {
|
||||
console.warn("minikube not running");
|
||||
return false;
|
||||
}
|
||||
describeif(ready)("workspaces", () => {
|
||||
beforeAll(appStart, 20000);
|
||||
|
||||
// Remove TEST_NAMESPACE if it already exists
|
||||
status = spawnSync(`minikube kubectl -- get namespace ${TEST_NAMESPACE}`, { shell: true });
|
||||
if (status.status === 0) {
|
||||
console.warn(`Removing existing ${TEST_NAMESPACE} namespace`);
|
||||
status = spawnSync(`minikube kubectl -- delete namespace ${TEST_NAMESPACE}`, { shell: true });
|
||||
if (status.status !== 0) {
|
||||
console.warn(`Error removing ${TEST_NAMESPACE} namespace: ${status.stderr.toString()}`);
|
||||
return false;
|
||||
afterAll(async () => {
|
||||
if (app && app.isRunning()) {
|
||||
return util.tearDown(app);
|
||||
}
|
||||
console.log(status.stdout.toString());
|
||||
}
|
||||
return true;
|
||||
};
|
||||
const ready = minikubeReady();
|
||||
});
|
||||
|
||||
it('creates new workspace', async () => {
|
||||
await clickWhatsNew(app);
|
||||
await app.client.click('#current-workspace .Icon');
|
||||
await app.client.click('a[href="/workspaces"]');
|
||||
await app.client.click('.Workspaces button.Button');
|
||||
await app.client.keys("test-workspace");
|
||||
await app.client.click('.Workspaces .Input.description input');
|
||||
await app.client.keys("test description");
|
||||
await app.client.click('.Workspaces .workspace.editing .Icon');
|
||||
await app.client.waitUntilTextExists(".workspace .name a", "test-workspace");
|
||||
});
|
||||
|
||||
it('adds cluster in default workspace', async () => {
|
||||
await addMinikubeCluster(app);
|
||||
await app.client.waitUntilTextExists("pre.kube-auth-out", "Authentication proxy started");
|
||||
await app.client.waitForExist(`iframe[name="minikube"]`);
|
||||
await app.client.waitForVisible(".ClustersMenu .ClusterIcon.active");
|
||||
});
|
||||
|
||||
it('adds cluster in test-workspace', async () => {
|
||||
await app.client.click('#current-workspace .Icon');
|
||||
await app.client.waitForVisible('.WorkspaceMenu li[title="test description"]');
|
||||
await app.client.click('.WorkspaceMenu li[title="test description"]');
|
||||
await addMinikubeCluster(app);
|
||||
await app.client.waitUntilTextExists("pre.kube-auth-out", "Authentication proxy started");
|
||||
await app.client.waitForExist(`iframe[name="minikube"]`);
|
||||
});
|
||||
|
||||
it('checks if default workspace has active cluster', async () => {
|
||||
await app.client.click('#current-workspace .Icon');
|
||||
await app.client.waitForVisible('.WorkspaceMenu > li:first-of-type');
|
||||
await app.client.click('.WorkspaceMenu > li:first-of-type');
|
||||
await app.client.waitForVisible(".ClustersMenu .ClusterIcon.active");
|
||||
});
|
||||
});
|
||||
|
||||
const addMinikubeCluster = async (app: Application) => {
|
||||
await app.client.click("div.add-cluster");
|
||||
|
||||
@ -8,9 +8,8 @@ const AppPaths: Partial<Record<NodeJS.Platform, string>> = {
|
||||
|
||||
export function setup(): Application {
|
||||
return new Application({
|
||||
// path to electron app
|
||||
path: AppPaths[process.platform], // path to electron app
|
||||
args: [],
|
||||
path: AppPaths[process.platform],
|
||||
startTimeout: 30000,
|
||||
waitTimeout: 60000,
|
||||
env: {
|
||||
@ -19,9 +18,10 @@ export function setup(): Application {
|
||||
});
|
||||
}
|
||||
|
||||
type AsyncPidGetter = () => Promise<number>;
|
||||
|
||||
export async function tearDown(app: Application) {
|
||||
const mpid: any = app.mainProcess.pid;
|
||||
const pid = await mpid();
|
||||
const pid = await (app.mainProcess.pid as any as AsyncPidGetter)();
|
||||
await app.stop();
|
||||
try {
|
||||
process.kill(pid, "SIGKILL");
|
||||
|
||||
@ -738,6 +738,7 @@ msgstr "Current / Target"
|
||||
msgid "Current Healthy"
|
||||
msgstr "Current Healthy"
|
||||
|
||||
#: src/renderer/components/+workloads-statefulsets/statefulset-scale-dialog.tsx:101
|
||||
#: src/renderer/components/+workloads-deployments/deployment-scale-dialog.tsx:103
|
||||
msgid "Current replica scale: {currentReplicas}"
|
||||
msgstr "Current replica scale: {currentReplicas}"
|
||||
@ -828,6 +829,7 @@ msgstr "Description"
|
||||
msgid "Desired Healthy"
|
||||
msgstr "Desired Healthy"
|
||||
|
||||
#: src/renderer/components/+workloads-statefulsets/statefulset-scale-dialog.tsx:105
|
||||
#: src/renderer/components/+workloads-deployments/deployment-scale-dialog.tsx:107
|
||||
msgid "Desired number of replicas"
|
||||
msgstr "Desired number of replicas"
|
||||
@ -1091,6 +1093,7 @@ msgstr "Helm branch <0>{0}</0> already in use"
|
||||
msgid "Hide"
|
||||
msgstr "Hide"
|
||||
|
||||
#: src/renderer/components/+workloads-statefulsets/statefulset-scale-dialog.tsx:127
|
||||
#: src/renderer/components/+workloads-deployments/deployment-scale-dialog.tsx:116
|
||||
msgid "High number of replicas may cause cluster performance issues"
|
||||
msgstr "High number of replicas may cause cluster performance issues"
|
||||
@ -2298,6 +2301,7 @@ msgstr "Runtime Class"
|
||||
msgid "Save"
|
||||
msgstr "Save"
|
||||
|
||||
#: src/renderer/components/+workloads-statefulsets/statefulset-scale-dialog.tsx:155
|
||||
#: src/renderer/components/+workloads-deployments/deployment-scale-dialog.tsx:128
|
||||
#: src/renderer/components/+workloads-deployments/deployments.tsx:83
|
||||
#: src/renderer/components/+workloads-deployments/deployments.tsx:84
|
||||
@ -2308,6 +2312,10 @@ msgstr "Scale"
|
||||
msgid "Scale Deployment <0>{deploymentName}</0>"
|
||||
msgstr "Scale Deployment <0>{deploymentName}</0>"
|
||||
|
||||
#: src/renderer/components/+workloads-statefulsets/statefulset-scale-dialog.tsx:139
|
||||
msgid "Scale Stateful Set <0>{statefulSetName}</0>"
|
||||
msgstr "Scale Stateful Set <0>{statefulSetName}</0>"
|
||||
|
||||
#: src/renderer/components/+workloads-cronjobs/cronjob-details.tsx:45
|
||||
#: src/renderer/components/+workloads-cronjobs/cronjobs.tsx:46
|
||||
msgid "Schedule"
|
||||
|
||||
@ -734,6 +734,7 @@ msgstr ""
|
||||
msgid "Current Healthy"
|
||||
msgstr ""
|
||||
|
||||
#: src/renderer/components/+workloads-statefulsets/statefulset-scale-dialog.tsx:101
|
||||
#: src/renderer/components/+workloads-deployments/deployment-scale-dialog.tsx:103
|
||||
msgid "Current replica scale: {currentReplicas}"
|
||||
msgstr ""
|
||||
@ -824,6 +825,7 @@ msgstr ""
|
||||
msgid "Desired Healthy"
|
||||
msgstr ""
|
||||
|
||||
#: src/renderer/components/+workloads-statefulsets/statefulset-scale-dialog.tsx:105
|
||||
#: src/renderer/components/+workloads-deployments/deployment-scale-dialog.tsx:107
|
||||
msgid "Desired number of replicas"
|
||||
msgstr ""
|
||||
@ -1082,6 +1084,7 @@ msgstr ""
|
||||
msgid "Hide"
|
||||
msgstr ""
|
||||
|
||||
#: src/renderer/components/+workloads-statefulsets/statefulset-scale-dialog.tsx:127
|
||||
#: src/renderer/components/+workloads-deployments/deployment-scale-dialog.tsx:116
|
||||
msgid "High number of replicas may cause cluster performance issues"
|
||||
msgstr ""
|
||||
@ -2281,6 +2284,7 @@ msgstr ""
|
||||
msgid "Save"
|
||||
msgstr ""
|
||||
|
||||
#: src/renderer/components/+workloads-statefulsets/statefulset-scale-dialog.tsx:155
|
||||
#: src/renderer/components/+workloads-deployments/deployment-scale-dialog.tsx:128
|
||||
#: src/renderer/components/+workloads-deployments/deployments.tsx:83
|
||||
#: src/renderer/components/+workloads-deployments/deployments.tsx:84
|
||||
@ -2291,6 +2295,10 @@ msgstr ""
|
||||
msgid "Scale Deployment <0>{deploymentName}</0>"
|
||||
msgstr ""
|
||||
|
||||
#: src/renderer/components/+workloads-statefulsets/statefulset-scale-dialog.tsx:139
|
||||
msgid "Scale Stateful Set <0>{statefulSetName}</0>"
|
||||
msgstr ""
|
||||
|
||||
#: src/renderer/components/+workloads-cronjobs/cronjob-details.tsx:45
|
||||
#: src/renderer/components/+workloads-cronjobs/cronjobs.tsx:46
|
||||
msgid "Schedule"
|
||||
|
||||
@ -739,6 +739,7 @@ msgstr "Текущее / Цель"
|
||||
msgid "Current Healthy"
|
||||
msgstr ""
|
||||
|
||||
#: src/renderer/components/+workloads-statefulsets/statefulset-scale-dialog.tsx:101
|
||||
#: src/renderer/components/+workloads-deployments/deployment-scale-dialog.tsx:103
|
||||
msgid "Current replica scale: {currentReplicas}"
|
||||
msgstr "Текущий размер реплики: {currentReplicas}"
|
||||
@ -829,6 +830,7 @@ msgstr "Описание"
|
||||
msgid "Desired Healthy"
|
||||
msgstr ""
|
||||
|
||||
#: src/renderer/components/+workloads-statefulsets/statefulset-scale-dialog.tsx:105
|
||||
#: src/renderer/components/+workloads-deployments/deployment-scale-dialog.tsx:107
|
||||
msgid "Desired number of replicas"
|
||||
msgstr "Нужный уровень реплик"
|
||||
@ -1092,6 +1094,7 @@ msgstr ""
|
||||
msgid "Hide"
|
||||
msgstr "Скрыть"
|
||||
|
||||
#: src/renderer/components/+workloads-statefulsets/statefulset-scale-dialog.tsx:127
|
||||
#: src/renderer/components/+workloads-deployments/deployment-scale-dialog.tsx:116
|
||||
msgid "High number of replicas may cause cluster performance issues"
|
||||
msgstr "Большое количество реплик может вызвать проблемы с производительностью кластера"
|
||||
@ -2299,6 +2302,7 @@ msgstr ""
|
||||
msgid "Save"
|
||||
msgstr "Сохранить"
|
||||
|
||||
#: src/renderer/components/+workloads-statefulsets/statefulset-scale-dialog.tsx:155
|
||||
#: src/renderer/components/+workloads-deployments/deployment-scale-dialog.tsx:128
|
||||
#: src/renderer/components/+workloads-deployments/deployments.tsx:83
|
||||
#: src/renderer/components/+workloads-deployments/deployments.tsx:84
|
||||
@ -2309,6 +2313,10 @@ msgstr "Масштабировать"
|
||||
msgid "Scale Deployment <0>{deploymentName}</0>"
|
||||
msgstr "Масштабировать Deployment <0>{deploymentName}</0>"
|
||||
|
||||
#: src/renderer/components/+workloads-statefulsets/statefulset-scale-dialog.tsx:139
|
||||
msgid "Scale Stateful Set <0>{statefulSetName}</0>"
|
||||
msgstr "Масштабировать Stateful Set <0>{statefulSetName}</0>"
|
||||
|
||||
#: src/renderer/components/+workloads-cronjobs/cronjob-details.tsx:45
|
||||
#: src/renderer/components/+workloads-cronjobs/cronjobs.tsx:46
|
||||
msgid "Schedule"
|
||||
|
||||
@ -32,6 +32,7 @@ nav:
|
||||
- Overview: extensions/guides/README.md
|
||||
- Main Extension: extensions/guides/main-extension.md
|
||||
- Renderer Extension: extensions/guides/renderer-extension.md
|
||||
- Generator: extensions/guides/generator.md
|
||||
- Testing and Publishing:
|
||||
- Testing Extensions: extensions/testing-and-publishing/testing.md
|
||||
- Publishing Extensions: extensions/testing-and-publishing/publishing.md
|
||||
@ -42,7 +43,7 @@ nav:
|
||||
- Documentation: contributing/documentation.md
|
||||
- Maintainers: contributing/maintainers.md
|
||||
- Promotion: contributing/promotion.md
|
||||
|
||||
- Support: support/README.md
|
||||
- FAQ: faq/README.md
|
||||
theme:
|
||||
name: 'material'
|
||||
|
||||
17
package.json
17
package.json
@ -2,7 +2,7 @@
|
||||
"name": "kontena-lens",
|
||||
"productName": "Lens",
|
||||
"description": "Lens - The Kubernetes IDE",
|
||||
"version": "4.0.0-beta.3",
|
||||
"version": "4.0.0-beta.4",
|
||||
"main": "static/build/main.js",
|
||||
"copyright": "© 2020, Mirantis, Inc.",
|
||||
"license": "MIT",
|
||||
@ -37,7 +37,7 @@
|
||||
"download:kubectl": "yarn run ts-node build/download_kubectl.ts",
|
||||
"download:helm": "yarn run ts-node build/download_helm.ts",
|
||||
"build:tray-icons": "yarn run ts-node build/build_tray_icon.ts",
|
||||
"lint": "yarn run eslint $@ --ext js,ts,tsx --max-warnings=0 src/ integration/ __mocks__/ build/",
|
||||
"lint": "yarn run eslint $@ --ext js,ts,tsx --max-warnings=0 src/ integration/ __mocks__/ build/ extensions/",
|
||||
"lint:fix": "yarn run lint --fix",
|
||||
"mkdocs-serve-local": "docker build -t mkdocs-serve-local:latest mkdocs/ && docker run --rm -it -p 8000:8000 -v ${PWD}:/docs mkdocs-serve-local:latest",
|
||||
"typedocs-extensions-api": "yarn run typedoc --ignoreCompilerErrors --readme docs/extensions/typedoc-readme.md.tpl --name @k8slens/extensions --out docs/extensions/api --mode library --excludePrivate --hideBreadcrumbs --includes src/ src/extensions/extension-api.ts"
|
||||
@ -47,7 +47,7 @@
|
||||
"bundledHelmVersion": "3.3.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12.0 <13.0"
|
||||
"node": ">=12 <13"
|
||||
},
|
||||
"lingui": {
|
||||
"locales": [
|
||||
@ -194,7 +194,6 @@
|
||||
"node-menu",
|
||||
"metrics-cluster-feature",
|
||||
"license-menu-item",
|
||||
"support-page",
|
||||
"kube-object-event-status"
|
||||
]
|
||||
},
|
||||
@ -215,15 +214,17 @@
|
||||
"@types/node": "^12.12.45",
|
||||
"@types/proper-lockfile": "^4.1.1",
|
||||
"@types/react-beautiful-dnd": "^13.0.0",
|
||||
"@types/tar": "^4.0.3",
|
||||
"@types/tar": "^4.0.4",
|
||||
"array-move": "^3.0.0",
|
||||
"await-lock": "^2.1.0",
|
||||
"chalk": "^4.1.0",
|
||||
"chokidar": "^3.4.3",
|
||||
"command-exists": "1.2.9",
|
||||
"conf": "^7.0.1",
|
||||
"crypto-js": "^4.0.0",
|
||||
"electron-devtools-installer": "^3.1.1",
|
||||
"electron-updater": "^4.3.1",
|
||||
"electron-window-state": "^5.0.3",
|
||||
"file-type": "^14.7.1",
|
||||
"filenamify": "^4.1.0",
|
||||
"fs-extra": "^9.0.1",
|
||||
"handlebars": "^4.7.6",
|
||||
@ -249,7 +250,7 @@
|
||||
"serializr": "^2.0.3",
|
||||
"shell-env": "^3.0.0",
|
||||
"spdy": "^4.0.2",
|
||||
"tar": "^6.0.2",
|
||||
"tar": "^6.0.5",
|
||||
"tcp-port-used": "^1.0.1",
|
||||
"tempy": "^0.5.0",
|
||||
"uuid": "^8.1.0",
|
||||
@ -280,6 +281,7 @@
|
||||
"@types/color": "^3.0.1",
|
||||
"@types/crypto-js": "^3.1.47",
|
||||
"@types/dompurify": "^2.0.2",
|
||||
"@types/electron-devtools-installer": "^2.2.0",
|
||||
"@types/electron-window-state": "^2.0.34",
|
||||
"@types/fs-extra": "^9.0.1",
|
||||
"@types/hapi": "^18.0.3",
|
||||
@ -311,7 +313,6 @@
|
||||
"@types/sharp": "^0.26.0",
|
||||
"@types/shelljs": "^0.8.8",
|
||||
"@types/spdy": "^3.4.4",
|
||||
"@types/tar": "^4.0.3",
|
||||
"@types/tcp-port-used": "^1.0.0",
|
||||
"@types/tempy": "^0.3.0",
|
||||
"@types/terser-webpack-plugin": "^3.0.0",
|
||||
|
||||
@ -65,6 +65,7 @@ describe("empty config", () => {
|
||||
it("sets active cluster", () => {
|
||||
clusterStore.setActive("foo");
|
||||
expect(clusterStore.active.id).toBe("foo");
|
||||
expect(workspaceStore.currentWorkspace.lastActiveClusterId).toBe("foo");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import type { WorkspaceId } from "./workspace-store";
|
||||
import { workspaceStore } from "./workspace-store";
|
||||
import path from "path";
|
||||
import { app, ipcRenderer, remote, webFrame } from "electron";
|
||||
import { unlink } from "fs-extra";
|
||||
@ -11,9 +11,10 @@ import { appEventBus } from "./event-bus";
|
||||
import { dumpConfigYaml } from "./kube-helpers";
|
||||
import { saveToAppFiles } from "./utils/saveToAppFiles";
|
||||
import { KubeConfig } from "@kubernetes/client-node";
|
||||
import { subscribeToBroadcast, unsubscribeAllFromBroadcast } from "./ipc";
|
||||
import _ from "lodash";
|
||||
import move from "array-move";
|
||||
import { subscribeToBroadcast, unsubscribeAllFromBroadcast } from "./ipc";
|
||||
import type { WorkspaceId } from "./workspace-store";
|
||||
|
||||
export interface ClusterIconUpload {
|
||||
clusterId: string;
|
||||
@ -92,10 +93,10 @@ export class ClusterStore extends BaseStore<ClusterStoreModel> {
|
||||
super({
|
||||
configName: "lens-cluster-store",
|
||||
accessPropertiesByDotNotation: false, // To make dots safe in cluster context names
|
||||
migrations: migrations,
|
||||
syncOptions: {
|
||||
equals: comparer.structural,
|
||||
},
|
||||
migrations,
|
||||
});
|
||||
|
||||
this.pushStateToViewsAutomatically();
|
||||
@ -154,7 +155,9 @@ export class ClusterStore extends BaseStore<ClusterStoreModel> {
|
||||
|
||||
@action
|
||||
setActive(id: ClusterId) {
|
||||
this.activeCluster = this.clusters.has(id) ? id : null;
|
||||
const clusterId = this.clusters.has(id) ? id : null;
|
||||
this.activeCluster = clusterId;
|
||||
workspaceStore.setLastActiveClusterId(clusterId);
|
||||
}
|
||||
|
||||
@action
|
||||
|
||||
@ -36,7 +36,7 @@ export class UserStore extends BaseStore<UserStoreModel> {
|
||||
private constructor() {
|
||||
super({
|
||||
// configName: "lens-user-store", // todo: migrate from default "config.json"
|
||||
migrations: migrations,
|
||||
migrations,
|
||||
});
|
||||
|
||||
this.handleOnLoad();
|
||||
|
||||
36
src/common/utils/downloadFile.ts
Normal file
36
src/common/utils/downloadFile.ts
Normal file
@ -0,0 +1,36 @@
|
||||
import request from "request";
|
||||
|
||||
export interface DownloadFileOptions {
|
||||
url: string;
|
||||
gzip?: boolean;
|
||||
timeout?: number;
|
||||
}
|
||||
|
||||
export interface DownloadFileTicket {
|
||||
url: string;
|
||||
promise: Promise<Buffer>;
|
||||
cancel(): void;
|
||||
}
|
||||
|
||||
export function downloadFile({ url, timeout, gzip = true }: DownloadFileOptions): DownloadFileTicket {
|
||||
const fileChunks: Buffer[] = [];
|
||||
const req = request(url, { gzip, timeout });
|
||||
const promise: Promise<Buffer> = new Promise((resolve, reject) => {
|
||||
req.on("data", (chunk: Buffer) => {
|
||||
fileChunks.push(chunk);
|
||||
});
|
||||
req.once("error", err => {
|
||||
reject({ url, err });
|
||||
});
|
||||
req.once("complete", () => {
|
||||
resolve(Buffer.concat(fileChunks));
|
||||
});
|
||||
});
|
||||
return {
|
||||
url,
|
||||
promise,
|
||||
cancel() {
|
||||
req.abort();
|
||||
}
|
||||
};
|
||||
}
|
||||
5
src/common/utils/escapeRegExp.ts
Normal file
5
src/common/utils/escapeRegExp.ts
Normal file
@ -0,0 +1,5 @@
|
||||
// Helper to sanitize / escape special chars for passing to RegExp-constructor
|
||||
|
||||
export function escapeRegExp(str: string) {
|
||||
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
|
||||
}
|
||||
@ -1,5 +1,7 @@
|
||||
// Common utils (main OR renderer)
|
||||
|
||||
export const noop: any = () => { /* empty */ };
|
||||
|
||||
export * from "./app-version";
|
||||
export * from "./autobind";
|
||||
export * from "./base64";
|
||||
@ -12,3 +14,7 @@ export * from "./splitArray";
|
||||
export * from "./saveToAppFiles";
|
||||
export * from "./singleton";
|
||||
export * from "./openExternal";
|
||||
export * from "./rectify-array";
|
||||
export * from "./downloadFile";
|
||||
export * from "./escapeRegExp";
|
||||
export * from "./tar";
|
||||
|
||||
8
src/common/utils/rectify-array.ts
Normal file
8
src/common/utils/rectify-array.ts
Normal file
@ -0,0 +1,8 @@
|
||||
/**
|
||||
* rectify condences the single item or array of T type, to an array.
|
||||
* @param items either one item or an array of items
|
||||
* @returns a list of items
|
||||
*/
|
||||
export function recitfy<T>(items: T | T[]): T[] {
|
||||
return Array.isArray(items) ? items : [items];
|
||||
}
|
||||
55
src/common/utils/tar.ts
Normal file
55
src/common/utils/tar.ts
Normal file
@ -0,0 +1,55 @@
|
||||
// Helper for working with tarball files (.tar, .tgz)
|
||||
// Docs: https://github.com/npm/node-tar
|
||||
import tar, { ExtractOptions, FileStat } from "tar";
|
||||
import path from "path";
|
||||
|
||||
export interface ReadFileFromTarOpts {
|
||||
tarPath: string;
|
||||
filePath: string;
|
||||
parseJson?: boolean;
|
||||
}
|
||||
|
||||
export function readFileFromTar<R = Buffer>({ tarPath, filePath, parseJson }: ReadFileFromTarOpts): Promise<R> {
|
||||
return new Promise(async (resolve, reject) => {
|
||||
const fileChunks: Buffer[] = [];
|
||||
|
||||
await tar.list({
|
||||
file: tarPath,
|
||||
filter: path => path === filePath,
|
||||
onentry(entry: FileStat) {
|
||||
entry.on("data", chunk => {
|
||||
fileChunks.push(chunk);
|
||||
});
|
||||
entry.once("error", err => {
|
||||
reject(new Error(`reading file has failed ${entry.path}: ${err}`));
|
||||
});
|
||||
entry.once("end", () => {
|
||||
const data = Buffer.concat(fileChunks);
|
||||
const result = parseJson ? JSON.parse(data.toString("utf8")) : data;
|
||||
resolve(result);
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
if (!fileChunks.length) {
|
||||
reject(new Error("Not found"));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export async function listTarEntries(filePath: string): Promise<string[]> {
|
||||
const entries: string[] = [];
|
||||
await tar.list({
|
||||
file: filePath,
|
||||
onentry: (entry: FileStat) => entries.push(entry.path as any as string),
|
||||
});
|
||||
return entries;
|
||||
}
|
||||
|
||||
export function extractTar(filePath: string, opts: ExtractOptions & { sync?: boolean } = {}) {
|
||||
return tar.extract({
|
||||
file: filePath,
|
||||
cwd: path.dirname(filePath),
|
||||
...opts,
|
||||
});
|
||||
}
|
||||
@ -6,8 +6,8 @@ import { defineGlobal } from "./utils/defineGlobal";
|
||||
export const isMac = process.platform === "darwin";
|
||||
export const isWindows = process.platform === "win32";
|
||||
export const isLinux = process.platform === "linux";
|
||||
export const isDebugging = process.env.DEBUG === "true";
|
||||
export const isSnap = !!process.env["SNAP"];
|
||||
export const isDebugging = ["true", "1", "yes", "y", "on"].includes((process.env.DEBUG ?? "").toLowerCase());
|
||||
export const isSnap = !!process.env.SNAP;
|
||||
export const isProduction = process.env.NODE_ENV === "production";
|
||||
export const isTestEnv = !!process.env.JEST_WORKER_ID;
|
||||
export const isDevelopment = !isTestEnv && !isProduction;
|
||||
@ -41,3 +41,5 @@ export const apiKubePrefix = "/api-kube"; // k8s cluster apis
|
||||
// Links
|
||||
export const issuesTrackerUrl = "https://github.com/lensapp/lens/issues";
|
||||
export const slackUrl = "https://join.slack.com/t/k8slens/shared_invite/enQtOTc5NjAyNjYyOTk4LWU1NDQ0ZGFkOWJkNTRhYTc2YjVmZDdkM2FkNGM5MjhiYTRhMDU2NDQ1MzIyMDA4ZGZlNmExOTc0N2JmY2M3ZGI";
|
||||
export const docsUrl = "https://docs.k8slens.dev/";
|
||||
export const supportUrl = "https://docs.k8slens.dev/latest/support/";
|
||||
|
||||
@ -5,12 +5,13 @@ import { clusterStore } from "./cluster-store";
|
||||
import { appEventBus } from "./event-bus";
|
||||
import { broadcastMessage } from "../common/ipc";
|
||||
import logger from "../main/logger";
|
||||
import type { ClusterId } from "./cluster-store";
|
||||
|
||||
export type WorkspaceId = string;
|
||||
|
||||
export interface WorkspaceStoreModel {
|
||||
workspaces: WorkspaceModel[];
|
||||
currentWorkspace?: WorkspaceId;
|
||||
workspaces: WorkspaceModel[]
|
||||
}
|
||||
|
||||
export interface WorkspaceModel {
|
||||
@ -18,6 +19,7 @@ export interface WorkspaceModel {
|
||||
name: string;
|
||||
description?: string;
|
||||
ownerRef?: string;
|
||||
lastActiveClusterId?: ClusterId;
|
||||
}
|
||||
|
||||
export interface WorkspaceState {
|
||||
@ -30,6 +32,7 @@ export class Workspace implements WorkspaceModel, WorkspaceState {
|
||||
@observable description?: string;
|
||||
@observable ownerRef?: string;
|
||||
@observable enabled: boolean;
|
||||
@observable lastActiveClusterId?: ClusterId;
|
||||
|
||||
constructor(data: WorkspaceModel) {
|
||||
Object.assign(this, data);
|
||||
@ -66,7 +69,8 @@ export class Workspace implements WorkspaceModel, WorkspaceState {
|
||||
id: this.id,
|
||||
name: this.name,
|
||||
description: this.description,
|
||||
ownerRef: this.ownerRef
|
||||
ownerRef: this.ownerRef,
|
||||
lastActiveClusterId: this.lastActiveClusterId
|
||||
});
|
||||
}
|
||||
}
|
||||
@ -138,13 +142,12 @@ export class WorkspaceStore extends BaseStore<WorkspaceStoreModel> {
|
||||
}
|
||||
|
||||
@action
|
||||
setActive(id = WorkspaceStore.defaultId, reset = true) {
|
||||
setActive(id = WorkspaceStore.defaultId) {
|
||||
if (id === this.currentWorkspaceId) return;
|
||||
if (!this.getById(id)) {
|
||||
throw new Error(`workspace ${id} doesn't exist`);
|
||||
}
|
||||
this.currentWorkspaceId = id;
|
||||
clusterStore.activeCluster = null; // fixme: handle previously selected cluster from current workspace
|
||||
}
|
||||
|
||||
@action
|
||||
@ -184,6 +187,11 @@ export class WorkspaceStore extends BaseStore<WorkspaceStoreModel> {
|
||||
clusterStore.removeByWorkspaceId(id);
|
||||
}
|
||||
|
||||
@action
|
||||
setLastActiveClusterId(clusterId?: ClusterId, workspaceId = this.currentWorkspaceId) {
|
||||
this.getById(workspaceId).lastActiveClusterId = clusterId;
|
||||
}
|
||||
|
||||
@action
|
||||
protected fromStore({ currentWorkspace, workspaces = [] }: WorkspaceStoreModel) {
|
||||
if (currentWorkspace) {
|
||||
|
||||
@ -10,17 +10,27 @@ import { requestMain } from "../common/ipc";
|
||||
import { clusterKubectlApplyAllHandler } from "../common/cluster-ipc";
|
||||
|
||||
export interface ClusterFeatureStatus {
|
||||
/** feature's current version, as set by the implementation */
|
||||
currentVersion: string;
|
||||
installed: boolean;
|
||||
/** feature's latest version, as set by the implementation */
|
||||
latestVersion: string;
|
||||
/** whether the feature is installed or not, as set by the implementation */
|
||||
installed: boolean;
|
||||
/** whether the feature can be upgraded or not, as set by the implementation */
|
||||
canUpgrade: boolean;
|
||||
}
|
||||
|
||||
export abstract class ClusterFeature {
|
||||
name: string;
|
||||
latestVersion: string;
|
||||
config: any;
|
||||
|
||||
/**
|
||||
* this field sets the template parameters that are to be applied to any templated kubernetes resources that are to be installed for the feature.
|
||||
* See the renderTemplates() method for more details
|
||||
*/
|
||||
templateContext: any;
|
||||
|
||||
/**
|
||||
* this field holds the current feature status, is accessed directly by Lens
|
||||
*/
|
||||
@observable status: ClusterFeatureStatus = {
|
||||
currentVersion: null,
|
||||
installed: false,
|
||||
@ -28,15 +38,59 @@ export abstract class ClusterFeature {
|
||||
canUpgrade: false
|
||||
};
|
||||
|
||||
/**
|
||||
* to be implemented in the derived class, this method is typically called by Lens when a user has indicated that this feature is to be installed. The implementation
|
||||
* of this method should install kubernetes resources using the applyResources() method, or by directly accessing the kubernetes api (K8sApi)
|
||||
*
|
||||
* @param cluster the cluster that the feature is to be installed on
|
||||
*/
|
||||
abstract async install(cluster: Cluster): Promise<void>;
|
||||
|
||||
/**
|
||||
* to be implemented in the derived class, this method is typically called by Lens when a user has indicated that this feature is to be ugraded. The implementation
|
||||
* of this method should upgrade the kubernetes resources already installed, if relevant to the feature
|
||||
*
|
||||
* @param cluster the cluster that the feature is to be upgraded on
|
||||
*/
|
||||
abstract async upgrade(cluster: Cluster): Promise<void>;
|
||||
|
||||
/**
|
||||
* to be implemented in the derived class, this method is typically called by Lens when a user has indicated that this feature is to be uninstalled. The implementation
|
||||
* of this method should install kubernetes resources using the kubernetes api (K8sApi)
|
||||
*
|
||||
* @param cluster the cluster that the feature is to be uninstalled from
|
||||
*/
|
||||
abstract async uninstall(cluster: Cluster): Promise<void>;
|
||||
|
||||
/**
|
||||
* to be implemented in the derived class, this method is called periodically by Lens to determine details about the feature's current status. The implementation
|
||||
* of this method should provide the current status information. The currentVersion and latestVersion fields may be displayed by Lens in describing the feature.
|
||||
* The installed field should be set to true if the feature has been installed, otherwise false. Also, Lens relies on the canUpgrade field to determine if the feature
|
||||
* can be upgraded so the implementation should set the canUpgrade field according to specific rules for the feature, if relevant.
|
||||
*
|
||||
* @param cluster the cluster that the feature may be installed on
|
||||
*
|
||||
* @return a promise, resolved with the updated ClusterFeatureStatus
|
||||
*/
|
||||
abstract async updateStatus(cluster: Cluster): Promise<ClusterFeatureStatus>;
|
||||
|
||||
protected async applyResources(cluster: Cluster, resources: string[]) {
|
||||
/**
|
||||
* this is a helper method that conveniently applies kubernetes resources to the cluster.
|
||||
*
|
||||
* @param cluster the cluster that the resources are to be applied to
|
||||
* @param resourceSpec as a string type this is a folder path that is searched for files specifying kubernetes resources. The files are read and if any of the resource
|
||||
* files are templated, the template parameters are filled using the templateContext field (See renderTemplate() method). Finally the resources are applied to the
|
||||
* cluster. As a string[] type resourceSpec is treated as an array of fully formed (not templated) kubernetes resources that are applied to the cluster
|
||||
*/
|
||||
protected async applyResources(cluster: Cluster, resourceSpec: string | string[]) {
|
||||
let resources: string[];
|
||||
|
||||
if ( typeof resourceSpec === "string" ) {
|
||||
resources = this.renderTemplates(resourceSpec);
|
||||
} else {
|
||||
resources = resourceSpec;
|
||||
}
|
||||
|
||||
if (app) {
|
||||
await new ResourceApplier(cluster).kubectlApplyAll(resources);
|
||||
} else {
|
||||
@ -44,6 +98,14 @@ export abstract class ClusterFeature {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* this is a helper method that conveniently reads kubernetes resource files into a string array. It also fills templated resource files with the template parameter values
|
||||
* specified by the templateContext field. Templated files must end with the extension '.hb' and the template syntax must be compatible with handlebars.js
|
||||
*
|
||||
* @param folderPath this is a folder path that is searched for files defining kubernetes resources.
|
||||
*
|
||||
* @return an array of strings, each string being the contents of a resource file found in the folder path. This can be passed directly to applyResources()
|
||||
*/
|
||||
protected renderTemplates(folderPath: string): string[] {
|
||||
const resources: string[] = [];
|
||||
logger.info(`[FEATURE]: render templates from ${folderPath}`);
|
||||
@ -52,7 +114,7 @@ export abstract class ClusterFeature {
|
||||
const raw = fs.readFileSync(file);
|
||||
if (filename.endsWith('.hb')) {
|
||||
const template = hb.compile(raw.toString());
|
||||
resources.push(template(this.config));
|
||||
resources.push(template(this.templateContext));
|
||||
} else {
|
||||
resources.push(raw.toString());
|
||||
}
|
||||
|
||||
@ -1,4 +1,8 @@
|
||||
import { getAppVersion } from "../../common/utils";
|
||||
import { extensionsStore } from "../extensions-store";
|
||||
|
||||
export const version = getAppVersion();
|
||||
export { isSnap, isWindows, isMac, isLinux, appName, slackUrl, issuesTrackerUrl } from "../../common/vars";
|
||||
export { isSnap, isWindows, isMac, isLinux, appName, slackUrl, issuesTrackerUrl } from "../../common/vars";
|
||||
export function getEnabledExtensions(): string[] {
|
||||
return extensionsStore.enabledExtensions;
|
||||
}
|
||||
|
||||
330
src/extensions/extension-discovery.ts
Normal file
330
src/extensions/extension-discovery.ts
Normal file
@ -0,0 +1,330 @@
|
||||
import chokidar from "chokidar";
|
||||
import { EventEmitter } from "events";
|
||||
import fs from "fs-extra";
|
||||
import os from "os";
|
||||
import path from "path";
|
||||
import { getBundledExtensions } from "../common/utils/app-version";
|
||||
import logger from "../main/logger";
|
||||
import { extensionInstaller, PackageJson } from "./extension-installer";
|
||||
import { extensionsStore } from "./extensions-store";
|
||||
import type { LensExtensionId, LensExtensionManifest } from "./lens-extension";
|
||||
|
||||
export interface InstalledExtension {
|
||||
readonly manifest: LensExtensionManifest;
|
||||
readonly manifestPath: string;
|
||||
readonly isBundled: boolean; // defined in project root's package.json
|
||||
isEnabled: boolean;
|
||||
}
|
||||
|
||||
const logModule = "[EXTENSION-DISCOVERY]";
|
||||
export const manifestFilename = "package.json";
|
||||
|
||||
/**
|
||||
* Returns true if the lstat is for a directory-like file (e.g. isDirectory or symbolic link)
|
||||
* @param lstat the stats to compare
|
||||
*/
|
||||
const isDirectoryLike = (lstat: fs.Stats) => lstat.isDirectory() || lstat.isSymbolicLink();
|
||||
|
||||
/**
|
||||
* Discovers installed bundled and local extensions from the filesystem.
|
||||
* Also watches for added and removed local extensions by watching the directory.
|
||||
* Uses ExtensionInstaller to install dependencies for all of the extensions.
|
||||
* This is also done when a new extension is copied to the local extensions directory.
|
||||
* .init() must be called to start the directory watching.
|
||||
* The class emits events for added and removed extensions:
|
||||
* - "add": When extension is added. The event is of type InstalledExtension
|
||||
* - "remove": When extension is removed. The event is of type LensExtensionId
|
||||
*/
|
||||
export class ExtensionDiscovery {
|
||||
protected bundledFolderPath: string;
|
||||
|
||||
private loadStarted = false;
|
||||
|
||||
// This promise is resolved when .load() is finished.
|
||||
// This allows operations to be added after .load() success.
|
||||
private loaded: Promise<void>;
|
||||
|
||||
// These are called to either resolve or reject this.loaded promise
|
||||
private resolveLoaded: () => void;
|
||||
private rejectLoaded: (error: any) => void;
|
||||
|
||||
public events: EventEmitter;
|
||||
|
||||
constructor() {
|
||||
this.loaded = new Promise((resolve, reject) => {
|
||||
this.resolveLoaded = resolve;
|
||||
this.rejectLoaded = reject;
|
||||
});
|
||||
|
||||
this.events = new EventEmitter();
|
||||
}
|
||||
|
||||
// Each extension is added as a single dependency to this object, which is written as package.json.
|
||||
// Each dependency key is the name of the dependency, and
|
||||
// each dependency value is the non-symlinked path to the dependency (folder).
|
||||
protected packagesJson: PackageJson = {
|
||||
dependencies: {}
|
||||
};
|
||||
|
||||
get localFolderPath(): string {
|
||||
return path.join(os.homedir(), ".k8slens", "extensions");
|
||||
}
|
||||
|
||||
get packageJsonPath() {
|
||||
return path.join(extensionInstaller.extensionPackagesRoot, manifestFilename);
|
||||
}
|
||||
|
||||
get inTreeTargetPath() {
|
||||
return path.join(extensionInstaller.extensionPackagesRoot, "extensions");
|
||||
}
|
||||
|
||||
get inTreeFolderPath(): string {
|
||||
return path.resolve(__static, "../extensions");
|
||||
}
|
||||
|
||||
get nodeModulesPath(): string {
|
||||
return path.join(extensionInstaller.extensionPackagesRoot, "node_modules");
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the class and setups the file watcher for added/removed local extensions.
|
||||
*/
|
||||
init() {
|
||||
this.watchExtensions();
|
||||
}
|
||||
|
||||
/**
|
||||
* Watches for added/removed local extensions.
|
||||
* Dependencies are installed automatically after an extension folder is copied.
|
||||
*/
|
||||
async watchExtensions() {
|
||||
logger.info(`${logModule} watching extension add/remove in ${this.localFolderPath}`);
|
||||
|
||||
// Wait until .load() has been called and has been resolved
|
||||
await this.loaded;
|
||||
|
||||
// chokidar works better than fs.watch
|
||||
chokidar.watch(this.localFolderPath, {
|
||||
// Dont watch recursively into subdirectories
|
||||
depth: 0,
|
||||
// Try to wait until the file has been completely copied.
|
||||
// The OS might emit an event for added file even it's not completely written to the filesysten.
|
||||
awaitWriteFinish: {
|
||||
// Wait 300ms until the file size doesn't change to consider the file written.
|
||||
// For a small file like package.json this should be plenty of time.
|
||||
stabilityThreshold: 300
|
||||
}
|
||||
})
|
||||
// Extension add is detected by watching "<extensionDir>package.json" add
|
||||
.on("add", this.handleWatchFileAdd)
|
||||
// Extension remove is detected by watching <extensionDir>" unlink
|
||||
.on("unlinkDir", this.handleWatchUnlinkDir);
|
||||
}
|
||||
|
||||
handleWatchFileAdd = async (filePath: string) => {
|
||||
if (path.basename(filePath) === manifestFilename) {
|
||||
try {
|
||||
const absPath = path.dirname(filePath);
|
||||
|
||||
// this.loadExtensionFromPath updates this.packagesJson
|
||||
const extension = await this.loadExtensionFromPath(absPath);
|
||||
|
||||
if (extension) {
|
||||
// Install dependencies for the new extension
|
||||
await this.installPackages();
|
||||
|
||||
logger.info(`${logModule} Added extension ${extension.manifest.name}`);
|
||||
this.events.emit("add", extension);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
handleWatchUnlinkDir = async (filePath: string) => {
|
||||
// filePath is the non-symlinked path to the extension folder
|
||||
// this.packagesJson.dependencies value is the non-symlinked path to the extension folder
|
||||
// LensExtensionId in extension-loader is the symlinked path to the extension folder manifest file
|
||||
|
||||
// Check that the removed path is directly under this.localFolderPath
|
||||
// Note that the watcher can create unlink events for subdirectories of the extension
|
||||
const extensionFolderName = path.basename(filePath);
|
||||
|
||||
if (path.relative(this.localFolderPath, filePath) === extensionFolderName) {
|
||||
const extensionName: string | undefined = Object
|
||||
.entries(this.packagesJson.dependencies)
|
||||
.find(([_name, extensionFolder]) => filePath === extensionFolder)?.[0];
|
||||
|
||||
if (extensionName !== undefined) {
|
||||
delete this.packagesJson.dependencies[extensionName];
|
||||
|
||||
// Reinstall dependencies to remove the extension from package.json
|
||||
await this.installPackages();
|
||||
|
||||
// The path to the manifest file is the lens extension id
|
||||
// Note that we need to use the symlinked path
|
||||
const lensExtensionId = path.join(this.nodeModulesPath, extensionName, "package.json");
|
||||
|
||||
logger.info(`${logModule} removed extension ${extensionName}`);
|
||||
this.events.emit("remove", lensExtensionId as LensExtensionId);
|
||||
} else {
|
||||
logger.warn(`${logModule} extension ${extensionFolderName} not found, can't remove`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
async load(): Promise<Map<LensExtensionId, InstalledExtension>> {
|
||||
if (this.loadStarted) {
|
||||
// The class is simplified by only supporting .load() to be called once
|
||||
throw new Error("ExtensionDiscovery.load() can be only be called once");
|
||||
}
|
||||
|
||||
this.loadStarted = true;
|
||||
|
||||
try {
|
||||
logger.info(`${logModule} loading extensions from ${extensionInstaller.extensionPackagesRoot}`);
|
||||
|
||||
if (fs.existsSync(path.join(extensionInstaller.extensionPackagesRoot, "package-lock.json"))) {
|
||||
await fs.remove(path.join(extensionInstaller.extensionPackagesRoot, "package-lock.json"));
|
||||
}
|
||||
|
||||
try {
|
||||
await fs.access(this.inTreeFolderPath, fs.constants.W_OK);
|
||||
this.bundledFolderPath = this.inTreeFolderPath;
|
||||
} catch {
|
||||
// we need to copy in-tree extensions so that we can symlink them properly on "npm install"
|
||||
await fs.remove(this.inTreeTargetPath);
|
||||
await fs.ensureDir(this.inTreeTargetPath);
|
||||
await fs.copy(this.inTreeFolderPath, this.inTreeTargetPath);
|
||||
this.bundledFolderPath = this.inTreeTargetPath;
|
||||
}
|
||||
|
||||
await fs.ensureDir(this.nodeModulesPath);
|
||||
await fs.ensureDir(this.localFolderPath);
|
||||
|
||||
const extensions = await this.loadExtensions();
|
||||
|
||||
// resolve the loaded promise
|
||||
this.resolveLoaded();
|
||||
|
||||
return extensions;
|
||||
} catch (error) {
|
||||
this.rejectLoaded(error);
|
||||
}
|
||||
}
|
||||
|
||||
protected async getByManifest(manifestPath: string, { isBundled = false }: {
|
||||
isBundled?: boolean;
|
||||
} = {}): Promise<InstalledExtension | null> {
|
||||
let manifestJson: LensExtensionManifest;
|
||||
let isEnabled: boolean;
|
||||
|
||||
try {
|
||||
// check manifest file for existence
|
||||
fs.accessSync(manifestPath, fs.constants.F_OK);
|
||||
|
||||
manifestJson = __non_webpack_require__(manifestPath);
|
||||
const installedManifestPath = path.join(this.nodeModulesPath, manifestJson.name, "package.json");
|
||||
this.packagesJson.dependencies[manifestJson.name] = path.dirname(manifestPath);
|
||||
const isEnabled = isBundled || extensionsStore.isEnabled(installedManifestPath);
|
||||
|
||||
return {
|
||||
manifestPath: installedManifestPath,
|
||||
manifest: manifestJson,
|
||||
isBundled,
|
||||
isEnabled
|
||||
};
|
||||
} catch (error) {
|
||||
logger.error(`${logModule}: can't install extension at ${manifestPath}: ${error}`, { manifestJson });
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async loadExtensions(): Promise<Map<LensExtensionId, InstalledExtension>> {
|
||||
const bundledExtensions = await this.loadBundledExtensions();
|
||||
const localExtensions = await this.loadFromFolder(this.localFolderPath);
|
||||
await this.installPackages();
|
||||
const extensions = bundledExtensions.concat(localExtensions);
|
||||
|
||||
return new Map(extensions.map(ext => [ext.manifestPath, ext]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Write package.json to file system and install dependencies.
|
||||
*/
|
||||
installPackages() {
|
||||
return extensionInstaller.installPackages(this.packageJsonPath, this.packagesJson);
|
||||
}
|
||||
|
||||
async loadBundledExtensions() {
|
||||
const extensions: InstalledExtension[] = [];
|
||||
const folderPath = this.bundledFolderPath;
|
||||
const bundledExtensions = getBundledExtensions();
|
||||
const paths = await fs.readdir(folderPath);
|
||||
|
||||
for (const fileName of paths) {
|
||||
if (!bundledExtensions.includes(fileName)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const absPath = path.resolve(folderPath, fileName);
|
||||
const extension = await this.loadExtensionFromPath(absPath, { isBundled: true });
|
||||
|
||||
if (extension) {
|
||||
extensions.push(extension);
|
||||
}
|
||||
}
|
||||
logger.debug(`${logModule}: ${extensions.length} extensions loaded`, { folderPath, extensions });
|
||||
|
||||
return extensions;
|
||||
}
|
||||
|
||||
async loadFromFolder(folderPath: string): Promise<InstalledExtension[]> {
|
||||
const bundledExtensions = getBundledExtensions();
|
||||
const extensions: InstalledExtension[] = [];
|
||||
const paths = await fs.readdir(folderPath);
|
||||
|
||||
for (const fileName of paths) {
|
||||
// do not allow to override bundled extensions
|
||||
if (bundledExtensions.includes(fileName)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const absPath = path.resolve(folderPath, fileName);
|
||||
|
||||
if (!fs.existsSync(absPath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const lstat = await fs.lstat(absPath);
|
||||
|
||||
// skip non-directories
|
||||
if (!isDirectoryLike(lstat)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const extension = await this.loadExtensionFromPath(absPath);
|
||||
if (extension) {
|
||||
extensions.push(extension);
|
||||
}
|
||||
}
|
||||
|
||||
logger.debug(`${logModule}: ${extensions.length} extensions loaded`, { folderPath, extensions });
|
||||
return extensions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads extension from absolute path, updates this.packagesJson to include it and returns the extension.
|
||||
*/
|
||||
async loadExtensionFromPath(absPath: string, { isBundled = false }: {
|
||||
isBundled?: boolean;
|
||||
} = {}): Promise<InstalledExtension | null> {
|
||||
const manifestPath = path.resolve(absPath, manifestFilename);
|
||||
|
||||
return this.getByManifest(manifestPath, { isBundled });
|
||||
}
|
||||
}
|
||||
|
||||
export const extensionDiscovery = new ExtensionDiscovery();
|
||||
69
src/extensions/extension-installer.ts
Normal file
69
src/extensions/extension-installer.ts
Normal file
@ -0,0 +1,69 @@
|
||||
import AwaitLock from 'await-lock';
|
||||
import child_process from "child_process";
|
||||
import fs from "fs-extra";
|
||||
import path from "path";
|
||||
import logger from "../main/logger";
|
||||
import { extensionPackagesRoot } from "./extension-loader";
|
||||
|
||||
const logModule = "[EXTENSION-INSTALLER]";
|
||||
|
||||
type Dependencies = {
|
||||
[name: string]: string;
|
||||
};
|
||||
|
||||
// Type for the package.json file that is written by ExtensionInstaller
|
||||
export type PackageJson = {
|
||||
dependencies: Dependencies;
|
||||
};
|
||||
|
||||
/**
|
||||
* Installs dependencies for extensions
|
||||
*/
|
||||
export class ExtensionInstaller {
|
||||
private installLock = new AwaitLock();
|
||||
|
||||
get extensionPackagesRoot() {
|
||||
return extensionPackagesRoot();
|
||||
}
|
||||
|
||||
get npmPath() {
|
||||
return __non_webpack_require__.resolve('npm/bin/npm-cli');
|
||||
}
|
||||
|
||||
installDependencies(): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
logger.info(`${logModule} installing dependencies at ${extensionPackagesRoot()}`);
|
||||
const child = child_process.fork(this.npmPath, ["install", "--silent", "--no-audit", "--only=prod", "--prefer-offline", "--no-package-lock"], {
|
||||
cwd: extensionPackagesRoot(),
|
||||
silent: true
|
||||
});
|
||||
child.on("close", () => {
|
||||
resolve();
|
||||
});
|
||||
child.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Write package.json to the file system and execute npm install for it.
|
||||
*/
|
||||
async installPackages(packageJsonPath: string, packagesJson: PackageJson): Promise<void> {
|
||||
// Mutual exclusion to install packages in sequence
|
||||
await this.installLock.acquireAsync();
|
||||
|
||||
try {
|
||||
// Write the package.json which will be installed in .installDependencies()
|
||||
await fs.writeFile(path.join(packageJsonPath), JSON.stringify(packagesJson, null, 2), {
|
||||
mode: 0o600
|
||||
});
|
||||
|
||||
await this.installDependencies();
|
||||
} finally {
|
||||
this.installLock.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const extensionInstaller = new ExtensionInstaller();
|
||||
@ -1,20 +1,26 @@
|
||||
import { app, ipcRenderer, remote } from "electron";
|
||||
import { action, computed, observable, reaction, toJS, when } from "mobx";
|
||||
import path from "path";
|
||||
import { getHostedCluster } from "../common/cluster-store";
|
||||
import { broadcastMessage, handleRequest, requestMain, subscribeToBroadcast } from "../common/ipc";
|
||||
import logger from "../main/logger";
|
||||
import type { InstalledExtension } from "./extension-discovery";
|
||||
import { extensionsStore } from "./extensions-store";
|
||||
import type { LensExtension, LensExtensionConstructor, LensExtensionId } from "./lens-extension";
|
||||
import type { LensMainExtension } from "./lens-main-extension";
|
||||
import type { LensRendererExtension } from "./lens-renderer-extension";
|
||||
import type { InstalledExtension } from "./extension-manager";
|
||||
import path from "path";
|
||||
import { broadcastMessage, handleRequest, requestMain, subscribeToBroadcast } from "../common/ipc";
|
||||
import { action, computed, observable, reaction, toJS, when } from "mobx";
|
||||
import logger from "../main/logger";
|
||||
import { app, ipcRenderer, remote } from "electron";
|
||||
import * as registries from "./registries";
|
||||
import { extensionsStore } from "./extensions-store";
|
||||
|
||||
// lazy load so that we get correct userData
|
||||
export function extensionPackagesRoot() {
|
||||
return path.join((app || remote.app).getPath("userData"));
|
||||
}
|
||||
|
||||
const logModule = "[EXTENSIONS-LOADER]";
|
||||
|
||||
/**
|
||||
* Loads installed extensions to the Lens application
|
||||
*/
|
||||
export class ExtensionLoader {
|
||||
protected extensions = observable.map<LensExtensionId, InstalledExtension>();
|
||||
protected instances = observable.map<LensExtensionId, LensExtension>();
|
||||
@ -47,6 +53,17 @@ export class ExtensionLoader {
|
||||
this.extensions.replace(extensions);
|
||||
}
|
||||
|
||||
addExtension(extension: InstalledExtension) {
|
||||
this.extensions.set(extension.manifestPath as LensExtensionId, extension);
|
||||
}
|
||||
|
||||
removeExtension(lensExtensionId: LensExtensionId) {
|
||||
// TODO: Remove the extension properly (from menus etc.)
|
||||
if (!this.extensions.delete(lensExtensionId)) {
|
||||
throw new Error(`Can't remove extension ${lensExtensionId}, doesn't exist.`);
|
||||
}
|
||||
}
|
||||
|
||||
protected async initMain() {
|
||||
this.isLoaded = true;
|
||||
this.loadOnMain();
|
||||
@ -77,15 +94,15 @@ export class ExtensionLoader {
|
||||
}
|
||||
|
||||
loadOnMain() {
|
||||
logger.info('[EXTENSIONS-LOADER]: load on main');
|
||||
this.autoInitExtensions((ext: LensMainExtension) => [
|
||||
logger.info(`${logModule}: load on main`);
|
||||
this.autoInitExtensions(async (ext: LensMainExtension) => [
|
||||
registries.menuRegistry.add(ext.appMenus)
|
||||
]);
|
||||
}
|
||||
|
||||
loadOnClusterManagerRenderer() {
|
||||
logger.info('[EXTENSIONS-LOADER]: load on main renderer (cluster manager)');
|
||||
this.autoInitExtensions((ext: LensRendererExtension) => [
|
||||
logger.info(`${logModule}: load on main renderer (cluster manager)`);
|
||||
this.autoInitExtensions(async (ext: LensRendererExtension) => [
|
||||
registries.globalPageRegistry.add(ext.globalPages, ext),
|
||||
registries.globalPageMenuRegistry.add(ext.globalPageMenus, ext),
|
||||
registries.appPreferenceRegistry.add(ext.appPreferences),
|
||||
@ -95,37 +112,48 @@ export class ExtensionLoader {
|
||||
}
|
||||
|
||||
loadOnClusterRenderer() {
|
||||
logger.info('[EXTENSIONS-LOADER]: load on cluster renderer (dashboard)');
|
||||
this.autoInitExtensions((ext: LensRendererExtension) => [
|
||||
registries.clusterPageRegistry.add(ext.clusterPages, ext),
|
||||
registries.clusterPageMenuRegistry.add(ext.clusterPageMenus, ext),
|
||||
registries.kubeObjectMenuRegistry.add(ext.kubeObjectMenuItems),
|
||||
registries.kubeObjectDetailRegistry.add(ext.kubeObjectDetailItems),
|
||||
registries.kubeObjectStatusRegistry.add(ext.kubeObjectStatusTexts)
|
||||
]);
|
||||
logger.info(`${logModule}: load on cluster renderer (dashboard)`);
|
||||
const cluster = getHostedCluster();
|
||||
this.autoInitExtensions(async (ext: LensRendererExtension) => {
|
||||
if (await ext.isEnabledForCluster(cluster) === false) {
|
||||
return [];
|
||||
}
|
||||
return [
|
||||
registries.clusterPageRegistry.add(ext.clusterPages, ext),
|
||||
registries.clusterPageMenuRegistry.add(ext.clusterPageMenus, ext),
|
||||
registries.kubeObjectMenuRegistry.add(ext.kubeObjectMenuItems),
|
||||
registries.kubeObjectDetailRegistry.add(ext.kubeObjectDetailItems),
|
||||
registries.kubeObjectStatusRegistry.add(ext.kubeObjectStatusTexts)
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
protected autoInitExtensions(register: (ext: LensExtension) => Function[]) {
|
||||
protected autoInitExtensions(register: (ext: LensExtension) => Promise<Function[]>) {
|
||||
return reaction(() => this.toJSON(), installedExtensions => {
|
||||
for (const [extId, ext] of installedExtensions) {
|
||||
let instance = this.instances.get(extId);
|
||||
if (ext.isEnabled && !instance) {
|
||||
const alreadyInit = this.instances.has(extId);
|
||||
|
||||
if (ext.isEnabled && !alreadyInit) {
|
||||
try {
|
||||
const LensExtensionClass: LensExtensionConstructor = this.requireExtension(ext);
|
||||
if (!LensExtensionClass) continue;
|
||||
instance = new LensExtensionClass(ext);
|
||||
const LensExtensionClass = this.requireExtension(ext);
|
||||
if (!LensExtensionClass) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const instance = new LensExtensionClass(ext);
|
||||
instance.whenEnabled(() => register(instance));
|
||||
instance.enable();
|
||||
this.instances.set(extId, instance);
|
||||
} catch (err) {
|
||||
logger.error(`[EXTENSION-LOADER]: activation extension error`, { ext, err });
|
||||
logger.error(`${logModule}: activation extension error`, { ext, err });
|
||||
}
|
||||
} else if (!ext.isEnabled && instance) {
|
||||
} else if (!ext.isEnabled && alreadyInit) {
|
||||
try {
|
||||
const instance = this.instances.get(extId);
|
||||
instance.disable();
|
||||
this.instances.delete(extId);
|
||||
} catch (err) {
|
||||
logger.error(`[EXTENSION-LOADER]: deactivation extension error`, { ext, err });
|
||||
logger.error(`${logModule}: deactivation extension error`, { ext, err });
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -134,7 +162,7 @@ export class ExtensionLoader {
|
||||
});
|
||||
}
|
||||
|
||||
protected requireExtension(extension: InstalledExtension) {
|
||||
protected requireExtension(extension: InstalledExtension): LensExtensionConstructor {
|
||||
let extEntrypoint = "";
|
||||
try {
|
||||
if (ipcRenderer && extension.manifest.renderer) {
|
||||
@ -146,7 +174,7 @@ export class ExtensionLoader {
|
||||
return __non_webpack_require__(extEntrypoint).default;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`[EXTENSION-LOADER]: can't load extension main at ${extEntrypoint}: ${err}`, { extension });
|
||||
console.error(`${logModule}: can't load extension main at ${extEntrypoint}: ${err}`, { extension });
|
||||
console.trace(err);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,172 +0,0 @@
|
||||
import type { LensExtensionId, LensExtensionManifest } from "./lens-extension";
|
||||
import path from "path";
|
||||
import os from "os";
|
||||
import fs from "fs-extra";
|
||||
import child_process from "child_process";
|
||||
import logger from "../main/logger";
|
||||
import { extensionPackagesRoot } from "./extension-loader";
|
||||
import { getBundledExtensions } from "../common/utils/app-version";
|
||||
|
||||
export interface InstalledExtension {
|
||||
readonly manifest: LensExtensionManifest;
|
||||
readonly manifestPath: string;
|
||||
readonly isBundled: boolean; // defined in project root's package.json
|
||||
isEnabled: boolean;
|
||||
}
|
||||
|
||||
type Dependencies = {
|
||||
[name: string]: string;
|
||||
};
|
||||
|
||||
type PackageJson = {
|
||||
dependencies: Dependencies;
|
||||
};
|
||||
|
||||
export class ExtensionManager {
|
||||
|
||||
protected bundledFolderPath: string;
|
||||
|
||||
protected packagesJson: PackageJson = {
|
||||
dependencies: {}
|
||||
};
|
||||
|
||||
get extensionPackagesRoot() {
|
||||
return extensionPackagesRoot();
|
||||
}
|
||||
|
||||
get inTreeTargetPath() {
|
||||
return path.join(this.extensionPackagesRoot, "extensions");
|
||||
}
|
||||
|
||||
get inTreeFolderPath(): string {
|
||||
return path.resolve(__static, "../extensions");
|
||||
}
|
||||
|
||||
get nodeModulesPath(): string {
|
||||
return path.join(this.extensionPackagesRoot, "node_modules");
|
||||
}
|
||||
|
||||
get localFolderPath(): string {
|
||||
return path.join(os.homedir(), ".k8slens", "extensions");
|
||||
}
|
||||
|
||||
get npmPath() {
|
||||
return __non_webpack_require__.resolve('npm/bin/npm-cli');
|
||||
}
|
||||
|
||||
get packageJsonPath() {
|
||||
return path.join(this.extensionPackagesRoot, "package.json");
|
||||
}
|
||||
|
||||
async load(): Promise<Map<LensExtensionId, InstalledExtension>> {
|
||||
logger.info("[EXTENSION-MANAGER] loading extensions from " + this.extensionPackagesRoot);
|
||||
if (fs.existsSync(path.join(this.extensionPackagesRoot, "package-lock.json"))) {
|
||||
await fs.remove(path.join(this.extensionPackagesRoot, "package-lock.json"));
|
||||
}
|
||||
try {
|
||||
await fs.access(this.inTreeFolderPath, fs.constants.W_OK);
|
||||
this.bundledFolderPath = this.inTreeFolderPath;
|
||||
} catch {
|
||||
// we need to copy in-tree extensions so that we can symlink them properly on "npm install"
|
||||
await fs.remove(this.inTreeTargetPath);
|
||||
await fs.ensureDir(this.inTreeTargetPath);
|
||||
await fs.copy(this.inTreeFolderPath, this.inTreeTargetPath);
|
||||
this.bundledFolderPath = this.inTreeTargetPath;
|
||||
}
|
||||
await fs.ensureDir(this.nodeModulesPath);
|
||||
await fs.ensureDir(this.localFolderPath);
|
||||
return await this.loadExtensions();
|
||||
}
|
||||
|
||||
protected async getByManifest(manifestPath: string, { isBundled = false } = {}): Promise<InstalledExtension> {
|
||||
let manifestJson: LensExtensionManifest;
|
||||
try {
|
||||
fs.accessSync(manifestPath, fs.constants.F_OK); // check manifest file for existence
|
||||
manifestJson = __non_webpack_require__(manifestPath);
|
||||
this.packagesJson.dependencies[manifestJson.name] = path.dirname(manifestPath);
|
||||
|
||||
logger.info("[EXTENSION-MANAGER] installed extension " + manifestJson.name);
|
||||
return {
|
||||
manifestPath: path.join(this.nodeModulesPath, manifestJson.name, "package.json"),
|
||||
manifest: manifestJson,
|
||||
isBundled: isBundled,
|
||||
isEnabled: isBundled,
|
||||
};
|
||||
} catch (err) {
|
||||
logger.error(`[EXTENSION-MANAGER]: can't install extension at ${manifestPath}: ${err}`, { manifestJson });
|
||||
}
|
||||
}
|
||||
|
||||
protected installPackages(): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = child_process.fork(this.npmPath, ["install", "--silent", "--no-audit", "--only=prod", "--prefer-offline", "--no-package-lock"], {
|
||||
cwd: extensionPackagesRoot(),
|
||||
silent: true
|
||||
});
|
||||
child.on("close", () => {
|
||||
resolve();
|
||||
});
|
||||
child.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async loadExtensions() {
|
||||
const bundledExtensions = await this.loadBundledExtensions();
|
||||
const localExtensions = await this.loadFromFolder(this.localFolderPath);
|
||||
await fs.writeFile(path.join(this.packageJsonPath), JSON.stringify(this.packagesJson, null, 2), { mode: 0o600 });
|
||||
await this.installPackages();
|
||||
const extensions = bundledExtensions.concat(localExtensions);
|
||||
return new Map(extensions.map(ext => [ext.manifestPath, ext]));
|
||||
}
|
||||
|
||||
async loadBundledExtensions() {
|
||||
const extensions: InstalledExtension[] = [];
|
||||
const folderPath = this.bundledFolderPath;
|
||||
const bundledExtensions = getBundledExtensions();
|
||||
const paths = await fs.readdir(folderPath);
|
||||
for (const fileName of paths) {
|
||||
if (!bundledExtensions.includes(fileName)) {
|
||||
continue;
|
||||
}
|
||||
const absPath = path.resolve(folderPath, fileName);
|
||||
const manifestPath = path.resolve(absPath, "package.json");
|
||||
const ext = await this.getByManifest(manifestPath, { isBundled: true }).catch(() => null);
|
||||
if (ext) {
|
||||
extensions.push(ext);
|
||||
}
|
||||
}
|
||||
logger.debug(`[EXTENSION-MANAGER]: ${extensions.length} extensions loaded`, { folderPath, extensions });
|
||||
return extensions;
|
||||
}
|
||||
|
||||
async loadFromFolder(folderPath: string): Promise<InstalledExtension[]> {
|
||||
const bundledExtensions = getBundledExtensions();
|
||||
const extensions: InstalledExtension[] = [];
|
||||
const paths = await fs.readdir(folderPath);
|
||||
for (const fileName of paths) {
|
||||
if (bundledExtensions.includes(fileName)) { // do no allow to override bundled extensions
|
||||
continue;
|
||||
}
|
||||
const absPath = path.resolve(folderPath, fileName);
|
||||
if (!fs.existsSync(absPath)) {
|
||||
continue;
|
||||
}
|
||||
const lstat = await fs.lstat(absPath);
|
||||
if (!lstat.isDirectory() && !lstat.isSymbolicLink()) { // skip non-directories
|
||||
continue;
|
||||
}
|
||||
const manifestPath = path.resolve(absPath, "package.json");
|
||||
const ext = await this.getByManifest(manifestPath).catch(() => null);
|
||||
if (ext) {
|
||||
extensions.push(ext);
|
||||
}
|
||||
}
|
||||
|
||||
logger.debug(`[EXTENSION-MANAGER]: ${extensions.length} extensions loaded`, { folderPath, extensions });
|
||||
return extensions;
|
||||
}
|
||||
}
|
||||
|
||||
export const extensionManager = new ExtensionManager();
|
||||
@ -1,7 +1,7 @@
|
||||
import type { LensExtensionId } from "./lens-extension";
|
||||
import type { ExtensionLoader } from "./extension-loader";
|
||||
import { BaseStore } from "../common/base-store";
|
||||
import { action, observable, reaction, toJS } from "mobx";
|
||||
import { action, computed, observable, reaction, toJS } from "mobx";
|
||||
|
||||
export interface LensExtensionsStoreModel {
|
||||
extensions: Record<LensExtensionId, LensExtensionState>;
|
||||
@ -9,6 +9,7 @@ export interface LensExtensionsStoreModel {
|
||||
|
||||
export interface LensExtensionState {
|
||||
enabled?: boolean;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export class ExtensionsStore extends BaseStore<LensExtensionsStoreModel> {
|
||||
@ -18,6 +19,17 @@ export class ExtensionsStore extends BaseStore<LensExtensionsStoreModel> {
|
||||
});
|
||||
}
|
||||
|
||||
@computed
|
||||
get enabledExtensions() {
|
||||
const extensions: string[] = [];
|
||||
this.state.forEach((state, id) => {
|
||||
if (state.enabled) {
|
||||
extensions.push(state.name);
|
||||
}
|
||||
});
|
||||
return extensions;
|
||||
}
|
||||
|
||||
protected state = observable.map<LensExtensionId, LensExtensionState>();
|
||||
|
||||
protected getState(extensionLoader: ExtensionLoader) {
|
||||
@ -25,6 +37,7 @@ export class ExtensionsStore extends BaseStore<LensExtensionsStoreModel> {
|
||||
return Array.from(extensionLoader.userExtensions).reduce((state, [extId, ext]) => {
|
||||
state[extId] = {
|
||||
enabled: ext.isEnabled,
|
||||
name: ext.manifest.name,
|
||||
};
|
||||
return state;
|
||||
}, state);
|
||||
@ -34,11 +47,6 @@ export class ExtensionsStore extends BaseStore<LensExtensionsStoreModel> {
|
||||
await extensionLoader.whenLoaded;
|
||||
await this.whenLoaded;
|
||||
|
||||
// activate user-extensions when state is ready
|
||||
extensionLoader.userExtensions.forEach((ext, extId) => {
|
||||
ext.isEnabled = this.isEnabled(extId);
|
||||
});
|
||||
|
||||
// apply state on changes from store
|
||||
reaction(() => this.state.toJS(), extensionsState => {
|
||||
extensionsState.forEach((state, extId) => {
|
||||
@ -57,7 +65,7 @@ export class ExtensionsStore extends BaseStore<LensExtensionsStoreModel> {
|
||||
|
||||
isEnabled(extId: LensExtensionId) {
|
||||
const state = this.state.get(extId);
|
||||
return !state /* enabled by default */ || state.enabled;
|
||||
return state && state.enabled; // by default false
|
||||
}
|
||||
|
||||
@action
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
import type { InstalledExtension } from "./extension-manager";
|
||||
import type { InstalledExtension } from "./extension-discovery";
|
||||
import { action, observable, reaction } from "mobx";
|
||||
import { filesystemProvisionerStore } from "../main/extension-filesystem";
|
||||
import logger from "../main/logger";
|
||||
|
||||
export type LensExtensionId = string; // path to manifest (package.json)
|
||||
@ -11,6 +12,7 @@ export interface LensExtensionManifest {
|
||||
description?: string;
|
||||
main?: string; // path to %ext/dist/main.js
|
||||
renderer?: string; // path to %ext/dist/renderer.js
|
||||
lens?: object; // fixme: add more required fields for validation
|
||||
}
|
||||
|
||||
export class LensExtension {
|
||||
@ -27,6 +29,7 @@ export class LensExtension {
|
||||
}
|
||||
|
||||
get id(): LensExtensionId {
|
||||
// This is the symlinked path under node_modules
|
||||
return this.manifestPath;
|
||||
}
|
||||
|
||||
@ -38,6 +41,17 @@ export class LensExtension {
|
||||
return this.manifest.version;
|
||||
}
|
||||
|
||||
/**
|
||||
* getExtensionFileFolder returns the path to an already created folder. This
|
||||
* folder is for the sole use of this extension.
|
||||
*
|
||||
* Note: there is no security done on this folder, only obfiscation of the
|
||||
* folder name.
|
||||
*/
|
||||
async getExtensionFileFolder(): Promise<string> {
|
||||
return filesystemProvisionerStore.requestDirectory(this.id);
|
||||
}
|
||||
|
||||
get description() {
|
||||
return this.manifest.description;
|
||||
}
|
||||
@ -66,15 +80,16 @@ export class LensExtension {
|
||||
}
|
||||
}
|
||||
|
||||
async whenEnabled(handlers: () => Function[]) {
|
||||
async whenEnabled(handlers: () => Promise<Function[]>) {
|
||||
const disposers: Function[] = [];
|
||||
const unregisterHandlers = () => {
|
||||
disposers.forEach(unregister => unregister());
|
||||
disposers.length = 0;
|
||||
};
|
||||
const cancelReaction = reaction(() => this.isEnabled, isEnabled => {
|
||||
const cancelReaction = reaction(() => this.isEnabled, async (isEnabled) => {
|
||||
if (isEnabled) {
|
||||
disposers.push(...handlers());
|
||||
const handlerDisposers = await handlers();
|
||||
disposers.push(...handlerDisposers);
|
||||
} else {
|
||||
unregisterHandlers();
|
||||
}
|
||||
@ -95,3 +110,7 @@ export class LensExtension {
|
||||
// mock
|
||||
}
|
||||
}
|
||||
|
||||
export function sanitizeExtensionName(name: string) {
|
||||
return name.replace("@", "").replace("/", "--");
|
||||
}
|
||||
|
||||
@ -5,13 +5,13 @@ import { WindowManager } from "../main/window-manager";
|
||||
import { getExtensionPageUrl } from "./registries/page-registry";
|
||||
|
||||
export class LensMainExtension extends LensExtension {
|
||||
@observable.shallow appMenus: MenuRegistration[] = [];
|
||||
appMenus: MenuRegistration[] = [];
|
||||
|
||||
async navigate<P extends object>(pageId?: string, params?: P, frameId?: number) {
|
||||
const windowManager = WindowManager.getInstance<WindowManager>();
|
||||
const pageUrl = getExtensionPageUrl({
|
||||
extensionId: this.name,
|
||||
pageId: pageId,
|
||||
pageId,
|
||||
params: params ?? {}, // compile to url with params
|
||||
});
|
||||
await windowManager.navigate(pageUrl, frameId);
|
||||
|
||||
@ -1,27 +1,36 @@
|
||||
import type { AppPreferenceRegistration, ClusterFeatureRegistration, KubeObjectDetailRegistration, KubeObjectMenuRegistration, KubeObjectStatusRegistration, PageMenuRegistration, PageRegistration, StatusBarRegistration, } from "./registries";
|
||||
import type { Cluster } from "../main/cluster";
|
||||
import { observable } from "mobx";
|
||||
import { LensExtension } from "./lens-extension";
|
||||
import { getExtensionPageUrl } from "./registries/page-registry";
|
||||
|
||||
|
||||
export class LensRendererExtension extends LensExtension {
|
||||
@observable.shallow globalPages: PageRegistration[] = [];
|
||||
@observable.shallow clusterPages: PageRegistration[] = [];
|
||||
@observable.shallow globalPageMenus: PageMenuRegistration[] = [];
|
||||
@observable.shallow clusterPageMenus: PageMenuRegistration[] = [];
|
||||
@observable.shallow kubeObjectStatusTexts: KubeObjectStatusRegistration[] = [];
|
||||
@observable.shallow appPreferences: AppPreferenceRegistration[] = [];
|
||||
@observable.shallow clusterFeatures: ClusterFeatureRegistration[] = [];
|
||||
@observable.shallow statusBarItems: StatusBarRegistration[] = [];
|
||||
@observable.shallow kubeObjectDetailItems: KubeObjectDetailRegistration[] = [];
|
||||
@observable.shallow kubeObjectMenuItems: KubeObjectMenuRegistration[] = [];
|
||||
globalPages: PageRegistration[] = [];
|
||||
clusterPages: PageRegistration[] = [];
|
||||
globalPageMenus: PageMenuRegistration[] = [];
|
||||
clusterPageMenus: PageMenuRegistration[] = [];
|
||||
kubeObjectStatusTexts: KubeObjectStatusRegistration[] = [];
|
||||
appPreferences: AppPreferenceRegistration[] = [];
|
||||
clusterFeatures: ClusterFeatureRegistration[] = [];
|
||||
statusBarItems: StatusBarRegistration[] = [];
|
||||
kubeObjectDetailItems: KubeObjectDetailRegistration[] = [];
|
||||
kubeObjectMenuItems: KubeObjectMenuRegistration[] = [];
|
||||
|
||||
async navigate<P extends object>(pageId?: string, params?: P) {
|
||||
const { navigate } = await import("../renderer/navigation");
|
||||
const pageUrl = getExtensionPageUrl({
|
||||
extensionId: this.name,
|
||||
pageId: pageId,
|
||||
pageId,
|
||||
params: params ?? {}, // compile to url with params
|
||||
});
|
||||
navigate(pageUrl);
|
||||
}
|
||||
|
||||
/**
|
||||
* Defines if extension is enabled for a given cluster. Defaults to `true`.
|
||||
*/
|
||||
async isEnabledForCluster(cluster: Cluster): Promise<Boolean> {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@ -25,8 +25,8 @@ describe("getPageUrl", () => {
|
||||
expect(getExtensionPageUrl({ extensionId: ext.name, pageId: "/test" })).toBe("/extension/foo-bar/test");
|
||||
});
|
||||
|
||||
it("removes @", () => {
|
||||
expect(getExtensionPageUrl({ extensionId: "@foo/bar" })).toBe("/extension/foo-bar");
|
||||
it("removes @ and replace `/` to `--`", () => {
|
||||
expect(getExtensionPageUrl({ extensionId: "@foo/bar" })).toBe("/extension/foo--bar");
|
||||
});
|
||||
|
||||
it("adds / prefix", () => {
|
||||
|
||||
@ -1,20 +1,21 @@
|
||||
// Base class for extensions-api registries
|
||||
import { action, observable } from "mobx";
|
||||
import { LensExtension } from "../lens-extension";
|
||||
import { recitfy } from "../../common/utils";
|
||||
|
||||
export class BaseRegistry<T = object, I extends T = T> {
|
||||
export class BaseRegistry<T> {
|
||||
private items = observable<T>([], { deep: false });
|
||||
|
||||
getItems(): I[] {
|
||||
return this.items.toJS() as I[];
|
||||
getItems(): T[] {
|
||||
return this.items.toJS();
|
||||
}
|
||||
|
||||
add(items: T | T[], ext?: LensExtension): () => void; // allow method overloading with required "ext"
|
||||
@action
|
||||
add(items: T | T[]) {
|
||||
const normalizedItems = (Array.isArray(items) ? items : [items]);
|
||||
this.items.push(...normalizedItems);
|
||||
return () => this.remove(...normalizedItems);
|
||||
const itemArray = recitfy(items);
|
||||
this.items.push(...itemArray);
|
||||
return () => this.remove(...itemArray);
|
||||
}
|
||||
|
||||
@action
|
||||
|
||||
@ -5,8 +5,9 @@ import path from "path";
|
||||
import { action } from "mobx";
|
||||
import { compile } from "path-to-regexp";
|
||||
import { BaseRegistry } from "./base-registry";
|
||||
import { LensExtension } from "../lens-extension";
|
||||
import { LensExtension, sanitizeExtensionName } from "../lens-extension";
|
||||
import logger from "../../main/logger";
|
||||
import { recitfy } from "../../common/utils";
|
||||
|
||||
export interface PageRegistration {
|
||||
/**
|
||||
@ -15,11 +16,6 @@ export interface PageRegistration {
|
||||
* When not provided, first registered page without "id" would be used for page-menus without target.pageId for same extension
|
||||
*/
|
||||
id?: string;
|
||||
/**
|
||||
* Alias to page ID which assume to be used as path with possible :param placeholders
|
||||
* @deprecated
|
||||
*/
|
||||
routePath?: string;
|
||||
/**
|
||||
* Strict route matching to provided page-id, read also: https://reactrouter.com/web/api/NavLink/exact-bool
|
||||
* In case when more than one page registered at same extension "pageId" is required to identify different pages,
|
||||
@ -44,10 +40,6 @@ export interface PageComponents {
|
||||
Page: React.ComponentType<any>;
|
||||
}
|
||||
|
||||
export function sanitizeExtensionName(name: string) {
|
||||
return name.replace("@", "").replace("/", "-");
|
||||
}
|
||||
|
||||
export function getExtensionPageUrl<P extends object>({ extensionId, pageId = "", params }: PageMenuTarget<P>): string {
|
||||
const extensionBaseUrl = compile(`/extension/:name`)({
|
||||
name: sanitizeExtensionName(extensionId), // compile only with extension-id first and define base path
|
||||
@ -59,15 +51,16 @@ export function getExtensionPageUrl<P extends object>({ extensionId, pageId = ""
|
||||
return extPageRoutePath;
|
||||
}
|
||||
|
||||
export class PageRegistry extends BaseRegistry<PageRegistration, RegisteredPage> {
|
||||
export class PageRegistry extends BaseRegistry<RegisteredPage> {
|
||||
@action
|
||||
add(items: PageRegistration[], ext: LensExtension) {
|
||||
add(items: PageRegistration | PageRegistration[], ext: LensExtension) {
|
||||
const itemArray = recitfy(items);
|
||||
let registeredPages: RegisteredPage[] = [];
|
||||
try {
|
||||
registeredPages = items.map(page => ({
|
||||
registeredPages = itemArray.map(page => ({
|
||||
...page,
|
||||
extensionId: ext.name,
|
||||
routePath: getExtensionPageUrl({ extensionId: ext.name, pageId: page.id ?? page.routePath }),
|
||||
routePath: getExtensionPageUrl({ extensionId: ext.name, pageId: page.id }),
|
||||
}));
|
||||
} catch (err) {
|
||||
logger.error(`[EXTENSION]: page-registration failed`, {
|
||||
|
||||
@ -13,7 +13,7 @@ export class ClusterIdDetector extends BaseClusterDetector {
|
||||
id = this.cluster.apiUrl;
|
||||
}
|
||||
const value = createHash("sha256").update(id).digest("hex");
|
||||
return { value: value, accuracy: 100 };
|
||||
return { value, accuracy: 100 };
|
||||
}
|
||||
|
||||
protected async getDefaultNamespaceId() {
|
||||
|
||||
@ -90,7 +90,7 @@ export class ContextHandler {
|
||||
return {
|
||||
target: proxyUrl,
|
||||
changeOrigin: true,
|
||||
timeout: timeout,
|
||||
timeout,
|
||||
headers: {
|
||||
"Host": this.clusterUrl.hostname,
|
||||
},
|
||||
|
||||
11
src/main/developer-tools.ts
Normal file
11
src/main/developer-tools.ts
Normal file
@ -0,0 +1,11 @@
|
||||
/**
|
||||
* Installs Electron developer tools in the development build.
|
||||
* The dependency is not bundled to the production build.
|
||||
*/
|
||||
export const installDeveloperTools = async () => {
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
const { default: devToolsInstaller, REACT_DEVELOPER_TOOLS } = await import('electron-devtools-installer');
|
||||
|
||||
return devToolsInstaller([REACT_DEVELOPER_TOOLS]);
|
||||
}
|
||||
};
|
||||
57
src/main/extension-filesystem.ts
Normal file
57
src/main/extension-filesystem.ts
Normal file
@ -0,0 +1,57 @@
|
||||
import { randomBytes } from "crypto";
|
||||
import { SHA256 } from "crypto-js";
|
||||
import { app } from "electron";
|
||||
import fse from "fs-extra";
|
||||
import { action, observable, toJS } from "mobx";
|
||||
import path from "path";
|
||||
import { BaseStore } from "../common/base-store";
|
||||
import { LensExtensionId } from "../extensions/lens-extension";
|
||||
|
||||
interface FSProvisionModel {
|
||||
extensions: Record<string, string>; // extension names to paths
|
||||
}
|
||||
|
||||
export class FilesystemProvisionerStore extends BaseStore<FSProvisionModel> {
|
||||
@observable registeredExtensions = observable.map<LensExtensionId, string>();
|
||||
|
||||
private constructor() {
|
||||
super({
|
||||
configName: "lens-filesystem-provisioner-store",
|
||||
accessPropertiesByDotNotation: false, // To make dots safe in cluster context names
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* This function retrieves the saved path to the folder which the extension
|
||||
* can saves files to. If the folder is not present then it is created.
|
||||
* @param extensionName the name of the extension requesting the path
|
||||
* @returns path to the folder that the extension can safely write files to.
|
||||
*/
|
||||
async requestDirectory(extensionName: string): Promise<string> {
|
||||
if (!this.registeredExtensions.has(extensionName)) {
|
||||
const salt = randomBytes(32).toString("hex");
|
||||
const hashedName = SHA256(`${extensionName}/${salt}`).toString();
|
||||
const dirPath = path.resolve(app.getPath("userData"), "extension_data", hashedName);
|
||||
this.registeredExtensions.set(extensionName, dirPath);
|
||||
}
|
||||
|
||||
const dirPath = this.registeredExtensions.get(extensionName);
|
||||
await fse.ensureDir(dirPath);
|
||||
return dirPath;
|
||||
}
|
||||
|
||||
@action
|
||||
protected fromStore({ extensions }: FSProvisionModel = { extensions: {} }): void {
|
||||
this.registeredExtensions.merge(extensions);
|
||||
}
|
||||
|
||||
toJSON(): FSProvisionModel {
|
||||
return toJS({
|
||||
extensions: this.registeredExtensions.toJSON(),
|
||||
}, {
|
||||
recurseEverything: true
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export const filesystemProvisionerStore = FilesystemProvisionerStore.getInstance<FilesystemProvisionerStore>();
|
||||
@ -8,7 +8,7 @@ export class HelmCli extends LensBinary {
|
||||
public constructor(baseDir: string, version: string) {
|
||||
const opts: LensBinaryOpts = {
|
||||
version,
|
||||
baseDir: baseDir,
|
||||
baseDir,
|
||||
originalBinaryName: "helm",
|
||||
newBinaryName: "helm3"
|
||||
};
|
||||
|
||||
@ -40,7 +40,7 @@ export class HelmReleaseManager {
|
||||
log: stdout,
|
||||
release: {
|
||||
name: releaseName,
|
||||
namespace: namespace
|
||||
namespace
|
||||
}
|
||||
};
|
||||
} finally {
|
||||
|
||||
@ -83,7 +83,7 @@ export class HelmRepoManager extends Singleton {
|
||||
repositories: []
|
||||
}));
|
||||
if (!repositories.length) {
|
||||
await this.addRepo({ name: "stable", url: "https://kubernetes-charts.storage.googleapis.com/" });
|
||||
await this.addRepo({ name: "bitnami", url: "https://charts.bitnami.com/bitnami" });
|
||||
return await this.repositories();
|
||||
}
|
||||
return repositories.map(repo => ({
|
||||
|
||||
@ -21,8 +21,11 @@ import { userStore } from "../common/user-store";
|
||||
import { workspaceStore } from "../common/workspace-store";
|
||||
import { appEventBus } from "../common/event-bus";
|
||||
import { extensionLoader } from "../extensions/extension-loader";
|
||||
import { extensionManager } from "../extensions/extension-manager";
|
||||
import { extensionsStore } from "../extensions/extensions-store";
|
||||
import { InstalledExtension, extensionDiscovery } from "../extensions/extension-discovery";
|
||||
import type { LensExtensionId } from "../extensions/lens-extension";
|
||||
import { installDeveloperTools } from "./developer-tools";
|
||||
import { filesystemProvisionerStore } from "./extension-filesystem";
|
||||
|
||||
const workingDir = path.join(app.getPath("appData"), appName);
|
||||
let proxyPort: number;
|
||||
@ -49,12 +52,15 @@ app.on("ready", async () => {
|
||||
|
||||
registerFileProtocol("static", __static);
|
||||
|
||||
await installDeveloperTools();
|
||||
|
||||
// preload
|
||||
await Promise.all([
|
||||
userStore.load(),
|
||||
clusterStore.load(),
|
||||
workspaceStore.load(),
|
||||
extensionsStore.load(),
|
||||
filesystemProvisionerStore.load(),
|
||||
]);
|
||||
|
||||
// find free port
|
||||
@ -79,8 +85,22 @@ app.on("ready", async () => {
|
||||
}
|
||||
|
||||
extensionLoader.init();
|
||||
|
||||
extensionDiscovery.init();
|
||||
windowManager = WindowManager.getInstance<WindowManager>(proxyPort);
|
||||
extensionLoader.initExtensions(await extensionManager.load()); // call after windowManager to see splash earlier
|
||||
|
||||
// call after windowManager to see splash earlier
|
||||
const extensions = await extensionDiscovery.load();
|
||||
|
||||
// Subscribe to extensions that are copied or deleted to/from the extensions folder
|
||||
extensionDiscovery.events.on("add", (extension: InstalledExtension) => {
|
||||
extensionLoader.addExtension(extension);
|
||||
});
|
||||
extensionDiscovery.events.on("remove", (lensExtensionId: LensExtensionId) => {
|
||||
extensionLoader.removeExtension(lensExtensionId);
|
||||
});
|
||||
|
||||
extensionLoader.initExtensions(extensions);
|
||||
|
||||
setTimeout(() => {
|
||||
appEventBus.emit({ name: "service", action: "start" });
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
import { app, BrowserWindow, dialog, ipcMain, IpcMainEvent, Menu, MenuItem, MenuItemConstructorOptions, webContents, shell } from "electron";
|
||||
import { autorun } from "mobx";
|
||||
import { WindowManager } from "./window-manager";
|
||||
import { appName, isMac, isWindows, isTestEnv } from "../common/vars";
|
||||
import { appName, isMac, isWindows, isTestEnv, docsUrl, supportUrl } from "../common/vars";
|
||||
import { addClusterURL } from "../renderer/components/+add-cluster/add-cluster.route";
|
||||
import { preferencesURL } from "../renderer/components/+preferences/preferences.route";
|
||||
import { whatsNewURL } from "../renderer/components/+whats-new/whats-new.route";
|
||||
@ -24,6 +24,7 @@ export function showAbout(browserWindow: BrowserWindow) {
|
||||
`${appName}: ${app.getVersion()}`,
|
||||
`Electron: ${process.versions.electron}`,
|
||||
`Chrome: ${process.versions.chrome}`,
|
||||
`Node: ${process.versions.node}`,
|
||||
`Copyright 2020 Mirantis, Inc.`,
|
||||
];
|
||||
dialog.showMessageBoxSync(browserWindow, {
|
||||
@ -215,7 +216,13 @@ export function buildMenu(windowManager: WindowManager) {
|
||||
{
|
||||
label: "Documentation",
|
||||
click: async () => {
|
||||
shell.openExternal('https://docs.k8slens.dev/');
|
||||
shell.openExternal(docsUrl);
|
||||
},
|
||||
},
|
||||
{
|
||||
label: "Support",
|
||||
click: async () => {
|
||||
shell.openExternal(supportUrl);
|
||||
},
|
||||
},
|
||||
...ignoreOnMac([
|
||||
|
||||
@ -24,60 +24,60 @@ export class PrometheusLens implements PrometheusProvider {
|
||||
|
||||
public getQueries(opts: PrometheusQueryOpts): PrometheusQuery {
|
||||
switch(opts.category) {
|
||||
case 'cluster':
|
||||
return {
|
||||
memoryUsage: `
|
||||
case 'cluster':
|
||||
return {
|
||||
memoryUsage: `
|
||||
sum(
|
||||
node_memory_MemTotal_bytes - (node_memory_MemFree_bytes + node_memory_Buffers_bytes + node_memory_Cached_bytes)
|
||||
) by (kubernetes_name)
|
||||
`.replace(/_bytes/g, `_bytes{kubernetes_node=~"${opts.nodes}"}`),
|
||||
memoryRequests: `sum(kube_pod_container_resource_requests{node=~"${opts.nodes}", resource="memory"}) by (component)`,
|
||||
memoryLimits: `sum(kube_pod_container_resource_limits{node=~"${opts.nodes}", resource="memory"}) by (component)`,
|
||||
memoryCapacity: `sum(kube_node_status_capacity{node=~"${opts.nodes}", resource="memory"}) by (component)`,
|
||||
cpuUsage: `sum(rate(node_cpu_seconds_total{kubernetes_node=~"${opts.nodes}", mode=~"user|system"}[${this.rateAccuracy}]))`,
|
||||
cpuRequests:`sum(kube_pod_container_resource_requests{node=~"${opts.nodes}", resource="cpu"}) by (component)`,
|
||||
cpuLimits: `sum(kube_pod_container_resource_limits{node=~"${opts.nodes}", resource="cpu"}) by (component)`,
|
||||
cpuCapacity: `sum(kube_node_status_capacity{node=~"${opts.nodes}", resource="cpu"}) by (component)`,
|
||||
podUsage: `sum(kubelet_running_pod_count{instance=~"${opts.nodes}"})`,
|
||||
podCapacity: `sum(kube_node_status_capacity{node=~"${opts.nodes}", resource="pods"}) by (component)`,
|
||||
fsSize: `sum(node_filesystem_size_bytes{kubernetes_node=~"${opts.nodes}", mountpoint="/"}) by (kubernetes_node)`,
|
||||
fsUsage: `sum(node_filesystem_size_bytes{kubernetes_node=~"${opts.nodes}", mountpoint="/"} - node_filesystem_avail_bytes{kubernetes_node=~"${opts.nodes}", mountpoint="/"}) by (kubernetes_node)`
|
||||
};
|
||||
case 'nodes':
|
||||
return {
|
||||
memoryUsage: `sum (node_memory_MemTotal_bytes - (node_memory_MemFree_bytes + node_memory_Buffers_bytes + node_memory_Cached_bytes)) by (kubernetes_node)`,
|
||||
memoryCapacity: `sum(kube_node_status_capacity{resource="memory"}) by (node)`,
|
||||
cpuUsage: `sum(rate(node_cpu_seconds_total{mode=~"user|system"}[${this.rateAccuracy}])) by(kubernetes_node)`,
|
||||
cpuCapacity: `sum(kube_node_status_allocatable{resource="cpu"}) by (node)`,
|
||||
fsSize: `sum(node_filesystem_size_bytes{mountpoint="/"}) by (kubernetes_node)`,
|
||||
fsUsage: `sum(node_filesystem_size_bytes{mountpoint="/"} - node_filesystem_avail_bytes{mountpoint="/"}) by (kubernetes_node)`
|
||||
};
|
||||
case 'pods':
|
||||
return {
|
||||
cpuUsage: `sum(rate(container_cpu_usage_seconds_total{container!="POD",container!="",pod=~"${opts.pods}",namespace="${opts.namespace}"}[${this.rateAccuracy}])) by (${opts.selector})`,
|
||||
cpuRequests: `sum(kube_pod_container_resource_requests{pod=~"${opts.pods}",resource="cpu",namespace="${opts.namespace}"}) by (${opts.selector})`,
|
||||
cpuLimits: `sum(kube_pod_container_resource_limits{pod=~"${opts.pods}",resource="cpu",namespace="${opts.namespace}"}) by (${opts.selector})`,
|
||||
memoryUsage: `sum(container_memory_working_set_bytes{container!="POD",container!="",pod=~"${opts.pods}",namespace="${opts.namespace}"}) by (${opts.selector})`,
|
||||
memoryRequests: `sum(kube_pod_container_resource_requests{pod=~"${opts.pods}",resource="memory",namespace="${opts.namespace}"}) by (${opts.selector})`,
|
||||
memoryLimits: `sum(kube_pod_container_resource_limits{pod=~"${opts.pods}",resource="memory",namespace="${opts.namespace}"}) by (${opts.selector})`,
|
||||
fsUsage: `sum(container_fs_usage_bytes{container!="POD",container!="",pod=~"${opts.pods}",namespace="${opts.namespace}"}) by (${opts.selector})`,
|
||||
networkReceive: `sum(rate(container_network_receive_bytes_total{pod=~"${opts.pods}",namespace="${opts.namespace}"}[${this.rateAccuracy}])) by (${opts.selector})`,
|
||||
networkTransmit: `sum(rate(container_network_transmit_bytes_total{pod=~"${opts.pods}",namespace="${opts.namespace}"}[${this.rateAccuracy}])) by (${opts.selector})`
|
||||
};
|
||||
case 'pvc':
|
||||
return {
|
||||
diskUsage: `sum(kubelet_volume_stats_used_bytes{persistentvolumeclaim="${opts.pvc}"}) by (persistentvolumeclaim, namespace)`,
|
||||
diskCapacity: `sum(kubelet_volume_stats_capacity_bytes{persistentvolumeclaim="${opts.pvc}"}) by (persistentvolumeclaim, namespace)`
|
||||
};
|
||||
case 'ingress':
|
||||
const bytesSent = (ingress: string, statuses: string) =>
|
||||
`sum(rate(nginx_ingress_controller_bytes_sent_sum{ingress="${ingress}", status=~"${statuses}"}[${this.rateAccuracy}])) by (ingress)`;
|
||||
return {
|
||||
bytesSentSuccess: bytesSent(opts.igress, "^2\\\\d*"),
|
||||
bytesSentFailure: bytesSent(opts.ingres, "^5\\\\d*"),
|
||||
requestDurationSeconds: `sum(rate(nginx_ingress_controller_request_duration_seconds_sum{ingress="${opts.ingress}"}[${this.rateAccuracy}])) by (ingress)`,
|
||||
responseDurationSeconds: `sum(rate(nginx_ingress_controller_response_duration_seconds_sum{ingress="${opts.ingress}"}[${this.rateAccuracy}])) by (ingress)`
|
||||
};
|
||||
memoryRequests: `sum(kube_pod_container_resource_requests{node=~"${opts.nodes}", resource="memory"}) by (component)`,
|
||||
memoryLimits: `sum(kube_pod_container_resource_limits{node=~"${opts.nodes}", resource="memory"}) by (component)`,
|
||||
memoryCapacity: `sum(kube_node_status_capacity{node=~"${opts.nodes}", resource="memory"}) by (component)`,
|
||||
cpuUsage: `sum(rate(node_cpu_seconds_total{kubernetes_node=~"${opts.nodes}", mode=~"user|system"}[${this.rateAccuracy}]))`,
|
||||
cpuRequests:`sum(kube_pod_container_resource_requests{node=~"${opts.nodes}", resource="cpu"}) by (component)`,
|
||||
cpuLimits: `sum(kube_pod_container_resource_limits{node=~"${opts.nodes}", resource="cpu"}) by (component)`,
|
||||
cpuCapacity: `sum(kube_node_status_capacity{node=~"${opts.nodes}", resource="cpu"}) by (component)`,
|
||||
podUsage: `sum({__name__=~"kubelet_running_pod_count|kubelet_running_pods", instance=~"${opts.nodes}"})`,
|
||||
podCapacity: `sum(kube_node_status_capacity{node=~"${opts.nodes}", resource="pods"}) by (component)`,
|
||||
fsSize: `sum(node_filesystem_size_bytes{kubernetes_node=~"${opts.nodes}", mountpoint="/"}) by (kubernetes_node)`,
|
||||
fsUsage: `sum(node_filesystem_size_bytes{kubernetes_node=~"${opts.nodes}", mountpoint="/"} - node_filesystem_avail_bytes{kubernetes_node=~"${opts.nodes}", mountpoint="/"}) by (kubernetes_node)`
|
||||
};
|
||||
case 'nodes':
|
||||
return {
|
||||
memoryUsage: `sum (node_memory_MemTotal_bytes - (node_memory_MemFree_bytes + node_memory_Buffers_bytes + node_memory_Cached_bytes)) by (kubernetes_node)`,
|
||||
memoryCapacity: `sum(kube_node_status_capacity{resource="memory"}) by (node)`,
|
||||
cpuUsage: `sum(rate(node_cpu_seconds_total{mode=~"user|system"}[${this.rateAccuracy}])) by(kubernetes_node)`,
|
||||
cpuCapacity: `sum(kube_node_status_allocatable{resource="cpu"}) by (node)`,
|
||||
fsSize: `sum(node_filesystem_size_bytes{mountpoint="/"}) by (kubernetes_node)`,
|
||||
fsUsage: `sum(node_filesystem_size_bytes{mountpoint="/"} - node_filesystem_avail_bytes{mountpoint="/"}) by (kubernetes_node)`
|
||||
};
|
||||
case 'pods':
|
||||
return {
|
||||
cpuUsage: `sum(rate(container_cpu_usage_seconds_total{container!="POD",container!="",pod=~"${opts.pods}",namespace="${opts.namespace}"}[${this.rateAccuracy}])) by (${opts.selector})`,
|
||||
cpuRequests: `sum(kube_pod_container_resource_requests{pod=~"${opts.pods}",resource="cpu",namespace="${opts.namespace}"}) by (${opts.selector})`,
|
||||
cpuLimits: `sum(kube_pod_container_resource_limits{pod=~"${opts.pods}",resource="cpu",namespace="${opts.namespace}"}) by (${opts.selector})`,
|
||||
memoryUsage: `sum(container_memory_working_set_bytes{container!="POD",container!="",pod=~"${opts.pods}",namespace="${opts.namespace}"}) by (${opts.selector})`,
|
||||
memoryRequests: `sum(kube_pod_container_resource_requests{pod=~"${opts.pods}",resource="memory",namespace="${opts.namespace}"}) by (${opts.selector})`,
|
||||
memoryLimits: `sum(kube_pod_container_resource_limits{pod=~"${opts.pods}",resource="memory",namespace="${opts.namespace}"}) by (${opts.selector})`,
|
||||
fsUsage: `sum(container_fs_usage_bytes{container!="POD",container!="",pod=~"${opts.pods}",namespace="${opts.namespace}"}) by (${opts.selector})`,
|
||||
networkReceive: `sum(rate(container_network_receive_bytes_total{pod=~"${opts.pods}",namespace="${opts.namespace}"}[${this.rateAccuracy}])) by (${opts.selector})`,
|
||||
networkTransmit: `sum(rate(container_network_transmit_bytes_total{pod=~"${opts.pods}",namespace="${opts.namespace}"}[${this.rateAccuracy}])) by (${opts.selector})`
|
||||
};
|
||||
case 'pvc':
|
||||
return {
|
||||
diskUsage: `sum(kubelet_volume_stats_used_bytes{persistentvolumeclaim="${opts.pvc}"}) by (persistentvolumeclaim, namespace)`,
|
||||
diskCapacity: `sum(kubelet_volume_stats_capacity_bytes{persistentvolumeclaim="${opts.pvc}"}) by (persistentvolumeclaim, namespace)`
|
||||
};
|
||||
case 'ingress':
|
||||
const bytesSent = (ingress: string, statuses: string) =>
|
||||
`sum(rate(nginx_ingress_controller_bytes_sent_sum{ingress="${ingress}", status=~"${statuses}"}[${this.rateAccuracy}])) by (ingress)`;
|
||||
return {
|
||||
bytesSentSuccess: bytesSent(opts.igress, "^2\\\\d*"),
|
||||
bytesSentFailure: bytesSent(opts.ingres, "^5\\\\d*"),
|
||||
requestDurationSeconds: `sum(rate(nginx_ingress_controller_request_duration_seconds_sum{ingress="${opts.ingress}"}[${this.rateAccuracy}])) by (ingress)`,
|
||||
responseDurationSeconds: `sum(rate(nginx_ingress_controller_response_duration_seconds_sum{ingress="${opts.ingress}"}[${this.rateAccuracy}])) by (ingress)`
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -32,60 +32,60 @@ export class PrometheusOperator implements PrometheusProvider {
|
||||
|
||||
public getQueries(opts: PrometheusQueryOpts): PrometheusQuery {
|
||||
switch(opts.category) {
|
||||
case 'cluster':
|
||||
return {
|
||||
memoryUsage: `
|
||||
case 'cluster':
|
||||
return {
|
||||
memoryUsage: `
|
||||
sum(
|
||||
node_memory_MemTotal_bytes - (node_memory_MemFree_bytes + node_memory_Buffers_bytes + node_memory_Cached_bytes)
|
||||
)
|
||||
`.replace(/_bytes/g, `_bytes * on (pod,namespace) group_left(node) kube_pod_info{node=~"${opts.nodes}"}`),
|
||||
memoryRequests: `sum(kube_pod_container_resource_requests{node=~"${opts.nodes}", resource="memory"})`,
|
||||
memoryLimits: `sum(kube_pod_container_resource_limits{node=~"${opts.nodes}", resource="memory"})`,
|
||||
memoryCapacity: `sum(kube_node_status_capacity{node=~"${opts.nodes}", resource="memory"})`,
|
||||
cpuUsage: `sum(rate(node_cpu_seconds_total{mode=~"user|system"}[${this.rateAccuracy}])* on (pod,namespace) group_left(node) kube_pod_info{node=~"${opts.nodes}"})`,
|
||||
cpuRequests:`sum(kube_pod_container_resource_requests{node=~"${opts.nodes}", resource="cpu"})`,
|
||||
cpuLimits: `sum(kube_pod_container_resource_limits{node=~"${opts.nodes}", resource="cpu"})`,
|
||||
cpuCapacity: `sum(kube_node_status_capacity{node=~"${opts.nodes}", resource="cpu"})`,
|
||||
podUsage: `sum(kubelet_running_pod_count{node=~"${opts.nodes}"})`,
|
||||
podCapacity: `sum(kube_node_status_capacity{node=~"${opts.nodes}", resource="pods"})`,
|
||||
fsSize: `sum(node_filesystem_size_bytes{mountpoint="/"} * on (pod,namespace) group_left(node) kube_pod_info{node=~"${opts.nodes}"})`,
|
||||
fsUsage: `sum(node_filesystem_size_bytes{mountpoint="/"} * on (pod,namespace) group_left(node) kube_pod_info{node=~"${opts.nodes}"} - node_filesystem_avail_bytes{mountpoint="/"} * on (pod,namespace) group_left(node) kube_pod_info{node=~"${opts.nodes}"})`
|
||||
};
|
||||
case 'nodes':
|
||||
return {
|
||||
memoryUsage: `sum((node_memory_MemTotal_bytes - (node_memory_MemFree_bytes + node_memory_Buffers_bytes + node_memory_Cached_bytes)) * on (pod,namespace) group_left(node) kube_pod_info) by (node)`,
|
||||
memoryCapacity: `sum(kube_node_status_capacity{resource="memory"}) by (node)`,
|
||||
cpuUsage: `sum(rate(node_cpu_seconds_total{mode=~"user|system"}[${this.rateAccuracy}]) * on (pod,namespace) group_left(node) kube_pod_info) by (node)`,
|
||||
cpuCapacity: `sum(kube_node_status_allocatable{resource="cpu"}) by (node)`,
|
||||
fsSize: `sum(node_filesystem_size_bytes{mountpoint="/"} * on (pod,namespace) group_left(node) kube_pod_info) by (node)`,
|
||||
fsUsage: `sum((node_filesystem_size_bytes{mountpoint="/"} - node_filesystem_avail_bytes{mountpoint="/"}) * on (pod,namespace) group_left(node) kube_pod_info) by (node)`
|
||||
};
|
||||
case 'pods':
|
||||
return {
|
||||
cpuUsage: `sum(rate(container_cpu_usage_seconds_total{container!="POD",container!="",image!="",pod=~"${opts.pods}",namespace="${opts.namespace}"}[${this.rateAccuracy}])) by (${opts.selector})`,
|
||||
cpuRequests: `sum(kube_pod_container_resource_requests{pod=~"${opts.pods}",resource="cpu",namespace="${opts.namespace}"}) by (${opts.selector})`,
|
||||
cpuLimits: `sum(kube_pod_container_resource_limits{pod=~"${opts.pods}",resource="cpu",namespace="${opts.namespace}"}) by (${opts.selector})`,
|
||||
memoryUsage: `sum(container_memory_working_set_bytes{container!="POD",container!="",image!="",pod=~"${opts.pods}",namespace="${opts.namespace}"}) by (${opts.selector})`,
|
||||
memoryRequests: `sum(kube_pod_container_resource_requests{pod=~"${opts.pods}",resource="memory",namespace="${opts.namespace}"}) by (${opts.selector})`,
|
||||
memoryLimits: `sum(kube_pod_container_resource_limits{pod=~"${opts.pods}",resource="memory",namespace="${opts.namespace}"}) by (${opts.selector})`,
|
||||
fsUsage: `sum(container_fs_usage_bytes{container!="POD",container!="",pod=~"${opts.pods}",namespace="${opts.namespace}"}) by (${opts.selector})`,
|
||||
networkReceive: `sum(rate(container_network_receive_bytes_total{pod=~"${opts.pods}",namespace="${opts.namespace}"}[${this.rateAccuracy}])) by (${opts.selector})`,
|
||||
networkTransmit: `sum(rate(container_network_transmit_bytes_total{pod=~"${opts.pods}",namespace="${opts.namespace}"}[${this.rateAccuracy}])) by (${opts.selector})`
|
||||
};
|
||||
case 'pvc':
|
||||
return {
|
||||
diskUsage: `sum(kubelet_volume_stats_used_bytes{persistentvolumeclaim="${opts.pvc}"}) by (persistentvolumeclaim, namespace)`,
|
||||
diskCapacity: `sum(kubelet_volume_stats_capacity_bytes{persistentvolumeclaim="${opts.pvc}"}) by (persistentvolumeclaim, namespace)`
|
||||
};
|
||||
case 'ingress':
|
||||
const bytesSent = (ingress: string, statuses: string) =>
|
||||
`sum(rate(nginx_ingress_controller_bytes_sent_sum{ingress="${ingress}", status=~"${statuses}"}[${this.rateAccuracy}])) by (ingress)`;
|
||||
return {
|
||||
bytesSentSuccess: bytesSent(opts.igress, "^2\\\\d*"),
|
||||
bytesSentFailure: bytesSent(opts.ingres, "^5\\\\d*"),
|
||||
requestDurationSeconds: `sum(rate(nginx_ingress_controller_request_duration_seconds_sum{ingress="${opts.ingress}"}[${this.rateAccuracy}])) by (ingress)`,
|
||||
responseDurationSeconds: `sum(rate(nginx_ingress_controller_response_duration_seconds_sum{ingress="${opts.ingress}"}[${this.rateAccuracy}])) by (ingress)`
|
||||
};
|
||||
memoryRequests: `sum(kube_pod_container_resource_requests{node=~"${opts.nodes}", resource="memory"})`,
|
||||
memoryLimits: `sum(kube_pod_container_resource_limits{node=~"${opts.nodes}", resource="memory"})`,
|
||||
memoryCapacity: `sum(kube_node_status_capacity{node=~"${opts.nodes}", resource="memory"})`,
|
||||
cpuUsage: `sum(rate(node_cpu_seconds_total{mode=~"user|system"}[${this.rateAccuracy}])* on (pod,namespace) group_left(node) kube_pod_info{node=~"${opts.nodes}"})`,
|
||||
cpuRequests:`sum(kube_pod_container_resource_requests{node=~"${opts.nodes}", resource="cpu"})`,
|
||||
cpuLimits: `sum(kube_pod_container_resource_limits{node=~"${opts.nodes}", resource="cpu"})`,
|
||||
cpuCapacity: `sum(kube_node_status_capacity{node=~"${opts.nodes}", resource="cpu"})`,
|
||||
podUsage: `sum({__name__=~"kubelet_running_pod_count|kubelet_running_pods", node=~"${opts.nodes}"})`,
|
||||
podCapacity: `sum(kube_node_status_capacity{node=~"${opts.nodes}", resource="pods"})`,
|
||||
fsSize: `sum(node_filesystem_size_bytes{mountpoint="/"} * on (pod,namespace) group_left(node) kube_pod_info{node=~"${opts.nodes}"})`,
|
||||
fsUsage: `sum(node_filesystem_size_bytes{mountpoint="/"} * on (pod,namespace) group_left(node) kube_pod_info{node=~"${opts.nodes}"} - node_filesystem_avail_bytes{mountpoint="/"} * on (pod,namespace) group_left(node) kube_pod_info{node=~"${opts.nodes}"})`
|
||||
};
|
||||
case 'nodes':
|
||||
return {
|
||||
memoryUsage: `sum((node_memory_MemTotal_bytes - (node_memory_MemFree_bytes + node_memory_Buffers_bytes + node_memory_Cached_bytes)) * on (pod,namespace) group_left(node) kube_pod_info) by (node)`,
|
||||
memoryCapacity: `sum(kube_node_status_capacity{resource="memory"}) by (node)`,
|
||||
cpuUsage: `sum(rate(node_cpu_seconds_total{mode=~"user|system"}[${this.rateAccuracy}]) * on (pod,namespace) group_left(node) kube_pod_info) by (node)`,
|
||||
cpuCapacity: `sum(kube_node_status_allocatable{resource="cpu"}) by (node)`,
|
||||
fsSize: `sum(node_filesystem_size_bytes{mountpoint="/"} * on (pod,namespace) group_left(node) kube_pod_info) by (node)`,
|
||||
fsUsage: `sum((node_filesystem_size_bytes{mountpoint="/"} - node_filesystem_avail_bytes{mountpoint="/"}) * on (pod,namespace) group_left(node) kube_pod_info) by (node)`
|
||||
};
|
||||
case 'pods':
|
||||
return {
|
||||
cpuUsage: `sum(rate(container_cpu_usage_seconds_total{container!="POD",container!="",image!="",pod=~"${opts.pods}",namespace="${opts.namespace}"}[${this.rateAccuracy}])) by (${opts.selector})`,
|
||||
cpuRequests: `sum(kube_pod_container_resource_requests{pod=~"${opts.pods}",resource="cpu",namespace="${opts.namespace}"}) by (${opts.selector})`,
|
||||
cpuLimits: `sum(kube_pod_container_resource_limits{pod=~"${opts.pods}",resource="cpu",namespace="${opts.namespace}"}) by (${opts.selector})`,
|
||||
memoryUsage: `sum(container_memory_working_set_bytes{container!="POD",container!="",image!="",pod=~"${opts.pods}",namespace="${opts.namespace}"}) by (${opts.selector})`,
|
||||
memoryRequests: `sum(kube_pod_container_resource_requests{pod=~"${opts.pods}",resource="memory",namespace="${opts.namespace}"}) by (${opts.selector})`,
|
||||
memoryLimits: `sum(kube_pod_container_resource_limits{pod=~"${opts.pods}",resource="memory",namespace="${opts.namespace}"}) by (${opts.selector})`,
|
||||
fsUsage: `sum(container_fs_usage_bytes{container!="POD",container!="",pod=~"${opts.pods}",namespace="${opts.namespace}"}) by (${opts.selector})`,
|
||||
networkReceive: `sum(rate(container_network_receive_bytes_total{pod=~"${opts.pods}",namespace="${opts.namespace}"}[${this.rateAccuracy}])) by (${opts.selector})`,
|
||||
networkTransmit: `sum(rate(container_network_transmit_bytes_total{pod=~"${opts.pods}",namespace="${opts.namespace}"}[${this.rateAccuracy}])) by (${opts.selector})`
|
||||
};
|
||||
case 'pvc':
|
||||
return {
|
||||
diskUsage: `sum(kubelet_volume_stats_used_bytes{persistentvolumeclaim="${opts.pvc}"}) by (persistentvolumeclaim, namespace)`,
|
||||
diskCapacity: `sum(kubelet_volume_stats_capacity_bytes{persistentvolumeclaim="${opts.pvc}"}) by (persistentvolumeclaim, namespace)`
|
||||
};
|
||||
case 'ingress':
|
||||
const bytesSent = (ingress: string, statuses: string) =>
|
||||
`sum(rate(nginx_ingress_controller_bytes_sent_sum{ingress="${ingress}", status=~"${statuses}"}[${this.rateAccuracy}])) by (ingress)`;
|
||||
return {
|
||||
bytesSentSuccess: bytesSent(opts.igress, "^2\\\\d*"),
|
||||
bytesSentFailure: bytesSent(opts.ingres, "^5\\\\d*"),
|
||||
requestDurationSeconds: `sum(rate(nginx_ingress_controller_request_duration_seconds_sum{ingress="${opts.ingress}"}[${this.rateAccuracy}])) by (ingress)`,
|
||||
responseDurationSeconds: `sum(rate(nginx_ingress_controller_response_duration_seconds_sum{ingress="${opts.ingress}"}[${this.rateAccuracy}])) by (ingress)`
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -24,60 +24,60 @@ export class PrometheusStacklight implements PrometheusProvider {
|
||||
|
||||
public getQueries(opts: PrometheusQueryOpts): PrometheusQuery {
|
||||
switch(opts.category) {
|
||||
case 'cluster':
|
||||
return {
|
||||
memoryUsage: `
|
||||
case 'cluster':
|
||||
return {
|
||||
memoryUsage: `
|
||||
sum(
|
||||
node_memory_MemTotal_bytes - (node_memory_MemFree_bytes + node_memory_Buffers_bytes + node_memory_Cached_bytes)
|
||||
) by (kubernetes_name)
|
||||
`.replace(/_bytes/g, `_bytes{node=~"${opts.nodes}"}`),
|
||||
memoryRequests: `sum(kube_pod_container_resource_requests{node=~"${opts.nodes}", resource="memory"}) by (component)`,
|
||||
memoryLimits: `sum(kube_pod_container_resource_limits{node=~"${opts.nodes}", resource="memory"}) by (component)`,
|
||||
memoryCapacity: `sum(kube_node_status_capacity{node=~"${opts.nodes}", resource="memory"}) by (component)`,
|
||||
cpuUsage: `sum(rate(node_cpu_seconds_total{node=~"${opts.nodes}", mode=~"user|system"}[${this.rateAccuracy}]))`,
|
||||
cpuRequests:`sum(kube_pod_container_resource_requests{node=~"${opts.nodes}", resource="cpu"}) by (component)`,
|
||||
cpuLimits: `sum(kube_pod_container_resource_limits{node=~"${opts.nodes}", resource="cpu"}) by (component)`,
|
||||
cpuCapacity: `sum(kube_node_status_capacity{node=~"${opts.nodes}", resource="cpu"}) by (component)`,
|
||||
podUsage: `sum(kubelet_running_pod_count{instance=~"${opts.nodes}"})`,
|
||||
podCapacity: `sum(kube_node_status_capacity{node=~"${opts.nodes}", resource="pods"}) by (component)`,
|
||||
fsSize: `sum(node_filesystem_size_bytes{node=~"${opts.nodes}", mountpoint="/"}) by (node)`,
|
||||
fsUsage: `sum(node_filesystem_size_bytes{node=~"${opts.nodes}", mountpoint="/"} - node_filesystem_avail_bytes{node=~"${opts.nodes}", mountpoint="/"}) by (node)`
|
||||
};
|
||||
case 'nodes':
|
||||
return {
|
||||
memoryUsage: `sum (node_memory_MemTotal_bytes - (node_memory_MemFree_bytes + node_memory_Buffers_bytes + node_memory_Cached_bytes)) by (node)`,
|
||||
memoryCapacity: `sum(kube_node_status_capacity{resource="memory"}) by (node)`,
|
||||
cpuUsage: `sum(rate(node_cpu_seconds_total{mode=~"user|system"}[${this.rateAccuracy}])) by(node)`,
|
||||
cpuCapacity: `sum(kube_node_status_allocatable{resource="cpu"}) by (node)`,
|
||||
fsSize: `sum(node_filesystem_size_bytes{mountpoint="/"}) by (node)`,
|
||||
fsUsage: `sum(node_filesystem_size_bytes{mountpoint="/"} - node_filesystem_avail_bytes{mountpoint="/"}) by (node)`
|
||||
};
|
||||
case 'pods':
|
||||
return {
|
||||
cpuUsage: `sum(rate(container_cpu_usage_seconds_total{container!="POD",container!="",pod=~"${opts.pods}",namespace="${opts.namespace}"}[${this.rateAccuracy}])) by (${opts.selector})`,
|
||||
cpuRequests: `sum(kube_pod_container_resource_requests{pod=~"${opts.pods}",resource="cpu",namespace="${opts.namespace}"}) by (${opts.selector})`,
|
||||
cpuLimits: `sum(kube_pod_container_resource_limits{pod=~"${opts.pods}",resource="cpu",namespace="${opts.namespace}"}) by (${opts.selector})`,
|
||||
memoryUsage: `sum(container_memory_working_set_bytes{container!="POD",container!="",pod=~"${opts.pods}",namespace="${opts.namespace}"}) by (${opts.selector})`,
|
||||
memoryRequests: `sum(kube_pod_container_resource_requests{pod=~"${opts.pods}",resource="memory",namespace="${opts.namespace}"}) by (${opts.selector})`,
|
||||
memoryLimits: `sum(kube_pod_container_resource_limits{pod=~"${opts.pods}",resource="memory",namespace="${opts.namespace}"}) by (${opts.selector})`,
|
||||
fsUsage: `sum(container_fs_usage_bytes{container!="POD",container!="",pod=~"${opts.pods}",namespace="${opts.namespace}"}) by (${opts.selector})`,
|
||||
networkReceive: `sum(rate(container_network_receive_bytes_total{pod=~"${opts.pods}",namespace="${opts.namespace}"}[${this.rateAccuracy}])) by (${opts.selector})`,
|
||||
networkTransmit: `sum(rate(container_network_transmit_bytes_total{pod=~"${opts.pods}",namespace="${opts.namespace}"}[${this.rateAccuracy}])) by (${opts.selector})`
|
||||
};
|
||||
case 'pvc':
|
||||
return {
|
||||
diskUsage: `sum(kubelet_volume_stats_used_bytes{persistentvolumeclaim="${opts.pvc}"}) by (persistentvolumeclaim, namespace)`,
|
||||
diskCapacity: `sum(kubelet_volume_stats_capacity_bytes{persistentvolumeclaim="${opts.pvc}"}) by (persistentvolumeclaim, namespace)`
|
||||
};
|
||||
case 'ingress':
|
||||
const bytesSent = (ingress: string, statuses: string) =>
|
||||
`sum(rate(nginx_ingress_controller_bytes_sent_sum{ingress="${ingress}", status=~"${statuses}"}[${this.rateAccuracy}])) by (ingress)`;
|
||||
return {
|
||||
bytesSentSuccess: bytesSent(opts.igress, "^2\\\\d*"),
|
||||
bytesSentFailure: bytesSent(opts.ingres, "^5\\\\d*"),
|
||||
requestDurationSeconds: `sum(rate(nginx_ingress_controller_request_duration_seconds_sum{ingress="${opts.ingress}"}[${this.rateAccuracy}])) by (ingress)`,
|
||||
responseDurationSeconds: `sum(rate(nginx_ingress_controller_response_duration_seconds_sum{ingress="${opts.ingress}"}[${this.rateAccuracy}])) by (ingress)`
|
||||
};
|
||||
memoryRequests: `sum(kube_pod_container_resource_requests{node=~"${opts.nodes}", resource="memory"}) by (component)`,
|
||||
memoryLimits: `sum(kube_pod_container_resource_limits{node=~"${opts.nodes}", resource="memory"}) by (component)`,
|
||||
memoryCapacity: `sum(kube_node_status_capacity{node=~"${opts.nodes}", resource="memory"}) by (component)`,
|
||||
cpuUsage: `sum(rate(node_cpu_seconds_total{node=~"${opts.nodes}", mode=~"user|system"}[${this.rateAccuracy}]))`,
|
||||
cpuRequests:`sum(kube_pod_container_resource_requests{node=~"${opts.nodes}", resource="cpu"}) by (component)`,
|
||||
cpuLimits: `sum(kube_pod_container_resource_limits{node=~"${opts.nodes}", resource="cpu"}) by (component)`,
|
||||
cpuCapacity: `sum(kube_node_status_capacity{node=~"${opts.nodes}", resource="cpu"}) by (component)`,
|
||||
podUsage: `sum({__name__=~"kubelet_running_pod_count|kubelet_running_pods", instance=~"${opts.nodes}"})`,
|
||||
podCapacity: `sum(kube_node_status_capacity{node=~"${opts.nodes}", resource="pods"}) by (component)`,
|
||||
fsSize: `sum(node_filesystem_size_bytes{node=~"${opts.nodes}", mountpoint="/"}) by (node)`,
|
||||
fsUsage: `sum(node_filesystem_size_bytes{node=~"${opts.nodes}", mountpoint="/"} - node_filesystem_avail_bytes{node=~"${opts.nodes}", mountpoint="/"}) by (node)`
|
||||
};
|
||||
case 'nodes':
|
||||
return {
|
||||
memoryUsage: `sum (node_memory_MemTotal_bytes - (node_memory_MemFree_bytes + node_memory_Buffers_bytes + node_memory_Cached_bytes)) by (node)`,
|
||||
memoryCapacity: `sum(kube_node_status_capacity{resource="memory"}) by (node)`,
|
||||
cpuUsage: `sum(rate(node_cpu_seconds_total{mode=~"user|system"}[${this.rateAccuracy}])) by(node)`,
|
||||
cpuCapacity: `sum(kube_node_status_allocatable{resource="cpu"}) by (node)`,
|
||||
fsSize: `sum(node_filesystem_size_bytes{mountpoint="/"}) by (node)`,
|
||||
fsUsage: `sum(node_filesystem_size_bytes{mountpoint="/"} - node_filesystem_avail_bytes{mountpoint="/"}) by (node)`
|
||||
};
|
||||
case 'pods':
|
||||
return {
|
||||
cpuUsage: `sum(rate(container_cpu_usage_seconds_total{container!="POD",container!="",pod=~"${opts.pods}",namespace="${opts.namespace}"}[${this.rateAccuracy}])) by (${opts.selector})`,
|
||||
cpuRequests: `sum(kube_pod_container_resource_requests{pod=~"${opts.pods}",resource="cpu",namespace="${opts.namespace}"}) by (${opts.selector})`,
|
||||
cpuLimits: `sum(kube_pod_container_resource_limits{pod=~"${opts.pods}",resource="cpu",namespace="${opts.namespace}"}) by (${opts.selector})`,
|
||||
memoryUsage: `sum(container_memory_working_set_bytes{container!="POD",container!="",pod=~"${opts.pods}",namespace="${opts.namespace}"}) by (${opts.selector})`,
|
||||
memoryRequests: `sum(kube_pod_container_resource_requests{pod=~"${opts.pods}",resource="memory",namespace="${opts.namespace}"}) by (${opts.selector})`,
|
||||
memoryLimits: `sum(kube_pod_container_resource_limits{pod=~"${opts.pods}",resource="memory",namespace="${opts.namespace}"}) by (${opts.selector})`,
|
||||
fsUsage: `sum(container_fs_usage_bytes{container!="POD",container!="",pod=~"${opts.pods}",namespace="${opts.namespace}"}) by (${opts.selector})`,
|
||||
networkReceive: `sum(rate(container_network_receive_bytes_total{pod=~"${opts.pods}",namespace="${opts.namespace}"}[${this.rateAccuracy}])) by (${opts.selector})`,
|
||||
networkTransmit: `sum(rate(container_network_transmit_bytes_total{pod=~"${opts.pods}",namespace="${opts.namespace}"}[${this.rateAccuracy}])) by (${opts.selector})`
|
||||
};
|
||||
case 'pvc':
|
||||
return {
|
||||
diskUsage: `sum(kubelet_volume_stats_used_bytes{persistentvolumeclaim="${opts.pvc}"}) by (persistentvolumeclaim, namespace)`,
|
||||
diskCapacity: `sum(kubelet_volume_stats_capacity_bytes{persistentvolumeclaim="${opts.pvc}"}) by (persistentvolumeclaim, namespace)`
|
||||
};
|
||||
case 'ingress':
|
||||
const bytesSent = (ingress: string, statuses: string) =>
|
||||
`sum(rate(nginx_ingress_controller_bytes_sent_sum{ingress="${ingress}", status=~"${statuses}"}[${this.rateAccuracy}])) by (ingress)`;
|
||||
return {
|
||||
bytesSentSuccess: bytesSent(opts.igress, "^2\\\\d*"),
|
||||
bytesSentFailure: bytesSent(opts.ingres, "^5\\\\d*"),
|
||||
requestDurationSeconds: `sum(rate(nginx_ingress_controller_request_duration_seconds_sum{ingress="${opts.ingress}"}[${this.rateAccuracy}])) by (ingress)`,
|
||||
responseDurationSeconds: `sum(rate(nginx_ingress_controller_response_duration_seconds_sum{ingress="${opts.ingress}"}[${this.rateAccuracy}])) by (ingress)`
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -67,15 +67,15 @@ export class Router {
|
||||
output: "data",
|
||||
});
|
||||
return {
|
||||
cluster: cluster,
|
||||
cluster,
|
||||
path: url.pathname,
|
||||
raw: {
|
||||
req: req,
|
||||
req,
|
||||
},
|
||||
response: res,
|
||||
query: url.searchParams,
|
||||
payload: payload,
|
||||
params: params
|
||||
payload,
|
||||
params
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@ -12,14 +12,22 @@ class HelmApiRoute extends LensApi {
|
||||
|
||||
public async getChart(request: LensApiRequest) {
|
||||
const { params, query, response } = request;
|
||||
const chart = await helmService.getChart(params.repo, params.chart, query.get("version"));
|
||||
this.respondJson(response, chart);
|
||||
try {
|
||||
const chart = await helmService.getChart(params.repo, params.chart, query.get("version"));
|
||||
this.respondJson(response, chart);
|
||||
} catch (error) {
|
||||
this.respondText(response, error, 422);
|
||||
}
|
||||
}
|
||||
|
||||
public async getChartValues(request: LensApiRequest) {
|
||||
const { params, query, response } = request;
|
||||
const values = await helmService.getChartValues(params.repo, params.chart, query.get("version"));
|
||||
this.respondJson(response, values);
|
||||
try {
|
||||
const values = await helmService.getChartValues(params.repo, params.chart, query.get("version"));
|
||||
this.respondJson(response, values);
|
||||
} catch (error) {
|
||||
this.respondText(response, error, 422);
|
||||
}
|
||||
}
|
||||
|
||||
public async installChart(request: LensApiRequest) {
|
||||
|
||||
@ -78,16 +78,16 @@ class PortForwardRoute extends LensApi {
|
||||
|
||||
let portForward = PortForward.getPortforward({
|
||||
clusterId: cluster.id, kind: resourceType, name: resourceName,
|
||||
namespace: namespace, port: port
|
||||
namespace, port
|
||||
});
|
||||
if (!portForward) {
|
||||
logger.info(`Creating a new port-forward ${namespace}/${resourceType}/${resourceName}:${port}`);
|
||||
portForward = new PortForward({
|
||||
clusterId: cluster.id,
|
||||
kind: resourceType,
|
||||
namespace: namespace,
|
||||
namespace,
|
||||
name: resourceName,
|
||||
port: port,
|
||||
port,
|
||||
kubeConfig: cluster.getProxyKubeconfigPath()
|
||||
});
|
||||
const started = await portForward.start();
|
||||
|
||||
@ -47,7 +47,7 @@ export class ShellSession extends EventEmitter {
|
||||
this.shellProcess = pty.spawn(shell, args, {
|
||||
cols: 80,
|
||||
cwd: this.cwd() || env.HOME,
|
||||
env: env,
|
||||
env,
|
||||
name: "xterm-256color",
|
||||
rows: 30,
|
||||
});
|
||||
@ -70,16 +70,16 @@ export class ShellSession extends EventEmitter {
|
||||
|
||||
protected async getShellArgs(shell: string): Promise<Array<string>> {
|
||||
switch(path.basename(shell)) {
|
||||
case "powershell.exe":
|
||||
return ["-NoExit", "-command", `& {Set-Location $Env:USERPROFILE; $Env:PATH="${this.helmBinDir};${this.kubectlPathDir};$Env:PATH"}`];
|
||||
case "bash":
|
||||
return ["--init-file", path.join(this.kubectlBinDir, '.bash_set_path')];
|
||||
case "fish":
|
||||
return ["--login", "--init-command", `export PATH="${this.helmBinDir}:${this.kubectlPathDir}:$PATH"; export KUBECONFIG="${this.kubeconfigPath}"`];
|
||||
case "zsh":
|
||||
return ["--login"];
|
||||
default:
|
||||
return [];
|
||||
case "powershell.exe":
|
||||
return ["-NoExit", "-command", `& {Set-Location $Env:USERPROFILE; $Env:PATH="${this.helmBinDir};${this.kubectlPathDir};$Env:PATH"}`];
|
||||
case "bash":
|
||||
return ["--init-file", path.join(this.kubectlBinDir, '.bash_set_path')];
|
||||
case "fish":
|
||||
return ["--login", "--init-command", `export PATH="${this.helmBinDir}:${this.kubectlPathDir}:$PATH"; export KUBECONFIG="${this.kubeconfigPath}"`];
|
||||
case "zsh":
|
||||
return ["--login"];
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
@ -148,16 +148,16 @@ export class ShellSession extends EventEmitter {
|
||||
|
||||
const message = Buffer.from(data.slice(1, data.length), "base64").toString();
|
||||
switch (data[0]) {
|
||||
case "0":
|
||||
this.shellProcess.write(message);
|
||||
break;
|
||||
case "4":
|
||||
const resizeMsgObj = JSON.parse(message);
|
||||
this.shellProcess.resize(resizeMsgObj["Width"], resizeMsgObj["Height"]);
|
||||
break;
|
||||
case "9":
|
||||
this.emit('newToken', message);
|
||||
break;
|
||||
case "0":
|
||||
this.shellProcess.write(message);
|
||||
break;
|
||||
case "4":
|
||||
const resizeMsgObj = JSON.parse(message);
|
||||
this.shellProcess.resize(resizeMsgObj["Width"], resizeMsgObj["Height"]);
|
||||
break;
|
||||
case "9":
|
||||
this.emit('newToken', message);
|
||||
break;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@ -95,7 +95,6 @@ export function createTrayMenu(windowManager: WindowManager): Menu {
|
||||
toolTip: clusterId,
|
||||
async click() {
|
||||
workspaceStore.setActive(workspace);
|
||||
clusterStore.setActive(clusterId);
|
||||
windowManager.navigate(clusterViewURL({ params: { clusterId } }));
|
||||
}
|
||||
};
|
||||
|
||||
@ -124,7 +124,7 @@ export class WindowManager extends Singleton {
|
||||
await this.ensureMainWindow();
|
||||
this.sendToView({
|
||||
channel: "renderer:navigate",
|
||||
frameId: frameId,
|
||||
frameId,
|
||||
data: [url],
|
||||
});
|
||||
}
|
||||
|
||||
@ -26,7 +26,7 @@ export default migration({
|
||||
user["auth-provider"].config = authConfig;
|
||||
kubeConfig.users = [{
|
||||
name: userObj.name,
|
||||
user: user
|
||||
user
|
||||
}];
|
||||
cluster.kubeConfig = yaml.safeDump(kubeConfig);
|
||||
store.set(clusterKey, cluster);
|
||||
|
||||
82
src/renderer/api/__tests__/kube-api.test.ts
Normal file
82
src/renderer/api/__tests__/kube-api.test.ts
Normal file
@ -0,0 +1,82 @@
|
||||
import { KubeApi } from "../kube-api";
|
||||
|
||||
describe("KubeApi", () => {
|
||||
it("uses url from apiBase if apiBase contains the resource", async () => {
|
||||
(fetch as any).mockResponse(async (request: any) => {
|
||||
if (request.url === "/api-kube/apis/networking.k8s.io/v1") {
|
||||
return {
|
||||
body: JSON.stringify({
|
||||
resources: [{
|
||||
name: "ingresses"
|
||||
}] as any []
|
||||
})
|
||||
};
|
||||
} else if (request.url === "/api-kube/apis/extensions/v1beta1") {
|
||||
// Even if the old API contains ingresses, KubeApi should prefer the apiBase url
|
||||
return {
|
||||
body: JSON.stringify({
|
||||
resources: [{
|
||||
name: "ingresses"
|
||||
}] as any []
|
||||
})
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
body: JSON.stringify({
|
||||
resources: [] as any []
|
||||
})
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
const apiBase = "/apis/networking.k8s.io/v1/ingresses";
|
||||
const fallbackApiBase = "/apis/extensions/v1beta1/ingresses";
|
||||
const kubeApi = new KubeApi({
|
||||
apiBase,
|
||||
fallbackApiBases: [fallbackApiBase],
|
||||
checkPreferredVersion: true,
|
||||
});
|
||||
|
||||
await kubeApi.get();
|
||||
expect(kubeApi.apiPrefix).toEqual("/apis");
|
||||
expect(kubeApi.apiGroup).toEqual("networking.k8s.io");
|
||||
});
|
||||
|
||||
it("uses url from fallbackApiBases if apiBase lacks the resource", async () => {
|
||||
(fetch as any).mockResponse(async (request: any) => {
|
||||
if (request.url === "/api-kube/apis/networking.k8s.io/v1") {
|
||||
return {
|
||||
body: JSON.stringify({
|
||||
resources: [] as any []
|
||||
})
|
||||
};
|
||||
} else if (request.url === "/api-kube/apis/extensions/v1beta1") {
|
||||
return {
|
||||
body: JSON.stringify({
|
||||
resources: [{
|
||||
name: "ingresses"
|
||||
}] as any []
|
||||
})
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
body: JSON.stringify({
|
||||
resources: [] as any []
|
||||
})
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
const apiBase = "apis/networking.k8s.io/v1/ingresses";
|
||||
const fallbackApiBase = "/apis/extensions/v1beta1/ingresses";
|
||||
const kubeApi = new KubeApi({
|
||||
apiBase,
|
||||
fallbackApiBases: [fallbackApiBase],
|
||||
checkPreferredVersion: true,
|
||||
});
|
||||
|
||||
await kubeApi.get();
|
||||
expect(kubeApi.apiPrefix).toEqual("/apis");
|
||||
expect(kubeApi.apiGroup).toEqual("extensions");
|
||||
});
|
||||
});
|
||||
@ -8,7 +8,7 @@ export class ClusterApi extends KubeApi<Cluster> {
|
||||
|
||||
async getMetrics(nodeNames: string[], params?: IMetricsReqParams): Promise<IClusterMetrics> {
|
||||
const nodes = nodeNames.join("|");
|
||||
const opts = { category: "cluster", nodes: nodes };
|
||||
const opts = { category: "cluster", nodes };
|
||||
|
||||
return metricsApi.getMetrics({
|
||||
memoryUsage: opts,
|
||||
|
||||
@ -20,7 +20,7 @@ export class DeploymentApi extends KubeApi<Deployment> {
|
||||
data: {
|
||||
metadata: params,
|
||||
spec: {
|
||||
replicas: replicas
|
||||
replicas
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@ -119,7 +119,7 @@ export const helmReleasesApi = {
|
||||
const path = endpoint({ name, namespace }) + "/rollback";
|
||||
return apiBase.put(path, {
|
||||
data: {
|
||||
revision: revision
|
||||
revision
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@ -101,14 +101,14 @@ export class HorizontalPodAutoscaler extends KubeObject {
|
||||
protected getMetricName(metric: IHpaMetric): string {
|
||||
const { type, resource, pods, object, external } = metric;
|
||||
switch (type) {
|
||||
case HpaMetricType.Resource:
|
||||
return resource.name;
|
||||
case HpaMetricType.Pods:
|
||||
return pods.metricName;
|
||||
case HpaMetricType.Object:
|
||||
return object.metricName;
|
||||
case HpaMetricType.External:
|
||||
return external.metricName;
|
||||
case HpaMetricType.Resource:
|
||||
return resource.name;
|
||||
case HpaMetricType.Pods:
|
||||
return pods.metricName;
|
||||
case HpaMetricType.Object:
|
||||
return object.metricName;
|
||||
case HpaMetricType.External:
|
||||
return external.metricName;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -29,11 +29,42 @@ export interface ILoadBalancerIngress {
|
||||
hostname?: string;
|
||||
ip?: string;
|
||||
}
|
||||
|
||||
// extensions/v1beta1
|
||||
interface IExtensionsBackend {
|
||||
serviceName: string;
|
||||
servicePort: number;
|
||||
}
|
||||
|
||||
// networking.k8s.io/v1
|
||||
interface INetworkingBackend {
|
||||
service: IIngressService;
|
||||
}
|
||||
|
||||
export type IIngressBackend = IExtensionsBackend | INetworkingBackend;
|
||||
|
||||
export interface IIngressService {
|
||||
name: string;
|
||||
port: {
|
||||
name?: string;
|
||||
number?: number;
|
||||
}
|
||||
}
|
||||
|
||||
export const getBackendServiceNamePort = (backend: IIngressBackend) => {
|
||||
// .service is available with networking.k8s.io/v1, otherwise using extensions/v1beta1 interface
|
||||
const serviceName = "service" in backend ? backend.service.name : backend.serviceName;
|
||||
// Port is specified either with a number or name
|
||||
const servicePort = "service" in backend ? backend.service.port.number ?? backend.service.port.name : backend.servicePort;
|
||||
|
||||
return { serviceName, servicePort };
|
||||
};
|
||||
|
||||
@autobind()
|
||||
export class Ingress extends KubeObject {
|
||||
static kind = "Ingress";
|
||||
static namespaced = true;
|
||||
static apiBase = "/apis/extensions/v1beta1/ingresses";
|
||||
static apiBase = "/apis/networking.k8s.io/v1/ingresses";
|
||||
|
||||
spec: {
|
||||
tls: {
|
||||
@ -44,17 +75,20 @@ export class Ingress extends KubeObject {
|
||||
http: {
|
||||
paths: {
|
||||
path?: string;
|
||||
backend: {
|
||||
serviceName: string;
|
||||
servicePort: number;
|
||||
};
|
||||
backend: IIngressBackend;
|
||||
}[];
|
||||
};
|
||||
}[];
|
||||
backend?: {
|
||||
serviceName: string;
|
||||
servicePort: number;
|
||||
};
|
||||
// extensions/v1beta1
|
||||
backend?: IExtensionsBackend;
|
||||
// networking.k8s.io/v1
|
||||
defaultBackend?: INetworkingBackend & {
|
||||
resource: {
|
||||
apiGroup: string;
|
||||
kind: string;
|
||||
name: string;
|
||||
}
|
||||
}
|
||||
};
|
||||
status: {
|
||||
loadBalancer: {
|
||||
@ -75,7 +109,9 @@ export class Ingress extends KubeObject {
|
||||
const host = rule.host ? rule.host : "*";
|
||||
if (rule.http && rule.http.paths) {
|
||||
rule.http.paths.forEach(path => {
|
||||
routes.push(protocol + "://" + host + (path.path || "/") + " ⇢ " + path.backend.serviceName + ":" + path.backend.servicePort);
|
||||
const { serviceName, servicePort } = getBackendServiceNamePort(path.backend);
|
||||
|
||||
routes.push(protocol + "://" + host + (path.path || "/") + " ⇢ " + serviceName + ":" + servicePort);
|
||||
});
|
||||
}
|
||||
});
|
||||
@ -83,6 +119,17 @@ export class Ingress extends KubeObject {
|
||||
return routes;
|
||||
}
|
||||
|
||||
getServiceNamePort() {
|
||||
const { spec } = this;
|
||||
const serviceName = spec?.defaultBackend?.service.name ?? spec?.backend?.serviceName;
|
||||
const servicePort = spec?.defaultBackend?.service.port.number ?? spec?.defaultBackend?.service.port.name ?? spec?.backend?.servicePort;
|
||||
|
||||
return {
|
||||
serviceName,
|
||||
servicePort
|
||||
};
|
||||
}
|
||||
|
||||
getHosts() {
|
||||
const { spec: { rules } } = this;
|
||||
if (!rules) return [];
|
||||
@ -91,22 +138,24 @@ export class Ingress extends KubeObject {
|
||||
|
||||
getPorts() {
|
||||
const ports: number[] = [];
|
||||
const { spec: { tls, rules, backend } } = this;
|
||||
const { spec: { tls, rules, backend, defaultBackend } } = this;
|
||||
const httpPort = 80;
|
||||
const tlsPort = 443;
|
||||
|
||||
// Note: not using the port name (string)
|
||||
const servicePort = defaultBackend?.service.port.number ?? backend?.servicePort;
|
||||
|
||||
if (rules && rules.length > 0) {
|
||||
if (rules.some(rule => rule.hasOwnProperty("http"))) {
|
||||
ports.push(httpPort);
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (backend && backend.servicePort) {
|
||||
ports.push(backend.servicePort);
|
||||
}
|
||||
} else if (servicePort !== undefined) {
|
||||
ports.push(Number(servicePort));
|
||||
}
|
||||
if (tls && tls.length > 0) {
|
||||
ports.push(tlsPort);
|
||||
}
|
||||
|
||||
return ports.join(", ");
|
||||
}
|
||||
|
||||
@ -121,4 +170,8 @@ export class Ingress extends KubeObject {
|
||||
|
||||
export const ingressApi = new IngressApi({
|
||||
objectConstructor: Ingress,
|
||||
});
|
||||
// Add fallback for Kubernetes <1.19
|
||||
checkPreferredVersion: true,
|
||||
fallbackApiBases: ["/apis/extensions/v1beta1/ingresses"],
|
||||
logStuff: true
|
||||
} as any);
|
||||
|
||||
@ -4,6 +4,29 @@ import { IAffinity, WorkloadKubeObject } from "../workload-kube-object";
|
||||
import { autobind } from "../../utils";
|
||||
import { KubeApi } from "../kube-api";
|
||||
|
||||
export class StatefulSetApi extends KubeApi<StatefulSet> {
|
||||
protected getScaleApiUrl(params: { namespace: string; name: string }) {
|
||||
return this.getUrl(params) + "/scale";
|
||||
}
|
||||
|
||||
getReplicas(params: { namespace: string; name: string }): Promise<number> {
|
||||
return this.request
|
||||
.get(this.getScaleApiUrl(params))
|
||||
.then(({ status }: any) => status?.replicas);
|
||||
}
|
||||
|
||||
scale(params: { namespace: string; name: string }, replicas: number) {
|
||||
return this.request.put(this.getScaleApiUrl(params), {
|
||||
data: {
|
||||
metadata: params,
|
||||
spec: {
|
||||
replicas
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@autobind()
|
||||
export class StatefulSet extends WorkloadKubeObject {
|
||||
static kind = "StatefulSet";
|
||||
@ -67,17 +90,22 @@ export class StatefulSet extends WorkloadKubeObject {
|
||||
observedGeneration: number;
|
||||
replicas: number;
|
||||
currentReplicas: number;
|
||||
readyReplicas: number;
|
||||
currentRevision: string;
|
||||
updateRevision: string;
|
||||
collisionCount: number;
|
||||
};
|
||||
|
||||
getReplicas() {
|
||||
return this.spec.replicas || 0;
|
||||
}
|
||||
|
||||
getImages() {
|
||||
const containers: IPodContainer[] = get(this, "spec.template.spec.containers", []);
|
||||
return [...containers].map(container => container.image);
|
||||
}
|
||||
}
|
||||
|
||||
export const statefulSetApi = new KubeApi({
|
||||
export const statefulSetApi = new StatefulSetApi({
|
||||
objectConstructor: StatefulSet,
|
||||
});
|
||||
|
||||
@ -15,10 +15,10 @@ export const apiKube = new KubeJsonApi({
|
||||
// Common handler for HTTP api errors
|
||||
export function onApiError(error: JsonApiErrorParsed, res: Response) {
|
||||
switch (res.status) {
|
||||
case 403:
|
||||
error.isUsedForNotification = true;
|
||||
Notifications.error(error);
|
||||
break;
|
||||
case 403:
|
||||
error.isUsedForNotification = true;
|
||||
Notifications.error(error);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -84,8 +84,8 @@ export class JsonApi<D = JsonApiData, P extends JsonApiParams = JsonApiParams> {
|
||||
}
|
||||
const infoLog: JsonApiLog = {
|
||||
method: reqInit.method.toUpperCase(),
|
||||
reqUrl: reqUrl,
|
||||
reqInit: reqInit,
|
||||
reqUrl,
|
||||
reqInit,
|
||||
};
|
||||
return cancelableFetch(reqUrl, reqInit).then(res => {
|
||||
return this.parseResponse<D>(res, infoLog);
|
||||
|
||||
@ -35,32 +35,32 @@ export function parseKubeApi(path: string): IKubeApiParsed {
|
||||
|
||||
if (namespaced) {
|
||||
switch (right.length) {
|
||||
case 1:
|
||||
name = right[0];
|
||||
case 1:
|
||||
name = right[0];
|
||||
// fallthrough
|
||||
case 0:
|
||||
resource = "namespaces"; // special case this due to `split` removing namespaces
|
||||
break;
|
||||
default:
|
||||
[namespace, resource, name] = right;
|
||||
break;
|
||||
case 0:
|
||||
resource = "namespaces"; // special case this due to `split` removing namespaces
|
||||
break;
|
||||
default:
|
||||
[namespace, resource, name] = right;
|
||||
break;
|
||||
}
|
||||
|
||||
apiVersion = left.pop();
|
||||
apiGroup = left.join("/");
|
||||
} else {
|
||||
switch (left.length) {
|
||||
case 4:
|
||||
[apiGroup, apiVersion, resource, name] = left;
|
||||
break;
|
||||
case 2:
|
||||
resource = left.pop();
|
||||
case 4:
|
||||
[apiGroup, apiVersion, resource, name] = left;
|
||||
break;
|
||||
case 2:
|
||||
resource = left.pop();
|
||||
// fallthrough
|
||||
case 1:
|
||||
apiVersion = left.pop();
|
||||
apiGroup = "";
|
||||
break;
|
||||
default:
|
||||
case 1:
|
||||
apiVersion = left.pop();
|
||||
apiGroup = "";
|
||||
break;
|
||||
default:
|
||||
/**
|
||||
* Given that
|
||||
* - `apiVersion` is `GROUP/VERSION` and
|
||||
@ -77,15 +77,15 @@ export function parseKubeApi(path: string): IKubeApiParsed {
|
||||
* 3. otherwise assume apiVersion <- left[0]
|
||||
* 4. always resource, name <- left[(0 or 1)+1..]
|
||||
*/
|
||||
if (left[0].includes('.') || left[1].match(/^v[0-9]/)) {
|
||||
[apiGroup, apiVersion] = left;
|
||||
resource = left.slice(2).join("/");
|
||||
} else {
|
||||
apiGroup = "";
|
||||
apiVersion = left[0];
|
||||
[resource, name] = left.slice(1);
|
||||
}
|
||||
break;
|
||||
if (left[0].includes('.') || left[1].match(/^v[0-9]/)) {
|
||||
[apiGroup, apiVersion] = left;
|
||||
resource = left.slice(2).join("/");
|
||||
} else {
|
||||
apiGroup = "";
|
||||
apiVersion = left[0];
|
||||
[resource, name] = left.slice(1);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user