Compare commits

..

No commits in common. "main" and "v0.0.1" have entirely different histories.
main ... v0.0.1

1185 changed files with 20555 additions and 204416 deletions

View File

@ -1 +0,0 @@
**/node_modules/

View File

@ -1,10 +0,0 @@
root = true
[*]
end_of_line = lf
insert_final_newline = true
[*.{js,json,yml}]
charset = utf-8
indent_style = space
indent_size = 2

View File

@ -1,16 +0,0 @@
build/
test/
coverage/
node_modules/
packages/velaux-ui/src/assets/
.DS_Store
public
*.d.ts
dist
pkg/

View File

@ -1,56 +0,0 @@
module.exports = {
extends: ['@grafana/eslint-config'],
root: true,
plugins: ['@emotion', 'lodash', 'jest', 'import', 'jsx-a11y'],
globals: {
page: true,
__COMMIT_HASH__: 'readonly',
},
rules: {
eqeqeq: 'off',
'react/prop-types': 'off',
// need to ignore emotion's `css` prop, see https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-unknown-property.md#rule-options
// 'react/no-unknown-property': ['error', { ignore: ['css'] }],
// 'import/order': [
// 'error',
// {
// groups: [['builtin', 'external'], 'internal', 'parent', 'sibling', 'index'],
// 'newlines-between': 'always',
// alphabetize: { order: 'asc' },
// },
// ],
'import/order': 'off',
'react/jsx-key': 'off',
'no-restricted-imports': [
'error',
{
paths: [
{
name: 'react-redux',
importNames: ['useDispatch', 'useSelector'],
message: 'Please import from app/types instead.',
},
{
name: 'react-i18next',
importNames: ['Trans', 't'],
message: 'Please import from app/core/internationalization instead',
},
],
},
],
'no-duplicate-imports': 'off',
"import/no-duplicates": "warn",
'react/no-deprecated': 'off',
'react/no-unknown-property': 'off',
'@typescript-eslint/explicit-member-accessibility': 'off',
'@typescript-eslint/array-type': 'off',
},
overrides: [
{
files: ['packages/velaux-ui/src/utils/common.ts'],
rules: {
'no-redeclare': 'off',
},
},
],
};

4
.gitattributes vendored
View File

@ -1,4 +0,0 @@
/.yarn/** linguist-vendored
/.yarn/releases/* binary
/.yarn/plugins/**/* binary
/.pnp.* binary linguist-generated

7
.github/CODEOWNERS vendored
View File

@ -1,7 +0,0 @@
# This file is a github code protect rule follow the codeowners https://docs.github.com/en/github/creating-cloning-and-archiving-repositories/creating-a-repository-on-github/about-code-owners#example-of-a-codeowners-file
* @barnettZQG @wonderflow @chivalryq
pkg @barnettZQG @chivalryq @wangyikewxgm @yangsoon @FogDong
packages @barnettZQG @chivalryq

View File

@ -1,42 +0,0 @@
---
name: "\U0001F41B Bug report"
about: Create a report to help us improve
title: ""
labels: kind/bug
assignees: ''
---
**Describe the bug**
<!--
A clear and concise description of what the bug is.
-->
**To Reproduce**
<!--
Steps to reproduce the behavior:
1. The YAML files of Component/Trait I used.
2. The YAML file of Application I applied.
3. Other operations I have done.
4. See error
-->
**Expected behavior**
<!--
A clear and concise description of what you expected to happen.
-->
**Screenshots**
<!--
If applicable, add screenshots to help explain your problem.
-->
**KubeVela Version**
<!--
Describe your KubeVela controller or CLI version information.
-->
**Additional context**
<!--
Add any other context about the problem here.
-->

View File

@ -1,5 +0,0 @@
blank_issues_enabled: true
contact_links:
- name: Questions & Help
url: https://github.com/kubevela/kubevela/discussions
about: Please ask and answer questions here.

View File

@ -1,27 +0,0 @@
---
name: "\U0001F680 Feature request"
about: Suggest an idea for this project
title: "[Feature]"
labels: kind/feature
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
<!--
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
-->
**Describe the solution you'd like**
<!--
A clear and concise description of what you want to happen.
-->
**Describe alternatives you've considered**
<!--
A clear and concise description of any alternative solutions or features you've considered.
-->
**Additional context**
<!--
Add any other context or screenshots about the feature request here.
-->

View File

@ -1,27 +0,0 @@
### Description of your changes
<!--
Briefly describe what this pull request does. We love pull requests that resolve an open KubeVela issue. If yours does, you
can uncomment the below line to indicate which issue your PR fixes, for example
"Fixes #500":
-->
Fixes #
I have:
- [ ] Read and followed KubeVela's [contribution process](https://github.com/oam-dev/kubevela/blob/master/contribute/create-pull-request.md).
- [ ] [Related Docs](https://github.com/oam-dev/kubevela.io) updated properly. In a new feature or configuration option, an update to the documentation is necessary.
- [ ] Run `yarn lint` to ensure the frontend changes are ready for review.
- [ ] Run `make reviewable`to ensure the server changes are ready for review.
- [ ] Added `backport release-x.y` labels to auto-backport this PR if necessary.
### Special notes for your reviewer
<!--
Be sure to direct your reviewers'
attention to anything that needs special consideration.
-->

View File

@ -1,11 +0,0 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
version: 2
updates:
- package-ecosystem: "" # See documentation for possible values
directory: "/" # Location of package manifests
schedule:
interval: "weekly"

View File

@ -1,33 +0,0 @@
{
"LABEL": {
"name": "title-needs-formatting",
"color": "EEEEEE"
},
"CHECKS": {
"prefixes": [
"Fix: ",
"Feat: ",
"Docs: ",
"Test: ",
"Chore: ",
"CI: ",
"Perf: ",
"Refactor: ",
"Revert: ",
"Style: ",
"Test: ",
"Fix(",
"Feat(",
"Docs(",
"Test(",
"Chore(",
"CI(",
"Perf(",
"Refactor(",
"Revert(",
"Style(",
"Test(",
"[Backport"
]
}
}

View File

@ -1,64 +0,0 @@
name: Arm64 Build Test
on:
push:
branches:
- main
- release-*
tags:
- v*
workflow_dispatch: { }
pull_request:
branches:
- main
- release-*
env:
# Common versions
GO_VERSION: '1.22.0'
permissions:
contents: read
jobs:
detect-noop:
runs-on: ubuntu-22.04
outputs:
noop: ${{ steps.noop.outputs.should_skip }}
steps:
- name: Detect No-op Changes
id: noop
uses: fkirc/skip-duplicate-actions@f75f66ce1886f00957d99748a42c724f4330bdcf
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
paths_ignore: '["**.md", "**.mdx", "**.png", "**.jpg"]'
do_not_skip: '["workflow_dispatch", "schedule", "push"]'
continue-on-error: true
arm64-build-test:
runs-on: ubuntu-22.04
needs: detect-noop
if: needs.detect-noop.outputs.noop != 'true'
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@6ccd57f4c5d15bdc2fef309bd9fb6cc9db2ef1c6
with:
submodules: true
- name: Set up QEMU
uses: docker/setup-qemu-action@5927c834f5b4fdf503fca6f4c7eccda82949e1ee
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@4fd812986e6c8c2a69e18311145f9371337f27d4
- name: Build linux/arm64 image
id: docker_build_2
uses: docker/build-push-action@1a162644f9a7e87d8f4b053101d1d9a712edc18c
with:
context: ./
build-args: |
GOPROXY=https://proxy.golang.org
file: ./Dockerfile
platforms: linux/arm64
push: false
tags: oamdev/velaux:latest

View File

@ -1,22 +0,0 @@
name: Backport
on:
pull_request_target:
types:
- closed
jobs:
# align with crossplane's choice https://github.com/crossplane/crossplane/blob/master/.github/workflows/backport.yml
open-pr:
runs-on: ubuntu-22.04
if: github.event.pull_request.merged
steps:
- name: Checkout
uses: actions/checkout@6ccd57f4c5d15bdc2fef309bd9fb6cc9db2ef1c6
with:
fetch-depth: 0
- name: Open Backport PR
uses: zeebe-io/backport-action@v0.0.9
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
github_workspace: ${{ github.workspace }}

View File

@ -1,41 +0,0 @@
name: "CodeQL"
on:
push:
branches: [ "main", "release-1.2", "release-1.3", "release-1.4", "release-1.5", "release-1.6" ]
pull_request:
branches: [ "main" ]
schedule:
- cron: "40 0 * * 5"
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [ go, javascript ]
steps:
- name: Checkout
uses: actions/checkout@6ccd57f4c5d15bdc2fef309bd9fb6cc9db2ef1c6
- name: Initialize CodeQL
uses: github/codeql-action/init@v3
with:
languages: ${{ matrix.language }}
queries: +security-and-quality
- name: Autobuild
uses: github/codeql-action/autobuild@v3
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
with:
category: "/language:${{ matrix.language }}"

View File

@ -1,21 +0,0 @@
name: PR Title Checker
on:
pull_request:
types:
- opened
- edited
- synchronize
- labeled
- unlabeled
jobs:
check:
runs-on: ubuntu-latest
permissions:
pull-requests: write
steps:
- uses: thehanimo/pr-title-checker@v1.4.2
with:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
pass_on_octokit_error: true
configuration_path: '.github/pr-title-checker-config.json'

99
.github/workflows/go.yml vendored Normal file
View File

@ -0,0 +1,99 @@
name: Go
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
env:
# Common versions
GO_VERSION: '1.16'
GOLANGCI_VERSION: 'v1.38.0'
jobs:
detect-noop:
runs-on: ubuntu-20.04
outputs:
noop: ${{ steps.noop.outputs.should_skip }}
steps:
- name: Detect No-op Changes
id: noop
uses: fkirc/skip-duplicate-actions@v3.3.0
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
paths_ignore: '["**.md", "**.mdx", "**.png", "**.jpg"]'
do_not_skip: '["workflow_dispatch", "schedule", "push"]'
concurrent_skipping: false
build:
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: ${{ env.GO_VERSION }}
- name: Build
run: make build-cp
- name: Test
run: make test
lint:
runs-on: ubuntu-20.04
needs: detect-noop
if: needs.detect-noop.outputs.noop != 'true'
steps:
- name: Checkout
uses: actions/checkout@v2
with:
submodules: true
- name: Cache Go Dependencies
uses: actions/cache@v2
with:
path: .work/pkg
key: ${{ runner.os }}-pkg-${{ hashFiles('**/go.sum') }}
restore-keys: ${{ runner.os }}-pkg-
# This action uses its own setup-go, which always seems to use the latest
# stable version of Go. We could run 'make lint' to ensure our desired Go
# version, but we prefer this action because it leaves 'annotations' (i.e.
# it comments on PRs to point out linter violations).
- name: Lint
uses: golangci/golangci-lint-action@v2
with:
version: ${{ env.GOLANGCI_VERSION }}
check-diff:
runs-on: ubuntu-20.04
needs: detect-noop
if: needs.detect-noop.outputs.noop != 'true'
steps:
- name: Checkout
uses: actions/checkout@v2
with:
submodules: true
- name: Setup Go
uses: actions/setup-go@v2
with:
go-version: ${{ env.GO_VERSION }}
- name: Cache Go Dependencies
uses: actions/cache@v2
with:
path: .work/pkg
key: ${{ runner.os }}-pkg-${{ hashFiles('**/go.sum') }}
restore-keys: ${{ runner.os }}-pkg-
- name: Check code formatting
run: go install golang.org/x/tools/cmd/goimports && make fmt
- name: Check Diff
run: make check-diff

View File

@ -1,29 +0,0 @@
name: "ImageScan"
on:
push:
branches: [ main, release-* ]
jobs:
images:
name: Image Scan
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@6ccd57f4c5d15bdc2fef309bd9fb6cc9db2ef1c6
- name: Build Vela Core image from Dockerfile
run: |
docker build -t docker.io/oamdev/vela-velaux:${{ github.sha }} .
- name: Run Trivy vulnerability scanner for velaux
uses: aquasecurity/trivy-action@master
with:
image-ref: 'docker.io/oamdev/vela-velaux:${{ github.sha }}'
format: 'sarif'
output: 'trivy-results.sarif'
- name: Upload Trivy scan results to GitHub Security tab
uses: github/codeql-action/upload-sarif@v3
if: always()
with:
sarif_file: 'trivy-results.sarif'

View File

@ -1,141 +0,0 @@
name: Run commands when issues are labeled or comments added
on:
issues:
types: [labeled, opened]
issue_comment:
types: [created]
permissions:
contents: read
jobs:
bot:
runs-on: ubuntu-22.04
steps:
- name: Checkout Actions
uses: actions/checkout@6ccd57f4c5d15bdc2fef309bd9fb6cc9db2ef1c6
with:
repository: "oam-dev/kubevela-github-actions"
path: ./actions
ref: v0.4.2
- name: Setup Node.js
uses: actions/setup-node@1e60f620b9541d16bece96c5465dc8ee9832be0b
with:
node-version: '16'
cache: 'npm'
cache-dependency-path: ./actions/package-lock.json
- name: Install Dependencies
run: npm ci --production --prefix ./actions
- name: Run Commands
uses: ./actions/commands
with:
token: ${{secrets.VELA_BOT_TOKEN}}
configPath: issue-commands
backport:
runs-on: ubuntu-22.04
if: github.event.issue.pull_request && contains(github.event.comment.body, '/backport')
permissions:
contents: write
pull-requests: write
issues: write
steps:
- name: Extract Command
id: command
uses: xt0rted/slash-command-action@bf51f8f5f4ea3d58abc7eca58f77104182b23e88
with:
repo-token: ${{ secrets.VELA_BOT_TOKEN }}
command: backport
reaction: "true"
reaction-type: "eyes"
allow-edits: "false"
permission-level: read
- name: Handle Command
uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea
env:
VERSION: ${{ steps.command.outputs.command-arguments }}
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const version = process.env.VERSION
let label = "backport release-" + version
if (version.includes("release")) {
label = "backport " + version
}
// Add our backport label.
github.rest.issues.addLabels({
// Every pull request is an issue, but not every issue is a pull request.
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
labels: [label]
})
console.log("Added '" + label + "' label.")
- name: Checkout
uses: actions/checkout@6ccd57f4c5d15bdc2fef309bd9fb6cc9db2ef1c6
with:
fetch-depth: 0
- name: Open Backport PR
uses: zeebe-io/backport-action@v0.0.9
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
github_workspace: ${{ github.workspace }}
retest:
runs-on: ubuntu-22.04
if: github.event.issue.pull_request && contains(github.event.comment.body, '/retest')
permissions:
actions: write
contents: write
pull-requests: write
issues: write
steps:
- name: Retest the current pull request
uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea
env:
PULL_REQUEST_ID: ${{ github.event.issue.number }}
COMMENT_ID: ${{ github.event.comment.id }}
COMMENT_BODY: ${{ github.event.comment.body }}
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const pull_request_id = process.env.PULL_REQUEST_ID
const comment_id = process.env.COMMENT_ID
const comment_body = process.env.COMMENT_BODY
console.log("retest pr: #" + pull_request_id + " comment: " + comment_body)
const {data: pr} = await github.rest.pulls.get({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: pull_request_id,
})
console.log("pr: " + JSON.stringify(pr))
const action = comment_body.split(" ")[0]
let workflow_ids = comment_body.split(" ").slice(1).filter(line => line.length > 0).map(line => line + ".yml")
if (workflow_ids.length == 0) workflow_ids = ["staticcheck.yml", "server-test.yml", "arm64-build-test.yml"]
for (let i = 0; i < workflow_ids.length; i++) {
const workflow_id = workflow_ids[i]
const {data: runs} = await github.rest.actions.listWorkflowRuns({
owner: context.repo.owner,
repo: context.repo.repo,
workflow_id: workflow_id,
head_sha: pr.head.sha,
})
console.log("runs for " + workflow_id + ": ", JSON.stringify(runs))
runs.workflow_runs.forEach((workflow_run) => {
if (workflow_run.status === "in_progress") return
let handler = github.rest.actions.reRunWorkflow
if (action === "/retest-failed") handler = github.rest.actions.reRunWorkflowFailedJobs
handler({
owner: context.repo.owner,
repo: context.repo.repo,
run_id: workflow_run.id
})
})
}
github.rest.reactions.createForIssueComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: comment_id,
content: "eyes",
});

View File

@ -7,44 +7,85 @@ on:
workflow_dispatch: {}
jobs:
build:
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@6ccd57f4c5d15bdc2fef309bd9fb6cc9db2ef1c6
- name: Get the version
id: get_version
run: |
VERSION=${GITHUB_REF#refs/tags/}
if [[ ${GITHUB_REF} == "refs/heads/main" ]]; then
VERSION=latest
fi
echo ::set-output name=VERSION::${VERSION}
- name: Get git revision
id: vars
shell: bash
run: |
echo "git_revision=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT
- name: Login to DockerHub
uses: docker/login-action@v3.2.0
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
release:
runs-on: ubuntu-latest
env:
# https://docs.github.com/en/actions/reference/authentication-in-a-workflow
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- uses: docker/setup-qemu-action@v3.1.0
- uses: docker/setup-buildx-action@v3.4.0
steps:
- name: Set up Go 1.16
uses: actions/setup-go@v1
with:
driver-opts: image=moby/buildkit:master
- name: Build docker image
id: acr_build
uses: docker/build-push-action@v6.3.0
go-version: 1.16
id: go
- name: Check out code into the Go module directory
uses: actions/checkout@v2
- name: Get the latest version
id: get_version
run: echo ::set-output name=VERSION::${GITHUB_REF#refs/tags/}
- name: Run cross-build
run: |
go get github.com/mitchellh/gox@v0.4.0
make cross-build
- name: Set up Node 14.x
uses: actions/setup-node@v1
with:
context: ./
file: ./Dockerfile
platforms: linux/amd64,linux/arm64
push: true
build-args: |
GITVERSION=git-${{ steps.vars.outputs.git_revision }}
VERSION=${{ steps.get_version.outputs.VERSION }}
GOPROXY=https://proxy.golang.org
tags: |-
oamdev/velaux:${{ steps.get_version.outputs.VERSION }}
node-version: '14.x'
- name: Build UI
run: |
cd ui/ && yarn && yarn build && cd ..
- name: Run compress binary
run: make compress
- name: Get release
id: get_release
uses: bruceadams/get-release@v1.2.2
- name: Upload Linux amd64 tar.gz
uses: actions/upload-release-asset@v1.0.2
with:
upload_url: ${{ steps.get_release.outputs.upload_url }}
asset_path: ./_bin/velacp-linux-amd64.tar.gz
asset_name: velacp-${{ steps.get_version.outputs.VERSION }}-linux-amd64.tar.gz
asset_content_type: binary/octet-stream
- name: Upload Linux amd64 zip
uses: actions/upload-release-asset@v1.0.2
with:
upload_url: ${{ steps.get_release.outputs.upload_url }}
asset_path: ./_bin/velacp-linux-amd64.zip
asset_name: velacp-${{ steps.get_version.outputs.VERSION }}-linux-amd64.zip
asset_content_type: binary/octet-stream
- name: Upload MacOS tar.gz
uses: actions/upload-release-asset@v1.0.2
with:
upload_url: ${{ steps.get_release.outputs.upload_url }}
asset_path: ./_bin/velacp-darwin-amd64.tar.gz
asset_name: velacp-${{ steps.get_version.outputs.VERSION }}-darwin-amd64.tar.gz
asset_content_type: binary/octet-stream
- name: Upload MacOS zip
uses: actions/upload-release-asset@v1.0.2
with:
upload_url: ${{ steps.get_release.outputs.upload_url }}
asset_path: ./_bin/velacp-darwin-amd64.zip
asset_name: velacp-${{ steps.get_version.outputs.VERSION }}-darwin-amd64.zip
asset_content_type: binary/octet-stream
- name: Upload Windows tar.gz
uses: actions/upload-release-asset@v1.0.2
with:
upload_url: ${{ steps.get_release.outputs.upload_url }}
asset_path: ./_bin/velacp-windows-amd64.tar.gz
asset_name: velacp-${{ steps.get_version.outputs.VERSION }}-windows-amd64.tar.gz
asset_content_type: binary/octet-stream
- name: Upload Windows zip
uses: actions/upload-release-asset@v1.0.2
with:
upload_url: ${{ steps.get_release.outputs.upload_url }}
asset_path: ./_bin/velacp-windows-amd64.zip
asset_name: velacp-${{ steps.get_version.outputs.VERSION }}-windows-amd64.zip
asset_content_type: binary/octet-stream
- name: Upload Checksums
uses: actions/upload-release-asset@v1.0.2
with:
upload_url: ${{ steps.get_release.outputs.upload_url }}
asset_path: ./_bin/sha256sums.txt
asset_name: sha256sums.txt
asset_content_type: text/plain

View File

@ -1,204 +0,0 @@
name: VelaUX APIServer Test
on:
push:
branches:
- main
- release-*
tags:
- v*
workflow_dispatch: { }
pull_request:
branches:
- main
- release-*
env:
# Common versions
GO_VERSION: '1.22.0'
permissions:
contents: read
jobs:
detect-noop:
runs-on: ubuntu-22.04
outputs:
noop: ${{ steps.noop.outputs.should_skip }}
steps:
- name: Detect No-op Changes
id: noop
uses: fkirc/skip-duplicate-actions@f75f66ce1886f00957d99748a42c724f4330bdcf
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
paths_ignore: '["**.md", "**.mdx", "**.png", "**.jpg"]'
do_not_skip: '["workflow_dispatch", "schedule", "push"]'
continue-on-error: true
server-unit-tests:
runs-on: ubuntu-22.04
needs: detect-noop
if: needs.detect-noop.outputs.noop != 'true'
steps:
- name: Set up Go
uses: actions/setup-go@cdcb36043654635271a94b9a6d1392de5bb323a7
with:
go-version: ${{ env.GO_VERSION }}
id: go
- name: Check out code into the Go module directory
uses: actions/checkout@6ccd57f4c5d15bdc2fef309bd9fb6cc9db2ef1c6
with:
submodules: true
- name: Cache Go Dependencies
uses: actions/cache@v4
with:
path: .work/pkg
key: ${{ runner.os }}-pkg-${{ hashFiles('**/go.sum') }}
restore-keys: ${{ runner.os }}-pkg-
- name: Install ginkgo
run: |
sudo sed -i 's/azure\.//' /etc/apt/sources.list
sudo apt-get update
sudo apt-get install -y golang-ginkgo-dev
- name : Set up MySQL
uses: mirromutth/mysql-action@v1.1
with:
mysql database: 'kubevela'
mysql root password: 'kubevelaSQL123'
- name: Set up Postgres
uses: Harmon758/postgresql-action@v1
with:
postgresql version: '11'
postgresql db: 'kubevela'
postgresql user: 'kubevela'
postgresql password: 'Kubevela-123'
- name: Start MongoDB
uses: supercharge/mongodb-github-action@5a87bd81f88e2a8b195f8b7b656f5cda1350815a # 1.11.0
with:
mongodb-version: '5.0'
# TODO need update action version to resolve node 12 deprecated.
- name: install Kubebuilder
uses: RyanSiu1995/kubebuilder-action@e7e4de1c1eaf1d089b9a186f7526239acadf0b40
with:
version: 3.1.0
kubebuilderOnly: false
kubernetesVersion: v1.26.0
- name: Run api server unit test
run: make unit-test-server
- name: Upload coverage report
uses: codecov/codecov-action@d9f34f8cd5cb3b3eb79b3e4b5dae3a16df499a70
with:
token: ${{ secrets.CODECOV_TOKEN }}
file: ./coverage.txt
flags: apiserver-unittests
name: codecov-umbrella
server-e2e-tests:
runs-on: ubuntu-22.04
needs: [ detect-noop ]
if: needs.detect-noop.outputs.noop != 'true'
strategy:
matrix:
k8s-version: ["v1.26"]
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}-${{ matrix.k8s-version }}
cancel-in-progress: true
steps:
- name: Set up Go
uses: actions/setup-go@cdcb36043654635271a94b9a6d1392de5bb323a7
with:
go-version: ${{ env.GO_VERSION }}
id: go
- name: Check out code into the Go module directory
uses: actions/checkout@6ccd57f4c5d15bdc2fef309bd9fb6cc9db2ef1c6
with:
submodules: true
- name: Build docker image
id: docker_build
uses: docker/build-push-action@1a162644f9a7e87d8f4b053101d1d9a712edc18c
with:
context: ./
build-args: |
GOPROXY=https://proxy.golang.org
file: ./Dockerfile.e2e
platforms: linux/amd64
push: false
tags: oamdev/velaux:latest
- name: Tear down K3d if exist
run: |
k3d cluster delete || true
k3d cluster delete worker || true
- name: Calculate K3d args
run: |
EGRESS_ARG=""
if [[ "${{ matrix.k8s-version }}" == v1.26 ]]; then
EGRESS_ARG="--k3s-arg --egress-selector-mode=disabled@server:0"
fi
echo "EGRESS_ARG=${EGRESS_ARG}" >> $GITHUB_ENV
- name: Setup K3d (Hub)
uses: nolar/setup-k3d-k3s@293b8e5822a20bc0d5bcdd4826f1a665e72aba96
with:
version: ${{ matrix.k8s-version }}
github-token: ${{ secrets.GITHUB_TOKEN }}
k3d-args: ${{ env.EGRESS_ARG }}
- name: Setup K3d (Worker)
uses: nolar/setup-k3d-k3s@293b8e5822a20bc0d5bcdd4826f1a665e72aba96
with:
version: ${{ matrix.k8s-version }}
github-token: ${{ secrets.GITHUB_TOKEN }}
k3d-name: worker
k3d-args: --kubeconfig-update-default=false --network=k3d-k3s-default ${{ env.EGRESS_ARG }}
- name: Kind Cluster (Worker)
run: |
internal_ip=$(docker network inspect k3d-k3s-default|jq ".[0].Containers"| jq -r '.[]| select(.Name=="k3d-worker-server-0")|.IPv4Address' | cut -d/ -f1)
k3d kubeconfig get worker > /tmp/worker.client.kubeconfig
cp /tmp/worker.client.kubeconfig /tmp/worker.kubeconfig
sed -i "s/0.0.0.0:[0-9]\+/$internal_ip:6443/" /tmp/worker.kubeconfig
- name: Setup KubeVela core environment
run: |
make e2e-setup-core
make start-addon-mock-server
make load-image
make enable-addon-no-replicas
- name: Run server e2e test
run: |
export ALIYUN_ACCESS_KEY_ID=${{ secrets.ALIYUN_ACCESS_KEY_ID }}
export ALIYUN_ACCESS_KEY_SECRET=${{ secrets.ALIYUN_ACCESS_KEY_SECRET }}
export GITHUB_TOKEN=${{ secrets.GITHUB_TOKEN }}
docker run --rm -v `pwd`/e2e-plugins:/plugins oamdev/velaux:latest cp -r -a /app/velaux/plugins/ /plugins/
make e2e-server-test
- name: Test addon enable
run: |
make enable-addon
- name: Upload coverage report
uses: codecov/codecov-action@e28ff129e5465c2c0dcc6f003fc735cb6ae0c673
with:
token: ${{ secrets.CODECOV_TOKEN }}
files: /tmp/e2e_apiserver_test.out
flags: server-e2e-tests
name: codecov-umbrella
- name: Clean e2e profile
run: rm /tmp/e2e_apiserver_test.out

View File

@ -1,54 +0,0 @@
name: Static Check
on:
push:
branches:
- main
- release-*
workflow_dispatch: {}
pull_request:
branches:
- main
- release-*
env:
# Common versions
GO_VERSION: '1.22.0'
jobs:
detect-noop:
runs-on: ubuntu-22.04
outputs:
noop: ${{ steps.noop.outputs.should_skip }}
steps:
- name: Detect No-op Changes
id: noop
uses: fkirc/skip-duplicate-actions@v5.3.1
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
paths_ignore: '["**.md", "**.mdx", "**.png", "**.jpg"]'
do_not_skip: '["workflow_dispatch", "schedule", "push"]'
concurrent_skipping: false
check:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@6ccd57f4c5d15bdc2fef309bd9fb6cc9db2ef1c6
- uses: actions/setup-node@1e60f620b9541d16bece96c5465dc8ee9832be0b
with:
node-version: '16'
cache: 'yarn'
- name: Set up Go
uses: actions/setup-go@cdcb36043654635271a94b9a6d1392de5bb323a7
with:
go-version: ${{ env.GO_VERSION }}
id: go
- name: Install Yarn
run: npm install --global yarn
- name: upgrade yarn
run: yarn set version 3.6.0
- run: yarn install
- run: yarn lint
name: Check Frontend Code Style
- run: yarn test
- run: make check-diff
name: Check Server Code Style

23
.gitignore vendored
View File

@ -17,30 +17,7 @@ node_modules/
# Dependency directories (remove the comment below to include it)
vendor/
build
# IDE
.idea
.vscode
.eslintcache
.env
package-lock.json
yarn-error.log
.DS_Store
dist
/packages/**/compiled
.yarn/.cache/
.yarn/cache/
.yarn/unplugged
.yarn/install-state.gz
.pnp.*
tsconfig.tsbuildinfo
e2e-plugins
npm-artifacts
bin

View File

@ -1,226 +0,0 @@
run:
timeout: 10m
skip-files:
- "zz_generated\\..+\\.go$"
- ".*_test.go$"
skip-dirs:
- "hack"
- "e2e"
output:
# colored-line-number|line-number|json|tab|checkstyle|code-climate, default is "colored-line-number"
format: colored-line-number
linters-settings:
errcheck:
# report about not checking of errors in type assetions: `a := b.(MyStruct)`;
# default is false: such cases aren't reported by default.
check-type-assertions: false
# report about assignment of errors to blank identifier: `num, _ := strconv.Atoi(numStr)`;
# default is false: such cases aren't reported by default.
check-blank: false
# [deprecated] comma-separated list of pairs of the form pkg:regex
# the regex is used to ignore names within pkg. (default "fmt:.*").
# see https://github.com/kisielk/errcheck#the-deprecated-method for details
ignore: fmt:.*,io/ioutil:^Read.*
exhaustive:
# indicates that switch statements are to be considered exhaustive if a
# 'default' case is present, even if all enum members aren't listed in the
# switch
default-signifies-exhaustive: true
govet:
# report about shadowed variables
check-shadowing: false
revive:
# minimal confidence for issues, default is 0.8
min-confidence: 0.8
gofmt:
# simplify code: gofmt with `-s` option, true by default
simplify: true
goimports:
# put imports beginning with prefix after 3rd-party packages;
# it's a comma-separated list of prefixes
local-prefixes: github.com/kubevela/velaux
gocyclo:
# minimal code complexity to report, 30 by default (but we recommend 10-20)
min-complexity: 30
maligned:
# print struct with more effective memory layout or not, false by default
suggest-new: true
dupl:
# tokens count to trigger issue, 150 by default
threshold: 100
goconst:
# minimal length of string constant, 3 by default
min-len: 3
# minimal occurrences count to trigger, 3 by default
min-occurrences: 5
lll:
# tab width in spaces. Default to 1.
tab-width: 1
unused:
# treat code as a program (not a library) and report unused exported identifiers; default is false.
# XXX: if you enable this setting, unused will report a lot of false-positives in text editors:
# if it's called for subdir of a project it can't find funcs usages. All text editor integrations
# with golangci-lint call it on a directory with the changed file.
check-exported: false
unparam:
# Inspect exported functions, default is false. Set to true if no external program/library imports your code.
# XXX: if you enable this setting, unparam will report a lot of false-positives in text editors:
# if it's called for subdir of a project it can't find external interfaces. All text editor integrations
# with golangci-lint call it on a directory with the changed file.
check-exported: false
nakedret:
# make an issue if func has more lines of code than this setting and it has naked returns; default is 30
max-func-lines: 30
gocritic:
# Enable multiple checks by tags, run `GL_DEBUG=gocritic golangci-lint` run to see all tags and checks.
# Empty list by default. See https://github.com/go-critic/go-critic#usage -> section "Tags".
enabled-tags:
- performance
settings: # settings passed to gocritic
captLocal: # must be valid enabled check name
paramsOnly: true
rangeValCopy:
sizeThreshold: 32
makezero:
# Allow only slices initialized with a length of zero. Default is false.
always: false
linters:
enable:
- megacheck
- govet
- gocyclo
- gocritic
- goconst
- goimports
- gofmt # We enable this as well as goimports for its simplify mode.
- revive
- unconvert
- misspell
- nakedret
- exportloopref
disable:
- deadcode
- scopelint
- structcheck
- varcheck
- rowserrcheck
- sqlclosecheck
- errchkjson
- contextcheck
presets:
- bugs
- unused
fast: false
issues:
# Excluding configuration per-path and per-linter
exclude-rules:
# Exclude some linters from running on tests files.
- path: _test(ing)?\.go
linters:
- gocyclo
- errcheck
- dupl
- gosec
- exportloopref
- unparam
# Ease some gocritic warnings on test files.
- path: _test\.go
text: "(unnamedResult|exitAfterDefer)"
linters:
- gocritic
# These are performance optimisations rather than style issues per se.
# They warn when function arguments or range values copy a lot of memory
# rather than using a pointer.
- text: "(hugeParam|rangeValCopy):"
linters:
- gocritic
# This "TestMain should call os.Exit to set exit code" warning is not clever
# enough to notice that we call a helper method that calls os.Exit.
- text: "SA3000:"
linters:
- staticcheck
- text: "k8s.io/api/core/v1"
linters:
- goimports
# This is a "potential hardcoded credentials" warning. It's triggered by
# any variable with 'secret' in the same, and thus hits a lot of false
# positives in Kubernetes land where a Secret is an object type.
- text: "G101:"
linters:
- gosec
- gas
# This is an 'errors unhandled' warning that duplicates errcheck.
- text: "G104:"
linters:
- gosec
- gas
# The Azure AddToUserAgent method appends to the existing user agent string.
# It returns an error if you pass it an empty string lettinga you know the
# user agent did not change, making it more of a warning.
- text: \.AddToUserAgent
linters:
- errcheck
- text: "don't use an underscore"
linters:
- revive
- text: "package-comments: should have a package comment"
linters:
- revive
- text: "error-strings: error strings should not be capitalized or end with punctuation or a newline"
linters:
- revive
# Independently from option `exclude` we use default exclude patterns,
# it can be disabled by this option. To list all
# excluded by default patterns execute `golangci-lint run --help`.
# Default value for this option is true.
exclude-use-default: false
# Show only new issues: if there are unstaged changes or untracked files,
# only those changes are analyzed, else only changes in HEAD~ are analyzed.
# It's a super-useful option for integration of golangci-lint into existing
# large codebase. It's not practical to fix all existing issues at the moment
# of integration: much better don't allow issues in new code.
# Default is false.
new: false
# Maximum issues count per one linter. Set to 0 to disable. Default is 50.
max-per-linter: 0
# Maximum count of issues with the same text. Set to 0 to disable. Default is 3.
max-same-issues: 0

View File

@ -1,5 +0,0 @@
module.exports = {
trailingComma: 'es5',
singleQuote: true,
printWidth: 120,
};

View File

@ -1,6 +0,0 @@
module.exports = {
extends: [require.resolve('@umijs/fabric/dist/stylelint')],
rules: {
// your rules
},
};

File diff suppressed because one or more lines are too long

View File

@ -1,20 +0,0 @@
#!/usr/bin/env node
const {existsSync} = require(`fs`);
const {createRequire} = require(`module`);
const {resolve} = require(`path`);
const relPnpApiPath = "../../../../.pnp.cjs";
const absPnpApiPath = resolve(__dirname, relPnpApiPath);
const absRequire = createRequire(absPnpApiPath);
if (existsSync(absPnpApiPath)) {
if (!process.versions.pnp) {
// Setup the environment to be able to require eslint/bin/eslint.js
require(absPnpApiPath).setup();
}
}
// Defer to the real eslint/bin/eslint.js your application uses
module.exports = absRequire(`eslint/bin/eslint.js`);

View File

@ -1,20 +0,0 @@
#!/usr/bin/env node
const {existsSync} = require(`fs`);
const {createRequire} = require(`module`);
const {resolve} = require(`path`);
const relPnpApiPath = "../../../../.pnp.cjs";
const absPnpApiPath = resolve(__dirname, relPnpApiPath);
const absRequire = createRequire(absPnpApiPath);
if (existsSync(absPnpApiPath)) {
if (!process.versions.pnp) {
// Setup the environment to be able to require eslint
require(absPnpApiPath).setup();
}
}
// Defer to the real eslint your application uses
module.exports = absRequire(`eslint`);

View File

@ -1,6 +0,0 @@
{
"name": "eslint",
"version": "8.34.0-sdk",
"main": "./lib/api.js",
"type": "commonjs"
}

View File

@ -1,5 +0,0 @@
# This file is automatically generated by @yarnpkg/sdks.
# Manual changes might be lost!
integrations:
- vscode

View File

@ -1,20 +0,0 @@
#!/usr/bin/env node
const {existsSync} = require(`fs`);
const {createRequire} = require(`module`);
const {resolve} = require(`path`);
const relPnpApiPath = "../../../.pnp.cjs";
const absPnpApiPath = resolve(__dirname, relPnpApiPath);
const absRequire = createRequire(absPnpApiPath);
if (existsSync(absPnpApiPath)) {
if (!process.versions.pnp) {
// Setup the environment to be able to require prettier/index.js
require(absPnpApiPath).setup();
}
}
// Defer to the real prettier/index.js your application uses
module.exports = absRequire(`prettier/index.js`);

View File

@ -1,6 +0,0 @@
{
"name": "prettier",
"version": "2.8.7-sdk",
"main": "./index.js",
"type": "commonjs"
}

View File

@ -1,20 +0,0 @@
#!/usr/bin/env node
const {existsSync} = require(`fs`);
const {createRequire} = require(`module`);
const {resolve} = require(`path`);
const relPnpApiPath = "../../../../.pnp.cjs";
const absPnpApiPath = resolve(__dirname, relPnpApiPath);
const absRequire = createRequire(absPnpApiPath);
if (existsSync(absPnpApiPath)) {
if (!process.versions.pnp) {
// Setup the environment to be able to require typescript/bin/tsc
require(absPnpApiPath).setup();
}
}
// Defer to the real typescript/bin/tsc your application uses
module.exports = absRequire(`typescript/bin/tsc`);

View File

@ -1,20 +0,0 @@
#!/usr/bin/env node
const {existsSync} = require(`fs`);
const {createRequire} = require(`module`);
const {resolve} = require(`path`);
const relPnpApiPath = "../../../../.pnp.cjs";
const absPnpApiPath = resolve(__dirname, relPnpApiPath);
const absRequire = createRequire(absPnpApiPath);
if (existsSync(absPnpApiPath)) {
if (!process.versions.pnp) {
// Setup the environment to be able to require typescript/bin/tsserver
require(absPnpApiPath).setup();
}
}
// Defer to the real typescript/bin/tsserver your application uses
module.exports = absRequire(`typescript/bin/tsserver`);

View File

@ -1,20 +0,0 @@
#!/usr/bin/env node
const {existsSync} = require(`fs`);
const {createRequire} = require(`module`);
const {resolve} = require(`path`);
const relPnpApiPath = "../../../../.pnp.cjs";
const absPnpApiPath = resolve(__dirname, relPnpApiPath);
const absRequire = createRequire(absPnpApiPath);
if (existsSync(absPnpApiPath)) {
if (!process.versions.pnp) {
// Setup the environment to be able to require typescript/lib/tsc.js
require(absPnpApiPath).setup();
}
}
// Defer to the real typescript/lib/tsc.js your application uses
module.exports = absRequire(`typescript/lib/tsc.js`);

View File

@ -1,225 +0,0 @@
#!/usr/bin/env node
const {existsSync} = require(`fs`);
const {createRequire} = require(`module`);
const {resolve} = require(`path`);
const relPnpApiPath = "../../../../.pnp.cjs";
const absPnpApiPath = resolve(__dirname, relPnpApiPath);
const absRequire = createRequire(absPnpApiPath);
const moduleWrapper = tsserver => {
if (!process.versions.pnp) {
return tsserver;
}
const {isAbsolute} = require(`path`);
const pnpApi = require(`pnpapi`);
const isVirtual = str => str.match(/\/(\$\$virtual|__virtual__)\//);
const isPortal = str => str.startsWith("portal:/");
const normalize = str => str.replace(/\\/g, `/`).replace(/^\/?/, `/`);
const dependencyTreeRoots = new Set(pnpApi.getDependencyTreeRoots().map(locator => {
return `${locator.name}@${locator.reference}`;
}));
// VSCode sends the zip paths to TS using the "zip://" prefix, that TS
// doesn't understand. This layer makes sure to remove the protocol
// before forwarding it to TS, and to add it back on all returned paths.
function toEditorPath(str) {
// We add the `zip:` prefix to both `.zip/` paths and virtual paths
if (isAbsolute(str) && !str.match(/^\^?(zip:|\/zip\/)/) && (str.match(/\.zip\//) || isVirtual(str))) {
// We also take the opportunity to turn virtual paths into physical ones;
// this makes it much easier to work with workspaces that list peer
// dependencies, since otherwise Ctrl+Click would bring us to the virtual
// file instances instead of the real ones.
//
// We only do this to modules owned by the the dependency tree roots.
// This avoids breaking the resolution when jumping inside a vendor
// with peer dep (otherwise jumping into react-dom would show resolution
// errors on react).
//
const resolved = isVirtual(str) ? pnpApi.resolveVirtual(str) : str;
if (resolved) {
const locator = pnpApi.findPackageLocator(resolved);
if (locator && (dependencyTreeRoots.has(`${locator.name}@${locator.reference}`) || isPortal(locator.reference))) {
str = resolved;
}
}
str = normalize(str);
if (str.match(/\.zip\//)) {
switch (hostInfo) {
// Absolute VSCode `Uri.fsPath`s need to start with a slash.
// VSCode only adds it automatically for supported schemes,
// so we have to do it manually for the `zip` scheme.
// The path needs to start with a caret otherwise VSCode doesn't handle the protocol
//
// Ref: https://github.com/microsoft/vscode/issues/105014#issuecomment-686760910
//
// 2021-10-08: VSCode changed the format in 1.61.
// Before | ^zip:/c:/foo/bar.zip/package.json
// After | ^/zip//c:/foo/bar.zip/package.json
//
// 2022-04-06: VSCode changed the format in 1.66.
// Before | ^/zip//c:/foo/bar.zip/package.json
// After | ^/zip/c:/foo/bar.zip/package.json
//
// 2022-05-06: VSCode changed the format in 1.68
// Before | ^/zip/c:/foo/bar.zip/package.json
// After | ^/zip//c:/foo/bar.zip/package.json
//
case `vscode <1.61`: {
str = `^zip:${str}`;
} break;
case `vscode <1.66`: {
str = `^/zip/${str}`;
} break;
case `vscode <1.68`: {
str = `^/zip${str}`;
} break;
case `vscode`: {
str = `^/zip/${str}`;
} break;
// To make "go to definition" work,
// We have to resolve the actual file system path from virtual path
// and convert scheme to supported by [vim-rzip](https://github.com/lbrayner/vim-rzip)
case `coc-nvim`: {
str = normalize(resolved).replace(/\.zip\//, `.zip::`);
str = resolve(`zipfile:${str}`);
} break;
// Support neovim native LSP and [typescript-language-server](https://github.com/theia-ide/typescript-language-server)
// We have to resolve the actual file system path from virtual path,
// everything else is up to neovim
case `neovim`: {
str = normalize(resolved).replace(/\.zip\//, `.zip::`);
str = `zipfile://${str}`;
} break;
default: {
str = `zip:${str}`;
} break;
}
} else {
str = str.replace(/^\/?/, process.platform === `win32` ? `` : `/`);
}
}
return str;
}
function fromEditorPath(str) {
switch (hostInfo) {
case `coc-nvim`: {
str = str.replace(/\.zip::/, `.zip/`);
// The path for coc-nvim is in format of /<pwd>/zipfile:/<pwd>/.yarn/...
// So in order to convert it back, we use .* to match all the thing
// before `zipfile:`
return process.platform === `win32`
? str.replace(/^.*zipfile:\//, ``)
: str.replace(/^.*zipfile:/, ``);
} break;
case `neovim`: {
str = str.replace(/\.zip::/, `.zip/`);
// The path for neovim is in format of zipfile:///<pwd>/.yarn/...
return str.replace(/^zipfile:\/\//, ``);
} break;
case `vscode`:
default: {
return str.replace(/^\^?(zip:|\/zip(\/ts-nul-authority)?)\/+/, process.platform === `win32` ? `` : `/`)
} break;
}
}
// Force enable 'allowLocalPluginLoads'
// TypeScript tries to resolve plugins using a path relative to itself
// which doesn't work when using the global cache
// https://github.com/microsoft/TypeScript/blob/1b57a0395e0bff191581c9606aab92832001de62/src/server/project.ts#L2238
// VSCode doesn't want to enable 'allowLocalPluginLoads' due to security concerns but
// TypeScript already does local loads and if this code is running the user trusts the workspace
// https://github.com/microsoft/vscode/issues/45856
const ConfiguredProject = tsserver.server.ConfiguredProject;
const {enablePluginsWithOptions: originalEnablePluginsWithOptions} = ConfiguredProject.prototype;
ConfiguredProject.prototype.enablePluginsWithOptions = function() {
this.projectService.allowLocalPluginLoads = true;
return originalEnablePluginsWithOptions.apply(this, arguments);
};
// And here is the point where we hijack the VSCode <-> TS communications
// by adding ourselves in the middle. We locate everything that looks
// like an absolute path of ours and normalize it.
const Session = tsserver.server.Session;
const {onMessage: originalOnMessage, send: originalSend} = Session.prototype;
let hostInfo = `unknown`;
Object.assign(Session.prototype, {
onMessage(/** @type {string | object} */ message) {
const isStringMessage = typeof message === 'string';
const parsedMessage = isStringMessage ? JSON.parse(message) : message;
if (
parsedMessage != null &&
typeof parsedMessage === `object` &&
parsedMessage.arguments &&
typeof parsedMessage.arguments.hostInfo === `string`
) {
hostInfo = parsedMessage.arguments.hostInfo;
if (hostInfo === `vscode` && process.env.VSCODE_IPC_HOOK) {
const [, major, minor] = (process.env.VSCODE_IPC_HOOK.match(
// The RegExp from https://semver.org/ but without the caret at the start
/(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/
) ?? []).map(Number)
if (major === 1) {
if (minor < 61) {
hostInfo += ` <1.61`;
} else if (minor < 66) {
hostInfo += ` <1.66`;
} else if (minor < 68) {
hostInfo += ` <1.68`;
}
}
}
}
const processedMessageJSON = JSON.stringify(parsedMessage, (key, value) => {
return typeof value === 'string' ? fromEditorPath(value) : value;
});
return originalOnMessage.call(
this,
isStringMessage ? processedMessageJSON : JSON.parse(processedMessageJSON)
);
},
send(/** @type {any} */ msg) {
return originalSend.call(this, JSON.parse(JSON.stringify(msg, (key, value) => {
return typeof value === `string` ? toEditorPath(value) : value;
})));
}
});
return tsserver;
};
if (existsSync(absPnpApiPath)) {
if (!process.versions.pnp) {
// Setup the environment to be able to require typescript/lib/tsserver.js
require(absPnpApiPath).setup();
}
}
// Defer to the real typescript/lib/tsserver.js your application uses
module.exports = moduleWrapper(absRequire(`typescript/lib/tsserver.js`));

View File

@ -1,225 +0,0 @@
#!/usr/bin/env node
const {existsSync} = require(`fs`);
const {createRequire} = require(`module`);
const {resolve} = require(`path`);
const relPnpApiPath = "../../../../.pnp.cjs";
const absPnpApiPath = resolve(__dirname, relPnpApiPath);
const absRequire = createRequire(absPnpApiPath);
const moduleWrapper = tsserver => {
if (!process.versions.pnp) {
return tsserver;
}
const {isAbsolute} = require(`path`);
const pnpApi = require(`pnpapi`);
const isVirtual = str => str.match(/\/(\$\$virtual|__virtual__)\//);
const isPortal = str => str.startsWith("portal:/");
const normalize = str => str.replace(/\\/g, `/`).replace(/^\/?/, `/`);
const dependencyTreeRoots = new Set(pnpApi.getDependencyTreeRoots().map(locator => {
return `${locator.name}@${locator.reference}`;
}));
// VSCode sends the zip paths to TS using the "zip://" prefix, that TS
// doesn't understand. This layer makes sure to remove the protocol
// before forwarding it to TS, and to add it back on all returned paths.
function toEditorPath(str) {
// We add the `zip:` prefix to both `.zip/` paths and virtual paths
if (isAbsolute(str) && !str.match(/^\^?(zip:|\/zip\/)/) && (str.match(/\.zip\//) || isVirtual(str))) {
// We also take the opportunity to turn virtual paths into physical ones;
// this makes it much easier to work with workspaces that list peer
// dependencies, since otherwise Ctrl+Click would bring us to the virtual
// file instances instead of the real ones.
//
// We only do this to modules owned by the the dependency tree roots.
// This avoids breaking the resolution when jumping inside a vendor
// with peer dep (otherwise jumping into react-dom would show resolution
// errors on react).
//
const resolved = isVirtual(str) ? pnpApi.resolveVirtual(str) : str;
if (resolved) {
const locator = pnpApi.findPackageLocator(resolved);
if (locator && (dependencyTreeRoots.has(`${locator.name}@${locator.reference}`) || isPortal(locator.reference))) {
str = resolved;
}
}
str = normalize(str);
if (str.match(/\.zip\//)) {
switch (hostInfo) {
// Absolute VSCode `Uri.fsPath`s need to start with a slash.
// VSCode only adds it automatically for supported schemes,
// so we have to do it manually for the `zip` scheme.
// The path needs to start with a caret otherwise VSCode doesn't handle the protocol
//
// Ref: https://github.com/microsoft/vscode/issues/105014#issuecomment-686760910
//
// 2021-10-08: VSCode changed the format in 1.61.
// Before | ^zip:/c:/foo/bar.zip/package.json
// After | ^/zip//c:/foo/bar.zip/package.json
//
// 2022-04-06: VSCode changed the format in 1.66.
// Before | ^/zip//c:/foo/bar.zip/package.json
// After | ^/zip/c:/foo/bar.zip/package.json
//
// 2022-05-06: VSCode changed the format in 1.68
// Before | ^/zip/c:/foo/bar.zip/package.json
// After | ^/zip//c:/foo/bar.zip/package.json
//
case `vscode <1.61`: {
str = `^zip:${str}`;
} break;
case `vscode <1.66`: {
str = `^/zip/${str}`;
} break;
case `vscode <1.68`: {
str = `^/zip${str}`;
} break;
case `vscode`: {
str = `^/zip/${str}`;
} break;
// To make "go to definition" work,
// We have to resolve the actual file system path from virtual path
// and convert scheme to supported by [vim-rzip](https://github.com/lbrayner/vim-rzip)
case `coc-nvim`: {
str = normalize(resolved).replace(/\.zip\//, `.zip::`);
str = resolve(`zipfile:${str}`);
} break;
// Support neovim native LSP and [typescript-language-server](https://github.com/theia-ide/typescript-language-server)
// We have to resolve the actual file system path from virtual path,
// everything else is up to neovim
case `neovim`: {
str = normalize(resolved).replace(/\.zip\//, `.zip::`);
str = `zipfile://${str}`;
} break;
default: {
str = `zip:${str}`;
} break;
}
} else {
str = str.replace(/^\/?/, process.platform === `win32` ? `` : `/`);
}
}
return str;
}
function fromEditorPath(str) {
switch (hostInfo) {
case `coc-nvim`: {
str = str.replace(/\.zip::/, `.zip/`);
// The path for coc-nvim is in format of /<pwd>/zipfile:/<pwd>/.yarn/...
// So in order to convert it back, we use .* to match all the thing
// before `zipfile:`
return process.platform === `win32`
? str.replace(/^.*zipfile:\//, ``)
: str.replace(/^.*zipfile:/, ``);
} break;
case `neovim`: {
str = str.replace(/\.zip::/, `.zip/`);
// The path for neovim is in format of zipfile:///<pwd>/.yarn/...
return str.replace(/^zipfile:\/\//, ``);
} break;
case `vscode`:
default: {
return str.replace(/^\^?(zip:|\/zip(\/ts-nul-authority)?)\/+/, process.platform === `win32` ? `` : `/`)
} break;
}
}
// Force enable 'allowLocalPluginLoads'
// TypeScript tries to resolve plugins using a path relative to itself
// which doesn't work when using the global cache
// https://github.com/microsoft/TypeScript/blob/1b57a0395e0bff191581c9606aab92832001de62/src/server/project.ts#L2238
// VSCode doesn't want to enable 'allowLocalPluginLoads' due to security concerns but
// TypeScript already does local loads and if this code is running the user trusts the workspace
// https://github.com/microsoft/vscode/issues/45856
const ConfiguredProject = tsserver.server.ConfiguredProject;
const {enablePluginsWithOptions: originalEnablePluginsWithOptions} = ConfiguredProject.prototype;
ConfiguredProject.prototype.enablePluginsWithOptions = function() {
this.projectService.allowLocalPluginLoads = true;
return originalEnablePluginsWithOptions.apply(this, arguments);
};
// And here is the point where we hijack the VSCode <-> TS communications
// by adding ourselves in the middle. We locate everything that looks
// like an absolute path of ours and normalize it.
const Session = tsserver.server.Session;
const {onMessage: originalOnMessage, send: originalSend} = Session.prototype;
let hostInfo = `unknown`;
Object.assign(Session.prototype, {
onMessage(/** @type {string | object} */ message) {
const isStringMessage = typeof message === 'string';
const parsedMessage = isStringMessage ? JSON.parse(message) : message;
if (
parsedMessage != null &&
typeof parsedMessage === `object` &&
parsedMessage.arguments &&
typeof parsedMessage.arguments.hostInfo === `string`
) {
hostInfo = parsedMessage.arguments.hostInfo;
if (hostInfo === `vscode` && process.env.VSCODE_IPC_HOOK) {
const [, major, minor] = (process.env.VSCODE_IPC_HOOK.match(
// The RegExp from https://semver.org/ but without the caret at the start
/(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/
) ?? []).map(Number)
if (major === 1) {
if (minor < 61) {
hostInfo += ` <1.61`;
} else if (minor < 66) {
hostInfo += ` <1.66`;
} else if (minor < 68) {
hostInfo += ` <1.68`;
}
}
}
}
const processedMessageJSON = JSON.stringify(parsedMessage, (key, value) => {
return typeof value === 'string' ? fromEditorPath(value) : value;
});
return originalOnMessage.call(
this,
isStringMessage ? processedMessageJSON : JSON.parse(processedMessageJSON)
);
},
send(/** @type {any} */ msg) {
return originalSend.call(this, JSON.parse(JSON.stringify(msg, (key, value) => {
return typeof value === `string` ? toEditorPath(value) : value;
})));
}
});
return tsserver;
};
if (existsSync(absPnpApiPath)) {
if (!process.versions.pnp) {
// Setup the environment to be able to require typescript/lib/tsserverlibrary.js
require(absPnpApiPath).setup();
}
}
// Defer to the real typescript/lib/tsserverlibrary.js your application uses
module.exports = moduleWrapper(absRequire(`typescript/lib/tsserverlibrary.js`));

View File

@ -1,20 +0,0 @@
#!/usr/bin/env node
const {existsSync} = require(`fs`);
const {createRequire} = require(`module`);
const {resolve} = require(`path`);
const relPnpApiPath = "../../../../.pnp.cjs";
const absPnpApiPath = resolve(__dirname, relPnpApiPath);
const absRequire = createRequire(absPnpApiPath);
if (existsSync(absPnpApiPath)) {
if (!process.versions.pnp) {
// Setup the environment to be able to require typescript/lib/typescript.js
require(absPnpApiPath).setup();
}
}
// Defer to the real typescript/lib/typescript.js your application uses
module.exports = absRequire(`typescript/lib/typescript.js`);

View File

@ -1,6 +0,0 @@
{
"name": "typescript",
"version": "4.4.4-sdk",
"main": "./lib/typescript.js",
"type": "commonjs"
}

View File

@ -1,3 +0,0 @@
nodeLinker: pnp
yarnPath: .yarn/releases/yarn-3.6.0.cjs

View File

@ -1,22 +1,21 @@
# CONTRIBUTING Guide
## About VelaUX
The [KubeVela](https://github.com/oam-dev/kubevela) User Experience (UX) Dashboard. Designed as an extensible, application-oriented delivery platform.
## About velacp
KubeVela control plane (velacp) includes the UI/CLI and HTTP server components to provide application and cluster management experience based on KubeVela & K8s.
To help us create a safe and positive community experience for all, we require all participants to adhere to the [Code of Conduct](https://github.com/oam-dev/kubevela/blob/master/CODE_OF_CONDUCT.md).
This document is a guide to help you through the process of contributing to VelaUX.
This document is a guide to help you through the process of contributing to velacp.
## Become a contributor
You can contribute to VelaUX in several ways. Here are some examples:
You can contribute to velacp in several ways. Here are some examples:
* Contribute to the VelaUX codebase.
* Contribute to the velacp codebase.
* Report and triage bugs.
* Write technical documentation and blog posts, for users and contributors.
* Organize meetups and user groups in your local area.
* Help others by answering questions about VelaUX.
* Help others by answering questions about velacp.
For more ways to contribute, check out the [Open Source Guides](https://opensource.guide/how-to-contribute/).
@ -24,13 +23,13 @@ For more ways to contribute, check out the [Open Source Guides](https://opensour
Unsure where to begin contributing to KubeVela? Start by browsing issues labeled `good first issue` or `help wanted`.
- [Good first issue](https://github.com/oam-dev/velaux/labels/good%20first%20issue) issues are generally straightforward to complete.
- [Help wanted](https://github.com/oam-dev/velaux/labels/help%20wanted) issues are problems we would like the community to help us with regardless of complexity.
- [Good first issue](https://github.com/oam-dev/velacp/labels/good%20first%20issue) issues are generally straightforward to complete.
- [Help wanted](https://github.com/oam-dev/velacp/labels/help%20wanted) issues are problems we would like the community to help us with regardless of complexity.
If you're looking to make a code change, see [how to set up your environment](docs/contributing/velaux.md).
If you're looking to make a code change, see how to set up your environment for [frontend development](docs/contributing/frontend.md) and [backend development](docs/contributing/backend.md).
When you're ready to contribute, it's time to [Create a pull request](https://github.com/oam-dev/kubevela/blob/master/contribute/create-pull-request.md).
### Report bugs / Suggest enhancements / Answering questions etc.
VelaUX follows the KubeVela [CONTRIBUTING Guide](https://github.com/oam-dev/kubevela/blob/master/CONTRIBUTING.md)
velacp follows the KubeVela [CONTRIBUTING Guide](https://github.com/oam-dev/kubevela/blob/master/CONTRIBUTING.md)

View File

@ -1,17 +1,6 @@
ARG BASE_IMAGE
FROM node:16-alpine as ui-builder
ARG VERSION
WORKDIR /app/velaux
ADD . .
ENV VERSION=${VERSION}
RUN apk add --no-cache git make clang build-base python3
RUN yarn install && yarn build
# Build the manager binary
FROM --platform=${BUILDPLATFORM:-linux/amd64} golang:1.19-alpine@sha256:2381c1e5f8350a901597d633b2e517775eeac7a6682be39225a93b22cfd0f8bb as server-builder
ARG GOPROXY
ENV GOPROXY=${GOPROXY:-https://goproxy.cn}
FROM golang:1.15 as builder
WORKDIR /workspace
# Copy the Go Modules manifests
COPY go.mod go.mod
@ -20,28 +9,19 @@ COPY go.sum go.sum
# and so that source changes don't invalidate our downloaded layer
RUN go mod download
# Copy the go source for building server
COPY cmd/server/ cmd/server/
COPY pkg/ pkg/
# Copy the go source
COPY main.go main.go
COPY api/ api/
COPY controllers/ controllers/
# Build
ARG TARGETARCH
ARG VERSION
ARG GITVERSION
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 GO111MODULE=on go build -a -o manager main.go
RUN GO111MODULE=on CGO_ENABLED=0 GOOS=linux GOARCH=${TARGETARCH} \
go build -a -ldflags "-s -w -X github.com/oam-dev/kubevela/version.VelaVersion=${VERSION:-undefined} -X github.com/oam-dev/kubevela/version.GitRevision=${GITVERSION:-undefined}" \
-o apiserver-${TARGETARCH} cmd/server/main.go
# Use distroless as minimal base image to package the manager binary
# Refer to https://github.com/GoogleContainerTools/distroless for more details
FROM gcr.io/distroless/static:nonroot
WORKDIR /
COPY --from=builder /workspace/manager .
USER nonroot:nonroot
FROM ${BASE_IMAGE:-alpine@sha256:e2e16842c9b54d985bf1ef9242a313f36b856181f188de21313820e177002501}
# This is required by daemon connecting with cri
RUN apk add --no-cache ca-certificates bash expat
WORKDIR /app/velaux
ARG TARGETARCH
ENV PATH=$PATH:/app/velaux
COPY --from=server-builder /workspace/apiserver-${TARGETARCH} /app/velaux/server
COPY --from=ui-builder /app/velaux/public /app/velaux/public
CMD ["server"]
ENTRYPOINT ["/manager"]

View File

@ -1,49 +0,0 @@
ARG BASE_IMAGE
FROM node:16-alpine as ui-builder
ARG VERSION
WORKDIR /app/velaux
ADD . .
ENV VERSION=${VERSION}
RUN apk add --no-cache git
RUN yarn install && yarn build && yarn packages:plugins
# Build the manager binary
FROM --platform=${BUILDPLATFORM:-linux/amd64} golang:1.19-alpine@sha256:2381c1e5f8350a901597d633b2e517775eeac7a6682be39225a93b22cfd0f8bb as server-builder
ARG GOPROXY
ENV GOPROXY=${GOPROXY:-https://goproxy.cn}
WORKDIR /workspace
# Copy the Go Modules manifests
COPY go.mod go.mod
COPY go.sum go.sum
# cache deps before building and copying source so that we don't need to re-download as much
# and so that source changes don't invalidate our downloaded layer
RUN go mod download
# Copy the go source for building server
COPY cmd/server/ cmd/server/
COPY pkg/ pkg/
# Build
ARG TARGETARCH
ARG VERSION
ARG GITVERSION
RUN GO111MODULE=on CGO_ENABLED=0 GOOS=linux GOARCH=${TARGETARCH} \
go build -a -ldflags "-s -w -X github.com/oam-dev/kubevela/version.VelaVersion=${VERSION:-undefined} -X github.com/oam-dev/kubevela/version.GitRevision=${GITVERSION:-undefined}" \
-o apiserver-${TARGETARCH} cmd/server/main.go
FROM ${BASE_IMAGE:-alpine@sha256:e2e16842c9b54d985bf1ef9242a313f36b856181f188de21313820e177002501}
# This is required by daemon connecting with cri
RUN apk add --no-cache ca-certificates bash expat
WORKDIR /app/velaux
ARG TARGETARCH
ENV PATH=$PATH:/app/velaux
COPY --from=server-builder /workspace/apiserver-${TARGETARCH} /app/velaux/server
COPY --from=ui-builder /app/velaux/public /app/velaux/public
COPY --from=ui-builder /app/velaux/plugins/app-demo/dist /app/velaux/plugins/app-demo
COPY --from=ui-builder /app/velaux/plugins/node-dashboard/dist /app/velaux/plugins/node-dashboard
CMD ["server"]

View File

@ -1,38 +0,0 @@
ARG BASE_IMAG
# Build the manager binary
FROM --platform=${BUILDPLATFORM:-linux/amd64} golang:1.19-alpine@sha256:2381c1e5f8350a901597d633b2e517775eeac7a6682be39225a93b22cfd0f8bb as server-builder
ARG GOPROXY
ENV GOPROXY=${GOPROXY:-https://goproxy.cn}
WORKDIR /workspace
# Copy the Go Modules manifests
COPY go.mod go.mod
COPY go.sum go.sum
# cache deps before building and copying source so that we don't need to re-download as much
# and so that source changes don't invalidate our downloaded layer
COPY vendor vendor
# Copy the go source for building server
COPY cmd/server/ cmd/server/
COPY pkg/ pkg/
# Build
ARG TARGETARCH
ARG VERSION
ARG GITVERSION
RUN GO111MODULE=on CGO_ENABLED=0 GOOS=linux GOARCH=${TARGETARCH} \
go build -a -ldflags "-s -w -X github.com/oam-dev/kubevela/version.VelaVersion=${VERSION:-undefined} -X github.com/oam-dev/kubevela/version.GitRevision=${GITVERSION:-undefined}" \
-o apiserver-${TARGETARCH} cmd/server/main.go
FROM ${BASE_IMAGE:-alpine@sha256:e2e16842c9b54d985bf1ef9242a313f36b856181f188de21313820e177002501}
# This is required by daemon connecting with cri
RUN apk add --no-cache ca-certificates bash expat
WORKDIR /app/velaux
ARG TARGETARCH
ENV PATH=$PATH:/app/velaux
COPY --from=server-builder /workspace/apiserver-${TARGETARCH} /app/velaux/server
COPY ./public /app/velaux/public
CMD ["server"]

203
Makefile
View File

@ -1,24 +1,103 @@
include makefiles/const.mk
include makefiles/build.mk
# VelaCP version
VELA_CP_VERSION ?= master
# Repo info
GIT_COMMIT ?= git-$(shell git rev-parse --short HEAD)
all: docker-build
ERR = echo ${TIME} ${RED}[FAIL]${CNone}
OK = echo ${TIME} ${GREEN}[ OK ]${CNone}
.PHONY: golangci
golangci:
ifeq ($(shell $(GLOBAL_GOLANGCILINT) version --format short), $(GOLANGCILINT_VERSION))
@$(OK) golangci-lint is already installed
GOLANGCILINT=$(GLOBAL_GOLANGCILINT)
else ifeq ($(shell $(GOBIN_GOLANGCILINT) version --format short), $(GOLANGCILINT_VERSION))
@$(OK) golangci-lint is already installed
GOLANGCILINT=$(GOBIN_GOLANGCILINT)
PROJECT_VERSION_VAR := github.com/oam-dev/velacp/pkg/version.Version
PROJECT_GITVERSION_VAR := github.com/oam-dev/velacp/pkg/version.GitRevision
LDFLAGS ?= "-X $(PROJECT_VERSION_VAR)=$(PROJECT_VERSION) -X $(PROJECT_GITVERSION_VAR)=$(GIT_COMMIT)"
GOX = go run github.com/mitchellh/gox
TARGETS := darwin/amd64 linux/amd64 windows/amd64
DIST_DIRS := find * -type d -maxdepth 0 -exec
# Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set)
ifeq (,$(shell go env GOBIN))
GOBIN=$(shell go env GOPATH)/bin
else
GOBIN=$(shell go env GOBIN)
endif
all: build
build: build-ui build-cp
build-ui:
cd ui/ && yarn build && cd ..
build-cp:
go build -o _bin/velacp ./cmd/velacp/main.go
build-cli:
go build -o _bin/velactl ./cmd/velactl/main.go
cross-build:
GO111MODULE=on CGO_ENABLED=0 $(GOX) -ldflags $(LDFLAGS) -parallel=2 -output="_bin/{{.OS}}-{{.Arch}}/velacp" -osarch="$(TARGETS)" ./cmd/velacp/
compress:
( \
echo "\n## Release Info\nVERSION: $(PROJECT_VERSION)" >> README.md && \
echo "GIT_COMMIT: $(GIT_COMMIT_LONG)\n" >> README.md && \
cd _bin && \
$(DIST_DIRS) cp -r ../ui/dist {} \; && \
$(DIST_DIRS) cp ../LICENSE {} \; && \
$(DIST_DIRS) cp ../README.md {} \; && \
$(DIST_DIRS) tar -zcf velacp-{}.tar.gz {} \; && \
$(DIST_DIRS) zip -r velacp-{}.zip {} \; && \
sha256sum velacp-* > sha256sums.txt \
)
proto:
hack/gen_proto.sh
# Run tests
test: fmt vet
go test ./pkg/... ./cmd/...
# Run go fmt against code
fmt:
go fmt ./pkg/... ./cmd/...
# Run go vet against code
vet:
go vet ./pkg/... ./cmd/...
reviewable: fmt vet lint staticcheck
go mod tidy
# Execute auto-gen code commands and ensure branch is clean.
check-diff: reviewable
git --no-pager diff
git diff --quiet || ($(ERR) please run 'make reviewable' to include all changes && false)
@$(OK) branch is clean
run: build-cp
_bin/velacp server \
--db-url=${MONGO_URL} \
--db-name=vela
staticcheck: staticchecktool
$(STATICCHECK) ./...
lint: golangci
$(GOLANGCILINT) run ./...
GOLANGCILINT_VERSION ?= v1.31.0
golangci:
ifeq (, $(shell which golangci-lint))
@{ \
set -e ;\
echo 'installing golangci-lint-$(GOLANGCILINT_VERSION)' ;\
curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(GOBIN) v$(GOLANGCILINT_VERSION) ;\
echo 'Successfully installed' ;\
curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(GOBIN) $(GOLANGCILINT_VERSION) ;\
echo 'Install succeed' ;\
}
GOLANGCILINT=$(GOBIN)/golangci-lint
else
GOLANGCILINT=$(shell which golangci-lint)
endif
.PHONY: staticchecktool
@ -27,105 +106,9 @@ ifeq (, $(shell which staticcheck))
@{ \
set -e ;\
echo 'installing honnef.co/go/tools/cmd/staticcheck ' ;\
go install honnef.co/go/tools/cmd/staticcheck@v0.4.7 ;\
GO111MODULE=off go get honnef.co/go/tools/cmd/staticcheck ;\
}
STATICCHECK=$(GOBIN)/staticcheck
else
STATICCHECK=$(shell which staticcheck)
endif
.PHONY: goimports
goimports:
ifeq (, $(shell which goimports))
@{ \
set -e ;\
go install golang.org/x/tools/cmd/goimports@6546d82b229aa5bd9ebcc38b09587462e34b48b6 ;\
}
GOIMPORTS=$(GOBIN)/goimports
else
GOIMPORTS=$(shell which goimports)
endif
.PHONY: e2e-setup-core
e2e-setup-core: install-vela install-core install-addon
.PHONY: install-vela
install-vela:
curl -fsSl https://kubevela.io/script/install.sh | bash -s v1.9.0-alpha.3
install-core:
vela install -v v1.9.0-alpha.2 -y
install-addon:
vela addon enable fluxcd
vela addon enable vela-workflow --override-definitions
kubectl wait --for=condition=Ready pod -l app=source-controller -n flux-system --timeout=600s
kubectl wait --for=condition=Ready pod -l app=helm-controller -n flux-system --timeout=600s
kubectl wait --for=condition=Ready pod -l app.kubernetes.io/name=vela-workflow -n vela-system --timeout=600s
start-addon-mock-server:
go run ./e2e-test/addon &
load-image:
k3d image import oamdev/velaux:latest || { echo >&2 "kind not installed or error loading image: $(VELA_CORE_TEST_IMAGE)"; exit 1; }
enable-addon-no-replicas:
vela addon enable ./addon replicas=0
enable-addon:
vela addon enable ./addon
.PHONY: e2e-server-test
e2e-server-test:
go test -v -coverpkg=./... -coverprofile=/tmp/e2e_apiserver_test.out ./e2e-test
@$(OK) tests pass
unit-test-server:
go test -gcflags=all=-l -coverprofile=coverage.txt $(shell go list ./pkg/... ./cmd/...)
setup-test-server:
curl -L -o kubebuilder https://go.kubebuilder.io/dl/latest/$(shell go env GOOS)/$(shell go env GOARCH)
chmod +x kubebuilder
sudo mv kubebuilder /usr/local/bin/
go install sigs.k8s.io/controller-runtime/tools/setup-envtest@latest
${eval OUTPUT = $(shell ${GOBIN}/setup-envtest --bin-dir /tmp use)}
${eval BIN_PATH=$(lastword $(subst Path:, ,${OUTPUT}))}
sudo mkdir -p /usr/local/kubebuilder/bin
sudo mv ${BIN_PATH}/* /usr/local/kubebuilder/bin
build-swagger:
go run ./cmd/server/main.go build-swagger ./docs/apidoc/swagger.json
lint: golangci
@$(INFO) lint
@$(GOLANGCILINT) run --timeout 5m
vet:
@$(INFO) go vet
@go vet $(shell go list ./...)
fmt: goimports
go fmt ./...
$(GOIMPORTS) -local github.com/kubevela/velaux -w $$(go list -f {{.Dir}} ./...)
staticcheck: staticchecktool
@$(INFO) staticcheck
@$(STATICCHECK) $(shell go list ./...)
mod:
go mod tidy
reviewable: mod fmt vet staticcheck lint
# Execute auto-gen code commands and ensure branch is clean.
check-diff: reviewable
git --no-pager diff
git diff --quiet || ($(ERR) please run 'make reviewable' to include all changes && false)
@$(OK) branch is clean
run-server:
go run ./cmd/server/main.go
build-ui:
@$(INFO) Building UI
yarn build
build-test-image: build-ui
@$(INFO) Building image
docker build -t velaux:latest -f Dockerfile.local .

9
OWNERS
View File

@ -1,8 +1,3 @@
owners:
- barnettZQG
approvers:
emeritus-members:
- wangbow
- hanxie-crypto
- hongchaodeng
- sunny0826

22
PROJECT Normal file
View File

@ -0,0 +1,22 @@
domain: velacp.oam.dev
repo: github.com/oam-dev/velacp
resources:
- group: velacp.oam.dev
kind: Environment
version: v1alpha1
- group: velacp.oam.dev
kind: Application
version: v1alpha1
- group: velacp.oam.dev
kind: Cluster
version: v1alpha1
- group: velacp.oam.dev
kind: Catalog
version: v1alpha1
- group: velacp.oam.dev
kind: Package
version: v1alpha1
- group: velacp.oam.dev
kind: AppTemplate
version: v1alpha1
version: "2"

101
README.md
View File

@ -1,90 +1,47 @@
![alt](docs/images/KubeVela-03.png)
# velacp
[![Go Report Card](https://goreportcard.com/badge/github.com/kubevela/velaux)](https://goreportcard.com/report/github.com/kubevela/velaux)
![Docker Pulls](https://img.shields.io/docker/pulls/oamdev/velaux)
KubeVela control plane (velacp) includes the UI/CLI and HTTP server components to provide application and cluster management experience based on KubeVela & K8s.
## Overview
## Architecture
[VelaUX](https://github.com/kubevela/velaux) is a web portal for KubeVela end users, and also functions as an opinionated application delivery platform. Additionally, it operates as a highly adaptable plugin framework, empowering developers to create bespoke plugins and smoothly integrate them into the KubeVela platform. This approach delivers unparalleled flexibility and customization options for scaling up the platform's capabilities.
This project is based on the following tech stacks:
### Highlights
- [Protobuf](https://developers.google.com/protocol-buffers/docs/gotutorial)
- Golang and [Echo](https://echo.labstack.com/)
- React and [Ant Design Pro](https://pro.ant.design/)
- Mongodb
*Customizable User Interface*: With VelaUX, enterprises can tailor the user interface to their specific needs for managing applications and infrastructure. This feature leads to a more intuitive and efficient user experience, resulting in increased productivity and better resource utilization.
![alt](docs/images/velacp-arch.png)
*Easy Integration*: VelaUX is designed for seamless integration with the KubeVela platform, simplifying the deployment and management of cloud-native atomic capabilities within the platform. This makes it easier for enterprises to build platforms that meet their needs for continuous application delivery, observability, security, and other requirements based on these cloud-native atomic capabilities.
## Quickstart
*Out-of-Box Platform*: VelaUX provides a comprehensive set of features that empower enterprises to deploy and monitor their applications effectively. These features include multi-cluster and multi-environment support, pipeline management, observability, and more. Additionally, VelaUX streamlines the complexities of Kubernetes, making it simpler for users to manage their deployments.
Build cli and server binaries:
## Quick Start
### Users
Please refer to this guide to install: [https://kubevela.net/docs/install](https://kubevela.net/docs/install)
### Developers
#### Build the frontend
Make sure you have installed [yarn 2.0](https://yarnpkg.com/getting-started/install), This is required.
Install frontend dependencies and build the frontend.
```shell
yarn install
yarn build
```
mkdir -p _bin/
make
```
#### Start the server
Setup a mongodb instance. Check the [official doc](https://docs.mongodb.com/guides/server/install/).
1. Install the Go 1.19+.
2. Prepare a KubeVela core environment.
Start velacp server:
```shell
## Linux or Mac
curl -fsSl https://static.kubevela.net/script/install-velad.sh | bash
## Windows
powershell -Command "iwr -useb https://static.kubevela.net/script/install-velad.ps1 | iex"
```bash
_bin/velacp server \
--db-url=${MONGO_URL} \
--db-name=vela
```
velad install
```
The dashboard will be served at http://localhost:8000 .
3. Init the dependencies.
### Cluster
```shell
vela addon enable ./addon replicas=0
```
![alt](docs/images/cluster-list.png)
![alt](docs/images/cluster-detail.png)
4. Start the server on local
### Application
```shell
# Install all dependencies
go mod tidy
![alt](docs/images/app-list.png)
![alt](docs/images/app-input.png)
![alt](docs/images/app-detail.png)
# Setting the kube config
export KUBECONFIG=$(velad kubeconfig --host)
# Start the server
make run-server
```
Then, you can open the http://127.0.0.1:8000. More info refer to [contributing](./docs/contributing/velaux.md)
## Community
- Slack: [CNCF Slack](https://slack.cncf.io/) #kubevela channel (*English*)
- [DingTalk Group](https://page.dingtalk.com/wow/dingtalk/act/en-home): `23310022` (*Chinese*)
- Wechat Group (*Chinese*) : Broker wechat to add you into the user group.
<img src="https://static.kubevela.net/images/barnett-wechat.jpg" width="200" />
## Contributing
Check out [CONTRIBUTING](./CONTRIBUTING.md) to see how to develop with KubeVela.
## Report Vulnerability
Security is a first priority thing for us at KubeVela. If you come across a related issue, please send email to security@mail.kubevela.io .
## Code of Conduct
KubeVela adopts [CNCF Code of Conduct](https://github.com/cncf/foundation/blob/master/code-of-conduct.md).

View File

@ -1,8 +0,0 @@
info: """
To open the dashboard directly by port-forward:
vela port-forward -n vela-system addon-velaux 8000:8000
Please refer to https://kubevela.io/docs/reference/addons/velaux for more VelaUX addon installation and visiting method.
"""
notes: (info)

View File

@ -1,77 +0,0 @@
import (
"encoding/base64"
"encoding/json"
"strconv"
"vela/config"
)
metadata: {
name: "image-registry"
alias: "Image Registry"
scope: "project"
description: "Config information to authenticate image registry"
sensitive: false
}
template: {
output: {
apiVersion: "v1"
kind: "Secret"
metadata: {
name: context.name
namespace: context.namespace
labels: {
"config.oam.dev/catalog": "velacore-config"
"config.oam.dev/type": "image-registry"
}
}
if parameter.auth != _|_ {
type: "kubernetes.io/dockerconfigjson"
}
if parameter.auth == _|_ {
type: "Opaque"
}
stringData: {
if parameter.auth != _|_ && parameter.auth.username != _|_ {
".dockerconfigjson": json.Marshal({
"auths": (parameter.registry): {
"username": parameter.auth.username
"password": parameter.auth.password
if parameter.auth.email != _|_ {
"email": parameter.auth.email
}
"auth": base64.Encode(null, (parameter.auth.username + ":" + parameter.auth.password))
}
})
}
if parameter.insecure != _|_ {
"insecure-skip-verify": strconv.FormatBool(parameter.insecure)
}
if parameter.useHTTP != _|_ {
"protocol-use-http": strconv.FormatBool(parameter.useHTTP)
}
}
}
validation: config.#ImageRegistry & {
$params: parameter
}
parameter: {
// +usage=Image registry FQDN, such as: index.docker.io
registry: *"index.docker.io" | string
// +usage=Authenticate the image registry
auth?: {
// +usage=Private Image registry username
username: string
// +usage=Private Image registry password
password: string
// +usage=Private Image registry email
email?: string
}
// +usage=For the registry server that uses the self-signed certificate
insecure?: bool
// +usage=For the registry server that uses the HTTP protocol
useHTTP?: bool
}
}

View File

@ -1,56 +0,0 @@
metadata: {
name: "nacos-config"
alias: "Nacos Configuration"
description: "Write the configuration to the nacos"
sensitive: false
scope: "system"
}
template: {
nacos: {
// The endpoint can not references the parameter.
endpoint: {
// Users must create a config base the nacos-server template firstly.
name: "nacos"
}
format: parameter.contentType
// could references the parameter
metadata: {
dataId: parameter.dataId
group: parameter.group
if parameter.appName != _|_ {
appName: parameter.appName
}
if parameter.namespaceId != _|_ {
namespaceId: parameter.namespaceId
}
if parameter.tenant != _|_ {
tenant: parameter.tenant
}
if parameter.tag != _|_ {
tag: parameter.tag
}
}
content: parameter.content
}
parameter: {
// +usage=Configuration ID
dataId: string
// +usage=Configuration group
group: *"DEFAULT_GROUP" | string
// +usage=The configuration content.
content: {
...
}
contentType: *"json" | "yaml" | "properties" | "toml"
// +usage=The app name of the configuration
appName?: string
// +usage=The namespaceId of the configuration
namespaceId?: string
// +usage=The tenant, corresponding to the namespace ID field of Nacos
tenant?: string
// +usage=The tag of the configuration
tag?: string
}
}

View File

@ -1,38 +0,0 @@
metadata: {
name: "nacos-server"
alias: "Nacos Server"
description: "Config the Nacos server connectors"
sensitive: false
scope: "system"
}
template: {
parameter: {
// +usage=Directly configure the Nacos server address
servers?: [...{
// +usage=the nacos server address
ipAddr: string
// +usage=nacos server port
port: *8849 | int
// +usage=nacos server grpc port, default=server port + 1000, this is not required
grpcPort?: int
}]
// +usage=Discover the Nacos servers by the client.
client?: {
// +usage=the endpoint for get Nacos server addresses
endpoint: string
// +usage=the AccessKey for kms
accessKey?: string
// +usage=the SecretKey for kms
secretKey?: string
// +usage=the regionId for kms
regionId?: string
// +usage=the username for nacos auth
username?: string
// +usage=the password for nacos auth
password?: string
// +usage=it's to open kms,default is false. https://help.aliyun.com/product/28933.html
openKMS?: bool
}
}
}

View File

@ -1,16 +0,0 @@
name: velaux
version: v1.8.0-rc.3
description: KubeVela User Experience (UX). An extensible, application-oriented delivery and management Platform.
icon: https://static.kubevela.net/images/logos/KubeVela%20-03.png
url: https://kubevela.io
tags:
- Official
- Dashboard
deployTo:
controlPlane: true
runtimeCluster: false
system:
vela: ">=v1.6.0"

View File

@ -1,28 +0,0 @@
parameter: {
// +usage=Specify the image hub of velaux, eg. "acr.kubevela.net"
repo?: string
// +usage=Specify the database type, current support KubeAPI(default) and MongoDB.
dbType: *"kubeapi" | "mongodb"
// +usage=Specify the database name, for the kubeapi db type, it represents namespace.
database?: string
// +usage=Specify the MongoDB URL. it only enabled where DB type is MongoDB.
dbURL?: string
// +usage=Specify the domain, if set, ingress will be created if the gateway driver is nginx.
domain?: string
// +usage=Specify the name of the certificate cecret, if set, means enable the HTTPs.
secretName?: string
// +usage=Specify the gateway type.
gatewayDriver: *"nginx" | "traefik"
// +usage=Specify the serviceAccountName for apiserver
serviceAccountName: *"kubevela-ux" | string
// +usage=Specify the service type.
serviceType: *"ClusterIP" | "NodePort" | "LoadBalancer"
// +usage=Specify the names of imagePullSecret for private image registry, eg. "{a,b,c}"
imagePullSecrets?: [...string]
// +usage=Specify the replicas.
replicas: *1 | int
// +usage=Specify nodeport. This will be ignored if serviceType is not NodePort.
nodePort: *30000 | int
// +usage=Enable impersonation means impersonating the login user to request the KubeAPI.
enableImpersonation: true | *false
}

View File

@ -1,20 +0,0 @@
# VelaUX
VelaUX provides end-to-end application delivery and management experience, including API services and UI dashboard.
## Installation
There are the following precautions
1. If you are used in production, please configure the MongoDB database.
2. Configure the Domain parameter to generate Ingress resources, otherwise, only Service resources will be generated.
## Feedback
If you have any questions or feedback during use, please contact us through the following methods.
- Create Issue: [https://github.com/oam-dev/velaux/issues](https://github.com/oam-dev/velaux/issues)
- Slack: [CNCF Slack](https://slack.cncf.io/) #kubevela channel (_English_)
- Join DingTalk Group: 23310022
- Join Wechat Group: Broker wechat to add you into the user group.
<img src="https://static.kubevela.net/images/barnett-wechat.jpg" width="200" />

View File

@ -1,17 +0,0 @@
# VelaUX 介绍
VelaUX 提供端到端的应用交付和管理体验,其中包括了 API 服务和 UI 控制面板。
## 安装说明
1. 如果是生产使用,建议配置 MongoDB 数据库。
2. 配置 Domain 参数即可生成 Ingress 资源,否则只会生成 Service 资源。
## 使用反馈
您在使用过程中有任何疑问或反馈,请通过以下方式与我们取得联系。
- 提交 Issue: [https://github.com/oam-dev/velaux/issues](https://github.com/oam-dev/velaux/issues)
- 加入钉钉群: 23310022
- 加入微信群: 添加管理员微信并注明反馈 VelaUX 问题
<img src="https://static.kubevela.net/images/barnett-wechat.jpg" width="200" />

View File

@ -1,50 +0,0 @@
package main
additionalPrivileges: {
type: "k8s-objects"
name: "velaux-additional-privileges"
properties: objects: [
{
apiVersion: "rbac.authorization.k8s.io/v1"
kind: "ClusterRoleBinding"
metadata: name: "clustergateway:kubevela:ux"
roleRef: {
apiGroup: "rbac.authorization.k8s.io"
kind: "ClusterRole"
name: "cluster-admin"
}
subjects: [{
kind: "Group"
name: "kubevela:ux"
apiGroup: "rbac.authorization.k8s.io"
}, {
kind: "ServiceAccount"
name: parameter["serviceAccountName"]
namespace: "vela-system"
}]
},
{
apiVersion: "v1"
kind: "ServiceAccount"
metadata: {
name: parameter["serviceAccountName"]
namespace: "vela-system"
}
secrets: [
{
name: parameter["serviceAccountName"] + "-token"
},
]
},
{
apiVersion: "v1"
kind: "Secret"
metadata: {
name: parameter["serviceAccountName"] + "-token"
namespace: "vela-system"
annotations: "kubernetes.io/service-account.name": parameter["serviceAccountName"]
}
type: "kubernetes.io/service-account-token"
},
]
}

View File

@ -1,94 +0,0 @@
package main
_version: context.metadata.version
database: *[ if parameter["database"] != _|_ {
"--datastore-database=" + parameter["database"]
}] | []
dbURL: *[ if parameter["dbURL"] != _|_ {
"--datastore-url=" + parameter["dbURL"]
}] | []
enableImpersonation: *[ if parameter["enableImpersonation"] {
"--feature-gates=EnableImpersonation=true"
}] | []
_nginxTrait: *[
if parameter["domain"] != _|_ && parameter["gatewayDriver"] == "nginx" {
{
type: "gateway"
properties: {
domain: parameter["domain"]
http: {
"/": 8000
}
class: "nginx"
}
}
},
] | []
_traefikTrait: *[
if parameter["domain"] != _|_ && parameter["gatewayDriver"] == "traefik" {
{
type: "http-route"
properties: {
domains: [ parameter["domain"]]
rules: [{port: 8000}]
}
}
},
] | []
_httpsTrait: *[ if parameter["secretName"] != _|_ && parameter["domain"] != _|_ && parameter["gatewayDriver"] == "traefik" {
type: "https-route"
properties: {
domains: [ parameter["domain"]]
rules: [{port: 8000}]
secrets: [{
name: parameter["secretName"]
}]
}}] | []
server: {
name: "velaux-server"
type: "webservice"
properties: {
if parameter["repo"] == _|_ {
image: "oamdev/velaux:" + _version
}
if parameter["repo"] != _|_ {
image: parameter["repo"] + "/" + "oamdev/velaux:" + _version
}
if parameter["imagePullSecrets"] != _|_ {
imagePullSecrets: parameter["imagePullSecrets"]
}
if parameter["serviceType"] != _|_ {
exposeType: parameter["serviceType"]
}
cmd: ["server", "--datastore-type=" + parameter["dbType"], "--feature-gates=EnableCacheJSFile=true"] + database + dbURL + enableImpersonation
ports: [
{
port: 8000
protocol: "TCP"
expose: true
if parameter["serviceType"] == "NodePort" {
nodePort: parameter["nodePort"]
}
},
]
}
dependsOn: ["velaux-additional-privileges"]
traits: [
{
type: "service-account"
properties: name: parameter["serviceAccountName"]
},
{type: "scaler", properties: replicas: parameter["replicas"]},
] + _nginxTrait + _traefikTrait + _httpsTrait
}

View File

@ -1,37 +0,0 @@
- jsonKey: dbType
label: DBType
validate:
required: true
defaultValue: kubeapi
options:
- label: MongoDB
value: mongodb
- label: KubeAPI
value: kubeapi
sort: 1
- jsonKey: dbURL
label: DatabaseURL
sort: 3
conditions:
- jsonKey: dbType
op: "=="
value: "mongodb"
validate:
required: true
- jsonKey: database
sort: 7
validate:
defaultValue: kubevela
required: true
- jsonKey: serviceAccountName
disable: true
- jsonKey: serviceType
sort: 8
- jsonKey: domain
sort: 9
- jsonKey: gatewayDriver
sort: 10
- jsonKey: repo
sort: 11
- jsonKey: imagePullSecrets
sort: 13

View File

@ -1,2 +0,0 @@
- jsonKey: objects
uiType: K8sObjectsCode

View File

@ -1,223 +0,0 @@
- uiType: ImageInput
jsonKey: image
label: Image
sort: 1
- jsonKey: imagePullSecret
sort: 2
disable: true
- jsonKey: restart
sort: 3
uiType: Select
validate:
required: true
defaultValue: Never
options:
- label: Never
value: Never
- label: OnFailure
value: OnFailure
- jsonKey: count
sort: 4
uiType: Number
validate:
required: true
defaultValue: 1
min: 0
max: 128
- jsonKey: memory
uiType: MemoryNumber
sort: 5
label: Memory
description: Specifies the memory resource required for the container, If set to 0, there is no limit.
validate:
required: true
defaultValue: "1024Mi"
style:
colSpan: 12
- jsonKey: cpu
uiType: CPUNumber
sort: 7
label: CPU
description: Specifies the cpu resource required for the container, If set to 0, there is no limit.
validate:
required: true
defaultValue: "0.5"
style:
colSpan: 12
- jsonKey: cmd
label: CMD
sort: 9
- jsonKey: env
sort: 10
label: ENV
subParameterGroupOption:
- label: Add By Value
keys:
- name
- value
- label: Add By Secret
keys:
- name
- valueFrom
subParameters:
- jsonKey: valueFrom
label: Secret Selector
uiType: Ignore
subParameters:
- jsonKey: configMapKeyRef
disable: true
- jsonKey: secretKeyRef
uiType: Ignore
subParameters:
- jsonKey: name
label: Secret Name
uiType: SecretSelect
sort: 1
- jsonKey: key
label: Secret Key
uiType: SecretKeySelect
sort: 3
uiType: Structs
- jsonKey: readinessProbe
uiType: Group
label: ReadinessProbe
subParameters:
- jsonKey: hostAliases
disable: true
- jsonKey: timeoutSeconds
sort: 1
style:
colSpan: 12
- jsonKey: failureThreshold
sort: 4
style:
colSpan: 12
- jsonKey: initialDelaySeconds
sort: 7
style:
colSpan: 12
validate:
defaultValue: 5
required: true
- jsonKey: periodSeconds
sort: 9
style:
colSpan: 12
- jsonKey: successThreshold
sort: 11
style:
colSpan: 12
- jsonKey: exec
sort: 14
- jsonKey: httpGet
sort: 19
subParameters:
- jsonKey: port
sort: 1
validate:
required: true
min: 1
style:
colSpan: 12
- jsonKey: path
sort: 3
validate:
required: true
pattern: ^/(.*)$
style:
colSpan: 12
- jsonKey: httpHeaders
sort: 5
- jsonKey: tcpSocket
sort: 19
subParameters:
- jsonKey: port
validate:
required: true
min: 1
sort: 13
- jsonKey: livenessProbe
uiType: Group
label: LivenessProbe
subParameters:
- jsonKey: hostAliases
disable: true
- jsonKey: timeoutSeconds
sort: 1
style:
colSpan: 12
- jsonKey: failureThreshold
sort: 4
style:
colSpan: 12
- jsonKey: initialDelaySeconds
sort: 7
style:
colSpan: 12
validate:
defaultValue: 5
required: true
- jsonKey: periodSeconds
sort: 9
style:
colSpan: 12
- jsonKey: successThreshold
sort: 11
style:
colSpan: 12
- jsonKey: exec
sort: 14
- jsonKey: httpGet
sort: 19
subParameters:
- jsonKey: port
sort: 1
validate:
required: true
min: 1
style:
colSpan: 12
- jsonKey: path
sort: 3
validate:
required: true
pattern: ^/(.*)$
style:
colSpan: 12
- jsonKey: httpHeaders
sort: 5
- jsonKey: tcpSocket
sort: 19
subParameters:
- jsonKey: port
validate:
required: true
min: 1
sort: 15
- jsonKey: annotations
sort: 19
- jsonKey: labels
sort: 21
- description: Specify image pull policy for your service
jsonKey: imagePullPolicy
label: Image Pull Policy
uiType: Select
sort: 24
validate:
defaultValue: IfNotPresent
options:
- label: IfNotPresent
value: IfNotPresent
- label: Always
value: Always
- label: Never
value: Never
- jsonKey: volumes
disable: true

View File

@ -1,301 +0,0 @@
- uiType: ImageInput
jsonKey: image
label: Container Image
sort: 1
- jsonKey: imagePullSecret
sort: 2
disable: true
- jsonKey: memory
uiType: MemoryNumber
sort: 4
label: Memory
description: Specifies the memory resource required for the container, If set to 0, there is no limit.
validate:
required: true
defaultValue: "1024Mi"
style:
colSpan: 12
- jsonKey: cpu
uiType: CPUNumber
sort: 5
label: CPU
description: Specifies the cpu resource required for the container, If set to 0, there is no limit.
validate:
required: true
defaultValue: "0.5"
style:
colSpan: 12
- jsonKey: exposeType
sort: 6
validate:
- jsonKey: ports
label: Service Ports
sort: 7
subParameters:
- jsonKey: port
sort: 1
validate:
required: true
min: 1
- jsonKey: protocol
sort: 3
- jsonKey: name
sort: 4
disable: true
- jsonKey: expose
sort: 5
validate:
required: true
defaultValue: [{"port": 80, "protocol": "TCP", "expose": true}]
- jsonKey: cmd
label: CMD
sort: 9
- jsonKey: env
sort: 10
label: ENV
subParameterGroupOption:
- label: Add By Value
keys:
- name
- value
- label: Add By Secret
keys:
- name
- valueFrom
subParameters:
- jsonKey: valueFrom
label: Secret Selector
uiType: Ignore
subParameters:
- jsonKey: configMapKeyRef
disable: true
- jsonKey: secretKeyRef
uiType: Ignore
subParameters:
- jsonKey: name
label: Secret Name
uiType: SecretSelect
sort: 1
- jsonKey: key
label: Secret Key
uiType: SecretKeySelect
sort: 3
uiType: Structs
- jsonKey: volumeMounts
label: Persistent Storage
description: "Set the path and type that the service needs to persist."
uiType: Group
subParameters:
- jsonKey: configMap
disable: true
- jsonKey: secret
disable: true
- jsonKey: pvc
label: Storage By PVC
sort: 1
subParameters:
- jsonKey: name
sort: 1
validate:
required: true
pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])$
- jsonKey: claimName
sort: 3
- jsonKey: mountPath
sort: 5
validate:
required: true
pattern: ^/(.*)$
- jsonKey: hostPath
label: Storage By HostPath
sort: 3
subParameters:
- jsonKey: name
sort: 1
validate:
required: true
pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])$
- jsonKey: path
label: Host Path
sort: 3
validate:
required: true
pattern: ^/(.*)$
- jsonKey: mountPath
sort: 5
validate:
required: true
pattern: ^/(.*)$
- jsonKey: emptyDir
label: Temporary Storage
sort: 5
subParameters:
- jsonKey: name
sort: 1
validate:
required: true
pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])$
- jsonKey: medium
sort: 3
validate:
required: false
options:
- label: Memory
value: memory
- label: Dir
value: ""
- jsonKey: mountPath
sort: 5
validate:
required: true
pattern: ^/(.*)$
sort: 12
- jsonKey: readinessProbe
uiType: Group
label: ReadinessProbe
subParameters:
- jsonKey: hostAliases
disable: true
- jsonKey: timeoutSeconds
sort: 1
style:
colSpan: 12
- jsonKey: failureThreshold
sort: 4
style:
colSpan: 12
- jsonKey: initialDelaySeconds
sort: 7
style:
colSpan: 12
validate:
defaultValue: 5
required: true
- jsonKey: periodSeconds
sort: 9
style:
colSpan: 12
- jsonKey: successThreshold
sort: 11
style:
colSpan: 12
- jsonKey: exec
sort: 14
- jsonKey: httpGet
sort: 19
subParameters:
- jsonKey: port
sort: 1
validate:
required: true
min: 1
style:
colSpan: 12
- jsonKey: path
sort: 3
validate:
required: true
pattern: ^/(.*)$
style:
colSpan: 12
- jsonKey: httpHeaders
sort: 5
- jsonKey: tcpSocket
sort: 19
subParameters:
- jsonKey: port
validate:
required: true
min: 1
sort: 13
- jsonKey: livenessProbe
uiType: Group
label: LivenessProbe
subParameters:
- jsonKey: hostAliases
disable: true
- jsonKey: timeoutSeconds
sort: 1
style:
colSpan: 12
- jsonKey: failureThreshold
sort: 4
style:
colSpan: 12
- jsonKey: initialDelaySeconds
sort: 7
style:
colSpan: 12
validate:
defaultValue: 5
required: true
- jsonKey: periodSeconds
sort: 9
style:
colSpan: 12
- jsonKey: successThreshold
sort: 11
style:
colSpan: 12
- jsonKey: exec
sort: 14
- jsonKey: httpGet
sort: 19
subParameters:
- jsonKey: port
sort: 1
validate:
required: true
min: 1
style:
colSpan: 12
- jsonKey: path
sort: 3
validate:
required: true
pattern: ^/(.*)$
style:
colSpan: 12
- jsonKey: httpHeaders
sort: 5
- jsonKey: tcpSocket
sort: 19
subParameters:
- jsonKey: port
validate:
required: true
min: 1
sort: 15
- jsonKey: annotations
sort: 19
- jsonKey: labels
sort: 21
- description: Specify image pull policy for your service
jsonKey: imagePullPolicy
label: Image Pull Policy
uiType: Select
sort: 24
validate:
defaultValue: IfNotPresent
options:
- label: IfNotPresent
value: IfNotPresent
- label: Always
value: Always
- label: Never
value: Never
- jsonKey: addRevisionLabel
disable: true
- jsonKey: port
disable: true
- jsonKey: volumes
disable: true

View File

@ -1,24 +0,0 @@
- jsonKey: registry
sort: 1
- jsonKey: insecure
sort: 3
style:
colSpan: 12
- jsonKey: useHTTP
sort: 5
style:
colSpan: 12
- jsonKey: auth
subParameters:
- jsonKey: username
sort: 1
style:
colSpan: 12
- jsonKey: password
sort: 3
style:
colSpan: 12
uiType: Password
- jsonKey: email
sort: 8

View File

@ -1,14 +0,0 @@
- jsonKey: dataId
sort: 1
style:
colSpan: 8
- jsonKey: group
sort: 3
style:
colSpan: 8
- jsonKey: contentType
sort: 5
style:
colSpan: 8
- jsonKey: content
sort: 7

View File

@ -1,43 +0,0 @@
- sort: 100
jsonKey: servers
subParameters:
- sort: 100
label: IPAddr
jsonKey: ipAddr
- sort: 101
label: Port
jsonKey: port
- sort: 102
label: GRPCPort
jsonKey: grpcPort
- sort: 101
jsonKey: client
subParameters:
- sort: 100
jsonKey: endpoint
- sort: 101
jsonKey: accessKey
uiType: Password
- sort: 102
jsonKey: secretKey
uiType: Password
- sort: 104
style:
colSpan: 12
jsonKey: regionId
- sort: 109
style:
colSpan: 12
jsonKey: openKMS
uiType: Switch
- sort: 110
jsonKey: username
uiType: Input
style:
colSpan: 12
- sort: 113
jsonKey: password
uiType: Password
style:
colSpan: 12

View File

@ -1,6 +0,0 @@
- sort: 100
jsonKey: selector
uiType: ComponentSelect
- sort: 101
jsonKey: components
uiType: ComponentPatches

View File

@ -1,4 +0,0 @@
- jsonKey: replicas
validate:
required: true
min: 0

View File

@ -1,86 +0,0 @@
- jsonKey: pvc
sort: 1
label: PersistentVolumeClaim
subParameters:
- jsonKey: name
sort: 1
validate:
required: true
pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])$
maxLength: 32
- jsonKey: mountPath
sort: 3
validate:
required: true
pattern: ^/(.*)$
- jsonKey: resources
sort: 7
validate:
required: true
defaultValue: {requests: {storage: "8Gi"}, limits: {storage: "8Gi"}}
subParameters:
- jsonKey: requests
uiType: Ignore
style:
colSpan: 12
subParameters:
- jsonKey: storage
uiType: DiskNumber
label: Request Storage
validate:
required: true
immutable: true
sort: 1
- jsonKey: limits
sort: 3
uiType: Ignore
style:
colSpan: 12
subParameters:
- jsonKey: storage
uiType: DiskNumber
label: Limit Storage
validate:
required: true
immutable: true
- jsonKey: storageClassName
sort: 9
description: If not specified, the cluster default StorageClass is used.
- jsonKey: accessModes
sort: 11
validate:
required: false
defaultValue: ["ReadWriteOnce"]
- jsonKey: volumeMode
sort: 12
description: You can set the value of volumeMode to Block to use a volume as a raw block device.
uiType: Select
validate:
defaultValue: Filesystem
options:
- label: Filesystem
value: Filesystem
- label: Block
value: Block
- jsonKey: volumeName
sort: 14
description: The VolumeName is the binding reference to the PersistentVolume backing this claim.
- jsonKey: selector
sort: 17
- jsonKey: dataSource
sort: 19
description: It will create a new volume based on the contents of the specified data source.
- jsonKey: dataSourceRef
sort: 20
disable: true
- jsonKey: mountOnly
disable: true
- jsonKey: secret
sort: 3
disable: true
- jsonKey: configMap
sort: 5
disable: true
- jsonKey: emptyDir
disable: true

View File

@ -1,14 +0,0 @@
- sort: 10
label: Policies
jsonKey: policies
uiType: PolicySelect
validate:
required: true
- sort: 20
jsonKey: parallelism
style:
colSpan: 12
- sort: 30
jsonKey: auto
style:
colSpan: 12

View File

@ -1,8 +0,0 @@
- jsonKey: parallel
validate:
defaultValue: false
sort: 5
- jsonKey: policy
sort: 1
- jsonKey: env
sort: 3

View File

@ -1,96 +0,0 @@
- jsonKey: dingding
sort: 1
description: Support push messages to Dingding Group.
subParameters:
- jsonKey: url
uiType: Ignore
sort: 1
subParameters:
- jsonKey: value
label: Webhook
uiType: Input
validate:
required: true
- jsonKey: message
description: Specify the message that you want to sent
sort: 3
uiType: Ignore
subParameters:
- jsonKey: msgtype
disable: true
- jsonKey: link
disable: true
- jsonKey: markdown
disable: true
- jsonKey: at
disable: true
- jsonKey: actionCard
disable: true
- jsonKey: feedCard
disable: true
- jsonKey: text
uiType: Ignore
subParameters:
- jsonKey: content
label: Message
description: Specify the message that you want to sent
- jsonKey: email
sort: 3
description: Support push email message.
subParameters:
- jsonKey: from
sort: 1
subParameters:
- jsonKey: host
sort: 1
- jsonKey: port
sort: 3
- jsonKey: address
sort: 5
- jsonKey: password
sort: 7
uiType: Ignore
subParameters:
- jsonKey: value
label: Password
uiType: Password
validate:
required: true
- jsonKey: alias
sort: 9
- jsonKey: to
sort: 3
- jsonKey: content
sort: 5
subParameters:
- jsonKey: subject
sort: 1
- jsonKey: body
sort: 3
- jsonKey: slack
sort: 5
description: Support push messages to slack channel.
subParameters:
- jsonKey: url
uiType: Ignore
sort: 1
subParameters:
- jsonKey: value
label: Webhook
uiType: Input
validate:
required: true
- jsonKey: message
uiType: Ignore
subParameters:
- jsonKey: blocks
disable: true
- jsonKey: attachments
disable: true
- jsonKey: thread_ts
disable: true
- jsonKey: mrkdwn
disable: true
- jsonKey: text
label: Message
description: Specify the message that you want to sent

View File

@ -1,12 +0,0 @@
- jsonKey: url
sort: 1
label: URL
uiType: Ignore
subParameters:
- jsonKey: value
label: URL
uiType: Input
validate:
required: true
- jsonKey: data
sort: 3

View File

@ -1,9 +0,0 @@
package main
output: {
apiVersion: "core.oam.dev/v1beta1"
kind: "Application"
spec: {
components: [additionalPrivileges, server]
}
}

View File

@ -1,37 +0,0 @@
import (
"vela/ql"
)
parameter: {
name: string
namespace?: string
cluster?: string
kind: string
apiVersion: string
}
response: ql.#Read & {
value: {
apiVersion: parameter.apiVersion
kind: parameter.kind
metadata: {
name: parameter.name
if parameter.namespace != _|_ {
namespace: parameter.namespace
}
}
}
if parameter.cluster != _|_ {
cluster: parameter.cluster
}
}
if response.err == _|_ {
status: {
resource: response.value
}
}
if response.err != _|_ {
status: {
error: response.err
}
}

View File

@ -1,33 +0,0 @@
import (
"vela/ql"
)
parameter: {
appName?: string
appNs?: string
}
secretList: ql.#List & {
resource: {
apiVersion: "v1"
kind: "Secret"
}
filter: {
matchingLabels: {
"created-by": "terraform-controller"
if parameter.appName != _|_ && parameter.appNs != _|_ {
"app.oam.dev/name": parameter.appName
"app.oam.dev/namespace": parameter.appNs
}
}
}
}
status: {
if secretList.err == _|_ {
secrets: secretList.list.items
}
if secretList.err != _|_ {
error: secretList.err
}
}

View File

@ -1,30 +0,0 @@
import (
"vela/ql"
)
parameter: {
appName: string
appNs: string
}
resources: ql.#ListResourcesInApp & {
app: {
name: parameter.appName
namespace: parameter.appNs
filter: {
"apiVersion": "terraform.core.oam.dev/v1beta2"
"kind": "Configuration"
}
withStatus: true
}
}
status: {
if resources.err == _|_ {
"cloud-resources": [ for i, resource in resources.list {
resource.object
}]
}
if resources.err != _|_ {
error: resources.err
}
}

View File

@ -1,43 +0,0 @@
import (
"vela/ql"
)
collectLogs: ql.#CollectLogsInPod & {
cluster: parameter.cluster
namespace: parameter.namespace
pod: parameter.pod
options: {
container: parameter.container
previous?: parameter.previous
sinceSeconds?: parameter.sinceSeconds
sinceTime?: parameter.sinceTime
timestamps?: parameter.timestamps
tailLines?: parameter.tailLines
limitBytes?: parameter.limitBytes
}
}
status: collectLogs.outputs
parameter: {
// +usage=Specify the cluster of the pod
cluster: string
// +usage=Specify the namespace of the pod
namespace: string
// +usage=Specify the name of the pod
pod: string
// +usage=Specify the name of the container
container: string
// +usage=If true, return previous terminated container logs
previous: *false | bool
// +usage=If set, show logs in relative times
sinceSeconds: *null | int
// +usage=RFC3339 timestamp, if set, show logs since this time
sinceTime: *null | string
// +usage=If true, add timestamp at the beginning of every line
timestamps: *false | bool
// +usage=If set, return the number of lines from the end of logs
tailLines: *null | int
// +usage=If set, limit the size of returned bytes
limitBytes: *null | int
}

View File

@ -1,55 +0,0 @@
import (
"vela/ql"
)
parameter: {
name: string
namespace: string
cluster: *"" | string
type: "deployment" | "statefulset" | "pod"
}
schema: {
"deployment": {
apiVersion: "apps/v1"
kind: "Deployment"
}
"statefulset": {
apiVersion: "apps/v1"
kind: "StatefulSet"
}
"pod": {
apiVersion: "v1"
kind: "Pod"
}
}
pod: ql.#Read & {
value: {
apiVersion: schema[parameter.type].apiVersion
kind: schema[parameter.type].kind
metadata: {
name: parameter.name
namespace: parameter.namespace
}
}
cluster: parameter.cluster
}
eventList: ql.#SearchEvents & {
value: {
apiVersion: schema[parameter.type].apiVersion
kind: schema[parameter.type].kind
metadata: pod.value.metadata
}
cluster: parameter.cluster
}
status: {
if eventList.err == _|_ {
events: eventList.list
}
if eventList.err != _|_ {
error: eventList.err
}
}

View File

@ -1,79 +0,0 @@
import (
"vela/ql"
)
parameter: {
name: string
namespace: string
cluster: *"" | string
}
pod: ql.#Read & {
value: {
apiVersion: "v1"
kind: "Pod"
metadata: {
name: parameter.name
namespace: parameter.namespace
}
}
cluster: parameter.cluster
}
eventList: ql.#SearchEvents & {
value: {
apiVersion: "v1"
kind: "Pod"
metadata: pod.value.metadata
}
cluster: parameter.cluster
}
podMetrics: ql.#Read & {
cluster: parameter.cluster
value: {
apiVersion: "metrics.k8s.io/v1beta1"
kind: "PodMetrics"
metadata: {
name: parameter.name
namespace: parameter.namespace
}
}
}
status: {
if pod.err == _|_ {
containers: [ for container in pod.value.spec.containers {
name: container.name
image: container.image
resources: {
if container.resources.limits != _|_ {
limits: container.resources.limits
}
if container.resources.requests != _|_ {
requests: container.resources.requests
}
if podMetrics.err == _|_ {
usage: {for containerUsage in podMetrics.value.containers {
if containerUsage.name == container.name {
cpu: containerUsage.usage.cpu
memory: containerUsage.usage.memory
}
}}
}
}
if pod.value.status.containerStatuses != _|_ {
status: {for containerStatus in pod.value.status.containerStatuses if containerStatus.name == container.name {
state: containerStatus.state
restartCount: containerStatus.restartCount
}}
}
}]
if eventList.err == _|_ {
events: eventList.list
}
}
if pod.err != _|_ {
error: pod.err
}
}

View File

@ -1,59 +0,0 @@
import (
"vela/ql"
)
parameter: {
type: string
namespace: *"" | string
cluster: *"" | string
}
schema: {
"secret": {
apiVersion: "v1"
kind: "Secret"
}
"configMap": {
apiVersion: "v1"
kind: "ConfigMap"
}
"pvc": {
apiVersion: "v1"
kind: "PersistentVolumeClaim"
}
"storageClass": {
apiVersion: "storage.k8s.io/v1"
kind: "StorageClass"
}
"ns": {
apiVersion: "v1"
kind: "Namespace"
}
"provider": {
apiVersion: "terraform.core.oam.dev/v1beta1"
kind: "Provider"
}
}
List: ql.#List & {
resource: schema[parameter.type]
filter: {
namespace: parameter.namespace
}
cluster: parameter.cluster
}
status: {
if List.err == _|_ {
if len(List.list.items) == 0 {
error: "failed to list \(parameter.type) in namespace \(parameter.namespace)"
}
if len(List.list.items) != 0 {
list: List.list.items
}
}
if List.err != _|_ {
error: List.err
}
}

View File

@ -1,38 +0,0 @@
import (
"vela/ql"
)
parameter: {
appName: string
appNs: string
cluster?: string
clusterNs?: string
}
resources: ql.#ListResourcesInApp & {
app: {
name: parameter.appName
namespace: parameter.appNs
filter: {
if parameter.cluster != _|_ {
cluster: parameter.cluster
}
if parameter.clusterNs != _|_ {
clusterNamespace: parameter.clusterNs
}
apiVersion: "v1"
kind: "Service"
}
withStatus: true
}
}
status: {
if resources.err == _|_ {
services: [ for i, resource in resources.list {
resource.object
}]
}
if resources.err != _|_ {
error: resources.err
}
}

View File

@ -1,62 +0,0 @@
{
"babelrc": false,
// Note: order is bottom-to-top and/or right-to-left
"presets": [
[
"@babel/preset-env",
{
"bugfixes": true,
"browserslistEnv": "dev",
"useBuiltIns": "entry",
"corejs": "3.10"
}
],
[
"@babel/preset-typescript",
{
"allowNamespaces": true,
"allowDeclareFields": true
}
],
[
"@babel/preset-react",
{
"runtime": "automatic"
}
]
],
"plugins": [
[
"@babel/plugin-transform-typescript",
{
"allowNamespaces": true,
"allowDeclareFields": true
}
],
// added to mitigate https://github.com/babel/babel/issues/14289
// package (and following line) can be removed once the issue is fixed and released
"@babel/plugin-proposal-class-properties",
["@babel/plugin-proposal-object-rest-spread", { "loose": true }],
"@babel/plugin-transform-react-constant-elements",
"@babel/plugin-proposal-nullish-coalescing-operator",
"@babel/plugin-proposal-optional-chaining",
"@babel/plugin-syntax-dynamic-import", // needed for `() => import()` in routes.ts
"angularjs-annotate",
"macros"
],
"env": {
"production": {
"presets": [
[
"@babel/preset-env",
{
"browserslistEnv": "production"
}
]
]
},
"hot": {
"plugins": ["react-refresh/babel"]
}
}
}

View File

@ -1,51 +0,0 @@
/*
Copyright 2022 The KubeVela Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package options
import (
"flag"
cliflag "k8s.io/component-base/cli/flag"
"k8s.io/klog/v2"
"github.com/kubevela/velaux/pkg/features"
"github.com/kubevela/velaux/pkg/server/config"
)
// ServerRunOptions contains everything necessary to create and run api server
type ServerRunOptions struct {
GenericServerRunOptions *config.Config
}
// NewServerRunOptions creates a new ServerRunOptions object with default parameters
func NewServerRunOptions() *ServerRunOptions {
s := &ServerRunOptions{
GenericServerRunOptions: config.NewConfig(),
}
return s
}
// Flags returns the complete NamedFlagSets
func (s *ServerRunOptions) Flags() (fss cliflag.NamedFlagSets) {
fs := fss.FlagSet("generic")
s.GenericServerRunOptions.AddFlags(fs, s.GenericServerRunOptions)
features.APIServerMutableFeatureGate.AddFlag(fss.FlagSet("featuregate"))
local := flag.NewFlagSet("klog", flag.ExitOnError)
klog.InitFlags(local)
fs.AddGoFlagSet(local)
return fss
}

View File

@ -1,28 +0,0 @@
/*
Copyright 2022 The KubeVela Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package options
import utilerrors "k8s.io/apimachinery/pkg/util/errors"
// Validate validates server run options, to find options' misconfiguration
func (s *ServerRunOptions) Validate() error {
var errors []error
errors = append(errors, s.GenericServerRunOptions.Validate()...)
return utilerrors.NewAggregate(errors)
}

View File

@ -1,151 +0,0 @@
/*
Copyright 2022 The KubeVela Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package app
import (
"context"
"encoding/json"
"fmt"
"os"
"os/signal"
"syscall"
"github.com/kubevela/pkg/util/profiling"
restfulspec "github.com/emicklei/go-restful-openapi/v2"
"github.com/fatih/color"
"github.com/go-openapi/spec"
"github.com/spf13/cobra"
"k8s.io/klog/v2"
"github.com/kubevela/velaux/cmd/server/app/options"
"github.com/kubevela/velaux/pkg/server"
"github.com/oam-dev/kubevela/version"
)
// NewAPIServerCommand creates a *cobra.Command object with default parameters
func NewAPIServerCommand() *cobra.Command {
s := options.NewServerRunOptions()
cmd := &cobra.Command{
Use: "apiserver",
Long: `The KubeVela API server validates and configures data for the API objects.
The API Server services REST operations and provides the frontend to the
cluster's shared state through which all other components interact.`,
RunE: func(cmd *cobra.Command, args []string) error { //nolint:revive,unused
if err := s.Validate(); err != nil {
return err
}
return Run(s)
},
SilenceUsage: true,
}
fs := cmd.Flags()
namedFlagSets := s.Flags()
for _, set := range namedFlagSets.FlagSets {
fs.AddFlagSet(set)
}
buildSwaggerCmd := &cobra.Command{
Use: "build-swagger",
Short: "Build swagger documentation of KubeVela apiserver",
RunE: func(cmd *cobra.Command, args []string) error { //nolint:revive,unused
name := "docs/apidoc/latest-swagger.json"
if len(args) > 0 {
name = args[0]
}
func() {
swagger, err := buildSwagger(s)
if err != nil {
klog.Fatal(err.Error())
}
outData, err := json.MarshalIndent(swagger, "", "\t")
if err != nil {
klog.Fatal(err.Error())
}
swaggerFile, err := os.OpenFile(name, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0600)
if err != nil {
klog.Fatal(err.Error())
}
defer func() {
if err := swaggerFile.Close(); err != nil {
klog.Errorf("close swagger file failure %s", err.Error())
}
}()
_, err = swaggerFile.Write(outData)
if err != nil {
klog.Fatal(err.Error())
}
fmt.Println("build swagger config file success")
}()
return nil
},
}
cmd.AddCommand(buildSwaggerCmd)
return cmd
}
// Run runs the specified APIServer. This should never exit.
func Run(s *options.ServerRunOptions) error {
// The server is not terminal, there is no color default.
// Force set to false, this is useful for the dry-run API.
color.NoColor = false
errChan := make(chan error)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go profiling.StartProfilingServer(errChan)
go func() {
if err := run(ctx, s, errChan); err != nil {
errChan <- fmt.Errorf("failed to run apiserver: %w", err)
}
}()
var term = make(chan os.Signal, 1)
signal.Notify(term, os.Interrupt, syscall.SIGTERM)
select {
case <-term:
klog.Infof("Received SIGTERM, exiting gracefully...")
case err := <-errChan:
klog.Errorf("Received an error: %s, exiting gracefully...", err.Error())
return err
}
klog.Infof("See you next time!")
return nil
}
func run(ctx context.Context, s *options.ServerRunOptions, errChan chan error) error {
klog.Infof("KubeVela information: version: %v, gitRevision: %v", version.VelaVersion, version.GitRevision)
server := server.New(*s.GenericServerRunOptions)
return server.Run(ctx, errChan)
}
func buildSwagger(s *options.ServerRunOptions) (*spec.Swagger, error) {
server := server.New(*s.GenericServerRunOptions)
config, err := server.BuildRestfulConfig()
if err != nil {
return nil, err
}
return restfulspec.BuildSwagger(*config), nil
}

View File

@ -1,30 +0,0 @@
/*
Copyright 2021 The KubeVela Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"log"
"github.com/kubevela/velaux/cmd/server/app"
)
func main() {
cmd := app.NewAPIServerCommand()
if err := cmd.Execute(); err != nil {
log.Fatalln(err)
}
}

21
cmd/velacp/main.go Normal file
View File

@ -0,0 +1,21 @@
package main
import (
"log"
"github.com/oam-dev/velacp/pkg/commands"
"github.com/oam-dev/velacp/pkg/commands/server"
)
func main() {
app := commands.NewCLI(
"velacp",
"KubeVela control plane",
)
app.AddCommands(
server.NewServerCommand(),
)
if err := app.Run(); err != nil {
log.Fatal(err)
}
}

View File

@ -1,25 +0,0 @@
module.exports = {
extends: ["@commitlint/config-conventional"],
rules: {
'type-enum': [
// 配置的具体规则这里是提交的type
// 报错级别 0为disable1为warning2为error 就是检查的级别
2,
'always',
// 枚举的type值不在下面的都报错
[
'build',
'chore',
'ci',
'docs',
'feat',
'fix',
'perf',
'refactor',
'revert',
'style',
'test'
]
]
}
};

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,115 @@
# How to Develop Backend Services
## Preparation
- Install [go](https://golang.org/dl/)
- Install [yarn](https://yarnpkg.com/)
- Install [protoc](https://grpc.io/docs/protoc-installation/) and [protoc-gen-go](https://grpc.io/docs/languages/go/quickstart/#prerequisites)
- Install [mongodb](https://docs.mongodb.com/manual/tutorial/install-mongodb-on-ubuntu/#install-mongodb-community-edition)
## Development
In [frontend development](./frontend.md), developers will use mock backend services first.
But eventually the production rollout of velacp will have both frontend and backend services served.
Developing backend services in velacp has a well-defined architecture and systematic process. We will walk through the steps in the following.
Let's assume we are building a new service "Cluster".
The process goes as:
1. All public APIs, including records stored in database, should be defined in protobuf. In `pkg/proto/`, add a new protobuf definition:
```
touch pkg/proto/cluster.proto
```
Add definitions for cluster service API types:
```protobuf
message Cluster {
string name = 1;
...
}
```
1. Generate go code:
```
make proto
```
1. Add the service endpoints. First create a new service in `pkg/rest/services/`:
```
touch pkg/rest/services//cluster.go
```
Implement the services:
```go
type ClusterService struct {
...
}
func NewClusterService(store storeadapter.ClusterStore) *ClusterService {
return &ClusterService{
...
}
}
func (s *ClusterService) GetClusters(c echo.Context) error {
...
}
```
The new service needs to be registered to in `pkg/rest/rest_server.go`:
```go
func (s *restServer) registerServices() {
...
clusterService := services.NewClusterService(storeadapter.NewClusterStore(s.ds))
s.server.GET("/api/clusters", clusterService.GetClusters)
}
```
1. There is a generic datastore interface defined in `pkg/datastore/datastore.go`. Its mongo backend is implemented in `pkg/datastore/mongodb/mongodb.go`. For each service, you will implement a more specific store adapter to handle its own types and special logic, e.g. ClusterStore.
All specific store adapter is defined in `pkg/datastore/storeadapter/`. Create one for ClusterStore:
```
touch pkg/datastore/storeadapter/clusterstore.go
```
We can see its interface:
```go
type ClusterStore interface {
PutCluster(cluster *model.Cluster) error
ListClusters() ([]*model.Cluster, error)
DelCluster(name string) error
}
```
Its returned model, i.e. `model.Cluster`, is defined in the `pkg/proto/model/cluster.proto`.
1. Once the code is done, build it:
```
make build
```
This will include the frontend as well.
1. Start [mongodb](https://docs.mongodb.com/manual/tutorial/install-mongodb-on-ubuntu/#run-mongodb-community-edition).
Ensure env `MONGO_URL` is set, e.g. "127.0.0.1:27017".
1. Start velacp:
```bash
_bin/velacp server \
--db-url=${MONGO_URL} \
--db-name=vela
```
You can now test the APIs and UIs.

View File

@ -0,0 +1,85 @@
# How to Develop UI Components
## Preparation
- Install [yarn](https://yarnpkg.com/)
## Development
The UI code is under ui/ . First, go to the folder:
```
cd ui/
```
Developing UI components in velacp has a well-defined architecture and systematic process. We will walk through the steps in the following.
Let's assume we are building a new UI page "Cluster".
The process goes as:
1. In `config/routes.ts`, add your route and component.
1. Add a new component in src/pages/:
```
mkdir src/pages/Cluster/
```
Develop and add your component code there.
1. For remote services, create interfaces in `services/kubevela`:
```
touch clusterapi.ts
```
Add your API calls there:
```js
import { request } from "umi";
export async function listClusterNames() {
return request<{ clusters: string[] }>('/api/clusternames');
}
```
For API types, define in `src/services/kubevela/typings.d.ts`:
```js
declare namespace API {
export type ApplicationType = {
name: string;
desc?: string;
updatedAt?: number; // unix milliseconds
components?: ComponentType[];
};
}
```
They should belong to API global namespace.
1. To mock the backend APIs, create mock servers in `mock/`:
```
touch mock/cluster.tx
```
Expose the mock services:
```js
export default {
"GET /api/clusternames": getClusterNames,
"GET /api/clusters": getClusters,
"POST /api/clusters": postClusters,
};
```
1. Run the UI to see the result:
```bash
# run `yarn` first if you haven't installed dependencies
yarn start
```

View File

@ -1,107 +0,0 @@
# How to build a plugin
VelUX plugin could help you customs any page applications. Most default and extensional runtime APIs make you develop the application easies.
## 1. Build the local server environment.
Refer [contributing](./docs/contributing/velaux.md) guide.
## 2. Initialize the plugin project.
```bash
mkdir custom-plugins
$pluginName=<your_plugin_name>
git clone https://github.com/kubevela-contrib/velaux-plugin-template custom-plugins/$pluginName
cd custom-plugins/$pluginName
```
## 3. Edit the plugin metadata.
* src/plugin.json: Plugin metadata, you should change it.
* package.json: Project metadata, you should change the project name, version, and description etc.
Plugin metadata spec:
```cue
{
"type": "page-app",
"name": string,
"id": string,
"info": {
"keywords": []string,
"description": string,
"author": {
"name": string
},
"logos": {
"small": string,
"large": string
},
"screenshots": [],
"version": string,
"updated": string
},
"backend"?: bool,
"proxy"?: bool,
"backendType?": "kube-api" | "kube-service",
"routes"?: [
{
"path": string,
"permission": {
"resource": string,
"action": string
}
}
],
"backendService"?: {
"name": string
"namespace"?: string
},
"kubePermissions"?: [
{
"apiGroups": string[],
"resources": string[],
"verbs": string[],
}
]
}
```
There are some example plugin configs. https://github.com/kubevela/velaux/tree/main/docs/plugins
## 4. Develop the plugin
```bash
yarn install
yarn dev
```
### Request the backend API
```js
import { getBackendSrv } from '@velaux/ui';
// Request the core APIs
getBackendSrv().get('/api/v1/clusters').then(res=>{console.log(res)})
// Request the plugin proxy APIs
getBackendSrv().get(`/proxy/plugins/${pluginID}/${realPath}`).then(res=>{console.log(res)})
```
Core API Reference: https://kubevela.net/docs/platform-engineers/openapi/overview
### UI Components
```js
import { Table, Form } from '@velaux/ui';
```
UI Component Reference: https://fusion.design/pc/component/box?themeid=2
## 5. Start the server to debug the plugin
```bash
go run ./cmd/server/main.go --plugin-path <custom-plugins-path>
```

View File

@ -1,127 +0,0 @@
# Contribute VelaUX
## Prepare the local environment
### Install VelaCore
1. Check requirements
* VelaD support installing KubeVela on machines based on these OS: Linux, macOS, Windows.
* If you are using Linux or macOS, make sure your machine have `curl` installed.
* If you are using macOS or Windows, make sure you've already installed [Docker](https://www.docker.com/products/docker-desktop).
2. Download the binary.
* MacOS/Linux
```bash
curl -fsSl https://static.kubevela.net/script/install-velad.sh | bash
```
* Windows
```bash
powershell -Command "iwr -useb https://static.kubevela.net/script/install-velad.ps1 | iex"
```
3. Install
```bash
velad install
```
4. Install VelaUX environment
```bash
vela addon enable ./addon
```
## Start the server on local
Make sure you have installed [yarn 2.0](https://yarnpkg.com/getting-started/install), This is required.
```shell
yarn install
yarn build-packages
## Build the frontend and watch the code changes
yarn dev
```
### Start the server
```shell
## Setting the KUBECONFIG environment
export KUBECONFIG=$(velad kubeconfig --host)
make run-server
```
Waiting the server started, open http://127.0.0.1:8000 via the browser.
Now, the local environment is built successfully, you could write the server or frontend code.
Notes:
* If you change the frontend code, it will take effect after the website refresh.
* If you change the server code, it will take effect after restarted the server.
### Check the code style
```shell
# Frontend
yarn lint
# Server
make reviewable
```
### Test the code
For testing server kubebuilder and its dependency tools are required. To install them you can use:
```shell
make setup-test-server
```
Frontend:
```shell
yarn test
```
Server:
```shell
make unit-test-server
make e2e-server-test
```
### Generate the OpenAPI schema
```shell
make build-swagger
```
### Config yarn2 in vscode
Add following config in `settings.json`
```json
{
"search.exclude": {
"**/.yarn": true,
"**/.pnp.*": true
},
"typescript.tsdk": ".yarn/sdks/typescript/lib",
"typescript.enablePromptUseWorkspaceTsdk": true
}
```
## Develop the plugin
Reference: [How to build a plugin](./how-to-build-plugin)
## References
* UI framework: [@alifd/next](https://fusion.design/)
* Icons: [react-icons](https://react-icons.github.io/react-icons)

96
docs/design/env.md Normal file
View File

@ -0,0 +1,96 @@
# Environment
User scenarios:
- Users want to define base application template and add patches based on environment. For example, in dev environment users would use ephemeral disk, while in prod environment use persistent volumes.
- Users want to define environments as the shared-bases for applications. For example, applications might need shared definitions, secrets, health checks, network gateways, etc.
To support the above scenarios, we will add the following concepts:
- AppTemplate that defines the template base as well as the env-based patches:
```yaml
name: example-app-template
base: # the base template
components:
- name: backend
settings:
cmd:
- /bin/myservice
traits:
- name: logging
properties:
rotate: 1d
patch: # kustomize-style overlay patch to base template based on env matching
- envs:
- dev # the name of the Environment
components:
- name: backend
settings:
image: dev/myimage
traits:
- name: scaler
properties:
replicas: 1
- envs:
- prod-beijing
- prod-shenzhen
components:
- name: backend
settings:
image: production/myimage
traits:
- name: scaler
properties:
replicas: 10
```
- Environment that defines a shared-base for applications:
```yaml
name: prod
clusters: # deploy to the following clusters
- prod-cluster
secrets: # The secrets that will be created for applications if not existed.
- name: redis
data:
url: redis-url
password: redis-password
definitions: # The definitions that will be created for applications if not existed.
- type: Component
name: function
source:
git: catalog-url
path: pacakge/function
- type: Trait
name: logging
source:
git: catalog-url
path: package/logging
```
> Note: we will define a definition catalog/package format: https://github.com/hongchaodeng/catalog-example
With the above concepts, the user story goes as:
- The operations/admin team sets up environments first
- The developer users prepare app templates and individual patches for each environment that will have apps to deploy to.
- Users choose a template, then choose an environment, and deploy!
- velacp will render the final Application based on the template and env
- velacp will prepare the necessary secrets, definitions in the environment for the applications
- The Application can use any of the definitions, secrets in this env.
```
Applicaton deployment workflow:
Env -> Controller -> (Secrets + Definitions)
AppTemplate + Env -> velacp -> Application -> Controller
```
Notes:
- AppTemplate will be implemented in velacp. Environment will be implemented as a CRD.

133
docs/design/environment.md Normal file
View File

@ -0,0 +1,133 @@
# Environment
DEPRECATED!!!
## 1. Introduction
An environment is a shared infra-base consisting of the same clusters, packages (equiv. capabilities), etc.
to which the applications are deployed.
Below are two examples of `staging-env` and `prod-env` environments:
```yaml
name: staging-env
clusters:
- name: staging-cluster
packages:
- catalog: staging-catalog
package: inmem-logging
---
name: prod-env
clusters:
- name: prod-cluster
packages:
- catalog: prod-catalog
package: loki-logging
```
We are going to explain what an environment includes in the following.
## 2. Clusters
An environment consists of a group of clusters. For example, multiple small clusters from different data centers could form a staging environment to simplify management and serve maximum availability. While each production environment might consist of only one cluster and users need to calibrate high availability for their apps.
When deploying apps to an environment, you might specify only the environment which will deploy to all clusters. Or you might pick some clusters within an environment.
```yaml
# When deploying an app you could choose env and select clusters within the env.
name: example-app
env: env-1
clusters:
- cluster-1
```
The clusters that environments reference to are abstraction over a k8s cluster. It could be an existing one which should have credentials set, or a need-to-be-created one that VelaCP can call over some cloud providers (e.g. ACK, GKE, EKS) to create one.
### Cluster Setup Workflow
Before creating any Environment, users need to create Clusters first. Here is an example:
```yaml
name: prod-cluster
spec:
external: # This is pointing to externally managed clusters without VelaCP reconciling
kubeconfig: "..."
managed: # This would trigger cluster reconciler in VelaCP to create and manage a cluster
provider: ack
parameters:
master:
instanceType: ecs.g6.large
worker:
instanceType: ecs.g6.small
replicas: 3
cni: terway
```
Once the cluster is setup, then create environments to reference it:
```yaml
name: prod-env
clusters:
- prod-cluster
```
## 3. Packages
Within an environment, deployment on all clusters should be consistent. Thus, all packages should be installed the same across clusters.
To provide such guarantee, environment includes `packages` list to ensure those dependencies are declared and installed consistently.
A package is an abstraction over manifests to prepare infrastructure environments. It could be Helm Charts, Kube resources, or Terraform resources. You can use it to set up Operators (Prometheus, ELK, Istio), RBAC rules, OAM Definitions, etc.
### Package Setup Workflow
First of all, the packages should be uploaded to a remote store. We support two kinds of storage backends:
- Git.
- Object storage.
The catalog and package structure must follow predefined format. Here is an example of the structure format: [catalog-example](https://github.com/hongchaodeng/catalog-example).
Before creating the Environment, create the Catalogs first. Here is an example:
```yaml
name: prod-catalog
spec:
git:
url: https://github.com/hongchaodeng/catalog-example
rootdir: catalog/
oss:
url: https://oss.aliyun.com/bucket_name/
```
Finally create the environment:
```yaml
name: prod-env
clusters:
- prod-cluster
packages:
- catalog: prod-catalog
package: grafana
```
By doing this, the environment reconciler from VelaCP would retrieve the packages from the catalog, and then:
- if the package is not installed, install the package
- if the package has been installed and version is older, upgrade the package
Note that the pacakge could be of type of Helm Chart or Kube resources or Terraform resources, no worry about that.
VelaCP will take care of them under the hood and use corresponding tooling to do the installation:
- Kube resources: same as `kubectl apply`
- Helm chart: same as `helm install`/`helm upgrade`
- Terraform resources: same as `terraform apply`
## 4. Env-based Config Patch
You can also do per-environment configuration management based on app templates.
Check out [this doc](env_based_patch.md)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.3 KiB

BIN
docs/images/app-detail.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 227 KiB

BIN
docs/images/app-input.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 191 KiB

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