Compare commits
15 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 864ba21a32 | |||
| 57a4f50747 | |||
| a0cf836c8a | |||
| cfa5be52f7 | |||
| bf296b2f19 | |||
| b2e8b93759 | |||
| 31ce3f5aa4 | |||
| b4b8d095a4 | |||
| 9310973f36 | |||
| 9cdd580dcf | |||
| df9990a42e | |||
| 2a2fd706b5 | |||
| b49c01546f | |||
| 374127eba5 | |||
| 793df2edbd |
@@ -4,12 +4,12 @@ description: |
|
||||
inputs:
|
||||
version:
|
||||
description: "The Go version to use."
|
||||
default: "1.22.3"
|
||||
default: "1.21.5"
|
||||
runs:
|
||||
using: "composite"
|
||||
steps:
|
||||
- name: Setup Go
|
||||
uses: buildjet/setup-go@v5
|
||||
uses: buildjet/setup-go@v4
|
||||
with:
|
||||
go-version: ${{ inputs.version }}
|
||||
|
||||
|
||||
@@ -11,11 +11,11 @@ runs:
|
||||
using: "composite"
|
||||
steps:
|
||||
- name: Install pnpm
|
||||
uses: pnpm/action-setup@v3
|
||||
uses: pnpm/action-setup@v2
|
||||
with:
|
||||
version: 8
|
||||
- name: Setup Node
|
||||
uses: buildjet/setup-node@v4.0.1
|
||||
uses: buildjet/setup-node@v3
|
||||
with:
|
||||
node-version: 18.19.0
|
||||
# See https://github.com/actions/setup-node#caching-global-packages-data
|
||||
|
||||
@@ -7,5 +7,5 @@ runs:
|
||||
- name: Install Terraform
|
||||
uses: hashicorp/setup-terraform@v3
|
||||
with:
|
||||
terraform_version: 1.8.4
|
||||
terraform_version: 1.5.7
|
||||
terraform_wrapper: false
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
codecov:
|
||||
require_ci_to_pass: false
|
||||
notify:
|
||||
after_n_builds: 5
|
||||
|
||||
comment: false
|
||||
|
||||
github_checks:
|
||||
annotations: false
|
||||
|
||||
coverage:
|
||||
range: 50..75
|
||||
round: down
|
||||
precision: 2
|
||||
status:
|
||||
patch:
|
||||
default:
|
||||
informational: yes
|
||||
project:
|
||||
default:
|
||||
target: 65%
|
||||
informational: true
|
||||
|
||||
ignore:
|
||||
# This is generated code.
|
||||
- coderd/database/models.go
|
||||
- coderd/database/queries.sql.go
|
||||
- coderd/database/databasefake
|
||||
# These are generated or don't require tests.
|
||||
- cmd
|
||||
- coderd/tunnel
|
||||
- coderd/database/dump
|
||||
- coderd/database/postgres
|
||||
- peerbroker/proto
|
||||
- provisionerd/proto
|
||||
- provisionersdk/proto
|
||||
- scripts
|
||||
- site/.storybook
|
||||
- rules.go
|
||||
# Packages used for writing tests.
|
||||
- cli/clitest
|
||||
- coderd/coderdtest
|
||||
- pty/ptytest
|
||||
@@ -112,3 +112,17 @@ updates:
|
||||
offlinedocs:
|
||||
patterns:
|
||||
- "*"
|
||||
|
||||
# Update dogfood.
|
||||
- package-ecosystem: "terraform"
|
||||
directory: "/dogfood/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
time: "06:00"
|
||||
timezone: "America/Chicago"
|
||||
commit-message:
|
||||
prefix: "chore"
|
||||
labels: []
|
||||
ignore:
|
||||
# We likely want to update this ourselves.
|
||||
- dependency-name: "coder/coder"
|
||||
|
||||
@@ -86,7 +86,6 @@ provider "kubernetes" {
|
||||
}
|
||||
|
||||
data "coder_workspace" "me" {}
|
||||
data "coder_workspace_owner" "me" {}
|
||||
|
||||
resource "coder_agent" "main" {
|
||||
os = "linux"
|
||||
@@ -176,21 +175,21 @@ resource "coder_app" "code-server" {
|
||||
|
||||
resource "kubernetes_persistent_volume_claim" "home" {
|
||||
metadata {
|
||||
name = "coder-${lower(data.coder_workspace_owner.me.name)}-${lower(data.coder_workspace.me.name)}-home"
|
||||
name = "coder-${lower(data.coder_workspace.me.owner)}-${lower(data.coder_workspace.me.name)}-home"
|
||||
namespace = var.namespace
|
||||
labels = {
|
||||
"app.kubernetes.io/name" = "coder-pvc"
|
||||
"app.kubernetes.io/instance" = "coder-pvc-${lower(data.coder_workspace_owner.me.name)}-${lower(data.coder_workspace.me.name)}"
|
||||
"app.kubernetes.io/instance" = "coder-pvc-${lower(data.coder_workspace.me.owner)}-${lower(data.coder_workspace.me.name)}"
|
||||
"app.kubernetes.io/part-of" = "coder"
|
||||
//Coder-specific labels.
|
||||
"com.coder.resource" = "true"
|
||||
"com.coder.workspace.id" = data.coder_workspace.me.id
|
||||
"com.coder.workspace.name" = data.coder_workspace.me.name
|
||||
"com.coder.user.id" = data.coder_workspace_owner.me.id
|
||||
"com.coder.user.username" = data.coder_workspace_owner.me.name
|
||||
"com.coder.user.id" = data.coder_workspace.me.owner_id
|
||||
"com.coder.user.username" = data.coder_workspace.me.owner
|
||||
}
|
||||
annotations = {
|
||||
"com.coder.user.email" = data.coder_workspace_owner.me.email
|
||||
"com.coder.user.email" = data.coder_workspace.me.owner_email
|
||||
}
|
||||
}
|
||||
wait_until_bound = false
|
||||
@@ -211,20 +210,20 @@ resource "kubernetes_deployment" "main" {
|
||||
]
|
||||
wait_for_rollout = false
|
||||
metadata {
|
||||
name = "coder-${lower(data.coder_workspace_owner.me.name)}-${lower(data.coder_workspace.me.name)}"
|
||||
name = "coder-${lower(data.coder_workspace.me.owner)}-${lower(data.coder_workspace.me.name)}"
|
||||
namespace = var.namespace
|
||||
labels = {
|
||||
"app.kubernetes.io/name" = "coder-workspace"
|
||||
"app.kubernetes.io/instance" = "coder-workspace-${lower(data.coder_workspace_owner.me.name)}-${lower(data.coder_workspace.me.name)}"
|
||||
"app.kubernetes.io/instance" = "coder-workspace-${lower(data.coder_workspace.me.owner)}-${lower(data.coder_workspace.me.name)}"
|
||||
"app.kubernetes.io/part-of" = "coder"
|
||||
"com.coder.resource" = "true"
|
||||
"com.coder.workspace.id" = data.coder_workspace.me.id
|
||||
"com.coder.workspace.name" = data.coder_workspace.me.name
|
||||
"com.coder.user.id" = data.coder_workspace_owner.me.id
|
||||
"com.coder.user.username" = data.coder_workspace_owner.me.name
|
||||
"com.coder.user.id" = data.coder_workspace.me.owner_id
|
||||
"com.coder.user.username" = data.coder_workspace.me.owner
|
||||
}
|
||||
annotations = {
|
||||
"com.coder.user.email" = data.coder_workspace_owner.me.email
|
||||
"com.coder.user.email" = data.coder_workspace.me.owner_email
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+82
-143
@@ -37,10 +37,8 @@ jobs:
|
||||
k8s: ${{ steps.filter.outputs.k8s }}
|
||||
ci: ${{ steps.filter.outputs.ci }}
|
||||
db: ${{ steps.filter.outputs.db }}
|
||||
gomod: ${{ steps.filter.outputs.gomod }}
|
||||
offlinedocs-only: ${{ steps.filter.outputs.offlinedocs_count == steps.filter.outputs.all_count }}
|
||||
offlinedocs: ${{ steps.filter.outputs.offlinedocs }}
|
||||
tailnet-integration: ${{ steps.filter.outputs.tailnet-integration }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
@@ -92,9 +90,6 @@ jobs:
|
||||
- "scaletest/**"
|
||||
- "tailnet/**"
|
||||
- "testutil/**"
|
||||
gomod:
|
||||
- "go.mod"
|
||||
- "go.sum"
|
||||
ts:
|
||||
- "site/**"
|
||||
- "Makefile"
|
||||
@@ -108,34 +103,11 @@ jobs:
|
||||
- ".github/workflows/ci.yaml"
|
||||
offlinedocs:
|
||||
- "offlinedocs/**"
|
||||
tailnet-integration:
|
||||
- "tailnet/**"
|
||||
- "go.mod"
|
||||
- "go.sum"
|
||||
|
||||
- id: debug
|
||||
run: |
|
||||
echo "${{ toJSON(steps.filter )}}"
|
||||
|
||||
update-flake:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.gomod == 'true'
|
||||
runs-on: ${{ github.repository_owner == 'coder' && 'buildjet-8vcpu-ubuntu-2204' || 'ubuntu-latest' }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Setup Go
|
||||
uses: ./.github/actions/setup-go
|
||||
|
||||
- name: Update Nix Flake SRI Hash
|
||||
run: ./scripts/update-flake.sh
|
||||
|
||||
- name: Ensure No Changes
|
||||
run: git diff --exit-code
|
||||
|
||||
lint:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.offlinedocs-only == 'false' || needs.changes.outputs.ci == 'true' || github.ref == 'refs/heads/main'
|
||||
@@ -170,7 +142,7 @@ jobs:
|
||||
|
||||
# Check for any typos
|
||||
- name: Check for typos
|
||||
uses: crate-ci/typos@v1.21.0
|
||||
uses: crate-ci/typos@v1.18.2
|
||||
with:
|
||||
config: .github/workflows/typos.toml
|
||||
|
||||
@@ -183,7 +155,7 @@ jobs:
|
||||
|
||||
# Needed for helm chart linting
|
||||
- name: Install helm
|
||||
uses: azure/setup-helm@v4
|
||||
uses: azure/setup-helm@v3
|
||||
with:
|
||||
version: v3.9.2
|
||||
|
||||
@@ -211,9 +183,6 @@ jobs:
|
||||
- name: Setup sqlc
|
||||
uses: ./.github/actions/setup-sqlc
|
||||
|
||||
- name: Setup Terraform
|
||||
uses: ./.github/actions/setup-tf
|
||||
|
||||
- name: go install tools
|
||||
run: |
|
||||
go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.30
|
||||
@@ -233,9 +202,7 @@ jobs:
|
||||
popd
|
||||
|
||||
- name: make gen
|
||||
# no `-j` flag as `make` fails with:
|
||||
# coderd/rbac/object_gen.go:1:1: syntax error: package statement must be first
|
||||
run: "make --output-sync -B gen"
|
||||
run: "make --output-sync -j -B gen"
|
||||
|
||||
- name: Check for unstaged files
|
||||
run: ./scripts/check_unstaged.sh
|
||||
@@ -259,7 +226,7 @@ jobs:
|
||||
with:
|
||||
# This doesn't need caching. It's super fast anyways!
|
||||
cache: false
|
||||
go-version: 1.21.9
|
||||
go-version: 1.21.5
|
||||
|
||||
- name: Install shfmt
|
||||
run: go install mvdan.cc/sh/v3/cmd/shfmt@v3.7.0
|
||||
@@ -300,6 +267,16 @@ jobs:
|
||||
id: test
|
||||
shell: bash
|
||||
run: |
|
||||
# Code coverage is more computationally expensive and also
|
||||
# prevents test caching, so we disable it on alternate operating
|
||||
# systems.
|
||||
if [ "${{ matrix.os }}" == "ubuntu-latest" ]; then
|
||||
echo "cover=true" >> $GITHUB_OUTPUT
|
||||
export COVERAGE_FLAGS='-covermode=atomic -coverprofile="gotests.coverage" -coverpkg=./...'
|
||||
else
|
||||
echo "cover=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
# if macOS, install google-chrome for scaletests. As another concern,
|
||||
# should we really have this kind of external dependency requirement
|
||||
# on standard CI?
|
||||
@@ -318,7 +295,7 @@ jobs:
|
||||
fi
|
||||
export TS_DEBUG_DISCO=true
|
||||
gotestsum --junitfile="gotests.xml" --jsonfile="gotests.json" \
|
||||
--packages="./..." -- $PARALLEL_FLAG -short -failfast
|
||||
--packages="./..." -- $PARALLEL_FLAG -short -failfast $COVERAGE_FLAGS
|
||||
|
||||
- name: Upload test stats to Datadog
|
||||
timeout-minutes: 1
|
||||
@@ -328,6 +305,19 @@ jobs:
|
||||
with:
|
||||
api-key: ${{ secrets.DATADOG_API_KEY }}
|
||||
|
||||
- name: Check code coverage
|
||||
uses: codecov/codecov-action@v4
|
||||
# This action has a tendency to error out unexpectedly, it has
|
||||
# the `fail_ci_if_error` option that defaults to `false`, but
|
||||
# that is no guarantee, see:
|
||||
# https://github.com/codecov/codecov-action/issues/788
|
||||
continue-on-error: true
|
||||
if: steps.test.outputs.cover && github.actor != 'dependabot[bot]' && !github.event.pull_request.head.repo.fork
|
||||
with:
|
||||
token: ${{ secrets.CODECOV_TOKEN }}
|
||||
files: ./gotests.coverage
|
||||
flags: unittest-go-${{ matrix.os }}
|
||||
|
||||
test-go-pg:
|
||||
runs-on: ${{ github.repository_owner == 'coder' && 'buildjet-8vcpu-ubuntu-2204' || 'ubuntu-latest' }}
|
||||
needs:
|
||||
@@ -363,6 +353,19 @@ jobs:
|
||||
with:
|
||||
api-key: ${{ secrets.DATADOG_API_KEY }}
|
||||
|
||||
- name: Check code coverage
|
||||
uses: codecov/codecov-action@v4
|
||||
# This action has a tendency to error out unexpectedly, it has
|
||||
# the `fail_ci_if_error` option that defaults to `false`, but
|
||||
# that is no guarantee, see:
|
||||
# https://github.com/codecov/codecov-action/issues/788
|
||||
continue-on-error: true
|
||||
if: github.actor != 'dependabot[bot]' && !github.event.pull_request.head.repo.fork
|
||||
with:
|
||||
token: ${{ secrets.CODECOV_TOKEN }}
|
||||
files: ./gotests.coverage
|
||||
flags: unittest-go-postgres-linux
|
||||
|
||||
test-go-race:
|
||||
runs-on: ${{ github.repository_owner == 'coder' && 'buildjet-8vcpu-ubuntu-2204' || 'ubuntu-latest' }}
|
||||
needs: changes
|
||||
@@ -392,34 +395,6 @@ jobs:
|
||||
with:
|
||||
api-key: ${{ secrets.DATADOG_API_KEY }}
|
||||
|
||||
# Tailnet integration tests only run when the `tailnet` directory or `go.sum`
|
||||
# and `go.mod` are changed. These tests are to ensure we don't add regressions
|
||||
# to tailnet, either due to our code or due to updating dependencies.
|
||||
#
|
||||
# These tests are skipped in the main go test jobs because they require root
|
||||
# and mess with networking.
|
||||
test-go-tailnet-integration:
|
||||
runs-on: ${{ github.repository_owner == 'coder' && 'buildjet-8vcpu-ubuntu-2204' || 'ubuntu-latest' }}
|
||||
needs: changes
|
||||
# Unnecessary to run on main for now
|
||||
if: needs.changes.outputs.tailnet-integration == 'true' || needs.changes.outputs.ci == 'true'
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Setup Go
|
||||
uses: ./.github/actions/setup-go
|
||||
|
||||
# Used by some integration tests.
|
||||
- name: Install Nginx
|
||||
run: sudo apt-get update && sudo apt-get install -y nginx
|
||||
|
||||
- name: Run Tests
|
||||
run: make test-tailnet-integration
|
||||
|
||||
test-js:
|
||||
runs-on: ${{ github.repository_owner == 'coder' && 'buildjet-8vcpu-ubuntu-2204' || 'ubuntu-latest' }}
|
||||
needs: changes
|
||||
@@ -437,20 +412,24 @@ jobs:
|
||||
- run: pnpm test:ci --max-workers $(nproc)
|
||||
working-directory: site
|
||||
|
||||
- name: Check code coverage
|
||||
uses: codecov/codecov-action@v4
|
||||
# This action has a tendency to error out unexpectedly, it has
|
||||
# the `fail_ci_if_error` option that defaults to `false`, but
|
||||
# that is no guarantee, see:
|
||||
# https://github.com/codecov/codecov-action/issues/788
|
||||
continue-on-error: true
|
||||
if: github.actor != 'dependabot[bot]' && !github.event.pull_request.head.repo.fork
|
||||
with:
|
||||
token: ${{ secrets.CODECOV_TOKEN }}
|
||||
files: ./site/coverage/lcov.info
|
||||
flags: unittest-js
|
||||
|
||||
test-e2e:
|
||||
runs-on: ${{ github.repository_owner == 'coder' && 'buildjet-16vcpu-ubuntu-2204' || 'ubuntu-latest' }}
|
||||
needs: changes
|
||||
if: needs.changes.outputs.go == 'true' || needs.changes.outputs.ts == 'true' || needs.changes.outputs.ci == 'true' || github.ref == 'refs/heads/main'
|
||||
timeout-minutes: 20
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
variant:
|
||||
- enterprise: false
|
||||
name: test-e2e
|
||||
- enterprise: true
|
||||
name: test-e2e-enterprise
|
||||
name: ${{ matrix.variant.name }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
@@ -463,40 +442,44 @@ jobs:
|
||||
- name: Setup Go
|
||||
uses: ./.github/actions/setup-go
|
||||
|
||||
# Assume that the checked-in versions are up-to-date
|
||||
- run: make gen/mark-fresh
|
||||
name: make gen
|
||||
- name: Setup Terraform
|
||||
uses: ./.github/actions/setup-tf
|
||||
|
||||
- run: pnpm build
|
||||
working-directory: site
|
||||
- name: go install tools
|
||||
run: |
|
||||
go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.30
|
||||
go install storj.io/drpc/cmd/protoc-gen-go-drpc@v0.0.33
|
||||
go install golang.org/x/tools/cmd/goimports@latest
|
||||
go install github.com/mikefarah/yq/v4@v4.30.6
|
||||
go install go.uber.org/mock/mockgen@v0.4.0
|
||||
|
||||
- name: Install Protoc
|
||||
run: |
|
||||
mkdir -p /tmp/proto
|
||||
pushd /tmp/proto
|
||||
curl -L -o protoc.zip https://github.com/protocolbuffers/protobuf/releases/download/v23.3/protoc-23.3-linux-x86_64.zip
|
||||
unzip protoc.zip
|
||||
cp -r ./bin/* /usr/local/bin
|
||||
cp -r ./include /usr/local/bin/include
|
||||
popd
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
make -B site/out/index.html
|
||||
|
||||
- run: pnpm playwright:install
|
||||
working-directory: site
|
||||
|
||||
# Run tests that don't require an enterprise license without an enterprise license
|
||||
- run: pnpm playwright:test --forbid-only --workers 1
|
||||
if: ${{ !matrix.variant.enterprise }}
|
||||
- run: pnpm playwright:test --workers 1
|
||||
env:
|
||||
DEBUG: pw:api
|
||||
working-directory: site
|
||||
|
||||
# Run all of the tests with an enterprise license
|
||||
- run: pnpm playwright:test --forbid-only --workers 1
|
||||
if: ${{ matrix.variant.enterprise }}
|
||||
env:
|
||||
DEBUG: pw:api
|
||||
CODER_E2E_ENTERPRISE_LICENSE: ${{ secrets.CODER_E2E_ENTERPRISE_LICENSE }}
|
||||
CODER_E2E_REQUIRE_ENTERPRISE_TESTS: "1"
|
||||
working-directory: site
|
||||
# Temporarily allow these to fail so that I can gather data about which
|
||||
# tests are failing.
|
||||
continue-on-error: true
|
||||
|
||||
- name: Upload Playwright Failed Tests
|
||||
if: always() && github.actor != 'dependabot[bot]' && runner.os == 'Linux' && !github.event.pull_request.head.repo.fork
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: failed-test-videos${{ matrix.variant.enterprise && '-enterprise' || '-agpl' }}
|
||||
name: failed-test-videos
|
||||
path: ./site/test-results/**/*.webm
|
||||
retention-days: 7
|
||||
|
||||
@@ -504,7 +487,7 @@ jobs:
|
||||
if: always() && github.actor != 'dependabot[bot]' && runner.os == 'Linux' && !github.event.pull_request.head.repo.fork
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: debug-pprof-dumps${{ matrix.variant.enterprise && '-enterprise' || '-agpl' }}
|
||||
name: debug-pprof-dumps
|
||||
path: ./site/test-results/**/debug-pprof-*.txt
|
||||
retention-days: 7
|
||||
|
||||
@@ -632,10 +615,8 @@ jobs:
|
||||
pnpm lint
|
||||
|
||||
- name: Build
|
||||
# no `-j` flag as `make` fails with:
|
||||
# coderd/rbac/object_gen.go:1:1: syntax error: package statement must be first
|
||||
run: |
|
||||
make build/coder_docs_"$(./scripts/version.sh)".tgz
|
||||
make -j build/coder_docs_"$(./scripts/version.sh)".tgz
|
||||
|
||||
required:
|
||||
runs-on: ubuntu-latest
|
||||
@@ -650,7 +631,6 @@ jobs:
|
||||
- test-e2e
|
||||
- offlinedocs
|
||||
- sqlc-vet
|
||||
- dependency-license-review
|
||||
# Allow this job to run even if the needed jobs fail, are skipped or
|
||||
# cancelled.
|
||||
if: always()
|
||||
@@ -667,7 +647,6 @@ jobs:
|
||||
echo "- test-js: ${{ needs.test-js.result }}"
|
||||
echo "- test-e2e: ${{ needs.test-e2e.result }}"
|
||||
echo "- offlinedocs: ${{ needs.offlinedocs.result }}"
|
||||
echo "- dependency-license-review: ${{ needs.dependency-license-review.result }}"
|
||||
echo
|
||||
|
||||
# We allow skipped jobs to pass, but not failed or cancelled jobs.
|
||||
@@ -683,7 +662,7 @@ jobs:
|
||||
# to main branch. We are only building this for amd64 platform. (>95% pulls
|
||||
# are for amd64)
|
||||
needs: changes
|
||||
if: github.ref == 'refs/heads/main' && needs.changes.outputs.docs-only == 'false' && !github.event.pull_request.head.repo.fork
|
||||
if: needs.changes.outputs.docs-only == 'false' && !github.event.pull_request.head.repo.fork
|
||||
runs-on: ${{ github.repository_owner == 'coder' && 'buildjet-8vcpu-ubuntu-2204' || 'ubuntu-latest' }}
|
||||
env:
|
||||
DOCKER_CLI_EXPERIMENTAL: "enabled"
|
||||
@@ -908,43 +887,3 @@ jobs:
|
||||
- name: Setup and run sqlc vet
|
||||
run: |
|
||||
make sqlc-vet
|
||||
|
||||
# dependency-license-review checks that no license-incompatible dependencies have been introduced.
|
||||
# This action is not intended to do a vulnerability check since that is handled by a separate action.
|
||||
dependency-license-review:
|
||||
runs-on: ubuntu-latest
|
||||
if: github.ref != 'refs/heads/main' && github.actor != 'dependabot[bot]'
|
||||
steps:
|
||||
- name: "Checkout Repository"
|
||||
uses: actions/checkout@v4
|
||||
- name: "Dependency Review"
|
||||
id: review
|
||||
uses: actions/dependency-review-action@v4.3.2
|
||||
with:
|
||||
allow-licenses: Apache-2.0, BSD-2-Clause, BSD-3-Clause, CC0-1.0, ISC, MIT, MIT-0, MPL-2.0
|
||||
allow-dependencies-licenses: "pkg:golang/github.com/coder/wgtunnel@0.1.13-0.20240522110300-ade90dfb2da0"
|
||||
license-check: true
|
||||
vulnerability-check: false
|
||||
- name: "Report"
|
||||
# make sure this step runs even if the previous failed
|
||||
if: always()
|
||||
shell: bash
|
||||
env:
|
||||
VULNERABLE_CHANGES: ${{ steps.review.outputs.invalid-license-changes }}
|
||||
run: |
|
||||
fields=( "unlicensed" "unresolved" "forbidden" )
|
||||
|
||||
# This is unfortunate that we have to do this but the action does not support failing on
|
||||
# an unknown license. The unknown dependency could easily have a GPL license which
|
||||
# would be problematic for us.
|
||||
# Track https://github.com/actions/dependency-review-action/issues/672 for when
|
||||
# we can remove this brittle workaround.
|
||||
for field in "${fields[@]}"; do
|
||||
# Use jq to check if the array is not empty
|
||||
if [[ $(echo "$VULNERABLE_CHANGES" | jq ".${field} | length") -ne 0 ]]; then
|
||||
echo "Invalid or unknown licenses detected, contact @sreya to ensure your added dependency falls under one of our allowed licenses."
|
||||
echo "$VULNERABLE_CHANGES" | jq
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
echo "No incompatible licenses detected"
|
||||
|
||||
@@ -34,7 +34,7 @@ jobs:
|
||||
steps:
|
||||
- name: cla
|
||||
if: (github.event.comment.body == 'recheck' || github.event.comment.body == 'I have read the CLA Document and I hereby sign the CLA') || github.event_name == 'pull_request_target'
|
||||
uses: contributor-assistant/github-action@v2.4.0
|
||||
uses: contributor-assistant/github-action@v2.3.1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
# the below token should have repo scope and must be manually added by you in the repository's secret
|
||||
|
||||
@@ -8,11 +8,6 @@ on:
|
||||
- scripts/Dockerfile.base
|
||||
- scripts/Dockerfile
|
||||
|
||||
pull_request:
|
||||
paths:
|
||||
- scripts/Dockerfile.base
|
||||
- .github/workflows/docker-base.yaml
|
||||
|
||||
schedule:
|
||||
# Run every week at 09:43 on Monday, Wednesday and Friday. We build this
|
||||
# frequently to ensure that packages are up-to-date.
|
||||
@@ -62,12 +57,11 @@ jobs:
|
||||
platforms: linux/amd64,linux/arm64,linux/arm/v7
|
||||
pull: true
|
||||
no-cache: true
|
||||
push: ${{ github.event_name != 'pull_request' }}
|
||||
push: true
|
||||
tags: |
|
||||
ghcr.io/coder/coder-base:latest
|
||||
|
||||
- name: Verify that images are pushed properly
|
||||
if: github.event_name != 'pull_request'
|
||||
run: |
|
||||
# retry 10 times with a 5 second delay as the images may not be
|
||||
# available immediately
|
||||
|
||||
@@ -17,9 +17,6 @@
|
||||
},
|
||||
{
|
||||
"pattern": "tailscale.com"
|
||||
},
|
||||
{
|
||||
"pattern": "wireguard.com"
|
||||
}
|
||||
],
|
||||
"aliveStatusCodes": [200, 0]
|
||||
|
||||
@@ -1,16 +1,11 @@
|
||||
# GitHub release workflow.
|
||||
name: Release
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "v*"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
release_channel:
|
||||
type: choice
|
||||
description: Release channel
|
||||
options:
|
||||
- mainline
|
||||
- stable
|
||||
release_notes:
|
||||
description: Release notes for the publishing the release. This is required to create a release.
|
||||
dry_run:
|
||||
description: Perform a dry-run release (devel). Note that ref must be an annotated tag when run without dry-run.
|
||||
type: boolean
|
||||
@@ -33,8 +28,6 @@ env:
|
||||
# https://github.blog/changelog/2022-06-10-github-actions-inputs-unified-across-manual-and-reusable-workflows/
|
||||
CODER_RELEASE: ${{ !inputs.dry_run }}
|
||||
CODER_DRY_RUN: ${{ inputs.dry_run }}
|
||||
CODER_RELEASE_CHANNEL: ${{ inputs.release_channel }}
|
||||
CODER_RELEASE_NOTES: ${{ inputs.release_notes }}
|
||||
|
||||
jobs:
|
||||
release:
|
||||
@@ -69,45 +62,21 @@ jobs:
|
||||
echo "CODER_FORCE_VERSION=$version" >> $GITHUB_ENV
|
||||
echo "$version"
|
||||
|
||||
# Verify that all expectations for a release are met.
|
||||
- name: Verify release input
|
||||
if: ${{ !inputs.dry_run }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
if [[ "${GITHUB_REF}" != "refs/tags/v"* ]]; then
|
||||
echo "Ref must be a semver tag when creating a release, did you use scripts/release.sh?"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 2.10.2 -> release/2.10
|
||||
version="$(./scripts/version.sh)"
|
||||
release_branch=release/${version%.*}
|
||||
branch_contains_tag=$(git branch --remotes --contains "${GITHUB_REF}" --list "*/${release_branch}" --format='%(refname)')
|
||||
if [[ -z "${branch_contains_tag}" ]]; then
|
||||
echo "Ref tag must exist in a branch named ${release_branch} when creating a release, did you use scripts/release.sh?"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ -z "${CODER_RELEASE_NOTES}" ]]; then
|
||||
echo "Release notes are required to create a release, did you use scripts/release.sh?"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Release inputs verified:"
|
||||
echo
|
||||
echo "- Ref: ${GITHUB_REF}"
|
||||
echo "- Version: ${version}"
|
||||
echo "- Release channel: ${CODER_RELEASE_CHANNEL}"
|
||||
echo "- Release branch: ${release_branch}"
|
||||
echo "- Release notes: true"
|
||||
|
||||
- name: Create release notes file
|
||||
- name: Create release notes
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
# We always have to set this since there might be commits on
|
||||
# main that didn't have a PR.
|
||||
CODER_IGNORE_MISSING_COMMIT_METADATA: "1"
|
||||
run: |
|
||||
set -euo pipefail
|
||||
ref=HEAD
|
||||
old_version="$(git describe --abbrev=0 "$ref^1")"
|
||||
version="v$(./scripts/version.sh)"
|
||||
|
||||
# Generate notes.
|
||||
release_notes_file="$(mktemp -t release_notes.XXXXXX)"
|
||||
echo "$CODER_RELEASE_NOTES" > "$release_notes_file"
|
||||
./scripts/release/generate_release_notes.sh --check-for-changelog --old-version "$old_version" --new-version "$version" --ref "$ref" >> "$release_notes_file"
|
||||
echo CODER_RELEASE_NOTES_FILE="$release_notes_file" >> $GITHUB_ENV
|
||||
|
||||
- name: Show release notes
|
||||
@@ -128,13 +97,6 @@ jobs:
|
||||
- name: Setup Node
|
||||
uses: ./.github/actions/setup-node
|
||||
|
||||
# Necessary for signing Windows binaries.
|
||||
- name: Setup Java
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: "zulu"
|
||||
java-version: "11.0"
|
||||
|
||||
- name: Install nsis and zstd
|
||||
run: sudo apt-get install -y nsis zstd
|
||||
|
||||
@@ -168,32 +130,6 @@ jobs:
|
||||
AC_CERTIFICATE_PASSWORD: ${{ secrets.AC_CERTIFICATE_PASSWORD }}
|
||||
AC_APIKEY_P8_BASE64: ${{ secrets.AC_APIKEY_P8_BASE64 }}
|
||||
|
||||
- name: Setup Windows EV Signing Certificate
|
||||
run: |
|
||||
set -euo pipefail
|
||||
touch /tmp/ev_cert.pem
|
||||
chmod 600 /tmp/ev_cert.pem
|
||||
echo "$EV_SIGNING_CERT" > /tmp/ev_cert.pem
|
||||
wget https://github.com/ebourg/jsign/releases/download/6.0/jsign-6.0.jar -O /tmp/jsign-6.0.jar
|
||||
env:
|
||||
EV_SIGNING_CERT: ${{ secrets.EV_SIGNING_CERT }}
|
||||
|
||||
- name: Test migrations from current ref to main
|
||||
run: |
|
||||
make test-migrations
|
||||
|
||||
# Setup GCloud for signing Windows binaries.
|
||||
- name: Authenticate to Google Cloud
|
||||
id: gcloud_auth
|
||||
uses: google-github-actions/auth@v2
|
||||
with:
|
||||
workload_identity_provider: ${{ secrets.GCP_CODE_SIGNING_WORKLOAD_ID_PROVIDER }}
|
||||
service_account: ${{ secrets.GCP_CODE_SIGNING_SERVICE_ACCOUNT }}
|
||||
token_format: "access_token"
|
||||
|
||||
- name: Setup GCloud SDK
|
||||
uses: "google-github-actions/setup-gcloud@v2"
|
||||
|
||||
- name: Build binaries
|
||||
run: |
|
||||
set -euo pipefail
|
||||
@@ -208,26 +144,16 @@ jobs:
|
||||
build/coder_helm_"$version".tgz \
|
||||
build/provisioner_helm_"$version".tgz
|
||||
env:
|
||||
CODER_SIGN_WINDOWS: "1"
|
||||
CODER_SIGN_DARWIN: "1"
|
||||
AC_CERTIFICATE_FILE: /tmp/apple_cert.p12
|
||||
AC_CERTIFICATE_PASSWORD_FILE: /tmp/apple_cert_password.txt
|
||||
AC_APIKEY_ISSUER_ID: ${{ secrets.AC_APIKEY_ISSUER_ID }}
|
||||
AC_APIKEY_ID: ${{ secrets.AC_APIKEY_ID }}
|
||||
AC_APIKEY_FILE: /tmp/apple_apikey.p8
|
||||
EV_KEY: ${{ secrets.EV_KEY }}
|
||||
EV_KEYSTORE: ${{ secrets.EV_KEYSTORE }}
|
||||
EV_TSA_URL: ${{ secrets.EV_TSA_URL }}
|
||||
EV_CERTIFICATE_PATH: /tmp/ev_cert.pem
|
||||
GCLOUD_ACCESS_TOKEN: ${{ steps.gcloud_auth.outputs.access_token }}
|
||||
JSIGN_PATH: /tmp/jsign-6.0.jar
|
||||
|
||||
- name: Delete Apple Developer certificate and API key
|
||||
run: rm -f /tmp/{apple_cert.p12,apple_cert_password.txt,apple_apikey.p8}
|
||||
|
||||
- name: Delete Windows EV Signing Cert
|
||||
run: rm /tmp/ev_cert.pem
|
||||
|
||||
- name: Determine base image tag
|
||||
id: image-base-tag
|
||||
run: |
|
||||
@@ -335,9 +261,6 @@ jobs:
|
||||
set -euo pipefail
|
||||
|
||||
publish_args=()
|
||||
if [[ $CODER_RELEASE_CHANNEL == "stable" ]]; then
|
||||
publish_args+=(--stable)
|
||||
fi
|
||||
if [[ $CODER_DRY_RUN == *t* ]]; then
|
||||
publish_args+=(--dry-run)
|
||||
fi
|
||||
|
||||
@@ -114,7 +114,7 @@ jobs:
|
||||
echo "image=$(cat "$image_job")" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Run Trivy vulnerability scanner
|
||||
uses: aquasecurity/trivy-action@fd25fed6972e341ff0007ddb61f77e88103953c2
|
||||
uses: aquasecurity/trivy-action@84384bd6e777ef152729993b8145ea352e9dd3ef
|
||||
with:
|
||||
image-ref: ${{ steps.build.outputs.image }}
|
||||
format: sarif
|
||||
|
||||
@@ -15,7 +15,6 @@ Hashi = "Hashi"
|
||||
trialer = "trialer"
|
||||
encrypter = "encrypter"
|
||||
hel = "hel" # as in helsinki
|
||||
pn = "pn" # this is used as proto node
|
||||
|
||||
[files]
|
||||
extend-exclude = [
|
||||
@@ -33,5 +32,4 @@ extend-exclude = [
|
||||
"**/pnpm-lock.yaml",
|
||||
"tailnet/testdata/**",
|
||||
"site/src/pages/SetupPage/countries.tsx",
|
||||
"provisioner/terraform/testdata/**",
|
||||
]
|
||||
|
||||
@@ -4,11 +4,6 @@ on:
|
||||
schedule:
|
||||
- cron: "0 9 * * 1"
|
||||
workflow_dispatch: # allows to run manually for testing
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- "docs/**"
|
||||
|
||||
jobs:
|
||||
check-docs:
|
||||
@@ -29,7 +24,7 @@ jobs:
|
||||
file-path: "./README.md"
|
||||
|
||||
- name: Send Slack notification
|
||||
if: failure() && github.event_name == 'schedule'
|
||||
if: failure()
|
||||
run: |
|
||||
curl -X POST -H 'Content-type: application/json' -d '{"msg":"Broken links found in the documentation. Please check the logs at ${{ env.LOGS_URL }}"}' ${{ secrets.DOCS_LINK_SLACK_WEBHOOK }}
|
||||
echo "Sent Slack notification"
|
||||
|
||||
Vendored
+2
-3
@@ -195,6 +195,7 @@
|
||||
"**.pb.go": true,
|
||||
"**/*.gen.json": true,
|
||||
"**/testdata/*": true,
|
||||
"**Generated.ts": true,
|
||||
"coderd/apidoc/**": true,
|
||||
"docs/api/*.md": true,
|
||||
"docs/templates/*.md": true,
|
||||
@@ -221,7 +222,5 @@
|
||||
"go.testFlags": ["-short", "-coverpkg=./..."],
|
||||
// We often use a version of TypeScript that's ahead of the version shipped
|
||||
// with VS Code.
|
||||
"typescript.tsdk": "./site/node_modules/typescript/lib",
|
||||
// Playwright tests in VSCode will open a browser to live "view" the test.
|
||||
"playwright.reuseBrowser": true
|
||||
"typescript.tsdk": "./site/node_modules/typescript/lib"
|
||||
}
|
||||
|
||||
@@ -56,9 +56,6 @@ GO_SRC_FILES := $(shell find . $(FIND_EXCLUSIONS) -type f -name '*.go' -not -nam
|
||||
# All the shell files in the repo, excluding ignored files.
|
||||
SHELL_SRC_FILES := $(shell find . $(FIND_EXCLUSIONS) -type f -name '*.sh')
|
||||
|
||||
# Ensure we don't use the user's git configs which might cause side-effects
|
||||
GIT_FLAGS = GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_SYSTEM=/dev/null
|
||||
|
||||
# All ${OS}_${ARCH} combos we build for. Windows binaries have the .exe suffix.
|
||||
OS_ARCHES := \
|
||||
linux_amd64 linux_arm64 linux_armv7 \
|
||||
@@ -203,8 +200,7 @@ endef
|
||||
# calling this manually.
|
||||
$(CODER_ALL_BINARIES): go.mod go.sum \
|
||||
$(GO_SRC_FILES) \
|
||||
$(shell find ./examples/templates) \
|
||||
site/static/error.html
|
||||
$(shell find ./examples/templates)
|
||||
|
||||
$(get-mode-os-arch-ext)
|
||||
if [[ "$$os" != "windows" ]] && [[ "$$ext" != "" ]]; then
|
||||
@@ -386,9 +382,9 @@ install: build/coder_$(VERSION)_$(GOOS)_$(GOARCH)$(GOOS_BIN_EXT)
|
||||
cp "$<" "$$output_file"
|
||||
.PHONY: install
|
||||
|
||||
BOLD := $(shell tput bold 2>/dev/null)
|
||||
GREEN := $(shell tput setaf 2 2>/dev/null)
|
||||
RESET := $(shell tput sgr0 2>/dev/null)
|
||||
BOLD := $(shell tput bold)
|
||||
GREEN := $(shell tput setaf 2)
|
||||
RESET := $(shell tput sgr0)
|
||||
|
||||
fmt: fmt/eslint fmt/prettier fmt/terraform fmt/shfmt fmt/go
|
||||
.PHONY: fmt
|
||||
@@ -432,7 +428,7 @@ else
|
||||
endif
|
||||
.PHONY: fmt/shfmt
|
||||
|
||||
lint: lint/shellcheck lint/go lint/ts lint/examples lint/helm lint/site-icons
|
||||
lint: lint/shellcheck lint/go lint/ts lint/helm lint/site-icons
|
||||
.PHONY: lint
|
||||
|
||||
lint/site-icons:
|
||||
@@ -451,10 +447,6 @@ lint/go:
|
||||
golangci-lint run
|
||||
.PHONY: lint/go
|
||||
|
||||
lint/examples:
|
||||
go run ./scripts/examplegen/main.go -lint
|
||||
.PHONY: lint/examples
|
||||
|
||||
# Use shfmt to determine the shell files, takes editorconfig into consideration.
|
||||
lint/shellcheck: $(SHELL_SRC_FILES)
|
||||
echo "--- shellcheck"
|
||||
@@ -486,14 +478,12 @@ gen: \
|
||||
$(DB_GEN_FILES) \
|
||||
site/src/api/typesGenerated.ts \
|
||||
coderd/rbac/object_gen.go \
|
||||
codersdk/rbacresources_gen.go \
|
||||
docs/admin/prometheus.md \
|
||||
docs/cli.md \
|
||||
docs/admin/audit-logs.md \
|
||||
coderd/apidoc/swagger.json \
|
||||
.prettierignore.include \
|
||||
.prettierignore \
|
||||
provisioner/terraform/testdata/version \
|
||||
site/.prettierrc.yaml \
|
||||
site/.prettierignore \
|
||||
site/.eslintignore \
|
||||
@@ -559,9 +549,6 @@ coderd/database/querier.go: coderd/database/sqlc.yaml coderd/database/dump.sql $
|
||||
coderd/database/dbmock/dbmock.go: coderd/database/db.go coderd/database/querier.go
|
||||
go generate ./coderd/database/dbmock/
|
||||
|
||||
coderd/database/pubsub/psmock/psmock.go: coderd/database/pubsub/pubsub.go
|
||||
go generate ./coderd/database/pubsub/psmock
|
||||
|
||||
tailnet/tailnettest/coordinatormock.go tailnet/tailnettest/multiagentmock.go tailnet/tailnettest/coordinateemock.go: tailnet/coordinator.go tailnet/multiagent.go
|
||||
go generate ./tailnet/tailnettest/
|
||||
|
||||
@@ -616,10 +603,7 @@ examples/examples.gen.json: scripts/examplegen/main.go examples/examples.go $(sh
|
||||
go run ./scripts/examplegen/main.go > examples/examples.gen.json
|
||||
|
||||
coderd/rbac/object_gen.go: scripts/rbacgen/main.go coderd/rbac/object.go
|
||||
go run scripts/rbacgen/main.go rbac > coderd/rbac/object_gen.go
|
||||
|
||||
codersdk/rbacresources_gen.go: scripts/rbacgen/main.go coderd/rbac/object.go
|
||||
go run scripts/rbacgen/main.go codersdk > codersdk/rbacresources_gen.go
|
||||
go run scripts/rbacgen/main.go ./coderd/rbac > coderd/rbac/object_gen.go
|
||||
|
||||
docs/admin/prometheus.md: scripts/metricsdocgen/main.go scripts/metricsdocgen/metrics
|
||||
go run scripts/metricsdocgen/main.go
|
||||
@@ -654,7 +638,7 @@ update-golden-files: \
|
||||
.PHONY: update-golden-files
|
||||
|
||||
cli/testdata/.gen-golden: $(wildcard cli/testdata/*.golden) $(wildcard cli/*.tpl) $(GO_SRC_FILES) $(wildcard cli/*_test.go)
|
||||
go test ./cli -run="Test(CommandHelp|ServerYAML|ErrorExamples)" -update
|
||||
go test ./cli -run="Test(CommandHelp|ServerYAML)" -update
|
||||
touch "$@"
|
||||
|
||||
enterprise/cli/testdata/.gen-golden: $(wildcard enterprise/cli/testdata/*.golden) $(wildcard cli/*.tpl) $(GO_SRC_FILES) $(wildcard enterprise/cli/*_test.go)
|
||||
@@ -685,12 +669,6 @@ provisioner/terraform/testdata/.gen-golden: $(wildcard provisioner/terraform/tes
|
||||
go test ./provisioner/terraform -run="Test.*Golden$$" -update
|
||||
touch "$@"
|
||||
|
||||
provisioner/terraform/testdata/version:
|
||||
if [[ "$(shell cat provisioner/terraform/testdata/version.txt)" != "$(shell terraform version -json | jq -r '.terraform_version')" ]]; then
|
||||
./provisioner/terraform/testdata/generate.sh
|
||||
fi
|
||||
.PHONY: provisioner/terraform/testdata/version
|
||||
|
||||
scripts/ci-report/testdata/.gen-golden: $(wildcard scripts/ci-report/testdata/*) $(wildcard scripts/ci-report/*.go)
|
||||
go test ./scripts/ci-report -run=TestOutputMatchesGoldenFile -update
|
||||
touch "$@"
|
||||
@@ -756,7 +734,7 @@ site/.eslintignore site/.prettierignore: .prettierignore Makefile
|
||||
done < "$<"
|
||||
|
||||
test:
|
||||
$(GIT_FLAGS) gotestsum --format standard-quiet -- -v -short -count=1 ./...
|
||||
gotestsum --format standard-quiet -- -v -short -count=1 ./...
|
||||
.PHONY: test
|
||||
|
||||
# sqlc-cloud-is-setup will fail if no SQLc auth token is set. Use this as a
|
||||
@@ -792,7 +770,7 @@ sqlc-vet: test-postgres-docker
|
||||
test-postgres: test-postgres-docker
|
||||
# The postgres test is prone to failure, so we limit parallelism for
|
||||
# more consistent execution.
|
||||
$(GIT_FLAGS) DB=ci DB_FROM=$(shell go run scripts/migrate-ci/main.go) gotestsum \
|
||||
DB=ci DB_FROM=$(shell go run scripts/migrate-ci/main.go) gotestsum \
|
||||
--junitfile="gotests.xml" \
|
||||
--jsonfile="gotests.json" \
|
||||
--packages="./..." -- \
|
||||
@@ -801,18 +779,6 @@ test-postgres: test-postgres-docker
|
||||
-count=1
|
||||
.PHONY: test-postgres
|
||||
|
||||
test-migrations: test-postgres-docker
|
||||
echo "--- test migrations"
|
||||
set -euo pipefail
|
||||
COMMIT_FROM=$(shell git log -1 --format='%h' HEAD)
|
||||
echo "COMMIT_FROM=$${COMMIT_FROM}"
|
||||
COMMIT_TO=$(shell git log -1 --format='%h' origin/main)
|
||||
echo "COMMIT_TO=$${COMMIT_TO}"
|
||||
if [[ "$${COMMIT_FROM}" == "$${COMMIT_TO}" ]]; then echo "Nothing to do!"; exit 0; fi
|
||||
echo "DROP DATABASE IF EXISTS migrate_test_$${COMMIT_FROM}; CREATE DATABASE migrate_test_$${COMMIT_FROM};" | psql 'postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable'
|
||||
go run ./scripts/migrate-test/main.go --from="$$COMMIT_FROM" --to="$$COMMIT_TO" --postgres-url="postgresql://postgres:postgres@localhost:5432/migrate_test_$${COMMIT_FROM}?sslmode=disable"
|
||||
|
||||
# NOTE: we set --memory to the same size as a GitHub runner.
|
||||
test-postgres-docker:
|
||||
docker rm -f test-postgres-docker || true
|
||||
docker run \
|
||||
@@ -825,7 +791,6 @@ test-postgres-docker:
|
||||
--name test-postgres-docker \
|
||||
--restart no \
|
||||
--detach \
|
||||
--memory 16GB \
|
||||
gcr.io/coder-dev-1/postgres:13 \
|
||||
-c shared_buffers=1GB \
|
||||
-c work_mem=1GB \
|
||||
@@ -844,21 +809,9 @@ test-postgres-docker:
|
||||
|
||||
# Make sure to keep this in sync with test-go-race from .github/workflows/ci.yaml.
|
||||
test-race:
|
||||
$(GIT_FLAGS) gotestsum --junitfile="gotests.xml" -- -race -count=1 ./...
|
||||
gotestsum --junitfile="gotests.xml" -- -race -count=1 ./...
|
||||
.PHONY: test-race
|
||||
|
||||
test-tailnet-integration:
|
||||
env \
|
||||
CODER_TAILNET_TESTS=true \
|
||||
CODER_MAGICSOCK_DEBUG_LOGGING=true \
|
||||
TS_DEBUG_NETCHECK=true \
|
||||
GOTRACEBACK=single \
|
||||
go test \
|
||||
-exec "sudo -E" \
|
||||
-timeout=5m \
|
||||
-count=1 \
|
||||
./tailnet/test/integration
|
||||
|
||||
# Note: we used to add this to the test target, but it's not necessary and we can
|
||||
# achieve the desired result by specifying -count=1 in the go test invocation
|
||||
# instead. Keeping it here for convenience.
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
[Quickstart](#quickstart) | [Docs](https://coder.com/docs) | [Why Coder](https://coder.com/why) | [Enterprise](https://coder.com/docs/v2/latest/enterprise)
|
||||
|
||||
[](https://discord.gg/coder)
|
||||
[](https://codecov.io/gh/coder/coder)
|
||||
[](https://github.com/coder/coder/releases/latest)
|
||||
[](https://pkg.go.dev/github.com/coder/coder)
|
||||
[](https://goreportcard.com/report/github.com/coder/coder)
|
||||
@@ -52,8 +53,8 @@ curl -L https://coder.com/install.sh | sh
|
||||
# Start the Coder server (caches data in ~/.cache/coder)
|
||||
coder server
|
||||
|
||||
# Navigate to http://localhost:3000 to create your initial user,
|
||||
# create a Docker template, and provision a workspace
|
||||
# Navigate to http://localhost:3000 to create your initial user
|
||||
# Create a Docker template, and provision a workspace
|
||||
```
|
||||
|
||||
## Install
|
||||
@@ -67,11 +68,11 @@ Releases.
|
||||
curl -L https://coder.com/install.sh | sh
|
||||
```
|
||||
|
||||
You can run the install script with `--dry-run` to see the commands that will be used to install without executing them. Run the install script with `--help` for additional flags.
|
||||
You can run the install script with `--dry-run` to see the commands that will be used to install without executing them. You can modify the installation process by including flags. Run the install script with `--help` for reference.
|
||||
|
||||
> See [install](https://coder.com/docs/v2/latest/install) for additional methods.
|
||||
|
||||
Once installed, you can start a production deployment with a single command:
|
||||
Once installed, you can start a production deployment<sup>1</sup> with a single command:
|
||||
|
||||
```shell
|
||||
# Automatically sets up an external access URL on *.try.coder.app
|
||||
@@ -81,6 +82,8 @@ coder server
|
||||
coder server --postgres-url <url> --access-url <url>
|
||||
```
|
||||
|
||||
> <sup>1</sup> For production deployments, set up an external PostgreSQL instance for reliability.
|
||||
|
||||
Use `coder --help` to get a list of flags and environment variables. Use our [install guides](https://coder.com/docs/v2/latest/install) for a full walkthrough.
|
||||
|
||||
## Documentation
|
||||
@@ -93,13 +96,19 @@ Browse our docs [here](https://coder.com/docs/v2) or visit a specific section be
|
||||
- [**Administration**](https://coder.com/docs/v2/latest/admin): Learn how to operate Coder
|
||||
- [**Enterprise**](https://coder.com/docs/v2/latest/enterprise): Learn about our paid features built for large teams
|
||||
|
||||
## Support
|
||||
## Community and Support
|
||||
|
||||
Feel free to [open an issue](https://github.com/coder/coder/issues/new) if you have questions, run into bugs, or have a feature request.
|
||||
|
||||
[Join our Discord](https://discord.gg/coder) to provide feedback on in-progress features, and chat with the community using Coder!
|
||||
[Join our Discord](https://discord.gg/coder) or [Slack](https://cdr.co/join-community) to provide feedback on in-progress features, and chat with the community using Coder!
|
||||
|
||||
## Integrations
|
||||
## Contributing
|
||||
|
||||
Contributions are welcome! Read the [contributing docs](https://coder.com/docs/v2/latest/CONTRIBUTING) to get started.
|
||||
|
||||
Find our list of contributors [here](https://github.com/coder/coder/graphs/contributors).
|
||||
|
||||
## Related
|
||||
|
||||
We are always working on new integrations. Feel free to open an issue to request an integration. Contributions are welcome in any official or community repositories.
|
||||
|
||||
@@ -107,22 +116,10 @@ We are always working on new integrations. Feel free to open an issue to request
|
||||
|
||||
- [**VS Code Extension**](https://marketplace.visualstudio.com/items?itemName=coder.coder-remote): Open any Coder workspace in VS Code with a single click
|
||||
- [**JetBrains Gateway Extension**](https://plugins.jetbrains.com/plugin/19620-coder): Open any Coder workspace in JetBrains Gateway with a single click
|
||||
- [**Dev Container Builder**](https://github.com/coder/envbuilder): Build development environments using `devcontainer.json` on Docker, Kubernetes, and OpenShift
|
||||
- [**Module Registry**](https://registry.coder.com): Extend development environments with common use-cases
|
||||
- [**Kubernetes Log Stream**](https://github.com/coder/coder-logstream-kube): Stream Kubernetes Pod events to the Coder startup logs
|
||||
- [**Self-Hosted VS Code Extension Marketplace**](https://github.com/coder/code-marketplace): A private extension marketplace that works in restricted or airgapped networks integrating with [code-server](https://github.com/coder/code-server).
|
||||
|
||||
### Community
|
||||
|
||||
- [**Provision Coder with Terraform**](https://github.com/ElliotG/coder-oss-tf): Provision Coder on Google GKE, Azure AKS, AWS EKS, DigitalOcean DOKS, IBMCloud K8s, OVHCloud K8s, and Scaleway K8s Kapsule with Terraform
|
||||
- [**Coder Template GitHub Action**](https://github.com/marketplace/actions/update-coder-template): A GitHub Action that updates Coder templates
|
||||
|
||||
## Contributing
|
||||
|
||||
We are always happy to see new contributors to Coder. If you are new to the Coder codebase, we have
|
||||
[a guide on how to get started](https://coder.com/docs/v2/latest/CONTRIBUTING). We'd love to see your
|
||||
contributions!
|
||||
|
||||
## Hiring
|
||||
|
||||
Apply [here](https://cdr.co/github-apply) if you're interested in joining our team.
|
||||
- [**Coder GitHub Action**](https://github.com/marketplace/actions/update-coder-template): A GitHub Action that updates Coder templates
|
||||
- [**Various Templates**](./examples/templates/community-templates.md): Hetzner Cloud, Docker in Docker, and other templates the community has built.
|
||||
|
||||
+176
-364
@@ -25,7 +25,6 @@ import (
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/google/uuid"
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/common/expfmt"
|
||||
"github.com/spf13/afero"
|
||||
"go.uber.org/atomic"
|
||||
"golang.org/x/exp/slices"
|
||||
@@ -35,9 +34,10 @@ import (
|
||||
"tailscale.com/net/speedtest"
|
||||
"tailscale.com/tailcfg"
|
||||
"tailscale.com/types/netlogtype"
|
||||
"tailscale.com/util/clientmetric"
|
||||
|
||||
"cdr.dev/slog"
|
||||
"github.com/coder/retry"
|
||||
|
||||
"github.com/coder/coder/v2/agent/agentproc"
|
||||
"github.com/coder/coder/v2/agent/agentscripts"
|
||||
"github.com/coder/coder/v2/agent/agentssh"
|
||||
@@ -48,10 +48,8 @@ import (
|
||||
"github.com/coder/coder/v2/coderd/database/dbtime"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/coder/v2/codersdk/agentsdk"
|
||||
"github.com/coder/coder/v2/codersdk/workspacesdk"
|
||||
"github.com/coder/coder/v2/tailnet"
|
||||
tailnetproto "github.com/coder/coder/v2/tailnet/proto"
|
||||
"github.com/coder/retry"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -62,10 +60,7 @@ const (
|
||||
|
||||
// EnvProcPrioMgmt determines whether we attempt to manage
|
||||
// process CPU and OOM Killer priority.
|
||||
const (
|
||||
EnvProcPrioMgmt = "CODER_PROC_PRIO_MGMT"
|
||||
EnvProcOOMScore = "CODER_PROC_OOM_SCORE"
|
||||
)
|
||||
const EnvProcPrioMgmt = "CODER_PROC_PRIO_MGMT"
|
||||
|
||||
type Options struct {
|
||||
Filesystem afero.Fs
|
||||
@@ -155,35 +150,35 @@ func New(options Options) Agent {
|
||||
hardCtx, hardCancel := context.WithCancel(context.Background())
|
||||
gracefulCtx, gracefulCancel := context.WithCancel(hardCtx)
|
||||
a := &agent{
|
||||
tailnetListenPort: options.TailnetListenPort,
|
||||
reconnectingPTYTimeout: options.ReconnectingPTYTimeout,
|
||||
logger: options.Logger,
|
||||
gracefulCtx: gracefulCtx,
|
||||
gracefulCancel: gracefulCancel,
|
||||
hardCtx: hardCtx,
|
||||
hardCancel: hardCancel,
|
||||
coordDisconnected: make(chan struct{}),
|
||||
environmentVariables: options.EnvironmentVariables,
|
||||
client: options.Client,
|
||||
exchangeToken: options.ExchangeToken,
|
||||
filesystem: options.Filesystem,
|
||||
logDir: options.LogDir,
|
||||
tempDir: options.TempDir,
|
||||
scriptDataDir: options.ScriptDataDir,
|
||||
lifecycleUpdate: make(chan struct{}, 1),
|
||||
lifecycleReported: make(chan codersdk.WorkspaceAgentLifecycle, 1),
|
||||
lifecycleStates: []agentsdk.PostLifecycleRequest{{State: codersdk.WorkspaceAgentLifecycleCreated}},
|
||||
ignorePorts: options.IgnorePorts,
|
||||
portCacheDuration: options.PortCacheDuration,
|
||||
reportMetadataInterval: options.ReportMetadataInterval,
|
||||
announcementBannersRefreshInterval: options.ServiceBannerRefreshInterval,
|
||||
sshMaxTimeout: options.SSHMaxTimeout,
|
||||
subsystems: options.Subsystems,
|
||||
addresses: options.Addresses,
|
||||
syscaller: options.Syscaller,
|
||||
modifiedProcs: options.ModifiedProcesses,
|
||||
processManagementTick: options.ProcessManagementTick,
|
||||
logSender: agentsdk.NewLogSender(options.Logger),
|
||||
tailnetListenPort: options.TailnetListenPort,
|
||||
reconnectingPTYTimeout: options.ReconnectingPTYTimeout,
|
||||
logger: options.Logger,
|
||||
gracefulCtx: gracefulCtx,
|
||||
gracefulCancel: gracefulCancel,
|
||||
hardCtx: hardCtx,
|
||||
hardCancel: hardCancel,
|
||||
coordDisconnected: make(chan struct{}),
|
||||
environmentVariables: options.EnvironmentVariables,
|
||||
client: options.Client,
|
||||
exchangeToken: options.ExchangeToken,
|
||||
filesystem: options.Filesystem,
|
||||
logDir: options.LogDir,
|
||||
tempDir: options.TempDir,
|
||||
scriptDataDir: options.ScriptDataDir,
|
||||
lifecycleUpdate: make(chan struct{}, 1),
|
||||
lifecycleReported: make(chan codersdk.WorkspaceAgentLifecycle, 1),
|
||||
lifecycleStates: []agentsdk.PostLifecycleRequest{{State: codersdk.WorkspaceAgentLifecycleCreated}},
|
||||
ignorePorts: options.IgnorePorts,
|
||||
portCacheDuration: options.PortCacheDuration,
|
||||
reportMetadataInterval: options.ReportMetadataInterval,
|
||||
serviceBannerRefreshInterval: options.ServiceBannerRefreshInterval,
|
||||
sshMaxTimeout: options.SSHMaxTimeout,
|
||||
subsystems: options.Subsystems,
|
||||
addresses: options.Addresses,
|
||||
syscaller: options.Syscaller,
|
||||
modifiedProcs: options.ModifiedProcesses,
|
||||
processManagementTick: options.ProcessManagementTick,
|
||||
logSender: agentsdk.NewLogSender(options.Logger),
|
||||
|
||||
prometheusRegistry: prometheusRegistry,
|
||||
metrics: newAgentMetrics(prometheusRegistry),
|
||||
@@ -193,7 +188,7 @@ func New(options Options) Agent {
|
||||
// that gets closed on disconnection. This is used to wait for graceful disconnection from the
|
||||
// coordinator during shut down.
|
||||
close(a.coordDisconnected)
|
||||
a.announcementBanners.Store(new([]codersdk.BannerConfig))
|
||||
a.serviceBanner.Store(new(codersdk.ServiceBannerConfig))
|
||||
a.sessionToken.Store(new(string))
|
||||
a.init()
|
||||
return a
|
||||
@@ -231,20 +226,19 @@ type agent struct {
|
||||
|
||||
environmentVariables map[string]string
|
||||
|
||||
manifest atomic.Pointer[agentsdk.Manifest] // manifest is atomic because values can change after reconnection.
|
||||
reportMetadataInterval time.Duration
|
||||
scriptRunner *agentscripts.Runner
|
||||
announcementBanners atomic.Pointer[[]codersdk.BannerConfig] // announcementBanners is atomic because it is periodically updated.
|
||||
announcementBannersRefreshInterval time.Duration
|
||||
sessionToken atomic.Pointer[string]
|
||||
sshServer *agentssh.Server
|
||||
sshMaxTimeout time.Duration
|
||||
manifest atomic.Pointer[agentsdk.Manifest] // manifest is atomic because values can change after reconnection.
|
||||
reportMetadataInterval time.Duration
|
||||
scriptRunner *agentscripts.Runner
|
||||
serviceBanner atomic.Pointer[codersdk.ServiceBannerConfig] // serviceBanner is atomic because it is periodically updated.
|
||||
serviceBannerRefreshInterval time.Duration
|
||||
sessionToken atomic.Pointer[string]
|
||||
sshServer *agentssh.Server
|
||||
sshMaxTimeout time.Duration
|
||||
|
||||
lifecycleUpdate chan struct{}
|
||||
lifecycleReported chan codersdk.WorkspaceAgentLifecycle
|
||||
lifecycleMu sync.RWMutex // Protects following.
|
||||
lifecycleStates []agentsdk.PostLifecycleRequest
|
||||
lifecycleLastReportedIndex int // Keeps track of the last lifecycle state we successfully reported.
|
||||
lifecycleUpdate chan struct{}
|
||||
lifecycleReported chan codersdk.WorkspaceAgentLifecycle
|
||||
lifecycleMu sync.RWMutex // Protects following.
|
||||
lifecycleStates []agentsdk.PostLifecycleRequest
|
||||
|
||||
network *tailnet.Conn
|
||||
addresses []netip.Prefix
|
||||
@@ -272,11 +266,11 @@ func (a *agent) TailnetConn() *tailnet.Conn {
|
||||
func (a *agent) init() {
|
||||
// pass the "hard" context because we explicitly close the SSH server as part of graceful shutdown.
|
||||
sshSrv, err := agentssh.NewServer(a.hardCtx, a.logger.Named("ssh-server"), a.prometheusRegistry, a.filesystem, &agentssh.Config{
|
||||
MaxTimeout: a.sshMaxTimeout,
|
||||
MOTDFile: func() string { return a.manifest.Load().MOTDFile },
|
||||
AnnouncementBanners: func() *[]codersdk.BannerConfig { return a.announcementBanners.Load() },
|
||||
UpdateEnv: a.updateCommandEnv,
|
||||
WorkingDirectory: func() string { return a.manifest.Load().Directory },
|
||||
MaxTimeout: a.sshMaxTimeout,
|
||||
MOTDFile: func() string { return a.manifest.Load().MOTDFile },
|
||||
ServiceBanner: func() *codersdk.ServiceBannerConfig { return a.serviceBanner.Load() },
|
||||
UpdateEnv: a.updateCommandEnv,
|
||||
WorkingDirectory: func() string { return a.manifest.Load().Directory },
|
||||
})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
@@ -626,6 +620,7 @@ func (a *agent) reportMetadata(ctx context.Context, conn drpc.Conn) error {
|
||||
// changes are reported in order.
|
||||
func (a *agent) reportLifecycle(ctx context.Context, conn drpc.Conn) error {
|
||||
aAPI := proto.NewDRPCAgentClient(conn)
|
||||
lastReportedIndex := 0 // Start off with the created state without reporting it.
|
||||
for {
|
||||
select {
|
||||
case <-a.lifecycleUpdate:
|
||||
@@ -636,20 +631,20 @@ func (a *agent) reportLifecycle(ctx context.Context, conn drpc.Conn) error {
|
||||
for {
|
||||
a.lifecycleMu.RLock()
|
||||
lastIndex := len(a.lifecycleStates) - 1
|
||||
report := a.lifecycleStates[a.lifecycleLastReportedIndex]
|
||||
if len(a.lifecycleStates) > a.lifecycleLastReportedIndex+1 {
|
||||
report = a.lifecycleStates[a.lifecycleLastReportedIndex+1]
|
||||
report := a.lifecycleStates[lastReportedIndex]
|
||||
if len(a.lifecycleStates) > lastReportedIndex+1 {
|
||||
report = a.lifecycleStates[lastReportedIndex+1]
|
||||
}
|
||||
a.lifecycleMu.RUnlock()
|
||||
|
||||
if lastIndex == a.lifecycleLastReportedIndex {
|
||||
if lastIndex == lastReportedIndex {
|
||||
break
|
||||
}
|
||||
l, err := agentsdk.ProtoFromLifecycle(report)
|
||||
if err != nil {
|
||||
a.logger.Critical(ctx, "failed to convert lifecycle state", slog.F("report", report))
|
||||
// Skip this report; there is no point retrying. Maybe we can successfully convert the next one?
|
||||
a.lifecycleLastReportedIndex++
|
||||
lastReportedIndex++
|
||||
continue
|
||||
}
|
||||
payload := &proto.UpdateLifecycleRequest{Lifecycle: l}
|
||||
@@ -662,13 +657,13 @@ func (a *agent) reportLifecycle(ctx context.Context, conn drpc.Conn) error {
|
||||
}
|
||||
|
||||
logger.Debug(ctx, "successfully reported lifecycle state")
|
||||
a.lifecycleLastReportedIndex++
|
||||
lastReportedIndex++
|
||||
select {
|
||||
case a.lifecycleReported <- report.State:
|
||||
case <-a.lifecycleReported:
|
||||
a.lifecycleReported <- report.State
|
||||
}
|
||||
if a.lifecycleLastReportedIndex < lastIndex {
|
||||
if lastReportedIndex < lastIndex {
|
||||
// Keep reporting until we've sent all messages, we can't
|
||||
// rely on the channel triggering us before the backlog is
|
||||
// consumed.
|
||||
@@ -709,26 +704,23 @@ func (a *agent) setLifecycle(state codersdk.WorkspaceAgentLifecycle) {
|
||||
// (and must be done before the session actually starts).
|
||||
func (a *agent) fetchServiceBannerLoop(ctx context.Context, conn drpc.Conn) error {
|
||||
aAPI := proto.NewDRPCAgentClient(conn)
|
||||
ticker := time.NewTicker(a.announcementBannersRefreshInterval)
|
||||
ticker := time.NewTicker(a.serviceBannerRefreshInterval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-ticker.C:
|
||||
bannersProto, err := aAPI.GetAnnouncementBanners(ctx, &proto.GetAnnouncementBannersRequest{})
|
||||
sbp, err := aAPI.GetServiceBanner(ctx, &proto.GetServiceBannerRequest{})
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
a.logger.Error(ctx, "failed to update notification banners", slog.Error(err))
|
||||
a.logger.Error(ctx, "failed to update service banner", slog.Error(err))
|
||||
return err
|
||||
}
|
||||
banners := make([]codersdk.BannerConfig, 0, len(bannersProto.AnnouncementBanners))
|
||||
for _, bannerProto := range bannersProto.AnnouncementBanners {
|
||||
banners = append(banners, agentsdk.BannerConfigFromProto(bannerProto))
|
||||
}
|
||||
a.announcementBanners.Store(&banners)
|
||||
serviceBanner := agentsdk.ServiceBannerFromProto(sbp)
|
||||
a.serviceBanner.Store(&serviceBanner)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -760,18 +752,15 @@ func (a *agent) run() (retErr error) {
|
||||
// redial the coder server and retry.
|
||||
connMan := newAPIConnRoutineManager(a.gracefulCtx, a.hardCtx, a.logger, conn)
|
||||
|
||||
connMan.start("init notification banners", gracefulShutdownBehaviorStop,
|
||||
connMan.start("init service banner", gracefulShutdownBehaviorStop,
|
||||
func(ctx context.Context, conn drpc.Conn) error {
|
||||
aAPI := proto.NewDRPCAgentClient(conn)
|
||||
bannersProto, err := aAPI.GetAnnouncementBanners(ctx, &proto.GetAnnouncementBannersRequest{})
|
||||
sbp, err := aAPI.GetServiceBanner(ctx, &proto.GetServiceBannerRequest{})
|
||||
if err != nil {
|
||||
return xerrors.Errorf("fetch service banner: %w", err)
|
||||
}
|
||||
banners := make([]codersdk.BannerConfig, 0, len(bannersProto.AnnouncementBanners))
|
||||
for _, bannerProto := range bannersProto.AnnouncementBanners {
|
||||
banners = append(banners, agentsdk.BannerConfigFromProto(bannerProto))
|
||||
}
|
||||
a.announcementBanners.Store(&banners)
|
||||
serviceBanner := agentsdk.ServiceBannerFromProto(sbp)
|
||||
a.serviceBanner.Store(&serviceBanner)
|
||||
return nil
|
||||
},
|
||||
)
|
||||
@@ -813,21 +802,23 @@ func (a *agent) run() (retErr error) {
|
||||
// coordination <--------------------------+
|
||||
// derp map subscriber <----------------+
|
||||
// stats report loop <---------------+
|
||||
networkOK := newCheckpoint(a.logger)
|
||||
manifestOK := newCheckpoint(a.logger)
|
||||
networkOK := make(chan struct{})
|
||||
manifestOK := make(chan struct{})
|
||||
|
||||
connMan.start("handle manifest", gracefulShutdownBehaviorStop, a.handleManifest(manifestOK))
|
||||
|
||||
connMan.start("app health reporter", gracefulShutdownBehaviorStop,
|
||||
func(ctx context.Context, conn drpc.Conn) error {
|
||||
if err := manifestOK.wait(ctx); err != nil {
|
||||
return xerrors.Errorf("no manifest: %w", err)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
case <-manifestOK:
|
||||
manifest := a.manifest.Load()
|
||||
NewWorkspaceAppHealthReporter(
|
||||
a.logger, manifest.Apps, agentsdk.AppHealthPoster(proto.NewDRPCAgentClient(conn)),
|
||||
)(ctx)
|
||||
return nil
|
||||
}
|
||||
manifest := a.manifest.Load()
|
||||
NewWorkspaceAppHealthReporter(
|
||||
a.logger, manifest.Apps, agentsdk.AppHealthPoster(proto.NewDRPCAgentClient(conn)),
|
||||
)(ctx)
|
||||
return nil
|
||||
})
|
||||
|
||||
connMan.start("create or update network", gracefulShutdownBehaviorStop,
|
||||
@@ -835,8 +826,10 @@ func (a *agent) run() (retErr error) {
|
||||
|
||||
connMan.start("coordination", gracefulShutdownBehaviorStop,
|
||||
func(ctx context.Context, conn drpc.Conn) error {
|
||||
if err := networkOK.wait(ctx); err != nil {
|
||||
return xerrors.Errorf("no network: %w", err)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
case <-networkOK:
|
||||
}
|
||||
return a.runCoordinator(ctx, conn, a.network)
|
||||
},
|
||||
@@ -844,8 +837,10 @@ func (a *agent) run() (retErr error) {
|
||||
|
||||
connMan.start("derp map subscriber", gracefulShutdownBehaviorStop,
|
||||
func(ctx context.Context, conn drpc.Conn) error {
|
||||
if err := networkOK.wait(ctx); err != nil {
|
||||
return xerrors.Errorf("no network: %w", err)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
case <-networkOK:
|
||||
}
|
||||
return a.runDERPMapSubscriber(ctx, conn, a.network)
|
||||
})
|
||||
@@ -853,8 +848,10 @@ func (a *agent) run() (retErr error) {
|
||||
connMan.start("fetch service banner loop", gracefulShutdownBehaviorStop, a.fetchServiceBannerLoop)
|
||||
|
||||
connMan.start("stats report loop", gracefulShutdownBehaviorStop, func(ctx context.Context, conn drpc.Conn) error {
|
||||
if err := networkOK.wait(ctx); err != nil {
|
||||
return xerrors.Errorf("no network: %w", err)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
case <-networkOK:
|
||||
}
|
||||
return a.statsReporter.reportLoop(ctx, proto.NewDRPCAgentClient(conn))
|
||||
})
|
||||
@@ -863,17 +860,8 @@ func (a *agent) run() (retErr error) {
|
||||
}
|
||||
|
||||
// handleManifest returns a function that fetches and processes the manifest
|
||||
func (a *agent) handleManifest(manifestOK *checkpoint) func(ctx context.Context, conn drpc.Conn) error {
|
||||
func (a *agent) handleManifest(manifestOK chan<- struct{}) func(ctx context.Context, conn drpc.Conn) error {
|
||||
return func(ctx context.Context, conn drpc.Conn) error {
|
||||
var (
|
||||
sentResult = false
|
||||
err error
|
||||
)
|
||||
defer func() {
|
||||
if !sentResult {
|
||||
manifestOK.complete(err)
|
||||
}
|
||||
}()
|
||||
aAPI := proto.NewDRPCAgentClient(conn)
|
||||
mp, err := aAPI.GetManifest(ctx, &proto.GetManifestRequest{})
|
||||
if err != nil {
|
||||
@@ -910,12 +898,14 @@ func (a *agent) handleManifest(manifestOK *checkpoint) func(ctx context.Context,
|
||||
Subsystems: subsys,
|
||||
}})
|
||||
if err != nil {
|
||||
if xerrors.Is(err, context.Canceled) {
|
||||
return nil
|
||||
}
|
||||
return xerrors.Errorf("update workspace agent startup: %w", err)
|
||||
}
|
||||
|
||||
oldManifest := a.manifest.Swap(&manifest)
|
||||
manifestOK.complete(nil)
|
||||
sentResult = true
|
||||
close(manifestOK)
|
||||
|
||||
// The startup script should only execute on the first run!
|
||||
if oldManifest == nil {
|
||||
@@ -976,15 +966,14 @@ func (a *agent) handleManifest(manifestOK *checkpoint) func(ctx context.Context,
|
||||
|
||||
// createOrUpdateNetwork waits for the manifest to be set using manifestOK, then creates or updates
|
||||
// the tailnet using the information in the manifest
|
||||
func (a *agent) createOrUpdateNetwork(manifestOK, networkOK *checkpoint) func(context.Context, drpc.Conn) error {
|
||||
return func(ctx context.Context, _ drpc.Conn) (retErr error) {
|
||||
if err := manifestOK.wait(ctx); err != nil {
|
||||
return xerrors.Errorf("no manifest: %w", err)
|
||||
func (a *agent) createOrUpdateNetwork(manifestOK <-chan struct{}, networkOK chan<- struct{}) func(context.Context, drpc.Conn) error {
|
||||
return func(ctx context.Context, _ drpc.Conn) error {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
case <-manifestOK:
|
||||
}
|
||||
var err error
|
||||
defer func() {
|
||||
networkOK.complete(retErr)
|
||||
}()
|
||||
manifest := a.manifest.Load()
|
||||
a.closeMutex.Lock()
|
||||
network := a.network
|
||||
@@ -1020,6 +1009,7 @@ func (a *agent) createOrUpdateNetwork(manifestOK, networkOK *checkpoint) func(co
|
||||
network.SetDERPForceWebSockets(manifest.DERPForceWebSockets)
|
||||
network.SetBlockEndpoints(manifest.DisableDirectConnections)
|
||||
}
|
||||
close(networkOK)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -1115,7 +1105,7 @@ func (a *agent) wireguardAddresses(agentID uuid.UUID) []netip.Prefix {
|
||||
netip.PrefixFrom(tailnet.IPFromUUID(agentID), 128),
|
||||
// We also listen on the legacy codersdk.WorkspaceAgentIP. This
|
||||
// allows for a transition away from wsconncache.
|
||||
netip.PrefixFrom(workspacesdk.AgentIP, 128),
|
||||
netip.PrefixFrom(codersdk.WorkspaceAgentIP, 128),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1155,7 +1145,7 @@ func (a *agent) createTailnet(ctx context.Context, agentID uuid.UUID, derpMap *t
|
||||
}
|
||||
}()
|
||||
|
||||
sshListener, err := network.Listen("tcp", ":"+strconv.Itoa(workspacesdk.AgentSSHPort))
|
||||
sshListener, err := network.Listen("tcp", ":"+strconv.Itoa(codersdk.WorkspaceAgentSSHPort))
|
||||
if err != nil {
|
||||
return nil, xerrors.Errorf("listen on the ssh port: %w", err)
|
||||
}
|
||||
@@ -1170,7 +1160,7 @@ func (a *agent) createTailnet(ctx context.Context, agentID uuid.UUID, derpMap *t
|
||||
return nil, err
|
||||
}
|
||||
|
||||
reconnectingPTYListener, err := network.Listen("tcp", ":"+strconv.Itoa(workspacesdk.AgentReconnectingPTYPort))
|
||||
reconnectingPTYListener, err := network.Listen("tcp", ":"+strconv.Itoa(codersdk.WorkspaceAgentReconnectingPTYPort))
|
||||
if err != nil {
|
||||
return nil, xerrors.Errorf("listen for reconnecting pty: %w", err)
|
||||
}
|
||||
@@ -1219,7 +1209,7 @@ func (a *agent) createTailnet(ctx context.Context, agentID uuid.UUID, derpMap *t
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var msg workspacesdk.AgentReconnectingPTYInit
|
||||
var msg codersdk.WorkspaceAgentReconnectingPTYInit
|
||||
err = json.Unmarshal(data, &msg)
|
||||
if err != nil {
|
||||
logger.Warn(ctx, "failed to unmarshal init", slog.F("raw", data))
|
||||
@@ -1233,7 +1223,7 @@ func (a *agent) createTailnet(ctx context.Context, agentID uuid.UUID, derpMap *t
|
||||
return nil, err
|
||||
}
|
||||
|
||||
speedtestListener, err := network.Listen("tcp", ":"+strconv.Itoa(workspacesdk.AgentSpeedtestPort))
|
||||
speedtestListener, err := network.Listen("tcp", ":"+strconv.Itoa(codersdk.WorkspaceAgentSpeedtestPort))
|
||||
if err != nil {
|
||||
return nil, xerrors.Errorf("listen for speedtest: %w", err)
|
||||
}
|
||||
@@ -1281,7 +1271,7 @@ func (a *agent) createTailnet(ctx context.Context, agentID uuid.UUID, derpMap *t
|
||||
return nil, err
|
||||
}
|
||||
|
||||
apiListener, err := network.Listen("tcp", ":"+strconv.Itoa(workspacesdk.AgentHTTPAPIServerPort))
|
||||
apiListener, err := network.Listen("tcp", ":"+strconv.Itoa(codersdk.WorkspaceAgentHTTPAPIServerPort))
|
||||
if err != nil {
|
||||
return nil, xerrors.Errorf("api listener: %w", err)
|
||||
}
|
||||
@@ -1394,7 +1384,7 @@ func (a *agent) runDERPMapSubscriber(ctx context.Context, conn drpc.Conn, networ
|
||||
}
|
||||
}
|
||||
|
||||
func (a *agent) handleReconnectingPTY(ctx context.Context, logger slog.Logger, msg workspacesdk.AgentReconnectingPTYInit, conn net.Conn) (retErr error) {
|
||||
func (a *agent) handleReconnectingPTY(ctx context.Context, logger slog.Logger, msg codersdk.WorkspaceAgentReconnectingPTYInit, conn net.Conn) (retErr error) {
|
||||
defer conn.Close()
|
||||
a.metrics.connectionsTotal.Add(1)
|
||||
|
||||
@@ -1583,31 +1573,10 @@ func (a *agent) manageProcessPriorityUntilGracefulShutdown() {
|
||||
a.processManagementTick = ticker.C
|
||||
}
|
||||
|
||||
oomScore := unsetOOMScore
|
||||
if scoreStr, ok := a.environmentVariables[EnvProcOOMScore]; ok {
|
||||
score, err := strconv.Atoi(strings.TrimSpace(scoreStr))
|
||||
if err == nil && score >= -1000 && score <= 1000 {
|
||||
oomScore = score
|
||||
} else {
|
||||
a.logger.Error(ctx, "invalid oom score",
|
||||
slog.F("min_value", -1000),
|
||||
slog.F("max_value", 1000),
|
||||
slog.F("value", scoreStr),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
debouncer := &logDebouncer{
|
||||
logger: a.logger,
|
||||
messages: map[string]time.Time{},
|
||||
interval: time.Minute,
|
||||
}
|
||||
|
||||
for {
|
||||
procs, err := a.manageProcessPriority(ctx, debouncer, oomScore)
|
||||
// Avoid spamming the logs too often.
|
||||
procs, err := a.manageProcessPriority(ctx)
|
||||
if err != nil {
|
||||
debouncer.Error(ctx, "manage process priority",
|
||||
a.logger.Error(ctx, "manage process priority",
|
||||
slog.Error(err),
|
||||
)
|
||||
}
|
||||
@@ -1623,34 +1592,27 @@ func (a *agent) manageProcessPriorityUntilGracefulShutdown() {
|
||||
}
|
||||
}
|
||||
|
||||
// unsetOOMScore is set to an invalid OOM score to imply an unset value.
|
||||
const unsetOOMScore = 1001
|
||||
|
||||
func (a *agent) manageProcessPriority(ctx context.Context, debouncer *logDebouncer, oomScore int) ([]*agentproc.Process, error) {
|
||||
func (a *agent) manageProcessPriority(ctx context.Context) ([]*agentproc.Process, error) {
|
||||
const (
|
||||
niceness = 10
|
||||
)
|
||||
|
||||
// We fetch the agent score each time because it's possible someone updates the
|
||||
// value after it is started.
|
||||
agentScore, err := a.getAgentOOMScore()
|
||||
if err != nil {
|
||||
agentScore = unsetOOMScore
|
||||
}
|
||||
if oomScore == unsetOOMScore && agentScore != unsetOOMScore {
|
||||
// If the child score has not been explicitly specified we should
|
||||
// set it to a score relative to the agent score.
|
||||
oomScore = childOOMScore(agentScore)
|
||||
}
|
||||
|
||||
procs, err := agentproc.List(a.filesystem, a.syscaller)
|
||||
if err != nil {
|
||||
return nil, xerrors.Errorf("list: %w", err)
|
||||
}
|
||||
|
||||
modProcs := []*agentproc.Process{}
|
||||
var (
|
||||
modProcs = []*agentproc.Process{}
|
||||
logger slog.Logger
|
||||
)
|
||||
|
||||
for _, proc := range procs {
|
||||
logger = a.logger.With(
|
||||
slog.F("cmd", proc.Cmd()),
|
||||
slog.F("pid", proc.PID),
|
||||
)
|
||||
|
||||
containsFn := func(e string) bool {
|
||||
contains := strings.Contains(proc.Cmd(), e)
|
||||
return contains
|
||||
@@ -1658,16 +1620,14 @@ func (a *agent) manageProcessPriority(ctx context.Context, debouncer *logDebounc
|
||||
|
||||
// If the process is prioritized we should adjust
|
||||
// it's oom_score_adj and avoid lowering its niceness.
|
||||
if slices.ContainsFunc(prioritizedProcs, containsFn) {
|
||||
if slices.ContainsFunc[[]string, string](prioritizedProcs, containsFn) {
|
||||
continue
|
||||
}
|
||||
|
||||
score, niceErr := proc.Niceness(a.syscaller)
|
||||
if niceErr != nil && !xerrors.Is(niceErr, os.ErrPermission) {
|
||||
debouncer.Warn(ctx, "unable to get proc niceness",
|
||||
slog.F("cmd", proc.Cmd()),
|
||||
slog.F("pid", proc.PID),
|
||||
slog.Error(niceErr),
|
||||
score, err := proc.Niceness(a.syscaller)
|
||||
if err != nil {
|
||||
logger.Warn(ctx, "unable to get proc niceness",
|
||||
slog.Error(err),
|
||||
)
|
||||
continue
|
||||
}
|
||||
@@ -1681,31 +1641,15 @@ func (a *agent) manageProcessPriority(ctx context.Context, debouncer *logDebounc
|
||||
continue
|
||||
}
|
||||
|
||||
if niceErr == nil {
|
||||
err := proc.SetNiceness(a.syscaller, niceness)
|
||||
if err != nil && !xerrors.Is(err, os.ErrPermission) {
|
||||
debouncer.Warn(ctx, "unable to set proc niceness",
|
||||
slog.F("cmd", proc.Cmd()),
|
||||
slog.F("pid", proc.PID),
|
||||
slog.F("niceness", niceness),
|
||||
slog.Error(err),
|
||||
)
|
||||
}
|
||||
err = proc.SetNiceness(a.syscaller, niceness)
|
||||
if err != nil {
|
||||
logger.Warn(ctx, "unable to set proc niceness",
|
||||
slog.F("niceness", niceness),
|
||||
slog.Error(err),
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
// If the oom score is valid and it's not already set and isn't a custom value set by another process then it's ok to update it.
|
||||
if oomScore != unsetOOMScore && oomScore != proc.OOMScoreAdj && !isCustomOOMScore(agentScore, proc) {
|
||||
oomScoreStr := strconv.Itoa(oomScore)
|
||||
err := afero.WriteFile(a.filesystem, fmt.Sprintf("/proc/%d/oom_score_adj", proc.PID), []byte(oomScoreStr), 0o644)
|
||||
if err != nil && !xerrors.Is(err, os.ErrPermission) {
|
||||
debouncer.Warn(ctx, "unable to set oom_score_adj",
|
||||
slog.F("cmd", proc.Cmd()),
|
||||
slog.F("pid", proc.PID),
|
||||
slog.F("score", oomScoreStr),
|
||||
slog.Error(err),
|
||||
)
|
||||
}
|
||||
}
|
||||
modProcs = append(modProcs, proc)
|
||||
}
|
||||
return modProcs, nil
|
||||
@@ -1716,87 +1660,52 @@ func (a *agent) isClosed() bool {
|
||||
return a.hardCtx.Err() != nil
|
||||
}
|
||||
|
||||
func (a *agent) requireNetwork() (*tailnet.Conn, bool) {
|
||||
a.closeMutex.Lock()
|
||||
defer a.closeMutex.Unlock()
|
||||
return a.network, a.network != nil
|
||||
}
|
||||
|
||||
func (a *agent) HandleHTTPDebugMagicsock(w http.ResponseWriter, r *http.Request) {
|
||||
network, ok := a.requireNetwork()
|
||||
if !ok {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
_, _ = w.Write([]byte("network is not ready yet"))
|
||||
return
|
||||
}
|
||||
network.MagicsockServeHTTPDebug(w, r)
|
||||
}
|
||||
|
||||
func (a *agent) HandleHTTPMagicsockDebugLoggingState(w http.ResponseWriter, r *http.Request) {
|
||||
state := chi.URLParam(r, "state")
|
||||
stateBool, err := strconv.ParseBool(state)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = fmt.Fprintf(w, "invalid state %q, must be a boolean", state)
|
||||
return
|
||||
}
|
||||
|
||||
network, ok := a.requireNetwork()
|
||||
if !ok {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
_, _ = w.Write([]byte("network is not ready yet"))
|
||||
return
|
||||
}
|
||||
|
||||
network.MagicsockSetDebugLoggingEnabled(stateBool)
|
||||
a.logger.Info(r.Context(), "updated magicsock debug logging due to debug request", slog.F("new_state", stateBool))
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = fmt.Fprintf(w, "updated magicsock debug logging to %v", stateBool)
|
||||
}
|
||||
|
||||
func (a *agent) HandleHTTPDebugManifest(w http.ResponseWriter, r *http.Request) {
|
||||
sdkManifest := a.manifest.Load()
|
||||
if sdkManifest == nil {
|
||||
a.logger.Error(r.Context(), "no manifest in-memory")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
_, _ = fmt.Fprintf(w, "no manifest in-memory")
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
if err := json.NewEncoder(w).Encode(sdkManifest); err != nil {
|
||||
a.logger.Error(a.hardCtx, "write debug manifest", slog.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
func (a *agent) HandleHTTPDebugLogs(w http.ResponseWriter, r *http.Request) {
|
||||
logPath := filepath.Join(a.logDir, "coder-agent.log")
|
||||
f, err := os.Open(logPath)
|
||||
if err != nil {
|
||||
a.logger.Error(r.Context(), "open agent log file", slog.Error(err), slog.F("path", logPath))
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
_, _ = fmt.Fprintf(w, "could not open log file: %s", err)
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
// Limit to 10MB.
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, err = io.Copy(w, io.LimitReader(f, 10*1024*1024))
|
||||
if err != nil && !errors.Is(err, io.EOF) {
|
||||
a.logger.Error(r.Context(), "read agent log file", slog.Error(err))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (a *agent) HTTPDebug() http.Handler {
|
||||
r := chi.NewRouter()
|
||||
|
||||
r.Get("/debug/logs", a.HandleHTTPDebugLogs)
|
||||
r.Get("/debug/magicsock", a.HandleHTTPDebugMagicsock)
|
||||
r.Get("/debug/magicsock/debug-logging/{state}", a.HandleHTTPMagicsockDebugLoggingState)
|
||||
r.Get("/debug/manifest", a.HandleHTTPDebugManifest)
|
||||
requireNetwork := func(w http.ResponseWriter) (*tailnet.Conn, bool) {
|
||||
a.closeMutex.Lock()
|
||||
network := a.network
|
||||
a.closeMutex.Unlock()
|
||||
|
||||
if network == nil {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
_, _ = w.Write([]byte("network is not ready yet"))
|
||||
return nil, false
|
||||
}
|
||||
|
||||
return network, true
|
||||
}
|
||||
|
||||
r.Get("/debug/magicsock", func(w http.ResponseWriter, r *http.Request) {
|
||||
network, ok := requireNetwork(w)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
network.MagicsockServeHTTPDebug(w, r)
|
||||
})
|
||||
|
||||
r.Get("/debug/magicsock/debug-logging/{state}", func(w http.ResponseWriter, r *http.Request) {
|
||||
state := chi.URLParam(r, "state")
|
||||
stateBool, err := strconv.ParseBool(state)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = fmt.Fprintf(w, "invalid state %q, must be a boolean", state)
|
||||
return
|
||||
}
|
||||
|
||||
network, ok := requireNetwork(w)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
network.MagicsockSetDebugLoggingEnabled(stateBool)
|
||||
a.logger.Info(r.Context(), "updated magicsock debug logging due to debug request", slog.F("new_state", stateBool))
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = fmt.Fprintf(w, "updated magicsock debug logging to %v", stateBool)
|
||||
})
|
||||
|
||||
r.NotFound(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
_, _ = w.Write([]byte("404 not found"))
|
||||
@@ -2036,100 +1945,3 @@ func (a *apiConnRoutineManager) start(name string, b gracefulShutdownBehavior, f
|
||||
func (a *apiConnRoutineManager) wait() error {
|
||||
return a.eg.Wait()
|
||||
}
|
||||
|
||||
func PrometheusMetricsHandler(prometheusRegistry *prometheus.Registry, logger slog.Logger) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
|
||||
// Based on: https://github.com/tailscale/tailscale/blob/280255acae604796a1113861f5a84e6fa2dc6121/ipn/localapi/localapi.go#L489
|
||||
clientmetric.WritePrometheusExpositionFormat(w)
|
||||
|
||||
metricFamilies, err := prometheusRegistry.Gather()
|
||||
if err != nil {
|
||||
logger.Error(context.Background(), "prometheus handler failed to gather metric families", slog.Error(err))
|
||||
return
|
||||
}
|
||||
|
||||
for _, metricFamily := range metricFamilies {
|
||||
_, err = expfmt.MetricFamilyToText(w, metricFamily)
|
||||
if err != nil {
|
||||
logger.Error(context.Background(), "expfmt.MetricFamilyToText failed", slog.Error(err))
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// childOOMScore returns the oom_score_adj for a child process. It is based
|
||||
// on the oom_score_adj of the agent process.
|
||||
func childOOMScore(agentScore int) int {
|
||||
// If the agent has a negative oom_score_adj, we set the child to 0
|
||||
// so it's treated like every other process.
|
||||
if agentScore < 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
// If the agent is already almost at the maximum then set it to the max.
|
||||
if agentScore >= 998 {
|
||||
return 1000
|
||||
}
|
||||
|
||||
// If the agent oom_score_adj is >=0, we set the child to slightly
|
||||
// less than the maximum. If users want a different score they set it
|
||||
// directly.
|
||||
return 998
|
||||
}
|
||||
|
||||
func (a *agent) getAgentOOMScore() (int, error) {
|
||||
scoreStr, err := afero.ReadFile(a.filesystem, "/proc/self/oom_score_adj")
|
||||
if err != nil {
|
||||
return 0, xerrors.Errorf("read file: %w", err)
|
||||
}
|
||||
|
||||
score, err := strconv.Atoi(strings.TrimSpace(string(scoreStr)))
|
||||
if err != nil {
|
||||
return 0, xerrors.Errorf("parse int: %w", err)
|
||||
}
|
||||
|
||||
return score, nil
|
||||
}
|
||||
|
||||
// isCustomOOMScore checks to see if the oom_score_adj is not a value that would
|
||||
// originate from an agent-spawned process.
|
||||
func isCustomOOMScore(agentScore int, process *agentproc.Process) bool {
|
||||
score := process.OOMScoreAdj
|
||||
return agentScore != score && score != 1000 && score != 0 && score != 998
|
||||
}
|
||||
|
||||
// logDebouncer skips writing a log for a particular message if
|
||||
// it's been emitted within the given interval duration.
|
||||
// It's a shoddy implementation used in one spot that should be replaced at
|
||||
// some point.
|
||||
type logDebouncer struct {
|
||||
logger slog.Logger
|
||||
messages map[string]time.Time
|
||||
interval time.Duration
|
||||
}
|
||||
|
||||
func (l *logDebouncer) Warn(ctx context.Context, msg string, fields ...any) {
|
||||
l.log(ctx, slog.LevelWarn, msg, fields...)
|
||||
}
|
||||
|
||||
func (l *logDebouncer) Error(ctx context.Context, msg string, fields ...any) {
|
||||
l.log(ctx, slog.LevelError, msg, fields...)
|
||||
}
|
||||
|
||||
func (l *logDebouncer) log(ctx context.Context, level slog.Level, msg string, fields ...any) {
|
||||
// This (bad) implementation assumes you wouldn't reuse the same msg
|
||||
// for different levels.
|
||||
if last, ok := l.messages[msg]; ok && time.Since(last) < l.interval {
|
||||
return
|
||||
}
|
||||
switch level {
|
||||
case slog.LevelWarn:
|
||||
l.logger.Warn(ctx, msg, fields...)
|
||||
case slog.LevelError:
|
||||
l.logger.Error(ctx, msg, fields...)
|
||||
}
|
||||
l.messages[msg] = time.Now()
|
||||
}
|
||||
|
||||
+21
-138
@@ -46,6 +46,7 @@ import (
|
||||
"cdr.dev/slog"
|
||||
"cdr.dev/slog/sloggers/sloghuman"
|
||||
"cdr.dev/slog/sloggers/slogtest"
|
||||
|
||||
"github.com/coder/coder/v2/agent"
|
||||
"github.com/coder/coder/v2/agent/agentproc"
|
||||
"github.com/coder/coder/v2/agent/agentproc/agentproctest"
|
||||
@@ -54,8 +55,6 @@ import (
|
||||
"github.com/coder/coder/v2/agent/proto"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/coder/v2/codersdk/agentsdk"
|
||||
"github.com/coder/coder/v2/codersdk/workspacesdk"
|
||||
"github.com/coder/coder/v2/cryptorand"
|
||||
"github.com/coder/coder/v2/pty/ptytest"
|
||||
"github.com/coder/coder/v2/tailnet"
|
||||
"github.com/coder/coder/v2/tailnet/tailnettest"
|
||||
@@ -113,7 +112,7 @@ func TestAgent_Stats_ReconnectingPTY(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
defer ptyConn.Close()
|
||||
|
||||
data, err := json.Marshal(workspacesdk.ReconnectingPTYRequest{
|
||||
data, err := json.Marshal(codersdk.ReconnectingPTYRequest{
|
||||
Data: "echo test\r\n",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
@@ -614,12 +613,12 @@ func TestAgent_Session_TTY_MOTD_Update(t *testing.T) {
|
||||
// Set new banner func and wait for the agent to call it to update the
|
||||
// banner.
|
||||
ready := make(chan struct{}, 2)
|
||||
client.SetAnnouncementBannersFunc(func() ([]codersdk.BannerConfig, error) {
|
||||
client.SetServiceBannerFunc(func() (codersdk.ServiceBannerConfig, error) {
|
||||
select {
|
||||
case ready <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
return []codersdk.BannerConfig{test.banner}, nil
|
||||
return test.banner, nil
|
||||
})
|
||||
<-ready
|
||||
<-ready // Wait for two updates to ensure the value has propagated.
|
||||
@@ -1606,7 +1605,7 @@ func TestAgent_ReconnectingPTY(t *testing.T) {
|
||||
require.NoError(t, tr1.ReadUntil(ctx, matchPrompt), "find prompt")
|
||||
require.NoError(t, tr2.ReadUntil(ctx, matchPrompt), "find prompt")
|
||||
|
||||
data, err := json.Marshal(workspacesdk.ReconnectingPTYRequest{
|
||||
data, err := json.Marshal(codersdk.ReconnectingPTYRequest{
|
||||
Data: "echo test\r",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
@@ -1634,7 +1633,7 @@ func TestAgent_ReconnectingPTY(t *testing.T) {
|
||||
require.NoError(t, tr3.ReadUntil(ctx, matchEchoOutput), "find echo output")
|
||||
|
||||
// Exit should cause the connection to close.
|
||||
data, err = json.Marshal(workspacesdk.ReconnectingPTYRequest{
|
||||
data, err = json.Marshal(codersdk.ReconnectingPTYRequest{
|
||||
Data: "exit\r",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
@@ -1783,7 +1782,7 @@ func TestAgent_UpdatedDERP(t *testing.T) {
|
||||
})
|
||||
|
||||
// Setup a client connection.
|
||||
newClientConn := func(derpMap *tailcfg.DERPMap, name string) *workspacesdk.AgentConn {
|
||||
newClientConn := func(derpMap *tailcfg.DERPMap, name string) *codersdk.WorkspaceAgentConn {
|
||||
conn, err := tailnet.NewConn(&tailnet.Options{
|
||||
Addresses: []netip.Prefix{netip.PrefixFrom(tailnet.IP(), 128)},
|
||||
DERPMap: derpMap,
|
||||
@@ -1812,9 +1811,9 @@ func TestAgent_UpdatedDERP(t *testing.T) {
|
||||
// Force DERP.
|
||||
conn.SetBlockEndpoints(true)
|
||||
|
||||
sdkConn := workspacesdk.NewAgentConn(conn, workspacesdk.AgentConnOptions{
|
||||
sdkConn := codersdk.NewWorkspaceAgentConn(conn, codersdk.WorkspaceAgentConnOptions{
|
||||
AgentID: agentID,
|
||||
CloseFunc: func() error { return workspacesdk.ErrSkipClose },
|
||||
CloseFunc: func() error { return codersdk.ErrSkipClose },
|
||||
})
|
||||
t.Cleanup(func() {
|
||||
t.Logf("closing sdkConn %s", name)
|
||||
@@ -1975,21 +1974,11 @@ func TestAgent_WriteVSCodeConfigs(t *testing.T) {
|
||||
func TestAgent_DebugServer(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
logDir := t.TempDir()
|
||||
logPath := filepath.Join(logDir, "coder-agent.log")
|
||||
randLogStr, err := cryptorand.String(32)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.WriteFile(logPath, []byte(randLogStr), 0o600))
|
||||
derpMap, _ := tailnettest.RunDERPAndSTUN(t)
|
||||
//nolint:dogsled
|
||||
conn, _, _, _, agnt := setupAgent(t, agentsdk.Manifest{
|
||||
DERPMap: derpMap,
|
||||
}, 0, func(c *agenttest.Client, o *agent.Options) {
|
||||
o.ExchangeToken = func(context.Context) (string, error) {
|
||||
return "token", nil
|
||||
}
|
||||
o.LogDir = logDir
|
||||
})
|
||||
}, 0)
|
||||
|
||||
awaitReachableCtx := testutil.Context(t, testutil.WaitLong)
|
||||
ok := conn.AwaitReachable(awaitReachableCtx)
|
||||
@@ -2070,40 +2059,6 @@ func TestAgent_DebugServer(t *testing.T) {
|
||||
require.Contains(t, string(resBody), `invalid state "blah", must be a boolean`)
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("Manifest", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL+"/debug/manifest", nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
res, err := srv.Client().Do(req)
|
||||
require.NoError(t, err)
|
||||
defer res.Body.Close()
|
||||
require.Equal(t, http.StatusOK, res.StatusCode)
|
||||
|
||||
var v agentsdk.Manifest
|
||||
require.NoError(t, json.NewDecoder(res.Body).Decode(&v))
|
||||
require.NotNil(t, v)
|
||||
})
|
||||
|
||||
t.Run("Logs", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL+"/debug/logs", nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
res, err := srv.Client().Do(req)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, http.StatusOK, res.StatusCode)
|
||||
defer res.Body.Close()
|
||||
resBody, err := io.ReadAll(res.Body)
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, string(resBody))
|
||||
require.Contains(t, string(resBody), randLogStr)
|
||||
})
|
||||
}
|
||||
|
||||
func TestAgent_ScriptLogging(t *testing.T) {
|
||||
@@ -2193,15 +2148,15 @@ func setupAgentSSHClient(ctx context.Context, t *testing.T) *ssh.Client {
|
||||
func setupSSHSession(
|
||||
t *testing.T,
|
||||
manifest agentsdk.Manifest,
|
||||
banner codersdk.BannerConfig,
|
||||
serviceBanner codersdk.ServiceBannerConfig,
|
||||
prepareFS func(fs afero.Fs),
|
||||
opts ...func(*agenttest.Client, *agent.Options),
|
||||
) *ssh.Session {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
|
||||
defer cancel()
|
||||
opts = append(opts, func(c *agenttest.Client, o *agent.Options) {
|
||||
c.SetAnnouncementBannersFunc(func() ([]codersdk.BannerConfig, error) {
|
||||
return []codersdk.BannerConfig{banner}, nil
|
||||
c.SetServiceBannerFunc(func() (codersdk.ServiceBannerConfig, error) {
|
||||
return serviceBanner, nil
|
||||
})
|
||||
})
|
||||
//nolint:dogsled
|
||||
@@ -2223,7 +2178,7 @@ func setupSSHSession(
|
||||
}
|
||||
|
||||
func setupAgent(t *testing.T, metadata agentsdk.Manifest, ptyTimeout time.Duration, opts ...func(*agenttest.Client, *agent.Options)) (
|
||||
*workspacesdk.AgentConn,
|
||||
*codersdk.WorkspaceAgentConn,
|
||||
*agenttest.Client,
|
||||
<-chan *proto.Stats,
|
||||
afero.Fs,
|
||||
@@ -2296,7 +2251,7 @@ func setupAgent(t *testing.T, metadata agentsdk.Manifest, ptyTimeout time.Durati
|
||||
t.Logf("error closing in-mem coordination: %s", err.Error())
|
||||
}
|
||||
})
|
||||
agentConn := workspacesdk.NewAgentConn(conn, workspacesdk.AgentConnOptions{
|
||||
agentConn := codersdk.NewWorkspaceAgentConn(conn, codersdk.WorkspaceAgentConnOptions{
|
||||
AgentID: metadata.AgentID,
|
||||
})
|
||||
t.Cleanup(func() {
|
||||
@@ -2529,11 +2484,11 @@ func TestAgent_ManageProcessPriority(t *testing.T) {
|
||||
logger = slog.Make(sloghuman.Sink(io.Discard))
|
||||
)
|
||||
|
||||
requireFileWrite(t, fs, "/proc/self/oom_score_adj", "-500")
|
||||
|
||||
// Create some processes.
|
||||
for i := 0; i < 4; i++ {
|
||||
// Create a prioritized process.
|
||||
// Create a prioritized process. This process should
|
||||
// have it's oom_score_adj set to -500 and its nice
|
||||
// score should be untouched.
|
||||
var proc agentproc.Process
|
||||
if i == 0 {
|
||||
proc = agentproctest.GenerateProcess(t, fs,
|
||||
@@ -2551,8 +2506,8 @@ func TestAgent_ManageProcessPriority(t *testing.T) {
|
||||
},
|
||||
)
|
||||
|
||||
syscaller.EXPECT().GetPriority(proc.PID).Return(20, nil)
|
||||
syscaller.EXPECT().SetPriority(proc.PID, 10).Return(nil)
|
||||
syscaller.EXPECT().GetPriority(proc.PID).Return(20, nil)
|
||||
}
|
||||
syscaller.EXPECT().
|
||||
Kill(proc.PID, syscall.Signal(0)).
|
||||
@@ -2571,9 +2526,6 @@ func TestAgent_ManageProcessPriority(t *testing.T) {
|
||||
})
|
||||
actualProcs := <-modProcs
|
||||
require.Len(t, actualProcs, len(expectedProcs)-1)
|
||||
for _, proc := range actualProcs {
|
||||
requireFileEquals(t, fs, fmt.Sprintf("/proc/%d/oom_score_adj", proc.PID), "0")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("IgnoreCustomNice", func(t *testing.T) {
|
||||
@@ -2592,11 +2544,8 @@ func TestAgent_ManageProcessPriority(t *testing.T) {
|
||||
logger = slog.Make(sloghuman.Sink(io.Discard))
|
||||
)
|
||||
|
||||
err := afero.WriteFile(fs, "/proc/self/oom_score_adj", []byte("0"), 0o644)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Create some processes.
|
||||
for i := 0; i < 3; i++ {
|
||||
for i := 0; i < 2; i++ {
|
||||
proc := agentproctest.GenerateProcess(t, fs)
|
||||
syscaller.EXPECT().
|
||||
Kill(proc.PID, syscall.Signal(0)).
|
||||
@@ -2624,59 +2573,7 @@ func TestAgent_ManageProcessPriority(t *testing.T) {
|
||||
})
|
||||
actualProcs := <-modProcs
|
||||
// We should ignore the process with a custom nice score.
|
||||
require.Len(t, actualProcs, 2)
|
||||
for _, proc := range actualProcs {
|
||||
_, ok := expectedProcs[proc.PID]
|
||||
require.True(t, ok)
|
||||
requireFileEquals(t, fs, fmt.Sprintf("/proc/%d/oom_score_adj", proc.PID), "998")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("CustomOOMScore", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
if runtime.GOOS != "linux" {
|
||||
t.Skip("Skipping non-linux environment")
|
||||
}
|
||||
|
||||
var (
|
||||
fs = afero.NewMemMapFs()
|
||||
ticker = make(chan time.Time)
|
||||
syscaller = agentproctest.NewMockSyscaller(gomock.NewController(t))
|
||||
modProcs = make(chan []*agentproc.Process)
|
||||
logger = slog.Make(sloghuman.Sink(io.Discard))
|
||||
)
|
||||
|
||||
err := afero.WriteFile(fs, "/proc/self/oom_score_adj", []byte("0"), 0o644)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Create some processes.
|
||||
for i := 0; i < 3; i++ {
|
||||
proc := agentproctest.GenerateProcess(t, fs)
|
||||
syscaller.EXPECT().
|
||||
Kill(proc.PID, syscall.Signal(0)).
|
||||
Return(nil)
|
||||
syscaller.EXPECT().GetPriority(proc.PID).Return(20, nil)
|
||||
syscaller.EXPECT().SetPriority(proc.PID, 10).Return(nil)
|
||||
}
|
||||
|
||||
_, _, _, _, _ = setupAgent(t, agentsdk.Manifest{}, 0, func(c *agenttest.Client, o *agent.Options) {
|
||||
o.Syscaller = syscaller
|
||||
o.ModifiedProcesses = modProcs
|
||||
o.EnvironmentVariables = map[string]string{
|
||||
agent.EnvProcPrioMgmt: "1",
|
||||
agent.EnvProcOOMScore: "-567",
|
||||
}
|
||||
o.Filesystem = fs
|
||||
o.Logger = logger
|
||||
o.ProcessManagementTick = ticker
|
||||
})
|
||||
actualProcs := <-modProcs
|
||||
// We should ignore the process with a custom nice score.
|
||||
require.Len(t, actualProcs, 3)
|
||||
for _, proc := range actualProcs {
|
||||
requireFileEquals(t, fs, fmt.Sprintf("/proc/%d/oom_score_adj", proc.PID), "-567")
|
||||
}
|
||||
require.Len(t, actualProcs, 1)
|
||||
})
|
||||
|
||||
t.Run("DisabledByDefault", func(t *testing.T) {
|
||||
@@ -2797,17 +2694,3 @@ func requireEcho(t *testing.T, conn net.Conn) {
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "test", string(b))
|
||||
}
|
||||
|
||||
func requireFileWrite(t testing.TB, fs afero.Fs, fp, data string) {
|
||||
t.Helper()
|
||||
err := afero.WriteFile(fs, fp, []byte(data), 0o600)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
func requireFileEquals(t testing.TB, fs afero.Fs, fp, expect string) {
|
||||
t.Helper()
|
||||
actual, err := afero.ReadFile(fs, fp)
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Equal(t, expect, string(actual))
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ package agentproctest
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/afero"
|
||||
@@ -30,9 +29,8 @@ func GenerateProcess(t *testing.T, fs afero.Fs, muts ...func(*agentproc.Process)
|
||||
cmdline := fmt.Sprintf("%s\x00%s\x00%s", arg1, arg2, arg3)
|
||||
|
||||
process := agentproc.Process{
|
||||
CmdLine: cmdline,
|
||||
PID: int32(pid),
|
||||
OOMScoreAdj: 0,
|
||||
CmdLine: cmdline,
|
||||
PID: int32(pid),
|
||||
}
|
||||
|
||||
for _, mut := range muts {
|
||||
@@ -47,9 +45,5 @@ func GenerateProcess(t *testing.T, fs afero.Fs, muts ...func(*agentproc.Process)
|
||||
err = afero.WriteFile(fs, fmt.Sprintf("%s/cmdline", process.Dir), []byte(process.CmdLine), 0o444)
|
||||
require.NoError(t, err)
|
||||
|
||||
score := strconv.Itoa(process.OOMScoreAdj)
|
||||
err = afero.WriteFile(fs, fmt.Sprintf("%s/oom_score_adj", process.Dir), []byte(score), 0o444)
|
||||
require.NoError(t, err)
|
||||
|
||||
return process
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ package agentproc
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -51,26 +50,10 @@ func List(fs afero.Fs, syscaller Syscaller) ([]*Process, error) {
|
||||
}
|
||||
return nil, xerrors.Errorf("read cmdline: %w", err)
|
||||
}
|
||||
|
||||
oomScore, err := afero.ReadFile(fs, filepath.Join(defaultProcDir, entry, "oom_score_adj"))
|
||||
if err != nil {
|
||||
if xerrors.Is(err, os.ErrPermission) {
|
||||
continue
|
||||
}
|
||||
|
||||
return nil, xerrors.Errorf("read oom_score_adj: %w", err)
|
||||
}
|
||||
|
||||
oom, err := strconv.Atoi(strings.TrimSpace(string(oomScore)))
|
||||
if err != nil {
|
||||
return nil, xerrors.Errorf("convert oom score: %w", err)
|
||||
}
|
||||
|
||||
processes = append(processes, &Process{
|
||||
PID: int32(pid),
|
||||
CmdLine: string(cmdline),
|
||||
Dir: filepath.Join(defaultProcDir, entry),
|
||||
OOMScoreAdj: oom,
|
||||
PID: int32(pid),
|
||||
CmdLine: string(cmdline),
|
||||
Dir: filepath.Join(defaultProcDir, entry),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -14,8 +14,7 @@ type Syscaller interface {
|
||||
const defaultProcDir = "/proc"
|
||||
|
||||
type Process struct {
|
||||
Dir string
|
||||
CmdLine string
|
||||
PID int32
|
||||
OOMScoreAdj int
|
||||
Dir string
|
||||
CmdLine string
|
||||
PID int32
|
||||
}
|
||||
|
||||
+11
-14
@@ -63,7 +63,7 @@ type Config struct {
|
||||
// file will be displayed to the user upon login.
|
||||
MOTDFile func() string
|
||||
// ServiceBanner returns the configuration for the Coder service banner.
|
||||
AnnouncementBanners func() *[]codersdk.BannerConfig
|
||||
ServiceBanner func() *codersdk.ServiceBannerConfig
|
||||
// UpdateEnv updates the environment variables for the command to be
|
||||
// executed. It can be used to add, modify or replace environment variables.
|
||||
UpdateEnv func(current []string) (updated []string, err error)
|
||||
@@ -123,8 +123,8 @@ func NewServer(ctx context.Context, logger slog.Logger, prometheusRegistry *prom
|
||||
if config.MOTDFile == nil {
|
||||
config.MOTDFile = func() string { return "" }
|
||||
}
|
||||
if config.AnnouncementBanners == nil {
|
||||
config.AnnouncementBanners = func() *[]codersdk.BannerConfig { return &[]codersdk.BannerConfig{} }
|
||||
if config.ServiceBanner == nil {
|
||||
config.ServiceBanner = func() *codersdk.ServiceBannerConfig { return &codersdk.ServiceBannerConfig{} }
|
||||
}
|
||||
if config.WorkingDirectory == nil {
|
||||
config.WorkingDirectory = func() string {
|
||||
@@ -441,15 +441,12 @@ func (s *Server) startPTYSession(logger slog.Logger, session ptySession, magicTy
|
||||
session.DisablePTYEmulation()
|
||||
|
||||
if isLoginShell(session.RawCommand()) {
|
||||
banners := s.config.AnnouncementBanners()
|
||||
if banners != nil {
|
||||
for _, banner := range *banners {
|
||||
err := showAnnouncementBanner(session, banner)
|
||||
if err != nil {
|
||||
logger.Error(ctx, "agent failed to show announcement banner", slog.Error(err))
|
||||
s.metrics.sessionErrors.WithLabelValues(magicTypeLabel, "yes", "announcement_banner").Add(1)
|
||||
break
|
||||
}
|
||||
serviceBanner := s.config.ServiceBanner()
|
||||
if serviceBanner != nil {
|
||||
err := showServiceBanner(session, serviceBanner)
|
||||
if err != nil {
|
||||
logger.Error(ctx, "agent failed to show service banner", slog.Error(err))
|
||||
s.metrics.sessionErrors.WithLabelValues(magicTypeLabel, "yes", "service_banner").Add(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -894,9 +891,9 @@ func isQuietLogin(fs afero.Fs, rawCommand string) bool {
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// showAnnouncementBanner will write the service banner if enabled and not blank
|
||||
// showServiceBanner will write the service banner if enabled and not blank
|
||||
// along with a blank line for spacing.
|
||||
func showAnnouncementBanner(session io.Writer, banner codersdk.BannerConfig) error {
|
||||
func showServiceBanner(session io.Writer, banner *codersdk.ServiceBannerConfig) error {
|
||||
if banner.Enabled && banner.Message != "" {
|
||||
// The banner supports Markdown so we might want to parse it but Markdown is
|
||||
// still fairly readable in its raw form.
|
||||
|
||||
+11
-19
@@ -138,8 +138,8 @@ func (c *Client) GetStartupLogs() []agentsdk.Log {
|
||||
return c.logs
|
||||
}
|
||||
|
||||
func (c *Client) SetAnnouncementBannersFunc(f func() ([]codersdk.BannerConfig, error)) {
|
||||
c.fakeAgentAPI.SetAnnouncementBannersFunc(f)
|
||||
func (c *Client) SetServiceBannerFunc(f func() (codersdk.ServiceBannerConfig, error)) {
|
||||
c.fakeAgentAPI.SetServiceBannerFunc(f)
|
||||
}
|
||||
|
||||
func (c *Client) PushDERPMapUpdate(update *tailcfg.DERPMap) error {
|
||||
@@ -171,39 +171,31 @@ type FakeAgentAPI struct {
|
||||
lifecycleStates []codersdk.WorkspaceAgentLifecycle
|
||||
metadata map[string]agentsdk.Metadata
|
||||
|
||||
getAnnouncementBannersFunc func() ([]codersdk.BannerConfig, error)
|
||||
getServiceBannerFunc func() (codersdk.ServiceBannerConfig, error)
|
||||
}
|
||||
|
||||
func (f *FakeAgentAPI) GetManifest(context.Context, *agentproto.GetManifestRequest) (*agentproto.Manifest, error) {
|
||||
return f.manifest, nil
|
||||
}
|
||||
|
||||
func (*FakeAgentAPI) GetServiceBanner(context.Context, *agentproto.GetServiceBannerRequest) (*agentproto.ServiceBanner, error) {
|
||||
return &agentproto.ServiceBanner{}, nil
|
||||
}
|
||||
|
||||
func (f *FakeAgentAPI) SetAnnouncementBannersFunc(fn func() ([]codersdk.BannerConfig, error)) {
|
||||
func (f *FakeAgentAPI) SetServiceBannerFunc(fn func() (codersdk.ServiceBannerConfig, error)) {
|
||||
f.Lock()
|
||||
defer f.Unlock()
|
||||
f.getAnnouncementBannersFunc = fn
|
||||
f.logger.Info(context.Background(), "updated notification banners")
|
||||
f.getServiceBannerFunc = fn
|
||||
f.logger.Info(context.Background(), "updated ServiceBannerFunc")
|
||||
}
|
||||
|
||||
func (f *FakeAgentAPI) GetAnnouncementBanners(context.Context, *agentproto.GetAnnouncementBannersRequest) (*agentproto.GetAnnouncementBannersResponse, error) {
|
||||
func (f *FakeAgentAPI) GetServiceBanner(context.Context, *agentproto.GetServiceBannerRequest) (*agentproto.ServiceBanner, error) {
|
||||
f.Lock()
|
||||
defer f.Unlock()
|
||||
if f.getAnnouncementBannersFunc == nil {
|
||||
return &agentproto.GetAnnouncementBannersResponse{AnnouncementBanners: []*agentproto.BannerConfig{}}, nil
|
||||
if f.getServiceBannerFunc == nil {
|
||||
return &agentproto.ServiceBanner{}, nil
|
||||
}
|
||||
banners, err := f.getAnnouncementBannersFunc()
|
||||
sb, err := f.getServiceBannerFunc()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
bannersProto := make([]*agentproto.BannerConfig, 0, len(banners))
|
||||
for _, banner := range banners {
|
||||
bannersProto = append(bannersProto, agentsdk.ProtoFromBannerConfig(banner))
|
||||
}
|
||||
return &agentproto.GetAnnouncementBannersResponse{AnnouncementBanners: bannersProto}, nil
|
||||
return agentsdk.ProtoFromServiceBanner(sb), nil
|
||||
}
|
||||
|
||||
func (f *FakeAgentAPI) UpdateStats(ctx context.Context, req *agentproto.UpdateStatsRequest) (*agentproto.UpdateStatsResponse, error) {
|
||||
|
||||
@@ -35,13 +35,7 @@ func (a *agent) apiHandler() http.Handler {
|
||||
ignorePorts: cpy,
|
||||
cacheDuration: cacheDuration,
|
||||
}
|
||||
promHandler := PrometheusMetricsHandler(a.prometheusRegistry, a.logger)
|
||||
r.Get("/api/v0/listening-ports", lp.handler)
|
||||
r.Get("/debug/logs", a.HandleHTTPDebugLogs)
|
||||
r.Get("/debug/magicsock", a.HandleHTTPDebugMagicsock)
|
||||
r.Get("/debug/magicsock/debug-logging/{state}", a.HandleHTTPMagicsockDebugLoggingState)
|
||||
r.Get("/debug/manifest", a.HandleHTTPDebugManifest)
|
||||
r.Get("/debug/prometheus", promHandler.ServeHTTP)
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"runtime"
|
||||
"sync"
|
||||
|
||||
"cdr.dev/slog"
|
||||
)
|
||||
|
||||
// checkpoint allows a goroutine to communicate when it is OK to proceed beyond some async condition
|
||||
// to other dependent goroutines.
|
||||
type checkpoint struct {
|
||||
logger slog.Logger
|
||||
mu sync.Mutex
|
||||
called bool
|
||||
done chan struct{}
|
||||
err error
|
||||
}
|
||||
|
||||
// complete the checkpoint. Pass nil to indicate the checkpoint was ok. It is an error to call this
|
||||
// more than once.
|
||||
func (c *checkpoint) complete(err error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.called {
|
||||
b := make([]byte, 2048)
|
||||
n := runtime.Stack(b, false)
|
||||
c.logger.Critical(context.Background(), "checkpoint complete called more than once", slog.F("stacktrace", b[:n]))
|
||||
return
|
||||
}
|
||||
c.called = true
|
||||
c.err = err
|
||||
close(c.done)
|
||||
}
|
||||
|
||||
func (c *checkpoint) wait(ctx context.Context) error {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-c.done:
|
||||
return c.err
|
||||
}
|
||||
}
|
||||
|
||||
func newCheckpoint(logger slog.Logger) *checkpoint {
|
||||
return &checkpoint{
|
||||
logger: logger,
|
||||
done: make(chan struct{}),
|
||||
}
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/xerrors"
|
||||
|
||||
"cdr.dev/slog/sloggers/slogtest"
|
||||
"github.com/coder/coder/v2/testutil"
|
||||
)
|
||||
|
||||
func TestCheckpoint_CompleteWait(t *testing.T) {
|
||||
t.Parallel()
|
||||
logger := slogtest.Make(t, nil)
|
||||
ctx := testutil.Context(t, testutil.WaitShort)
|
||||
uut := newCheckpoint(logger)
|
||||
err := xerrors.New("test")
|
||||
uut.complete(err)
|
||||
got := uut.wait(ctx)
|
||||
require.Equal(t, err, got)
|
||||
}
|
||||
|
||||
func TestCheckpoint_CompleteTwice(t *testing.T) {
|
||||
t.Parallel()
|
||||
logger := slogtest.Make(t, &slogtest.Options{IgnoreErrors: true})
|
||||
ctx := testutil.Context(t, testutil.WaitShort)
|
||||
uut := newCheckpoint(logger)
|
||||
err := xerrors.New("test")
|
||||
uut.complete(err)
|
||||
uut.complete(nil) // drops CRITICAL log
|
||||
got := uut.wait(ctx)
|
||||
require.Equal(t, err, got)
|
||||
}
|
||||
|
||||
func TestCheckpoint_WaitComplete(t *testing.T) {
|
||||
t.Parallel()
|
||||
logger := slogtest.Make(t, nil)
|
||||
ctx := testutil.Context(t, testutil.WaitShort)
|
||||
uut := newCheckpoint(logger)
|
||||
err := xerrors.New("test")
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
errCh <- uut.wait(ctx)
|
||||
}()
|
||||
uut.complete(err)
|
||||
got := testutil.RequireRecvCtx(ctx, t, errCh)
|
||||
require.Equal(t, err, got)
|
||||
}
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
"golang.org/x/xerrors"
|
||||
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/coder/v2/codersdk/workspacesdk"
|
||||
)
|
||||
|
||||
func (lp *listeningPortsHandler) getListeningPorts() ([]codersdk.WorkspaceAgentListeningPort, error) {
|
||||
@@ -33,7 +32,7 @@ func (lp *listeningPortsHandler) getListeningPorts() ([]codersdk.WorkspaceAgentL
|
||||
seen := make(map[uint16]struct{}, len(tabs))
|
||||
ports := []codersdk.WorkspaceAgentListeningPort{}
|
||||
for _, tab := range tabs {
|
||||
if tab.LocalAddr == nil || tab.LocalAddr.Port < workspacesdk.AgentMinimumListeningPort {
|
||||
if tab.LocalAddr == nil || tab.LocalAddr.Port < codersdk.WorkspaceAgentMinimumListeningPort {
|
||||
continue
|
||||
}
|
||||
|
||||
|
||||
+129
-342
@@ -1859,154 +1859,6 @@ func (x *BatchCreateLogsResponse) GetLogLimitExceeded() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
type GetAnnouncementBannersRequest struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
}
|
||||
|
||||
func (x *GetAnnouncementBannersRequest) Reset() {
|
||||
*x = GetAnnouncementBannersRequest{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_agent_proto_agent_proto_msgTypes[22]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *GetAnnouncementBannersRequest) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*GetAnnouncementBannersRequest) ProtoMessage() {}
|
||||
|
||||
func (x *GetAnnouncementBannersRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_agent_proto_agent_proto_msgTypes[22]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use GetAnnouncementBannersRequest.ProtoReflect.Descriptor instead.
|
||||
func (*GetAnnouncementBannersRequest) Descriptor() ([]byte, []int) {
|
||||
return file_agent_proto_agent_proto_rawDescGZIP(), []int{22}
|
||||
}
|
||||
|
||||
type GetAnnouncementBannersResponse struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
AnnouncementBanners []*BannerConfig `protobuf:"bytes,1,rep,name=announcement_banners,json=announcementBanners,proto3" json:"announcement_banners,omitempty"`
|
||||
}
|
||||
|
||||
func (x *GetAnnouncementBannersResponse) Reset() {
|
||||
*x = GetAnnouncementBannersResponse{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_agent_proto_agent_proto_msgTypes[23]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *GetAnnouncementBannersResponse) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*GetAnnouncementBannersResponse) ProtoMessage() {}
|
||||
|
||||
func (x *GetAnnouncementBannersResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_agent_proto_agent_proto_msgTypes[23]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use GetAnnouncementBannersResponse.ProtoReflect.Descriptor instead.
|
||||
func (*GetAnnouncementBannersResponse) Descriptor() ([]byte, []int) {
|
||||
return file_agent_proto_agent_proto_rawDescGZIP(), []int{23}
|
||||
}
|
||||
|
||||
func (x *GetAnnouncementBannersResponse) GetAnnouncementBanners() []*BannerConfig {
|
||||
if x != nil {
|
||||
return x.AnnouncementBanners
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type BannerConfig struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
Enabled bool `protobuf:"varint,1,opt,name=enabled,proto3" json:"enabled,omitempty"`
|
||||
Message string `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"`
|
||||
BackgroundColor string `protobuf:"bytes,3,opt,name=background_color,json=backgroundColor,proto3" json:"background_color,omitempty"`
|
||||
}
|
||||
|
||||
func (x *BannerConfig) Reset() {
|
||||
*x = BannerConfig{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_agent_proto_agent_proto_msgTypes[24]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *BannerConfig) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*BannerConfig) ProtoMessage() {}
|
||||
|
||||
func (x *BannerConfig) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_agent_proto_agent_proto_msgTypes[24]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use BannerConfig.ProtoReflect.Descriptor instead.
|
||||
func (*BannerConfig) Descriptor() ([]byte, []int) {
|
||||
return file_agent_proto_agent_proto_rawDescGZIP(), []int{24}
|
||||
}
|
||||
|
||||
func (x *BannerConfig) GetEnabled() bool {
|
||||
if x != nil {
|
||||
return x.Enabled
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (x *BannerConfig) GetMessage() string {
|
||||
if x != nil {
|
||||
return x.Message
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *BannerConfig) GetBackgroundColor() string {
|
||||
if x != nil {
|
||||
return x.BackgroundColor
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type WorkspaceApp_Healthcheck struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
@@ -2020,7 +1872,7 @@ type WorkspaceApp_Healthcheck struct {
|
||||
func (x *WorkspaceApp_Healthcheck) Reset() {
|
||||
*x = WorkspaceApp_Healthcheck{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_agent_proto_agent_proto_msgTypes[25]
|
||||
mi := &file_agent_proto_agent_proto_msgTypes[22]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -2033,7 +1885,7 @@ func (x *WorkspaceApp_Healthcheck) String() string {
|
||||
func (*WorkspaceApp_Healthcheck) ProtoMessage() {}
|
||||
|
||||
func (x *WorkspaceApp_Healthcheck) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_agent_proto_agent_proto_msgTypes[25]
|
||||
mi := &file_agent_proto_agent_proto_msgTypes[22]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -2084,7 +1936,7 @@ type WorkspaceAgentMetadata_Result struct {
|
||||
func (x *WorkspaceAgentMetadata_Result) Reset() {
|
||||
*x = WorkspaceAgentMetadata_Result{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_agent_proto_agent_proto_msgTypes[26]
|
||||
mi := &file_agent_proto_agent_proto_msgTypes[23]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -2097,7 +1949,7 @@ func (x *WorkspaceAgentMetadata_Result) String() string {
|
||||
func (*WorkspaceAgentMetadata_Result) ProtoMessage() {}
|
||||
|
||||
func (x *WorkspaceAgentMetadata_Result) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_agent_proto_agent_proto_msgTypes[26]
|
||||
mi := &file_agent_proto_agent_proto_msgTypes[23]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -2156,7 +2008,7 @@ type WorkspaceAgentMetadata_Description struct {
|
||||
func (x *WorkspaceAgentMetadata_Description) Reset() {
|
||||
*x = WorkspaceAgentMetadata_Description{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_agent_proto_agent_proto_msgTypes[27]
|
||||
mi := &file_agent_proto_agent_proto_msgTypes[24]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -2169,7 +2021,7 @@ func (x *WorkspaceAgentMetadata_Description) String() string {
|
||||
func (*WorkspaceAgentMetadata_Description) ProtoMessage() {}
|
||||
|
||||
func (x *WorkspaceAgentMetadata_Description) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_agent_proto_agent_proto_msgTypes[27]
|
||||
mi := &file_agent_proto_agent_proto_msgTypes[24]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -2234,7 +2086,7 @@ type Stats_Metric struct {
|
||||
func (x *Stats_Metric) Reset() {
|
||||
*x = Stats_Metric{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_agent_proto_agent_proto_msgTypes[30]
|
||||
mi := &file_agent_proto_agent_proto_msgTypes[27]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -2247,7 +2099,7 @@ func (x *Stats_Metric) String() string {
|
||||
func (*Stats_Metric) ProtoMessage() {}
|
||||
|
||||
func (x *Stats_Metric) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_agent_proto_agent_proto_msgTypes[30]
|
||||
mi := &file_agent_proto_agent_proto_msgTypes[27]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -2303,7 +2155,7 @@ type Stats_Metric_Label struct {
|
||||
func (x *Stats_Metric_Label) Reset() {
|
||||
*x = Stats_Metric_Label{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_agent_proto_agent_proto_msgTypes[31]
|
||||
mi := &file_agent_proto_agent_proto_msgTypes[28]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -2316,7 +2168,7 @@ func (x *Stats_Metric_Label) String() string {
|
||||
func (*Stats_Metric_Label) ProtoMessage() {}
|
||||
|
||||
func (x *Stats_Metric_Label) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_agent_proto_agent_proto_msgTypes[31]
|
||||
mi := &file_agent_proto_agent_proto_msgTypes[28]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -2358,7 +2210,7 @@ type BatchUpdateAppHealthRequest_HealthUpdate struct {
|
||||
func (x *BatchUpdateAppHealthRequest_HealthUpdate) Reset() {
|
||||
*x = BatchUpdateAppHealthRequest_HealthUpdate{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_agent_proto_agent_proto_msgTypes[32]
|
||||
mi := &file_agent_proto_agent_proto_msgTypes[29]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -2371,7 +2223,7 @@ func (x *BatchUpdateAppHealthRequest_HealthUpdate) String() string {
|
||||
func (*BatchUpdateAppHealthRequest_HealthUpdate) ProtoMessage() {}
|
||||
|
||||
func (x *BatchUpdateAppHealthRequest_HealthUpdate) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_agent_proto_agent_proto_msgTypes[32]
|
||||
mi := &file_agent_proto_agent_proto_msgTypes[29]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -2742,87 +2594,64 @@ var file_agent_proto_agent_proto_rawDesc = []byte{
|
||||
0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x2c, 0x0a, 0x12, 0x6c, 0x6f, 0x67, 0x5f, 0x6c, 0x69,
|
||||
0x6d, 0x69, 0x74, 0x5f, 0x65, 0x78, 0x63, 0x65, 0x65, 0x64, 0x65, 0x64, 0x18, 0x01, 0x20, 0x01,
|
||||
0x28, 0x08, 0x52, 0x10, 0x6c, 0x6f, 0x67, 0x4c, 0x69, 0x6d, 0x69, 0x74, 0x45, 0x78, 0x63, 0x65,
|
||||
0x65, 0x64, 0x65, 0x64, 0x22, 0x1f, 0x0a, 0x1d, 0x47, 0x65, 0x74, 0x41, 0x6e, 0x6e, 0x6f, 0x75,
|
||||
0x6e, 0x63, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x42, 0x61, 0x6e, 0x6e, 0x65, 0x72, 0x73, 0x52, 0x65,
|
||||
0x71, 0x75, 0x65, 0x73, 0x74, 0x22, 0x71, 0x0a, 0x1e, 0x47, 0x65, 0x74, 0x41, 0x6e, 0x6e, 0x6f,
|
||||
0x75, 0x6e, 0x63, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x42, 0x61, 0x6e, 0x6e, 0x65, 0x72, 0x73, 0x52,
|
||||
0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x4f, 0x0a, 0x14, 0x61, 0x6e, 0x6e, 0x6f, 0x75,
|
||||
0x6e, 0x63, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x5f, 0x62, 0x61, 0x6e, 0x6e, 0x65, 0x72, 0x73, 0x18,
|
||||
0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x72, 0x2e, 0x61, 0x67,
|
||||
0x65, 0x6e, 0x74, 0x2e, 0x76, 0x32, 0x2e, 0x42, 0x61, 0x6e, 0x6e, 0x65, 0x72, 0x43, 0x6f, 0x6e,
|
||||
0x66, 0x69, 0x67, 0x52, 0x13, 0x61, 0x6e, 0x6e, 0x6f, 0x75, 0x6e, 0x63, 0x65, 0x6d, 0x65, 0x6e,
|
||||
0x74, 0x42, 0x61, 0x6e, 0x6e, 0x65, 0x72, 0x73, 0x22, 0x6d, 0x0a, 0x0c, 0x42, 0x61, 0x6e, 0x6e,
|
||||
0x65, 0x72, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x18, 0x0a, 0x07, 0x65, 0x6e, 0x61, 0x62,
|
||||
0x6c, 0x65, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c,
|
||||
0x65, 0x64, 0x12, 0x18, 0x0a, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x02, 0x20,
|
||||
0x01, 0x28, 0x09, 0x52, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x29, 0x0a, 0x10,
|
||||
0x62, 0x61, 0x63, 0x6b, 0x67, 0x72, 0x6f, 0x75, 0x6e, 0x64, 0x5f, 0x63, 0x6f, 0x6c, 0x6f, 0x72,
|
||||
0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0f, 0x62, 0x61, 0x63, 0x6b, 0x67, 0x72, 0x6f, 0x75,
|
||||
0x6e, 0x64, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x2a, 0x63, 0x0a, 0x09, 0x41, 0x70, 0x70, 0x48, 0x65,
|
||||
0x61, 0x6c, 0x74, 0x68, 0x12, 0x1a, 0x0a, 0x16, 0x41, 0x50, 0x50, 0x5f, 0x48, 0x45, 0x41, 0x4c,
|
||||
0x54, 0x48, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00,
|
||||
0x12, 0x0c, 0x0a, 0x08, 0x44, 0x49, 0x53, 0x41, 0x42, 0x4c, 0x45, 0x44, 0x10, 0x01, 0x12, 0x10,
|
||||
0x0a, 0x0c, 0x49, 0x4e, 0x49, 0x54, 0x49, 0x41, 0x4c, 0x49, 0x5a, 0x49, 0x4e, 0x47, 0x10, 0x02,
|
||||
0x12, 0x0b, 0x0a, 0x07, 0x48, 0x45, 0x41, 0x4c, 0x54, 0x48, 0x59, 0x10, 0x03, 0x12, 0x0d, 0x0a,
|
||||
0x09, 0x55, 0x4e, 0x48, 0x45, 0x41, 0x4c, 0x54, 0x48, 0x59, 0x10, 0x04, 0x32, 0xef, 0x06, 0x0a,
|
||||
0x05, 0x41, 0x67, 0x65, 0x6e, 0x74, 0x12, 0x4b, 0x0a, 0x0b, 0x47, 0x65, 0x74, 0x4d, 0x61, 0x6e,
|
||||
0x69, 0x66, 0x65, 0x73, 0x74, 0x12, 0x22, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x72, 0x2e, 0x61, 0x67,
|
||||
0x65, 0x6e, 0x74, 0x2e, 0x76, 0x32, 0x2e, 0x47, 0x65, 0x74, 0x4d, 0x61, 0x6e, 0x69, 0x66, 0x65,
|
||||
0x73, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x18, 0x2e, 0x63, 0x6f, 0x64, 0x65,
|
||||
0x72, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x32, 0x2e, 0x4d, 0x61, 0x6e, 0x69, 0x66,
|
||||
0x65, 0x73, 0x74, 0x12, 0x5a, 0x0a, 0x10, 0x47, 0x65, 0x74, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63,
|
||||
0x65, 0x42, 0x61, 0x6e, 0x6e, 0x65, 0x72, 0x12, 0x27, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x72, 0x2e,
|
||||
0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x32, 0x2e, 0x47, 0x65, 0x74, 0x53, 0x65, 0x72, 0x76,
|
||||
0x69, 0x63, 0x65, 0x42, 0x61, 0x6e, 0x6e, 0x65, 0x72, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74,
|
||||
0x1a, 0x1d, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x72, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x76,
|
||||
0x32, 0x2e, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x42, 0x61, 0x6e, 0x6e, 0x65, 0x72, 0x12,
|
||||
0x56, 0x0a, 0x0b, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x53, 0x74, 0x61, 0x74, 0x73, 0x12, 0x22,
|
||||
0x2e, 0x63, 0x6f, 0x64, 0x65, 0x72, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x32, 0x2e,
|
||||
0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x53, 0x74, 0x61, 0x74, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65,
|
||||
0x73, 0x74, 0x1a, 0x23, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x72, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74,
|
||||
0x2e, 0x76, 0x32, 0x2e, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x53, 0x74, 0x61, 0x74, 0x73, 0x52,
|
||||
0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x54, 0x0a, 0x0f, 0x55, 0x70, 0x64, 0x61, 0x74,
|
||||
0x65, 0x4c, 0x69, 0x66, 0x65, 0x63, 0x79, 0x63, 0x6c, 0x65, 0x12, 0x26, 0x2e, 0x63, 0x6f, 0x64,
|
||||
0x65, 0x72, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x32, 0x2e, 0x55, 0x70, 0x64, 0x61,
|
||||
0x74, 0x65, 0x4c, 0x69, 0x66, 0x65, 0x63, 0x79, 0x63, 0x6c, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65,
|
||||
0x73, 0x74, 0x1a, 0x19, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x72, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74,
|
||||
0x2e, 0x76, 0x32, 0x2e, 0x4c, 0x69, 0x66, 0x65, 0x63, 0x79, 0x63, 0x6c, 0x65, 0x12, 0x72, 0x0a,
|
||||
0x15, 0x42, 0x61, 0x74, 0x63, 0x68, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x41, 0x70, 0x70, 0x48,
|
||||
0x65, 0x61, 0x6c, 0x74, 0x68, 0x73, 0x12, 0x2b, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x72, 0x2e, 0x61,
|
||||
0x67, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x32, 0x2e, 0x42, 0x61, 0x74, 0x63, 0x68, 0x55, 0x70, 0x64,
|
||||
0x61, 0x74, 0x65, 0x41, 0x70, 0x70, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x52, 0x65, 0x71, 0x75,
|
||||
0x65, 0x73, 0x74, 0x1a, 0x2c, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x72, 0x2e, 0x61, 0x67, 0x65, 0x6e,
|
||||
0x65, 0x64, 0x65, 0x64, 0x2a, 0x63, 0x0a, 0x09, 0x41, 0x70, 0x70, 0x48, 0x65, 0x61, 0x6c, 0x74,
|
||||
0x68, 0x12, 0x1a, 0x0a, 0x16, 0x41, 0x50, 0x50, 0x5f, 0x48, 0x45, 0x41, 0x4c, 0x54, 0x48, 0x5f,
|
||||
0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x0c, 0x0a,
|
||||
0x08, 0x44, 0x49, 0x53, 0x41, 0x42, 0x4c, 0x45, 0x44, 0x10, 0x01, 0x12, 0x10, 0x0a, 0x0c, 0x49,
|
||||
0x4e, 0x49, 0x54, 0x49, 0x41, 0x4c, 0x49, 0x5a, 0x49, 0x4e, 0x47, 0x10, 0x02, 0x12, 0x0b, 0x0a,
|
||||
0x07, 0x48, 0x45, 0x41, 0x4c, 0x54, 0x48, 0x59, 0x10, 0x03, 0x12, 0x0d, 0x0a, 0x09, 0x55, 0x4e,
|
||||
0x48, 0x45, 0x41, 0x4c, 0x54, 0x48, 0x59, 0x10, 0x04, 0x32, 0xf6, 0x05, 0x0a, 0x05, 0x41, 0x67,
|
||||
0x65, 0x6e, 0x74, 0x12, 0x4b, 0x0a, 0x0b, 0x47, 0x65, 0x74, 0x4d, 0x61, 0x6e, 0x69, 0x66, 0x65,
|
||||
0x73, 0x74, 0x12, 0x22, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x72, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74,
|
||||
0x2e, 0x76, 0x32, 0x2e, 0x47, 0x65, 0x74, 0x4d, 0x61, 0x6e, 0x69, 0x66, 0x65, 0x73, 0x74, 0x52,
|
||||
0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x18, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x72, 0x2e, 0x61,
|
||||
0x67, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x32, 0x2e, 0x4d, 0x61, 0x6e, 0x69, 0x66, 0x65, 0x73, 0x74,
|
||||
0x12, 0x5a, 0x0a, 0x10, 0x47, 0x65, 0x74, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x42, 0x61,
|
||||
0x6e, 0x6e, 0x65, 0x72, 0x12, 0x27, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x72, 0x2e, 0x61, 0x67, 0x65,
|
||||
0x6e, 0x74, 0x2e, 0x76, 0x32, 0x2e, 0x47, 0x65, 0x74, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65,
|
||||
0x42, 0x61, 0x6e, 0x6e, 0x65, 0x72, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1d, 0x2e,
|
||||
0x63, 0x6f, 0x64, 0x65, 0x72, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x32, 0x2e, 0x53,
|
||||
0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x42, 0x61, 0x6e, 0x6e, 0x65, 0x72, 0x12, 0x56, 0x0a, 0x0b,
|
||||
0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x53, 0x74, 0x61, 0x74, 0x73, 0x12, 0x22, 0x2e, 0x63, 0x6f,
|
||||
0x64, 0x65, 0x72, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x32, 0x2e, 0x55, 0x70, 0x64,
|
||||
0x61, 0x74, 0x65, 0x53, 0x74, 0x61, 0x74, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a,
|
||||
0x23, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x72, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x32,
|
||||
0x2e, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x53, 0x74, 0x61, 0x74, 0x73, 0x52, 0x65, 0x73, 0x70,
|
||||
0x6f, 0x6e, 0x73, 0x65, 0x12, 0x54, 0x0a, 0x0f, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x4c, 0x69,
|
||||
0x66, 0x65, 0x63, 0x79, 0x63, 0x6c, 0x65, 0x12, 0x26, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x72, 0x2e,
|
||||
0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x32, 0x2e, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x4c,
|
||||
0x69, 0x66, 0x65, 0x63, 0x79, 0x63, 0x6c, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a,
|
||||
0x19, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x72, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x32,
|
||||
0x2e, 0x4c, 0x69, 0x66, 0x65, 0x63, 0x79, 0x63, 0x6c, 0x65, 0x12, 0x72, 0x0a, 0x15, 0x42, 0x61,
|
||||
0x74, 0x63, 0x68, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x41, 0x70, 0x70, 0x48, 0x65, 0x61, 0x6c,
|
||||
0x74, 0x68, 0x73, 0x12, 0x2b, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x72, 0x2e, 0x61, 0x67, 0x65, 0x6e,
|
||||
0x74, 0x2e, 0x76, 0x32, 0x2e, 0x42, 0x61, 0x74, 0x63, 0x68, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65,
|
||||
0x41, 0x70, 0x70, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73,
|
||||
0x65, 0x12, 0x4e, 0x0a, 0x0d, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x53, 0x74, 0x61, 0x72, 0x74,
|
||||
0x75, 0x70, 0x12, 0x24, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x72, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74,
|
||||
0x2e, 0x76, 0x32, 0x2e, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x53, 0x74, 0x61, 0x72, 0x74, 0x75,
|
||||
0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x17, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x72,
|
||||
0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x32, 0x2e, 0x53, 0x74, 0x61, 0x72, 0x74, 0x75,
|
||||
0x70, 0x12, 0x6e, 0x0a, 0x13, 0x42, 0x61, 0x74, 0x63, 0x68, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65,
|
||||
0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12, 0x2a, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x72,
|
||||
0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x32, 0x2e, 0x42, 0x61, 0x74, 0x63, 0x68, 0x55,
|
||||
0x70, 0x64, 0x61, 0x74, 0x65, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x52, 0x65, 0x71,
|
||||
0x75, 0x65, 0x73, 0x74, 0x1a, 0x2b, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x72, 0x2e, 0x61, 0x67, 0x65,
|
||||
0x6e, 0x74, 0x2e, 0x76, 0x32, 0x2e, 0x42, 0x61, 0x74, 0x63, 0x68, 0x55, 0x70, 0x64, 0x61, 0x74,
|
||||
0x65, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73,
|
||||
0x65, 0x12, 0x62, 0x0a, 0x0f, 0x42, 0x61, 0x74, 0x63, 0x68, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65,
|
||||
0x4c, 0x6f, 0x67, 0x73, 0x12, 0x26, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x72, 0x2e, 0x61, 0x67, 0x65,
|
||||
0x6e, 0x74, 0x2e, 0x76, 0x32, 0x2e, 0x42, 0x61, 0x74, 0x63, 0x68, 0x43, 0x72, 0x65, 0x61, 0x74,
|
||||
0x65, 0x4c, 0x6f, 0x67, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x27, 0x2e, 0x63,
|
||||
0x6f, 0x64, 0x65, 0x72, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x32, 0x2e, 0x42, 0x61,
|
||||
0x74, 0x63, 0x68, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x4c, 0x6f, 0x67, 0x73, 0x52, 0x65, 0x73,
|
||||
0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x77, 0x0a, 0x16, 0x47, 0x65, 0x74, 0x41, 0x6e, 0x6e, 0x6f,
|
||||
0x75, 0x6e, 0x63, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x42, 0x61, 0x6e, 0x6e, 0x65, 0x72, 0x73, 0x12,
|
||||
0x2d, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x72, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x32,
|
||||
0x2e, 0x47, 0x65, 0x74, 0x41, 0x6e, 0x6e, 0x6f, 0x75, 0x6e, 0x63, 0x65, 0x6d, 0x65, 0x6e, 0x74,
|
||||
0x42, 0x61, 0x6e, 0x6e, 0x65, 0x72, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2e,
|
||||
0x2e, 0x63, 0x6f, 0x64, 0x65, 0x72, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x32, 0x2e,
|
||||
0x47, 0x65, 0x74, 0x41, 0x6e, 0x6e, 0x6f, 0x75, 0x6e, 0x63, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x42,
|
||||
0x61, 0x6e, 0x6e, 0x65, 0x72, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x27,
|
||||
0x5a, 0x25, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x6f, 0x64,
|
||||
0x65, 0x72, 0x2f, 0x63, 0x6f, 0x64, 0x65, 0x72, 0x2f, 0x76, 0x32, 0x2f, 0x61, 0x67, 0x65, 0x6e,
|
||||
0x74, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
|
||||
0x41, 0x70, 0x70, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74,
|
||||
0x1a, 0x2c, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x72, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x76,
|
||||
0x32, 0x2e, 0x42, 0x61, 0x74, 0x63, 0x68, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x41, 0x70, 0x70,
|
||||
0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x4e,
|
||||
0x0a, 0x0d, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x53, 0x74, 0x61, 0x72, 0x74, 0x75, 0x70, 0x12,
|
||||
0x24, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x72, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x32,
|
||||
0x2e, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x53, 0x74, 0x61, 0x72, 0x74, 0x75, 0x70, 0x52, 0x65,
|
||||
0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x17, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x72, 0x2e, 0x61, 0x67,
|
||||
0x65, 0x6e, 0x74, 0x2e, 0x76, 0x32, 0x2e, 0x53, 0x74, 0x61, 0x72, 0x74, 0x75, 0x70, 0x12, 0x6e,
|
||||
0x0a, 0x13, 0x42, 0x61, 0x74, 0x63, 0x68, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x4d, 0x65, 0x74,
|
||||
0x61, 0x64, 0x61, 0x74, 0x61, 0x12, 0x2a, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x72, 0x2e, 0x61, 0x67,
|
||||
0x65, 0x6e, 0x74, 0x2e, 0x76, 0x32, 0x2e, 0x42, 0x61, 0x74, 0x63, 0x68, 0x55, 0x70, 0x64, 0x61,
|
||||
0x74, 0x65, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73,
|
||||
0x74, 0x1a, 0x2b, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x72, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e,
|
||||
0x76, 0x32, 0x2e, 0x42, 0x61, 0x74, 0x63, 0x68, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x4d, 0x65,
|
||||
0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x62,
|
||||
0x0a, 0x0f, 0x42, 0x61, 0x74, 0x63, 0x68, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x4c, 0x6f, 0x67,
|
||||
0x73, 0x12, 0x26, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x72, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e,
|
||||
0x76, 0x32, 0x2e, 0x42, 0x61, 0x74, 0x63, 0x68, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x4c, 0x6f,
|
||||
0x67, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x27, 0x2e, 0x63, 0x6f, 0x64, 0x65,
|
||||
0x72, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x32, 0x2e, 0x42, 0x61, 0x74, 0x63, 0x68,
|
||||
0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x4c, 0x6f, 0x67, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e,
|
||||
0x73, 0x65, 0x42, 0x27, 0x5a, 0x25, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d,
|
||||
0x2f, 0x63, 0x6f, 0x64, 0x65, 0x72, 0x2f, 0x63, 0x6f, 0x64, 0x65, 0x72, 0x2f, 0x76, 0x32, 0x2f,
|
||||
0x61, 0x67, 0x65, 0x6e, 0x74, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x06, 0x70, 0x72, 0x6f,
|
||||
0x74, 0x6f, 0x33,
|
||||
}
|
||||
|
||||
var (
|
||||
@@ -2838,7 +2667,7 @@ func file_agent_proto_agent_proto_rawDescGZIP() []byte {
|
||||
}
|
||||
|
||||
var file_agent_proto_agent_proto_enumTypes = make([]protoimpl.EnumInfo, 7)
|
||||
var file_agent_proto_agent_proto_msgTypes = make([]protoimpl.MessageInfo, 33)
|
||||
var file_agent_proto_agent_proto_msgTypes = make([]protoimpl.MessageInfo, 30)
|
||||
var file_agent_proto_agent_proto_goTypes = []interface{}{
|
||||
(AppHealth)(0), // 0: coder.agent.v2.AppHealth
|
||||
(WorkspaceApp_SharingLevel)(0), // 1: coder.agent.v2.WorkspaceApp.SharingLevel
|
||||
@@ -2869,79 +2698,73 @@ var file_agent_proto_agent_proto_goTypes = []interface{}{
|
||||
(*Log)(nil), // 26: coder.agent.v2.Log
|
||||
(*BatchCreateLogsRequest)(nil), // 27: coder.agent.v2.BatchCreateLogsRequest
|
||||
(*BatchCreateLogsResponse)(nil), // 28: coder.agent.v2.BatchCreateLogsResponse
|
||||
(*GetAnnouncementBannersRequest)(nil), // 29: coder.agent.v2.GetAnnouncementBannersRequest
|
||||
(*GetAnnouncementBannersResponse)(nil), // 30: coder.agent.v2.GetAnnouncementBannersResponse
|
||||
(*BannerConfig)(nil), // 31: coder.agent.v2.BannerConfig
|
||||
(*WorkspaceApp_Healthcheck)(nil), // 32: coder.agent.v2.WorkspaceApp.Healthcheck
|
||||
(*WorkspaceAgentMetadata_Result)(nil), // 33: coder.agent.v2.WorkspaceAgentMetadata.Result
|
||||
(*WorkspaceAgentMetadata_Description)(nil), // 34: coder.agent.v2.WorkspaceAgentMetadata.Description
|
||||
nil, // 35: coder.agent.v2.Manifest.EnvironmentVariablesEntry
|
||||
nil, // 36: coder.agent.v2.Stats.ConnectionsByProtoEntry
|
||||
(*Stats_Metric)(nil), // 37: coder.agent.v2.Stats.Metric
|
||||
(*Stats_Metric_Label)(nil), // 38: coder.agent.v2.Stats.Metric.Label
|
||||
(*BatchUpdateAppHealthRequest_HealthUpdate)(nil), // 39: coder.agent.v2.BatchUpdateAppHealthRequest.HealthUpdate
|
||||
(*durationpb.Duration)(nil), // 40: google.protobuf.Duration
|
||||
(*proto.DERPMap)(nil), // 41: coder.tailnet.v2.DERPMap
|
||||
(*timestamppb.Timestamp)(nil), // 42: google.protobuf.Timestamp
|
||||
(*WorkspaceApp_Healthcheck)(nil), // 29: coder.agent.v2.WorkspaceApp.Healthcheck
|
||||
(*WorkspaceAgentMetadata_Result)(nil), // 30: coder.agent.v2.WorkspaceAgentMetadata.Result
|
||||
(*WorkspaceAgentMetadata_Description)(nil), // 31: coder.agent.v2.WorkspaceAgentMetadata.Description
|
||||
nil, // 32: coder.agent.v2.Manifest.EnvironmentVariablesEntry
|
||||
nil, // 33: coder.agent.v2.Stats.ConnectionsByProtoEntry
|
||||
(*Stats_Metric)(nil), // 34: coder.agent.v2.Stats.Metric
|
||||
(*Stats_Metric_Label)(nil), // 35: coder.agent.v2.Stats.Metric.Label
|
||||
(*BatchUpdateAppHealthRequest_HealthUpdate)(nil), // 36: coder.agent.v2.BatchUpdateAppHealthRequest.HealthUpdate
|
||||
(*durationpb.Duration)(nil), // 37: google.protobuf.Duration
|
||||
(*proto.DERPMap)(nil), // 38: coder.tailnet.v2.DERPMap
|
||||
(*timestamppb.Timestamp)(nil), // 39: google.protobuf.Timestamp
|
||||
}
|
||||
var file_agent_proto_agent_proto_depIdxs = []int32{
|
||||
1, // 0: coder.agent.v2.WorkspaceApp.sharing_level:type_name -> coder.agent.v2.WorkspaceApp.SharingLevel
|
||||
32, // 1: coder.agent.v2.WorkspaceApp.healthcheck:type_name -> coder.agent.v2.WorkspaceApp.Healthcheck
|
||||
29, // 1: coder.agent.v2.WorkspaceApp.healthcheck:type_name -> coder.agent.v2.WorkspaceApp.Healthcheck
|
||||
2, // 2: coder.agent.v2.WorkspaceApp.health:type_name -> coder.agent.v2.WorkspaceApp.Health
|
||||
40, // 3: coder.agent.v2.WorkspaceAgentScript.timeout:type_name -> google.protobuf.Duration
|
||||
33, // 4: coder.agent.v2.WorkspaceAgentMetadata.result:type_name -> coder.agent.v2.WorkspaceAgentMetadata.Result
|
||||
34, // 5: coder.agent.v2.WorkspaceAgentMetadata.description:type_name -> coder.agent.v2.WorkspaceAgentMetadata.Description
|
||||
35, // 6: coder.agent.v2.Manifest.environment_variables:type_name -> coder.agent.v2.Manifest.EnvironmentVariablesEntry
|
||||
41, // 7: coder.agent.v2.Manifest.derp_map:type_name -> coder.tailnet.v2.DERPMap
|
||||
37, // 3: coder.agent.v2.WorkspaceAgentScript.timeout:type_name -> google.protobuf.Duration
|
||||
30, // 4: coder.agent.v2.WorkspaceAgentMetadata.result:type_name -> coder.agent.v2.WorkspaceAgentMetadata.Result
|
||||
31, // 5: coder.agent.v2.WorkspaceAgentMetadata.description:type_name -> coder.agent.v2.WorkspaceAgentMetadata.Description
|
||||
32, // 6: coder.agent.v2.Manifest.environment_variables:type_name -> coder.agent.v2.Manifest.EnvironmentVariablesEntry
|
||||
38, // 7: coder.agent.v2.Manifest.derp_map:type_name -> coder.tailnet.v2.DERPMap
|
||||
8, // 8: coder.agent.v2.Manifest.scripts:type_name -> coder.agent.v2.WorkspaceAgentScript
|
||||
7, // 9: coder.agent.v2.Manifest.apps:type_name -> coder.agent.v2.WorkspaceApp
|
||||
34, // 10: coder.agent.v2.Manifest.metadata:type_name -> coder.agent.v2.WorkspaceAgentMetadata.Description
|
||||
36, // 11: coder.agent.v2.Stats.connections_by_proto:type_name -> coder.agent.v2.Stats.ConnectionsByProtoEntry
|
||||
37, // 12: coder.agent.v2.Stats.metrics:type_name -> coder.agent.v2.Stats.Metric
|
||||
31, // 10: coder.agent.v2.Manifest.metadata:type_name -> coder.agent.v2.WorkspaceAgentMetadata.Description
|
||||
33, // 11: coder.agent.v2.Stats.connections_by_proto:type_name -> coder.agent.v2.Stats.ConnectionsByProtoEntry
|
||||
34, // 12: coder.agent.v2.Stats.metrics:type_name -> coder.agent.v2.Stats.Metric
|
||||
14, // 13: coder.agent.v2.UpdateStatsRequest.stats:type_name -> coder.agent.v2.Stats
|
||||
40, // 14: coder.agent.v2.UpdateStatsResponse.report_interval:type_name -> google.protobuf.Duration
|
||||
37, // 14: coder.agent.v2.UpdateStatsResponse.report_interval:type_name -> google.protobuf.Duration
|
||||
4, // 15: coder.agent.v2.Lifecycle.state:type_name -> coder.agent.v2.Lifecycle.State
|
||||
42, // 16: coder.agent.v2.Lifecycle.changed_at:type_name -> google.protobuf.Timestamp
|
||||
39, // 16: coder.agent.v2.Lifecycle.changed_at:type_name -> google.protobuf.Timestamp
|
||||
17, // 17: coder.agent.v2.UpdateLifecycleRequest.lifecycle:type_name -> coder.agent.v2.Lifecycle
|
||||
39, // 18: coder.agent.v2.BatchUpdateAppHealthRequest.updates:type_name -> coder.agent.v2.BatchUpdateAppHealthRequest.HealthUpdate
|
||||
36, // 18: coder.agent.v2.BatchUpdateAppHealthRequest.updates:type_name -> coder.agent.v2.BatchUpdateAppHealthRequest.HealthUpdate
|
||||
5, // 19: coder.agent.v2.Startup.subsystems:type_name -> coder.agent.v2.Startup.Subsystem
|
||||
21, // 20: coder.agent.v2.UpdateStartupRequest.startup:type_name -> coder.agent.v2.Startup
|
||||
33, // 21: coder.agent.v2.Metadata.result:type_name -> coder.agent.v2.WorkspaceAgentMetadata.Result
|
||||
30, // 21: coder.agent.v2.Metadata.result:type_name -> coder.agent.v2.WorkspaceAgentMetadata.Result
|
||||
23, // 22: coder.agent.v2.BatchUpdateMetadataRequest.metadata:type_name -> coder.agent.v2.Metadata
|
||||
42, // 23: coder.agent.v2.Log.created_at:type_name -> google.protobuf.Timestamp
|
||||
39, // 23: coder.agent.v2.Log.created_at:type_name -> google.protobuf.Timestamp
|
||||
6, // 24: coder.agent.v2.Log.level:type_name -> coder.agent.v2.Log.Level
|
||||
26, // 25: coder.agent.v2.BatchCreateLogsRequest.logs:type_name -> coder.agent.v2.Log
|
||||
31, // 26: coder.agent.v2.GetAnnouncementBannersResponse.announcement_banners:type_name -> coder.agent.v2.BannerConfig
|
||||
40, // 27: coder.agent.v2.WorkspaceApp.Healthcheck.interval:type_name -> google.protobuf.Duration
|
||||
42, // 28: coder.agent.v2.WorkspaceAgentMetadata.Result.collected_at:type_name -> google.protobuf.Timestamp
|
||||
40, // 29: coder.agent.v2.WorkspaceAgentMetadata.Description.interval:type_name -> google.protobuf.Duration
|
||||
40, // 30: coder.agent.v2.WorkspaceAgentMetadata.Description.timeout:type_name -> google.protobuf.Duration
|
||||
3, // 31: coder.agent.v2.Stats.Metric.type:type_name -> coder.agent.v2.Stats.Metric.Type
|
||||
38, // 32: coder.agent.v2.Stats.Metric.labels:type_name -> coder.agent.v2.Stats.Metric.Label
|
||||
0, // 33: coder.agent.v2.BatchUpdateAppHealthRequest.HealthUpdate.health:type_name -> coder.agent.v2.AppHealth
|
||||
11, // 34: coder.agent.v2.Agent.GetManifest:input_type -> coder.agent.v2.GetManifestRequest
|
||||
13, // 35: coder.agent.v2.Agent.GetServiceBanner:input_type -> coder.agent.v2.GetServiceBannerRequest
|
||||
15, // 36: coder.agent.v2.Agent.UpdateStats:input_type -> coder.agent.v2.UpdateStatsRequest
|
||||
18, // 37: coder.agent.v2.Agent.UpdateLifecycle:input_type -> coder.agent.v2.UpdateLifecycleRequest
|
||||
19, // 38: coder.agent.v2.Agent.BatchUpdateAppHealths:input_type -> coder.agent.v2.BatchUpdateAppHealthRequest
|
||||
22, // 39: coder.agent.v2.Agent.UpdateStartup:input_type -> coder.agent.v2.UpdateStartupRequest
|
||||
24, // 40: coder.agent.v2.Agent.BatchUpdateMetadata:input_type -> coder.agent.v2.BatchUpdateMetadataRequest
|
||||
27, // 41: coder.agent.v2.Agent.BatchCreateLogs:input_type -> coder.agent.v2.BatchCreateLogsRequest
|
||||
29, // 42: coder.agent.v2.Agent.GetAnnouncementBanners:input_type -> coder.agent.v2.GetAnnouncementBannersRequest
|
||||
10, // 43: coder.agent.v2.Agent.GetManifest:output_type -> coder.agent.v2.Manifest
|
||||
12, // 44: coder.agent.v2.Agent.GetServiceBanner:output_type -> coder.agent.v2.ServiceBanner
|
||||
16, // 45: coder.agent.v2.Agent.UpdateStats:output_type -> coder.agent.v2.UpdateStatsResponse
|
||||
17, // 46: coder.agent.v2.Agent.UpdateLifecycle:output_type -> coder.agent.v2.Lifecycle
|
||||
20, // 47: coder.agent.v2.Agent.BatchUpdateAppHealths:output_type -> coder.agent.v2.BatchUpdateAppHealthResponse
|
||||
21, // 48: coder.agent.v2.Agent.UpdateStartup:output_type -> coder.agent.v2.Startup
|
||||
25, // 49: coder.agent.v2.Agent.BatchUpdateMetadata:output_type -> coder.agent.v2.BatchUpdateMetadataResponse
|
||||
28, // 50: coder.agent.v2.Agent.BatchCreateLogs:output_type -> coder.agent.v2.BatchCreateLogsResponse
|
||||
30, // 51: coder.agent.v2.Agent.GetAnnouncementBanners:output_type -> coder.agent.v2.GetAnnouncementBannersResponse
|
||||
43, // [43:52] is the sub-list for method output_type
|
||||
34, // [34:43] is the sub-list for method input_type
|
||||
34, // [34:34] is the sub-list for extension type_name
|
||||
34, // [34:34] is the sub-list for extension extendee
|
||||
0, // [0:34] is the sub-list for field type_name
|
||||
37, // 26: coder.agent.v2.WorkspaceApp.Healthcheck.interval:type_name -> google.protobuf.Duration
|
||||
39, // 27: coder.agent.v2.WorkspaceAgentMetadata.Result.collected_at:type_name -> google.protobuf.Timestamp
|
||||
37, // 28: coder.agent.v2.WorkspaceAgentMetadata.Description.interval:type_name -> google.protobuf.Duration
|
||||
37, // 29: coder.agent.v2.WorkspaceAgentMetadata.Description.timeout:type_name -> google.protobuf.Duration
|
||||
3, // 30: coder.agent.v2.Stats.Metric.type:type_name -> coder.agent.v2.Stats.Metric.Type
|
||||
35, // 31: coder.agent.v2.Stats.Metric.labels:type_name -> coder.agent.v2.Stats.Metric.Label
|
||||
0, // 32: coder.agent.v2.BatchUpdateAppHealthRequest.HealthUpdate.health:type_name -> coder.agent.v2.AppHealth
|
||||
11, // 33: coder.agent.v2.Agent.GetManifest:input_type -> coder.agent.v2.GetManifestRequest
|
||||
13, // 34: coder.agent.v2.Agent.GetServiceBanner:input_type -> coder.agent.v2.GetServiceBannerRequest
|
||||
15, // 35: coder.agent.v2.Agent.UpdateStats:input_type -> coder.agent.v2.UpdateStatsRequest
|
||||
18, // 36: coder.agent.v2.Agent.UpdateLifecycle:input_type -> coder.agent.v2.UpdateLifecycleRequest
|
||||
19, // 37: coder.agent.v2.Agent.BatchUpdateAppHealths:input_type -> coder.agent.v2.BatchUpdateAppHealthRequest
|
||||
22, // 38: coder.agent.v2.Agent.UpdateStartup:input_type -> coder.agent.v2.UpdateStartupRequest
|
||||
24, // 39: coder.agent.v2.Agent.BatchUpdateMetadata:input_type -> coder.agent.v2.BatchUpdateMetadataRequest
|
||||
27, // 40: coder.agent.v2.Agent.BatchCreateLogs:input_type -> coder.agent.v2.BatchCreateLogsRequest
|
||||
10, // 41: coder.agent.v2.Agent.GetManifest:output_type -> coder.agent.v2.Manifest
|
||||
12, // 42: coder.agent.v2.Agent.GetServiceBanner:output_type -> coder.agent.v2.ServiceBanner
|
||||
16, // 43: coder.agent.v2.Agent.UpdateStats:output_type -> coder.agent.v2.UpdateStatsResponse
|
||||
17, // 44: coder.agent.v2.Agent.UpdateLifecycle:output_type -> coder.agent.v2.Lifecycle
|
||||
20, // 45: coder.agent.v2.Agent.BatchUpdateAppHealths:output_type -> coder.agent.v2.BatchUpdateAppHealthResponse
|
||||
21, // 46: coder.agent.v2.Agent.UpdateStartup:output_type -> coder.agent.v2.Startup
|
||||
25, // 47: coder.agent.v2.Agent.BatchUpdateMetadata:output_type -> coder.agent.v2.BatchUpdateMetadataResponse
|
||||
28, // 48: coder.agent.v2.Agent.BatchCreateLogs:output_type -> coder.agent.v2.BatchCreateLogsResponse
|
||||
41, // [41:49] is the sub-list for method output_type
|
||||
33, // [33:41] is the sub-list for method input_type
|
||||
33, // [33:33] is the sub-list for extension type_name
|
||||
33, // [33:33] is the sub-list for extension extendee
|
||||
0, // [0:33] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_agent_proto_agent_proto_init() }
|
||||
@@ -3215,42 +3038,6 @@ func file_agent_proto_agent_proto_init() {
|
||||
}
|
||||
}
|
||||
file_agent_proto_agent_proto_msgTypes[22].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*GetAnnouncementBannersRequest); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
file_agent_proto_agent_proto_msgTypes[23].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*GetAnnouncementBannersResponse); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
file_agent_proto_agent_proto_msgTypes[24].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*BannerConfig); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
file_agent_proto_agent_proto_msgTypes[25].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*WorkspaceApp_Healthcheck); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
@@ -3262,7 +3049,7 @@ func file_agent_proto_agent_proto_init() {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
file_agent_proto_agent_proto_msgTypes[26].Exporter = func(v interface{}, i int) interface{} {
|
||||
file_agent_proto_agent_proto_msgTypes[23].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*WorkspaceAgentMetadata_Result); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
@@ -3274,7 +3061,7 @@ func file_agent_proto_agent_proto_init() {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
file_agent_proto_agent_proto_msgTypes[27].Exporter = func(v interface{}, i int) interface{} {
|
||||
file_agent_proto_agent_proto_msgTypes[24].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*WorkspaceAgentMetadata_Description); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
@@ -3286,7 +3073,7 @@ func file_agent_proto_agent_proto_init() {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
file_agent_proto_agent_proto_msgTypes[30].Exporter = func(v interface{}, i int) interface{} {
|
||||
file_agent_proto_agent_proto_msgTypes[27].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*Stats_Metric); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
@@ -3298,7 +3085,7 @@ func file_agent_proto_agent_proto_init() {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
file_agent_proto_agent_proto_msgTypes[31].Exporter = func(v interface{}, i int) interface{} {
|
||||
file_agent_proto_agent_proto_msgTypes[28].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*Stats_Metric_Label); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
@@ -3310,7 +3097,7 @@ func file_agent_proto_agent_proto_init() {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
file_agent_proto_agent_proto_msgTypes[32].Exporter = func(v interface{}, i int) interface{} {
|
||||
file_agent_proto_agent_proto_msgTypes[29].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*BatchUpdateAppHealthRequest_HealthUpdate); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
@@ -3329,7 +3116,7 @@ func file_agent_proto_agent_proto_init() {
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: file_agent_proto_agent_proto_rawDesc,
|
||||
NumEnums: 7,
|
||||
NumMessages: 33,
|
||||
NumMessages: 30,
|
||||
NumExtensions: 0,
|
||||
NumServices: 1,
|
||||
},
|
||||
|
||||
@@ -251,18 +251,6 @@ message BatchCreateLogsResponse {
|
||||
bool log_limit_exceeded = 1;
|
||||
}
|
||||
|
||||
message GetAnnouncementBannersRequest {}
|
||||
|
||||
message GetAnnouncementBannersResponse {
|
||||
repeated BannerConfig announcement_banners = 1;
|
||||
}
|
||||
|
||||
message BannerConfig {
|
||||
bool enabled = 1;
|
||||
string message = 2;
|
||||
string background_color = 3;
|
||||
}
|
||||
|
||||
service Agent {
|
||||
rpc GetManifest(GetManifestRequest) returns (Manifest);
|
||||
rpc GetServiceBanner(GetServiceBannerRequest) returns (ServiceBanner);
|
||||
@@ -272,5 +260,4 @@ service Agent {
|
||||
rpc UpdateStartup(UpdateStartupRequest) returns (Startup);
|
||||
rpc BatchUpdateMetadata(BatchUpdateMetadataRequest) returns (BatchUpdateMetadataResponse);
|
||||
rpc BatchCreateLogs(BatchCreateLogsRequest) returns (BatchCreateLogsResponse);
|
||||
rpc GetAnnouncementBanners(GetAnnouncementBannersRequest) returns (GetAnnouncementBannersResponse);
|
||||
}
|
||||
|
||||
@@ -46,7 +46,6 @@ type DRPCAgentClient interface {
|
||||
UpdateStartup(ctx context.Context, in *UpdateStartupRequest) (*Startup, error)
|
||||
BatchUpdateMetadata(ctx context.Context, in *BatchUpdateMetadataRequest) (*BatchUpdateMetadataResponse, error)
|
||||
BatchCreateLogs(ctx context.Context, in *BatchCreateLogsRequest) (*BatchCreateLogsResponse, error)
|
||||
GetAnnouncementBanners(ctx context.Context, in *GetAnnouncementBannersRequest) (*GetAnnouncementBannersResponse, error)
|
||||
}
|
||||
|
||||
type drpcAgentClient struct {
|
||||
@@ -131,15 +130,6 @@ func (c *drpcAgentClient) BatchCreateLogs(ctx context.Context, in *BatchCreateLo
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *drpcAgentClient) GetAnnouncementBanners(ctx context.Context, in *GetAnnouncementBannersRequest) (*GetAnnouncementBannersResponse, error) {
|
||||
out := new(GetAnnouncementBannersResponse)
|
||||
err := c.cc.Invoke(ctx, "/coder.agent.v2.Agent/GetAnnouncementBanners", drpcEncoding_File_agent_proto_agent_proto{}, in, out)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
type DRPCAgentServer interface {
|
||||
GetManifest(context.Context, *GetManifestRequest) (*Manifest, error)
|
||||
GetServiceBanner(context.Context, *GetServiceBannerRequest) (*ServiceBanner, error)
|
||||
@@ -149,7 +139,6 @@ type DRPCAgentServer interface {
|
||||
UpdateStartup(context.Context, *UpdateStartupRequest) (*Startup, error)
|
||||
BatchUpdateMetadata(context.Context, *BatchUpdateMetadataRequest) (*BatchUpdateMetadataResponse, error)
|
||||
BatchCreateLogs(context.Context, *BatchCreateLogsRequest) (*BatchCreateLogsResponse, error)
|
||||
GetAnnouncementBanners(context.Context, *GetAnnouncementBannersRequest) (*GetAnnouncementBannersResponse, error)
|
||||
}
|
||||
|
||||
type DRPCAgentUnimplementedServer struct{}
|
||||
@@ -186,13 +175,9 @@ func (s *DRPCAgentUnimplementedServer) BatchCreateLogs(context.Context, *BatchCr
|
||||
return nil, drpcerr.WithCode(errors.New("Unimplemented"), drpcerr.Unimplemented)
|
||||
}
|
||||
|
||||
func (s *DRPCAgentUnimplementedServer) GetAnnouncementBanners(context.Context, *GetAnnouncementBannersRequest) (*GetAnnouncementBannersResponse, error) {
|
||||
return nil, drpcerr.WithCode(errors.New("Unimplemented"), drpcerr.Unimplemented)
|
||||
}
|
||||
|
||||
type DRPCAgentDescription struct{}
|
||||
|
||||
func (DRPCAgentDescription) NumMethods() int { return 9 }
|
||||
func (DRPCAgentDescription) NumMethods() int { return 8 }
|
||||
|
||||
func (DRPCAgentDescription) Method(n int) (string, drpc.Encoding, drpc.Receiver, interface{}, bool) {
|
||||
switch n {
|
||||
@@ -268,15 +253,6 @@ func (DRPCAgentDescription) Method(n int) (string, drpc.Encoding, drpc.Receiver,
|
||||
in1.(*BatchCreateLogsRequest),
|
||||
)
|
||||
}, DRPCAgentServer.BatchCreateLogs, true
|
||||
case 8:
|
||||
return "/coder.agent.v2.Agent/GetAnnouncementBanners", drpcEncoding_File_agent_proto_agent_proto{},
|
||||
func(srv interface{}, ctx context.Context, in1, in2 interface{}) (drpc.Message, error) {
|
||||
return srv.(DRPCAgentServer).
|
||||
GetAnnouncementBanners(
|
||||
ctx,
|
||||
in1.(*GetAnnouncementBannersRequest),
|
||||
)
|
||||
}, DRPCAgentServer.GetAnnouncementBanners, true
|
||||
default:
|
||||
return "", nil, nil, nil, false
|
||||
}
|
||||
@@ -413,19 +389,3 @@ func (x *drpcAgent_BatchCreateLogsStream) SendAndClose(m *BatchCreateLogsRespons
|
||||
}
|
||||
return x.CloseSend()
|
||||
}
|
||||
|
||||
type DRPCAgent_GetAnnouncementBannersStream interface {
|
||||
drpc.Stream
|
||||
SendAndClose(*GetAnnouncementBannersResponse) error
|
||||
}
|
||||
|
||||
type drpcAgent_GetAnnouncementBannersStream struct {
|
||||
drpc.Stream
|
||||
}
|
||||
|
||||
func (x *drpcAgent_GetAnnouncementBannersStream) SendAndClose(m *GetAnnouncementBannersResponse) error {
|
||||
if err := x.MsgSend(m, drpcEncoding_File_agent_proto_agent_proto{}); err != nil {
|
||||
return err
|
||||
}
|
||||
return x.CloseSend()
|
||||
}
|
||||
|
||||
@@ -14,7 +14,8 @@ import (
|
||||
"golang.org/x/xerrors"
|
||||
|
||||
"cdr.dev/slog"
|
||||
"github.com/coder/coder/v2/codersdk/workspacesdk"
|
||||
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/coder/v2/pty"
|
||||
)
|
||||
|
||||
@@ -196,7 +197,7 @@ func (s *ptyState) waitForStateOrContext(ctx context.Context, state State) (Stat
|
||||
func readConnLoop(ctx context.Context, conn net.Conn, ptty pty.PTYCmd, metrics *prometheus.CounterVec, logger slog.Logger) {
|
||||
decoder := json.NewDecoder(conn)
|
||||
for {
|
||||
var req workspacesdk.ReconnectingPTYRequest
|
||||
var req codersdk.ReconnectingPTYRequest
|
||||
err := decoder.Decode(&req)
|
||||
if xerrors.Is(err, io.EOF) {
|
||||
return
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/netip"
|
||||
"sync"
|
||||
"testing"
|
||||
@@ -17,7 +14,6 @@ import (
|
||||
"tailscale.com/types/netlogtype"
|
||||
|
||||
"cdr.dev/slog"
|
||||
"cdr.dev/slog/sloggers/slogjson"
|
||||
"cdr.dev/slog/sloggers/slogtest"
|
||||
"github.com/coder/coder/v2/agent/proto"
|
||||
"github.com/coder/coder/v2/testutil"
|
||||
@@ -214,58 +210,3 @@ func newFakeStatsDest() *fakeStatsDest {
|
||||
resps: make(chan *proto.UpdateStatsResponse),
|
||||
}
|
||||
}
|
||||
|
||||
func Test_logDebouncer(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var (
|
||||
buf bytes.Buffer
|
||||
logger = slog.Make(slogjson.Sink(&buf))
|
||||
ctx = context.Background()
|
||||
)
|
||||
|
||||
debouncer := &logDebouncer{
|
||||
logger: logger,
|
||||
messages: map[string]time.Time{},
|
||||
interval: time.Minute,
|
||||
}
|
||||
|
||||
fields := map[string]interface{}{
|
||||
"field_1": float64(1),
|
||||
"field_2": "2",
|
||||
}
|
||||
|
||||
debouncer.Error(ctx, "my message", "field_1", 1, "field_2", "2")
|
||||
debouncer.Warn(ctx, "another message", "field_1", 1, "field_2", "2")
|
||||
// Shouldn't log this.
|
||||
debouncer.Warn(ctx, "another message", "field_1", 1, "field_2", "2")
|
||||
|
||||
require.Len(t, debouncer.messages, 2)
|
||||
|
||||
type entry struct {
|
||||
Msg string `json:"msg"`
|
||||
Level string `json:"level"`
|
||||
Fields map[string]interface{} `json:"fields"`
|
||||
}
|
||||
|
||||
assertLog := func(msg string, level string, fields map[string]interface{}) {
|
||||
line, err := buf.ReadString('\n')
|
||||
require.NoError(t, err)
|
||||
|
||||
var e entry
|
||||
err = json.Unmarshal([]byte(line), &e)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, msg, e.Msg)
|
||||
require.Equal(t, level, e.Level)
|
||||
require.Equal(t, fields, e.Fields)
|
||||
}
|
||||
assertLog("my message", "ERROR", fields)
|
||||
assertLog("another message", "WARN", fields)
|
||||
|
||||
debouncer.messages["another message"] = time.Now().Add(-2 * time.Minute)
|
||||
debouncer.Warn(ctx, "another message", "field_1", 1, "field_2", "2")
|
||||
assertLog("another message", "WARN", fields)
|
||||
// Assert nothing else was written.
|
||||
_, err := buf.ReadString('\n')
|
||||
require.ErrorIs(t, err, io.EOF)
|
||||
}
|
||||
|
||||
+43
-22
@@ -18,8 +18,10 @@ import (
|
||||
"cloud.google.com/go/compute/metadata"
|
||||
"golang.org/x/xerrors"
|
||||
"gopkg.in/natefinch/lumberjack.v2"
|
||||
"tailscale.com/util/clientmetric"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/common/expfmt"
|
||||
|
||||
"cdr.dev/slog"
|
||||
"cdr.dev/slog/sloggers/sloghuman"
|
||||
@@ -29,12 +31,12 @@ import (
|
||||
"github.com/coder/coder/v2/agent/agentproc"
|
||||
"github.com/coder/coder/v2/agent/reaper"
|
||||
"github.com/coder/coder/v2/buildinfo"
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/coder/v2/codersdk/agentsdk"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
func (r *RootCmd) workspaceAgent() *serpent.Command {
|
||||
func (r *RootCmd) workspaceAgent() *clibase.Cmd {
|
||||
var (
|
||||
auth string
|
||||
logDir string
|
||||
@@ -49,12 +51,12 @@ func (r *RootCmd) workspaceAgent() *serpent.Command {
|
||||
slogJSONPath string
|
||||
slogStackdriverPath string
|
||||
)
|
||||
cmd := &serpent.Command{
|
||||
cmd := &clibase.Cmd{
|
||||
Use: "agent",
|
||||
Short: `Starts the Coder workspace agent.`,
|
||||
// This command isn't useful to manually execute.
|
||||
Hidden: true,
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
ctx, cancel := context.WithCancel(inv.Context())
|
||||
defer cancel()
|
||||
|
||||
@@ -283,9 +285,6 @@ func (r *RootCmd) workspaceAgent() *serpent.Command {
|
||||
if v, ok := os.LookupEnv(agent.EnvProcPrioMgmt); ok {
|
||||
environmentVariables[agent.EnvProcPrioMgmt] = v
|
||||
}
|
||||
if v, ok := os.LookupEnv(agent.EnvProcOOMScore); ok {
|
||||
environmentVariables[agent.EnvProcOOMScore] = v
|
||||
}
|
||||
|
||||
agnt := agent.New(agent.Options{
|
||||
Client: client,
|
||||
@@ -316,8 +315,7 @@ func (r *RootCmd) workspaceAgent() *serpent.Command {
|
||||
ModifiedProcesses: nil,
|
||||
})
|
||||
|
||||
promHandler := agent.PrometheusMetricsHandler(prometheusRegistry, logger)
|
||||
prometheusSrvClose := ServeHandler(ctx, logger, promHandler, prometheusAddress, "prometheus")
|
||||
prometheusSrvClose := ServeHandler(ctx, logger, prometheusMetricsHandler(prometheusRegistry, logger), prometheusAddress, "prometheus")
|
||||
defer prometheusSrvClose()
|
||||
|
||||
debugSrvClose := ServeHandler(ctx, logger, agnt.HTTPDebug(), debugAddress, "debug")
|
||||
@@ -328,33 +326,33 @@ func (r *RootCmd) workspaceAgent() *serpent.Command {
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Options = serpent.OptionSet{
|
||||
cmd.Options = clibase.OptionSet{
|
||||
{
|
||||
Flag: "auth",
|
||||
Default: "token",
|
||||
Description: "Specify the authentication type to use for the agent.",
|
||||
Env: "CODER_AGENT_AUTH",
|
||||
Value: serpent.StringOf(&auth),
|
||||
Value: clibase.StringOf(&auth),
|
||||
},
|
||||
{
|
||||
Flag: "log-dir",
|
||||
Default: os.TempDir(),
|
||||
Description: "Specify the location for the agent log files.",
|
||||
Env: "CODER_AGENT_LOG_DIR",
|
||||
Value: serpent.StringOf(&logDir),
|
||||
Value: clibase.StringOf(&logDir),
|
||||
},
|
||||
{
|
||||
Flag: "script-data-dir",
|
||||
Default: os.TempDir(),
|
||||
Description: "Specify the location for storing script data.",
|
||||
Env: "CODER_AGENT_SCRIPT_DATA_DIR",
|
||||
Value: serpent.StringOf(&scriptDataDir),
|
||||
Value: clibase.StringOf(&scriptDataDir),
|
||||
},
|
||||
{
|
||||
Flag: "pprof-address",
|
||||
Default: "127.0.0.1:6060",
|
||||
Env: "CODER_AGENT_PPROF_ADDRESS",
|
||||
Value: serpent.StringOf(&pprofAddress),
|
||||
Value: clibase.StringOf(&pprofAddress),
|
||||
Description: "The address to serve pprof.",
|
||||
},
|
||||
{
|
||||
@@ -362,7 +360,7 @@ func (r *RootCmd) workspaceAgent() *serpent.Command {
|
||||
|
||||
Env: "",
|
||||
Description: "Do not start a process reaper.",
|
||||
Value: serpent.BoolOf(&noReap),
|
||||
Value: clibase.BoolOf(&noReap),
|
||||
},
|
||||
{
|
||||
Flag: "ssh-max-timeout",
|
||||
@@ -370,27 +368,27 @@ func (r *RootCmd) workspaceAgent() *serpent.Command {
|
||||
Default: "72h",
|
||||
Env: "CODER_AGENT_SSH_MAX_TIMEOUT",
|
||||
Description: "Specify the max timeout for a SSH connection, it is advisable to set it to a minimum of 60s, but no more than 72h.",
|
||||
Value: serpent.DurationOf(&sshMaxTimeout),
|
||||
Value: clibase.DurationOf(&sshMaxTimeout),
|
||||
},
|
||||
{
|
||||
Flag: "tailnet-listen-port",
|
||||
Default: "0",
|
||||
Env: "CODER_AGENT_TAILNET_LISTEN_PORT",
|
||||
Description: "Specify a static port for Tailscale to use for listening.",
|
||||
Value: serpent.Int64Of(&tailnetListenPort),
|
||||
Value: clibase.Int64Of(&tailnetListenPort),
|
||||
},
|
||||
{
|
||||
Flag: "prometheus-address",
|
||||
Default: "127.0.0.1:2112",
|
||||
Env: "CODER_AGENT_PROMETHEUS_ADDRESS",
|
||||
Value: serpent.StringOf(&prometheusAddress),
|
||||
Value: clibase.StringOf(&prometheusAddress),
|
||||
Description: "The bind address to serve Prometheus metrics.",
|
||||
},
|
||||
{
|
||||
Flag: "debug-address",
|
||||
Default: "127.0.0.1:2113",
|
||||
Env: "CODER_AGENT_DEBUG_ADDRESS",
|
||||
Value: serpent.StringOf(&debugAddress),
|
||||
Value: clibase.StringOf(&debugAddress),
|
||||
Description: "The bind address to serve a debug HTTP server.",
|
||||
},
|
||||
{
|
||||
@@ -399,7 +397,7 @@ func (r *RootCmd) workspaceAgent() *serpent.Command {
|
||||
Flag: "log-human",
|
||||
Env: "CODER_AGENT_LOGGING_HUMAN",
|
||||
Default: "/dev/stderr",
|
||||
Value: serpent.StringOf(&slogHumanPath),
|
||||
Value: clibase.StringOf(&slogHumanPath),
|
||||
},
|
||||
{
|
||||
Name: "JSON Log Location",
|
||||
@@ -407,7 +405,7 @@ func (r *RootCmd) workspaceAgent() *serpent.Command {
|
||||
Flag: "log-json",
|
||||
Env: "CODER_AGENT_LOGGING_JSON",
|
||||
Default: "",
|
||||
Value: serpent.StringOf(&slogJSONPath),
|
||||
Value: clibase.StringOf(&slogJSONPath),
|
||||
},
|
||||
{
|
||||
Name: "Stackdriver Log Location",
|
||||
@@ -415,7 +413,7 @@ func (r *RootCmd) workspaceAgent() *serpent.Command {
|
||||
Flag: "log-stackdriver",
|
||||
Env: "CODER_AGENT_LOGGING_STACKDRIVER",
|
||||
Default: "",
|
||||
Value: serpent.StringOf(&slogStackdriverPath),
|
||||
Value: clibase.StringOf(&slogStackdriverPath),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -503,3 +501,26 @@ func urlPort(u string) (int, error) {
|
||||
}
|
||||
return -1, xerrors.Errorf("invalid port: %s", u)
|
||||
}
|
||||
|
||||
func prometheusMetricsHandler(prometheusRegistry *prometheus.Registry, logger slog.Logger) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
|
||||
// Based on: https://github.com/tailscale/tailscale/blob/280255acae604796a1113861f5a84e6fa2dc6121/ipn/localapi/localapi.go#L489
|
||||
clientmetric.WritePrometheusExpositionFormat(w)
|
||||
|
||||
metricFamilies, err := prometheusRegistry.Gather()
|
||||
if err != nil {
|
||||
logger.Error(context.Background(), "Prometheus handler can't gather metric families", slog.Error(err))
|
||||
return
|
||||
}
|
||||
|
||||
for _, metricFamily := range metricFamilies {
|
||||
_, err = expfmt.MetricFamilyToText(w, metricFamily)
|
||||
if err != nil {
|
||||
logger.Error(context.Background(), "expfmt.MetricFamilyToText failed", slog.Error(err))
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+3
-6
@@ -19,7 +19,6 @@ import (
|
||||
"github.com/coder/coder/v2/coderd/database"
|
||||
"github.com/coder/coder/v2/coderd/database/dbfake"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/coder/v2/codersdk/workspacesdk"
|
||||
"github.com/coder/coder/v2/provisionersdk/proto"
|
||||
"github.com/coder/coder/v2/testutil"
|
||||
)
|
||||
@@ -92,8 +91,7 @@ func TestWorkspaceAgent(t *testing.T) {
|
||||
if assert.NotEmpty(t, workspace.LatestBuild.Resources) && assert.NotEmpty(t, resources[0].Agents) {
|
||||
assert.NotEmpty(t, resources[0].Agents[0].Version)
|
||||
}
|
||||
dialer, err := workspacesdk.New(client).
|
||||
DialAgent(ctx, resources[0].Agents[0].ID, nil)
|
||||
dialer, err := client.DialWorkspaceAgent(ctx, resources[0].Agents[0].ID, nil)
|
||||
require.NoError(t, err)
|
||||
defer dialer.Close()
|
||||
require.True(t, dialer.AwaitReachable(ctx))
|
||||
@@ -132,8 +130,7 @@ func TestWorkspaceAgent(t *testing.T) {
|
||||
if assert.NotEmpty(t, resources) && assert.NotEmpty(t, resources[0].Agents) {
|
||||
assert.NotEmpty(t, resources[0].Agents[0].Version)
|
||||
}
|
||||
dialer, err := workspacesdk.New(client).
|
||||
DialAgent(ctx, resources[0].Agents[0].ID, nil)
|
||||
dialer, err := client.DialWorkspaceAgent(ctx, resources[0].Agents[0].ID, nil)
|
||||
require.NoError(t, err)
|
||||
defer dialer.Close()
|
||||
require.True(t, dialer.AwaitReachable(ctx))
|
||||
@@ -176,7 +173,7 @@ func TestWorkspaceAgent(t *testing.T) {
|
||||
if assert.NotEmpty(t, resources) && assert.NotEmpty(t, resources[0].Agents) {
|
||||
assert.NotEmpty(t, resources[0].Agents[0].Version)
|
||||
}
|
||||
dialer, err := workspacesdk.New(client).DialAgent(ctx, resources[0].Agents[0].ID, nil)
|
||||
dialer, err := client.DialWorkspaceAgent(ctx, resources[0].Agents[0].ID, nil)
|
||||
require.NoError(t, err)
|
||||
defer dialer.Close()
|
||||
require.True(t, dialer.AwaitReachable(ctx))
|
||||
|
||||
+6
-6
@@ -6,22 +6,22 @@ import (
|
||||
|
||||
"golang.org/x/xerrors"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/cli/cliui"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
func (r *RootCmd) autoupdate() *serpent.Command {
|
||||
func (r *RootCmd) autoupdate() *clibase.Cmd {
|
||||
client := new(codersdk.Client)
|
||||
cmd := &serpent.Command{
|
||||
cmd := &clibase.Cmd{
|
||||
Annotations: workspaceCommand,
|
||||
Use: "autoupdate <workspace> <always|never>",
|
||||
Short: "Toggle auto-update policy for a workspace",
|
||||
Middleware: serpent.Chain(
|
||||
serpent.RequireNArgs(2),
|
||||
Middleware: clibase.Chain(
|
||||
clibase.RequireNArgs(2),
|
||||
r.InitClient(client),
|
||||
),
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
policy := strings.ToLower(inv.Args[1])
|
||||
err := validateAutoUpdatePolicy(policy)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
// Package clibase offers an all-in-one solution for a highly configurable CLI
|
||||
// application. Within Coder, we use it for all of our subcommands, which
|
||||
// demands more functionality than cobra/viber offers.
|
||||
//
|
||||
// The Command interface is loosely based on the chi middleware pattern and
|
||||
// http.Handler/HandlerFunc.
|
||||
package clibase
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"golang.org/x/exp/maps"
|
||||
)
|
||||
|
||||
// Group describes a hierarchy of groups that an option or command belongs to.
|
||||
type Group struct {
|
||||
Parent *Group `json:"parent,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
YAML string `json:"yaml,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
}
|
||||
|
||||
// Ancestry returns the group and all of its parents, in order.
|
||||
func (g *Group) Ancestry() []Group {
|
||||
if g == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
groups := []Group{*g}
|
||||
for p := g.Parent; p != nil; p = p.Parent {
|
||||
// Prepend to the slice so that the order is correct.
|
||||
groups = append([]Group{*p}, groups...)
|
||||
}
|
||||
return groups
|
||||
}
|
||||
|
||||
func (g *Group) FullName() string {
|
||||
var names []string
|
||||
for _, g := range g.Ancestry() {
|
||||
names = append(names, g.Name)
|
||||
}
|
||||
return strings.Join(names, " / ")
|
||||
}
|
||||
|
||||
// Annotations is an arbitrary key-mapping used to extend the Option and Command types.
|
||||
// Its methods won't panic if the map is nil.
|
||||
type Annotations map[string]string
|
||||
|
||||
// Mark sets a value on the annotations map, creating one
|
||||
// if it doesn't exist. Mark does not mutate the original and
|
||||
// returns a copy. It is suitable for chaining.
|
||||
func (a Annotations) Mark(key string, value string) Annotations {
|
||||
var aa Annotations
|
||||
if a != nil {
|
||||
aa = maps.Clone(a)
|
||||
} else {
|
||||
aa = make(Annotations)
|
||||
}
|
||||
aa[key] = value
|
||||
return aa
|
||||
}
|
||||
|
||||
// IsSet returns true if the key is set in the annotations map.
|
||||
func (a Annotations) IsSet(key string) bool {
|
||||
if a == nil {
|
||||
return false
|
||||
}
|
||||
_, ok := a[key]
|
||||
return ok
|
||||
}
|
||||
|
||||
// Get retrieves a key from the map, returning false if the key is not found
|
||||
// or the map is nil.
|
||||
func (a Annotations) Get(key string) (string, bool) {
|
||||
if a == nil {
|
||||
return "", false
|
||||
}
|
||||
v, ok := a[key]
|
||||
return v, ok
|
||||
}
|
||||
@@ -0,0 +1,633 @@
|
||||
package clibase
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strings"
|
||||
"testing"
|
||||
"unicode"
|
||||
|
||||
"cdr.dev/slog"
|
||||
|
||||
"github.com/spf13/pflag"
|
||||
"golang.org/x/exp/slices"
|
||||
"golang.org/x/xerrors"
|
||||
"gopkg.in/yaml.v3"
|
||||
|
||||
"github.com/coder/coder/v2/coderd/util/slice"
|
||||
)
|
||||
|
||||
// Cmd describes an executable command.
|
||||
type Cmd struct {
|
||||
// Parent is the direct parent of the command.
|
||||
Parent *Cmd
|
||||
// Children is a list of direct descendants.
|
||||
Children []*Cmd
|
||||
// Use is provided in form "command [flags] [args...]".
|
||||
Use string
|
||||
|
||||
// Aliases is a list of alternative names for the command.
|
||||
Aliases []string
|
||||
|
||||
// Short is a one-line description of the command.
|
||||
Short string
|
||||
|
||||
// Hidden determines whether the command should be hidden from help.
|
||||
Hidden bool
|
||||
|
||||
// RawArgs determines whether the command should receive unparsed arguments.
|
||||
// No flags are parsed when set, and the command is responsible for parsing
|
||||
// its own flags.
|
||||
RawArgs bool
|
||||
|
||||
// Long is a detailed description of the command,
|
||||
// presented on its help page. It may contain examples.
|
||||
Long string
|
||||
Options OptionSet
|
||||
Annotations Annotations
|
||||
|
||||
// Middleware is called before the Handler.
|
||||
// Use Chain() to combine multiple middlewares.
|
||||
Middleware MiddlewareFunc
|
||||
Handler HandlerFunc
|
||||
HelpHandler HandlerFunc
|
||||
}
|
||||
|
||||
// AddSubcommands adds the given subcommands, setting their
|
||||
// Parent field automatically.
|
||||
func (c *Cmd) AddSubcommands(cmds ...*Cmd) {
|
||||
for _, cmd := range cmds {
|
||||
cmd.Parent = c
|
||||
c.Children = append(c.Children, cmd)
|
||||
}
|
||||
}
|
||||
|
||||
// Walk calls fn for the command and all its children.
|
||||
func (c *Cmd) Walk(fn func(*Cmd)) {
|
||||
fn(c)
|
||||
for _, child := range c.Children {
|
||||
child.Parent = c
|
||||
child.Walk(fn)
|
||||
}
|
||||
}
|
||||
|
||||
// PrepareAll performs initialization and linting on the command and all its children.
|
||||
func (c *Cmd) PrepareAll() error {
|
||||
if c.Use == "" {
|
||||
return xerrors.New("command must have a Use field so that it has a name")
|
||||
}
|
||||
var merr error
|
||||
|
||||
for i := range c.Options {
|
||||
opt := &c.Options[i]
|
||||
if opt.Name == "" {
|
||||
switch {
|
||||
case opt.Flag != "":
|
||||
opt.Name = opt.Flag
|
||||
case opt.Env != "":
|
||||
opt.Name = opt.Env
|
||||
case opt.YAML != "":
|
||||
opt.Name = opt.YAML
|
||||
default:
|
||||
merr = errors.Join(merr, xerrors.Errorf("option must have a Name, Flag, Env or YAML field"))
|
||||
}
|
||||
}
|
||||
if opt.Description != "" {
|
||||
// Enforce that description uses sentence form.
|
||||
if unicode.IsLower(rune(opt.Description[0])) {
|
||||
merr = errors.Join(merr, xerrors.Errorf("option %q description should start with a capital letter", opt.Name))
|
||||
}
|
||||
if !strings.HasSuffix(opt.Description, ".") {
|
||||
merr = errors.Join(merr, xerrors.Errorf("option %q description should end with a period", opt.Name))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
slices.SortFunc(c.Options, func(a, b Option) int {
|
||||
return slice.Ascending(a.Name, b.Name)
|
||||
})
|
||||
slices.SortFunc(c.Children, func(a, b *Cmd) int {
|
||||
return slice.Ascending(a.Name(), b.Name())
|
||||
})
|
||||
for _, child := range c.Children {
|
||||
child.Parent = c
|
||||
err := child.PrepareAll()
|
||||
if err != nil {
|
||||
merr = errors.Join(merr, xerrors.Errorf("command %v: %w", child.Name(), err))
|
||||
}
|
||||
}
|
||||
return merr
|
||||
}
|
||||
|
||||
// Name returns the first word in the Use string.
|
||||
func (c *Cmd) Name() string {
|
||||
return strings.Split(c.Use, " ")[0]
|
||||
}
|
||||
|
||||
// FullName returns the full invocation name of the command,
|
||||
// as seen on the command line.
|
||||
func (c *Cmd) FullName() string {
|
||||
var names []string
|
||||
if c.Parent != nil {
|
||||
names = append(names, c.Parent.FullName())
|
||||
}
|
||||
names = append(names, c.Name())
|
||||
return strings.Join(names, " ")
|
||||
}
|
||||
|
||||
// FullName returns usage of the command, preceded
|
||||
// by the usage of its parents.
|
||||
func (c *Cmd) FullUsage() string {
|
||||
var uses []string
|
||||
if c.Parent != nil {
|
||||
uses = append(uses, c.Parent.FullName())
|
||||
}
|
||||
uses = append(uses, c.Use)
|
||||
return strings.Join(uses, " ")
|
||||
}
|
||||
|
||||
// FullOptions returns the options of the command and its parents.
|
||||
func (c *Cmd) FullOptions() OptionSet {
|
||||
var opts OptionSet
|
||||
if c.Parent != nil {
|
||||
opts = append(opts, c.Parent.FullOptions()...)
|
||||
}
|
||||
opts = append(opts, c.Options...)
|
||||
return opts
|
||||
}
|
||||
|
||||
// Invoke creates a new invocation of the command, with
|
||||
// stdio discarded.
|
||||
//
|
||||
// The returned invocation is not live until Run() is called.
|
||||
func (c *Cmd) Invoke(args ...string) *Invocation {
|
||||
return &Invocation{
|
||||
Command: c,
|
||||
Args: args,
|
||||
Stdout: io.Discard,
|
||||
Stderr: io.Discard,
|
||||
Stdin: strings.NewReader(""),
|
||||
Logger: slog.Make(),
|
||||
}
|
||||
}
|
||||
|
||||
// Invocation represents an instance of a command being executed.
|
||||
type Invocation struct {
|
||||
ctx context.Context
|
||||
Command *Cmd
|
||||
parsedFlags *pflag.FlagSet
|
||||
Args []string
|
||||
// Environ is a list of environment variables. Use EnvsWithPrefix to parse
|
||||
// os.Environ.
|
||||
Environ Environ
|
||||
Stdout io.Writer
|
||||
Stderr io.Writer
|
||||
Stdin io.Reader
|
||||
Logger slog.Logger
|
||||
Net Net
|
||||
|
||||
// testing
|
||||
signalNotifyContext func(parent context.Context, signals ...os.Signal) (ctx context.Context, stop context.CancelFunc)
|
||||
}
|
||||
|
||||
// WithOS returns the invocation as a main package, filling in the invocation's unset
|
||||
// fields with OS defaults.
|
||||
func (inv *Invocation) WithOS() *Invocation {
|
||||
return inv.with(func(i *Invocation) {
|
||||
i.Stdout = os.Stdout
|
||||
i.Stderr = os.Stderr
|
||||
i.Stdin = os.Stdin
|
||||
i.Args = os.Args[1:]
|
||||
i.Environ = ParseEnviron(os.Environ(), "")
|
||||
i.Net = osNet{}
|
||||
})
|
||||
}
|
||||
|
||||
// WithTestSignalNotifyContext allows overriding the default implementation of SignalNotifyContext.
|
||||
// This should only be used in testing.
|
||||
func (inv *Invocation) WithTestSignalNotifyContext(
|
||||
_ testing.TB, // ensure we only call this from tests
|
||||
f func(parent context.Context, signals ...os.Signal) (ctx context.Context, stop context.CancelFunc),
|
||||
) *Invocation {
|
||||
return inv.with(func(i *Invocation) {
|
||||
i.signalNotifyContext = f
|
||||
})
|
||||
}
|
||||
|
||||
// SignalNotifyContext is equivalent to signal.NotifyContext, but supports being overridden in
|
||||
// tests.
|
||||
func (inv *Invocation) SignalNotifyContext(parent context.Context, signals ...os.Signal) (ctx context.Context, stop context.CancelFunc) {
|
||||
if inv.signalNotifyContext == nil {
|
||||
return signal.NotifyContext(parent, signals...)
|
||||
}
|
||||
return inv.signalNotifyContext(parent, signals...)
|
||||
}
|
||||
|
||||
func (inv *Invocation) WithTestParsedFlags(
|
||||
_ testing.TB, // ensure we only call this from tests
|
||||
parsedFlags *pflag.FlagSet,
|
||||
) *Invocation {
|
||||
return inv.with(func(i *Invocation) {
|
||||
i.parsedFlags = parsedFlags
|
||||
})
|
||||
}
|
||||
|
||||
func (inv *Invocation) Context() context.Context {
|
||||
if inv.ctx == nil {
|
||||
return context.Background()
|
||||
}
|
||||
return inv.ctx
|
||||
}
|
||||
|
||||
func (inv *Invocation) ParsedFlags() *pflag.FlagSet {
|
||||
if inv.parsedFlags == nil {
|
||||
panic("flags not parsed, has Run() been called?")
|
||||
}
|
||||
return inv.parsedFlags
|
||||
}
|
||||
|
||||
type runState struct {
|
||||
allArgs []string
|
||||
commandDepth int
|
||||
|
||||
flagParseErr error
|
||||
}
|
||||
|
||||
func copyFlagSetWithout(fs *pflag.FlagSet, without string) *pflag.FlagSet {
|
||||
fs2 := pflag.NewFlagSet("", pflag.ContinueOnError)
|
||||
fs2.Usage = func() {}
|
||||
fs.VisitAll(func(f *pflag.Flag) {
|
||||
if f.Name == without {
|
||||
return
|
||||
}
|
||||
fs2.AddFlag(f)
|
||||
})
|
||||
return fs2
|
||||
}
|
||||
|
||||
// run recursively executes the command and its children.
|
||||
// allArgs is wired through the stack so that global flags can be accepted
|
||||
// anywhere in the command invocation.
|
||||
func (inv *Invocation) run(state *runState) error {
|
||||
err := inv.Command.Options.ParseEnv(inv.Environ)
|
||||
if err != nil {
|
||||
return xerrors.Errorf("parsing env: %w", err)
|
||||
}
|
||||
|
||||
// Now the fun part, argument parsing!
|
||||
|
||||
children := make(map[string]*Cmd)
|
||||
for _, child := range inv.Command.Children {
|
||||
child.Parent = inv.Command
|
||||
for _, name := range append(child.Aliases, child.Name()) {
|
||||
if _, ok := children[name]; ok {
|
||||
return xerrors.Errorf("duplicate command name: %s", name)
|
||||
}
|
||||
children[name] = child
|
||||
}
|
||||
}
|
||||
|
||||
if inv.parsedFlags == nil {
|
||||
inv.parsedFlags = pflag.NewFlagSet(inv.Command.Name(), pflag.ContinueOnError)
|
||||
// We handle Usage ourselves.
|
||||
inv.parsedFlags.Usage = func() {}
|
||||
}
|
||||
|
||||
// If we find a duplicate flag, we want the deeper command's flag to override
|
||||
// the shallow one. Unfortunately, pflag has no way to remove a flag, so we
|
||||
// have to create a copy of the flagset without a value.
|
||||
inv.Command.Options.FlagSet().VisitAll(func(f *pflag.Flag) {
|
||||
if inv.parsedFlags.Lookup(f.Name) != nil {
|
||||
inv.parsedFlags = copyFlagSetWithout(inv.parsedFlags, f.Name)
|
||||
}
|
||||
inv.parsedFlags.AddFlag(f)
|
||||
})
|
||||
|
||||
var parsedArgs []string
|
||||
|
||||
if !inv.Command.RawArgs {
|
||||
// Flag parsing will fail on intermediate commands in the command tree,
|
||||
// so we check the error after looking for a child command.
|
||||
state.flagParseErr = inv.parsedFlags.Parse(state.allArgs)
|
||||
parsedArgs = inv.parsedFlags.Args()
|
||||
}
|
||||
|
||||
// Set value sources for flags.
|
||||
for i, opt := range inv.Command.Options {
|
||||
if fl := inv.parsedFlags.Lookup(opt.Flag); fl != nil && fl.Changed {
|
||||
inv.Command.Options[i].ValueSource = ValueSourceFlag
|
||||
}
|
||||
}
|
||||
|
||||
// Read YAML configs, if any.
|
||||
for _, opt := range inv.Command.Options {
|
||||
path, ok := opt.Value.(*YAMLConfigPath)
|
||||
if !ok || path.String() == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
byt, err := os.ReadFile(path.String())
|
||||
if err != nil {
|
||||
return xerrors.Errorf("reading yaml: %w", err)
|
||||
}
|
||||
|
||||
var n yaml.Node
|
||||
err = yaml.Unmarshal(byt, &n)
|
||||
if err != nil {
|
||||
return xerrors.Errorf("decoding yaml: %w", err)
|
||||
}
|
||||
|
||||
err = inv.Command.Options.UnmarshalYAML(&n)
|
||||
if err != nil {
|
||||
return xerrors.Errorf("applying yaml: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
err = inv.Command.Options.SetDefaults()
|
||||
if err != nil {
|
||||
return xerrors.Errorf("setting defaults: %w", err)
|
||||
}
|
||||
|
||||
// Run child command if found (next child only)
|
||||
// We must do subcommand detection after flag parsing so we don't mistake flag
|
||||
// values for subcommand names.
|
||||
if len(parsedArgs) > state.commandDepth {
|
||||
nextArg := parsedArgs[state.commandDepth]
|
||||
if child, ok := children[nextArg]; ok {
|
||||
child.Parent = inv.Command
|
||||
inv.Command = child
|
||||
state.commandDepth++
|
||||
return inv.run(state)
|
||||
}
|
||||
}
|
||||
|
||||
// Flag parse errors are irrelevant for raw args commands.
|
||||
if !inv.Command.RawArgs && state.flagParseErr != nil && !errors.Is(state.flagParseErr, pflag.ErrHelp) {
|
||||
return xerrors.Errorf(
|
||||
"parsing flags (%v) for %q: %w",
|
||||
state.allArgs,
|
||||
inv.Command.FullName(), state.flagParseErr,
|
||||
)
|
||||
}
|
||||
|
||||
// All options should be set. Check all required options have sources,
|
||||
// meaning they were set by the user in some way (env, flag, etc).
|
||||
var missing []string
|
||||
for _, opt := range inv.Command.Options {
|
||||
if opt.Required && opt.ValueSource == ValueSourceNone {
|
||||
missing = append(missing, opt.Flag)
|
||||
}
|
||||
}
|
||||
// Don't error for missing flags if `--help` was supplied.
|
||||
if len(missing) > 0 && !errors.Is(state.flagParseErr, pflag.ErrHelp) {
|
||||
return xerrors.Errorf("Missing values for the required flags: %s", strings.Join(missing, ", "))
|
||||
}
|
||||
|
||||
if inv.Command.RawArgs {
|
||||
// If we're at the root command, then the name is omitted
|
||||
// from the arguments, so we can just use the entire slice.
|
||||
if state.commandDepth == 0 {
|
||||
inv.Args = state.allArgs
|
||||
} else {
|
||||
argPos, err := findArg(inv.Command.Name(), state.allArgs, inv.parsedFlags)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
inv.Args = state.allArgs[argPos+1:]
|
||||
}
|
||||
} else {
|
||||
// In non-raw-arg mode, we want to skip over flags.
|
||||
inv.Args = parsedArgs[state.commandDepth:]
|
||||
}
|
||||
|
||||
mw := inv.Command.Middleware
|
||||
if mw == nil {
|
||||
mw = Chain()
|
||||
}
|
||||
|
||||
ctx := inv.ctx
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
inv = inv.WithContext(ctx)
|
||||
|
||||
if inv.Command.Handler == nil || errors.Is(state.flagParseErr, pflag.ErrHelp) {
|
||||
if inv.Command.HelpHandler == nil {
|
||||
return xerrors.Errorf("no handler or help for command %s", inv.Command.FullName())
|
||||
}
|
||||
return inv.Command.HelpHandler(inv)
|
||||
}
|
||||
|
||||
err = mw(inv.Command.Handler)(inv)
|
||||
if err != nil {
|
||||
return &RunCommandError{
|
||||
Cmd: inv.Command,
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type RunCommandError struct {
|
||||
Cmd *Cmd
|
||||
Err error
|
||||
}
|
||||
|
||||
func (e *RunCommandError) Unwrap() error {
|
||||
return e.Err
|
||||
}
|
||||
|
||||
func (e *RunCommandError) Error() string {
|
||||
return fmt.Sprintf("running command %q: %+v", e.Cmd.FullName(), e.Err)
|
||||
}
|
||||
|
||||
// findArg returns the index of the first occurrence of arg in args, skipping
|
||||
// over all flags.
|
||||
func findArg(want string, args []string, fs *pflag.FlagSet) (int, error) {
|
||||
for i := 0; i < len(args); i++ {
|
||||
arg := args[i]
|
||||
if !strings.HasPrefix(arg, "-") {
|
||||
if arg == want {
|
||||
return i, nil
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// This is a flag!
|
||||
if strings.Contains(arg, "=") {
|
||||
// The flag contains the value in the same arg, just skip.
|
||||
continue
|
||||
}
|
||||
|
||||
// We need to check if NoOptValue is set, then we should not wait
|
||||
// for the next arg to be the value.
|
||||
f := fs.Lookup(strings.TrimLeft(arg, "-"))
|
||||
if f == nil {
|
||||
return -1, xerrors.Errorf("unknown flag: %s", arg)
|
||||
}
|
||||
if f.NoOptDefVal != "" {
|
||||
continue
|
||||
}
|
||||
|
||||
if i == len(args)-1 {
|
||||
return -1, xerrors.Errorf("flag %s requires a value", arg)
|
||||
}
|
||||
|
||||
// Skip the value.
|
||||
i++
|
||||
}
|
||||
|
||||
return -1, xerrors.Errorf("arg %s not found", want)
|
||||
}
|
||||
|
||||
// Run executes the command.
|
||||
// If two command share a flag name, the first command wins.
|
||||
//
|
||||
//nolint:revive
|
||||
func (inv *Invocation) Run() (err error) {
|
||||
defer func() {
|
||||
// Pflag is panicky, so additional context is helpful in tests.
|
||||
if flag.Lookup("test.v") == nil {
|
||||
return
|
||||
}
|
||||
if r := recover(); r != nil {
|
||||
err = xerrors.Errorf("panic recovered for %s: %v", inv.Command.FullName(), r)
|
||||
panic(err)
|
||||
}
|
||||
}()
|
||||
// We close Stdin to prevent deadlocks, e.g. when the command
|
||||
// has ended but an io.Copy is still reading from Stdin.
|
||||
defer func() {
|
||||
if inv.Stdin == nil {
|
||||
return
|
||||
}
|
||||
rc, ok := inv.Stdin.(io.ReadCloser)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
e := rc.Close()
|
||||
err = errors.Join(err, e)
|
||||
}()
|
||||
err = inv.run(&runState{
|
||||
allArgs: inv.Args,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
// WithContext returns a copy of the Invocation with the given context.
|
||||
func (inv *Invocation) WithContext(ctx context.Context) *Invocation {
|
||||
return inv.with(func(i *Invocation) {
|
||||
i.ctx = ctx
|
||||
})
|
||||
}
|
||||
|
||||
// with returns a copy of the Invocation with the given function applied.
|
||||
func (inv *Invocation) with(fn func(*Invocation)) *Invocation {
|
||||
i2 := *inv
|
||||
fn(&i2)
|
||||
return &i2
|
||||
}
|
||||
|
||||
// MiddlewareFunc returns the next handler in the chain,
|
||||
// or nil if there are no more.
|
||||
type MiddlewareFunc func(next HandlerFunc) HandlerFunc
|
||||
|
||||
func chain(ms ...MiddlewareFunc) MiddlewareFunc {
|
||||
return MiddlewareFunc(func(next HandlerFunc) HandlerFunc {
|
||||
if len(ms) > 0 {
|
||||
return chain(ms[1:]...)(ms[0](next))
|
||||
}
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
// Chain returns a Handler that first calls middleware in order.
|
||||
//
|
||||
//nolint:revive
|
||||
func Chain(ms ...MiddlewareFunc) MiddlewareFunc {
|
||||
// We need to reverse the array to provide top-to-bottom execution
|
||||
// order when defining a command.
|
||||
reversed := make([]MiddlewareFunc, len(ms))
|
||||
for i := range ms {
|
||||
reversed[len(ms)-1-i] = ms[i]
|
||||
}
|
||||
return chain(reversed...)
|
||||
}
|
||||
|
||||
func ShowUsageOnError(next HandlerFunc) HandlerFunc {
|
||||
return func(i *Invocation) error {
|
||||
err := next(i)
|
||||
if err != nil {
|
||||
return xerrors.Errorf("Usage: %s\nError: %w", i.Command.FullUsage(), err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func RequireNArgs(want int) MiddlewareFunc {
|
||||
return RequireRangeArgs(want, want)
|
||||
}
|
||||
|
||||
// RequireRangeArgs returns a Middleware that requires the number of arguments
|
||||
// to be between start and end (inclusive). If end is -1, then the number of
|
||||
// arguments must be at least start.
|
||||
func RequireRangeArgs(start, end int) MiddlewareFunc {
|
||||
if start < 0 {
|
||||
panic("start must be >= 0")
|
||||
}
|
||||
return func(next HandlerFunc) HandlerFunc {
|
||||
// ShowUsageOnError will add the command usage before the error message.
|
||||
return ShowUsageOnError(func(i *Invocation) error {
|
||||
got := len(i.Args)
|
||||
switch {
|
||||
case start == end && got != start:
|
||||
switch start {
|
||||
case 0:
|
||||
if len(i.Command.Children) > 0 {
|
||||
return xerrors.Errorf("unrecognized subcommand %q", i.Args[0])
|
||||
}
|
||||
return xerrors.Errorf("wanted no args but got %v %v", got, i.Args)
|
||||
default:
|
||||
return xerrors.Errorf(
|
||||
"wanted %v args but got %v %v",
|
||||
start,
|
||||
got,
|
||||
i.Args,
|
||||
)
|
||||
}
|
||||
case start > 0 && end == -1:
|
||||
switch {
|
||||
case got < start:
|
||||
return xerrors.Errorf(
|
||||
"wanted at least %v args but got %v",
|
||||
start,
|
||||
got,
|
||||
)
|
||||
default:
|
||||
return next(i)
|
||||
}
|
||||
case start > end:
|
||||
panic("start must be <= end")
|
||||
case got < start || got > end:
|
||||
return xerrors.Errorf(
|
||||
"wanted between %v and %v args but got %v",
|
||||
start, end,
|
||||
got,
|
||||
)
|
||||
default:
|
||||
return next(i)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// HandlerFunc handles an Invocation of a command.
|
||||
type HandlerFunc func(i *Invocation) error
|
||||
@@ -0,0 +1,735 @@
|
||||
package clibase_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/xerrors"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
)
|
||||
|
||||
// ioBufs is the standard input, output, and error for a command.
|
||||
type ioBufs struct {
|
||||
Stdin bytes.Buffer
|
||||
Stdout bytes.Buffer
|
||||
Stderr bytes.Buffer
|
||||
}
|
||||
|
||||
// fakeIO sets Stdin, Stdout, and Stderr to buffers.
|
||||
func fakeIO(i *clibase.Invocation) *ioBufs {
|
||||
var b ioBufs
|
||||
i.Stdout = &b.Stdout
|
||||
i.Stderr = &b.Stderr
|
||||
i.Stdin = &b.Stdin
|
||||
return &b
|
||||
}
|
||||
|
||||
func TestCommand(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cmd := func() *clibase.Cmd {
|
||||
var (
|
||||
verbose bool
|
||||
lower bool
|
||||
prefix string
|
||||
reqBool bool
|
||||
reqStr string
|
||||
)
|
||||
return &clibase.Cmd{
|
||||
Use: "root [subcommand]",
|
||||
Options: clibase.OptionSet{
|
||||
clibase.Option{
|
||||
Name: "verbose",
|
||||
Flag: "verbose",
|
||||
Value: clibase.BoolOf(&verbose),
|
||||
},
|
||||
clibase.Option{
|
||||
Name: "prefix",
|
||||
Flag: "prefix",
|
||||
Value: clibase.StringOf(&prefix),
|
||||
},
|
||||
},
|
||||
Children: []*clibase.Cmd{
|
||||
{
|
||||
Use: "required-flag --req-bool=true --req-string=foo",
|
||||
Short: "Example with required flags",
|
||||
Options: clibase.OptionSet{
|
||||
clibase.Option{
|
||||
Name: "req-bool",
|
||||
Flag: "req-bool",
|
||||
Value: clibase.BoolOf(&reqBool),
|
||||
Required: true,
|
||||
},
|
||||
clibase.Option{
|
||||
Name: "req-string",
|
||||
Flag: "req-string",
|
||||
Value: clibase.Validate(clibase.StringOf(&reqStr), func(value *clibase.String) error {
|
||||
ok := strings.Contains(value.String(), " ")
|
||||
if !ok {
|
||||
return xerrors.Errorf("string must contain a space")
|
||||
}
|
||||
return nil
|
||||
}),
|
||||
Required: true,
|
||||
},
|
||||
},
|
||||
HelpHandler: func(i *clibase.Invocation) error {
|
||||
_, _ = i.Stdout.Write([]byte("help text.png"))
|
||||
return nil
|
||||
},
|
||||
Handler: func(i *clibase.Invocation) error {
|
||||
_, _ = i.Stdout.Write([]byte(fmt.Sprintf("%s-%t", reqStr, reqBool)))
|
||||
return nil
|
||||
},
|
||||
},
|
||||
{
|
||||
Use: "toupper [word]",
|
||||
Short: "Converts a word to upper case",
|
||||
Middleware: clibase.Chain(
|
||||
clibase.RequireNArgs(1),
|
||||
),
|
||||
Aliases: []string{"up"},
|
||||
Options: clibase.OptionSet{
|
||||
clibase.Option{
|
||||
Name: "lower",
|
||||
Flag: "lower",
|
||||
Value: clibase.BoolOf(&lower),
|
||||
},
|
||||
},
|
||||
Handler: func(i *clibase.Invocation) error {
|
||||
_, _ = i.Stdout.Write([]byte(prefix))
|
||||
w := i.Args[0]
|
||||
if lower {
|
||||
w = strings.ToLower(w)
|
||||
} else {
|
||||
w = strings.ToUpper(w)
|
||||
}
|
||||
_, _ = i.Stdout.Write(
|
||||
[]byte(
|
||||
w,
|
||||
),
|
||||
)
|
||||
if verbose {
|
||||
i.Stdout.Write([]byte("!!!"))
|
||||
}
|
||||
return nil
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("SimpleOK", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
i := cmd().Invoke("toupper", "hello")
|
||||
io := fakeIO(i)
|
||||
i.Run()
|
||||
require.Equal(t, "HELLO", io.Stdout.String())
|
||||
})
|
||||
|
||||
t.Run("Alias", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
i := cmd().Invoke(
|
||||
"up", "hello",
|
||||
)
|
||||
io := fakeIO(i)
|
||||
i.Run()
|
||||
require.Equal(t, "HELLO", io.Stdout.String())
|
||||
})
|
||||
|
||||
t.Run("NoSubcommand", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
i := cmd().Invoke(
|
||||
"na",
|
||||
)
|
||||
io := fakeIO(i)
|
||||
err := i.Run()
|
||||
require.Empty(t, io.Stdout.String())
|
||||
require.Error(t, err)
|
||||
})
|
||||
|
||||
t.Run("BadArgs", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
i := cmd().Invoke(
|
||||
"toupper",
|
||||
)
|
||||
io := fakeIO(i)
|
||||
err := i.Run()
|
||||
require.Empty(t, io.Stdout.String())
|
||||
require.Error(t, err)
|
||||
})
|
||||
|
||||
t.Run("UnknownFlags", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
i := cmd().Invoke(
|
||||
"toupper", "--unknown",
|
||||
)
|
||||
io := fakeIO(i)
|
||||
err := i.Run()
|
||||
require.Empty(t, io.Stdout.String())
|
||||
require.Error(t, err)
|
||||
})
|
||||
|
||||
t.Run("Verbose", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
i := cmd().Invoke(
|
||||
"--verbose", "toupper", "hello",
|
||||
)
|
||||
io := fakeIO(i)
|
||||
require.NoError(t, i.Run())
|
||||
require.Equal(t, "HELLO!!!", io.Stdout.String())
|
||||
})
|
||||
|
||||
t.Run("Verbose=", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
i := cmd().Invoke(
|
||||
"--verbose=true", "toupper", "hello",
|
||||
)
|
||||
io := fakeIO(i)
|
||||
require.NoError(t, i.Run())
|
||||
require.Equal(t, "HELLO!!!", io.Stdout.String())
|
||||
})
|
||||
|
||||
t.Run("PrefixSpace", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
i := cmd().Invoke(
|
||||
"--prefix", "conv: ", "toupper", "hello",
|
||||
)
|
||||
io := fakeIO(i)
|
||||
require.NoError(t, i.Run())
|
||||
require.Equal(t, "conv: HELLO", io.Stdout.String())
|
||||
})
|
||||
|
||||
t.Run("GlobalFlagsAnywhere", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
i := cmd().Invoke(
|
||||
"toupper", "--prefix", "conv: ", "hello", "--verbose",
|
||||
)
|
||||
io := fakeIO(i)
|
||||
require.NoError(t, i.Run())
|
||||
require.Equal(t, "conv: HELLO!!!", io.Stdout.String())
|
||||
})
|
||||
|
||||
t.Run("LowerVerbose", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
i := cmd().Invoke(
|
||||
"toupper", "--verbose", "hello", "--lower",
|
||||
)
|
||||
io := fakeIO(i)
|
||||
require.NoError(t, i.Run())
|
||||
require.Equal(t, "hello!!!", io.Stdout.String())
|
||||
})
|
||||
|
||||
t.Run("ParsedFlags", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
i := cmd().Invoke(
|
||||
"toupper", "--verbose", "hello", "--lower",
|
||||
)
|
||||
_ = fakeIO(i)
|
||||
require.NoError(t, i.Run())
|
||||
require.Equal(t,
|
||||
"true",
|
||||
i.ParsedFlags().Lookup("verbose").Value.String(),
|
||||
)
|
||||
})
|
||||
|
||||
t.Run("NoDeepChild", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
i := cmd().Invoke(
|
||||
"root", "level", "level", "toupper", "--verbose", "hello", "--lower",
|
||||
)
|
||||
fio := fakeIO(i)
|
||||
require.Error(t, i.Run(), fio.Stdout.String())
|
||||
})
|
||||
|
||||
t.Run("RequiredFlagsMissing", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
i := cmd().Invoke(
|
||||
"required-flag",
|
||||
)
|
||||
fio := fakeIO(i)
|
||||
err := i.Run()
|
||||
require.Error(t, err, fio.Stdout.String())
|
||||
require.ErrorContains(t, err, "Missing values")
|
||||
})
|
||||
|
||||
t.Run("RequiredFlagsMissingWithHelp", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
i := cmd().Invoke(
|
||||
"required-flag",
|
||||
"--help",
|
||||
)
|
||||
fio := fakeIO(i)
|
||||
err := i.Run()
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, fio.Stdout.String(), "help text.png")
|
||||
})
|
||||
|
||||
t.Run("RequiredFlagsMissingBool", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
i := cmd().Invoke(
|
||||
"required-flag", "--req-string", "foo bar",
|
||||
)
|
||||
fio := fakeIO(i)
|
||||
err := i.Run()
|
||||
require.Error(t, err, fio.Stdout.String())
|
||||
require.ErrorContains(t, err, "Missing values for the required flags: req-bool")
|
||||
})
|
||||
|
||||
t.Run("RequiredFlagsMissingString", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
i := cmd().Invoke(
|
||||
"required-flag", "--req-bool", "true",
|
||||
)
|
||||
fio := fakeIO(i)
|
||||
err := i.Run()
|
||||
require.Error(t, err, fio.Stdout.String())
|
||||
require.ErrorContains(t, err, "Missing values for the required flags: req-string")
|
||||
})
|
||||
|
||||
t.Run("RequiredFlagsInvalid", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
i := cmd().Invoke(
|
||||
"required-flag", "--req-string", "nospace",
|
||||
)
|
||||
fio := fakeIO(i)
|
||||
err := i.Run()
|
||||
require.Error(t, err, fio.Stdout.String())
|
||||
require.ErrorContains(t, err, "string must contain a space")
|
||||
})
|
||||
|
||||
t.Run("RequiredFlagsOK", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
i := cmd().Invoke(
|
||||
"required-flag", "--req-bool", "true", "--req-string", "foo bar",
|
||||
)
|
||||
fio := fakeIO(i)
|
||||
err := i.Run()
|
||||
require.NoError(t, err, fio.Stdout.String())
|
||||
})
|
||||
}
|
||||
|
||||
func TestCommand_DeepNest(t *testing.T) {
|
||||
t.Parallel()
|
||||
cmd := &clibase.Cmd{
|
||||
Use: "1",
|
||||
Children: []*clibase.Cmd{
|
||||
{
|
||||
Use: "2",
|
||||
Children: []*clibase.Cmd{
|
||||
{
|
||||
Use: "3",
|
||||
Handler: func(i *clibase.Invocation) error {
|
||||
i.Stdout.Write([]byte("3"))
|
||||
return nil
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
inv := cmd.Invoke("2", "3")
|
||||
stdio := fakeIO(inv)
|
||||
err := inv.Run()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "3", stdio.Stdout.String())
|
||||
}
|
||||
|
||||
func TestCommand_FlagOverride(t *testing.T) {
|
||||
t.Parallel()
|
||||
var flag string
|
||||
|
||||
cmd := &clibase.Cmd{
|
||||
Use: "1",
|
||||
Options: clibase.OptionSet{
|
||||
{
|
||||
Name: "flag",
|
||||
Flag: "f",
|
||||
Value: clibase.DiscardValue,
|
||||
},
|
||||
},
|
||||
Children: []*clibase.Cmd{
|
||||
{
|
||||
Use: "2",
|
||||
Options: clibase.OptionSet{
|
||||
{
|
||||
Name: "flag",
|
||||
Flag: "f",
|
||||
Value: clibase.StringOf(&flag),
|
||||
},
|
||||
},
|
||||
Handler: func(i *clibase.Invocation) error {
|
||||
return nil
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
err := cmd.Invoke("2", "--f", "mhmm").Run()
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Equal(t, "mhmm", flag)
|
||||
}
|
||||
|
||||
func TestCommand_MiddlewareOrder(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
mw := func(letter string) clibase.MiddlewareFunc {
|
||||
return func(next clibase.HandlerFunc) clibase.HandlerFunc {
|
||||
return (func(i *clibase.Invocation) error {
|
||||
_, _ = i.Stdout.Write([]byte(letter))
|
||||
return next(i)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
cmd := &clibase.Cmd{
|
||||
Use: "toupper [word]",
|
||||
Short: "Converts a word to upper case",
|
||||
Middleware: clibase.Chain(
|
||||
mw("A"),
|
||||
mw("B"),
|
||||
mw("C"),
|
||||
),
|
||||
Handler: (func(i *clibase.Invocation) error {
|
||||
return nil
|
||||
}),
|
||||
}
|
||||
|
||||
i := cmd.Invoke(
|
||||
"hello", "world",
|
||||
)
|
||||
io := fakeIO(i)
|
||||
require.NoError(t, i.Run())
|
||||
require.Equal(t, "ABC", io.Stdout.String())
|
||||
}
|
||||
|
||||
func TestCommand_RawArgs(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cmd := func() *clibase.Cmd {
|
||||
return &clibase.Cmd{
|
||||
Use: "root",
|
||||
Options: clibase.OptionSet{
|
||||
{
|
||||
Name: "password",
|
||||
Flag: "password",
|
||||
Value: clibase.StringOf(new(string)),
|
||||
},
|
||||
},
|
||||
Children: []*clibase.Cmd{
|
||||
{
|
||||
Use: "sushi <args...>",
|
||||
Short: "Throws back raw output",
|
||||
RawArgs: true,
|
||||
Handler: (func(i *clibase.Invocation) error {
|
||||
if v := i.ParsedFlags().Lookup("password").Value.String(); v != "codershack" {
|
||||
return xerrors.Errorf("password %q is wrong!", v)
|
||||
}
|
||||
i.Stdout.Write([]byte(strings.Join(i.Args, " ")))
|
||||
return nil
|
||||
}),
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("OK", func(t *testing.T) {
|
||||
// Flag parsed before the raw arg command should still work.
|
||||
t.Parallel()
|
||||
|
||||
i := cmd().Invoke(
|
||||
"--password", "codershack", "sushi", "hello", "--verbose", "world",
|
||||
)
|
||||
io := fakeIO(i)
|
||||
require.NoError(t, i.Run())
|
||||
require.Equal(t, "hello --verbose world", io.Stdout.String())
|
||||
})
|
||||
|
||||
t.Run("BadFlag", func(t *testing.T) {
|
||||
// Verbose before the raw arg command should fail.
|
||||
t.Parallel()
|
||||
|
||||
i := cmd().Invoke(
|
||||
"--password", "codershack", "--verbose", "sushi", "hello", "world",
|
||||
)
|
||||
io := fakeIO(i)
|
||||
require.Error(t, i.Run())
|
||||
require.Empty(t, io.Stdout.String())
|
||||
})
|
||||
|
||||
t.Run("NoPassword", func(t *testing.T) {
|
||||
// Flag parsed before the raw arg command should still work.
|
||||
t.Parallel()
|
||||
i := cmd().Invoke(
|
||||
"sushi", "hello", "--verbose", "world",
|
||||
)
|
||||
_ = fakeIO(i)
|
||||
require.Error(t, i.Run())
|
||||
})
|
||||
}
|
||||
|
||||
func TestCommand_RootRaw(t *testing.T) {
|
||||
t.Parallel()
|
||||
cmd := &clibase.Cmd{
|
||||
RawArgs: true,
|
||||
Handler: func(i *clibase.Invocation) error {
|
||||
i.Stdout.Write([]byte(strings.Join(i.Args, " ")))
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
inv := cmd.Invoke("hello", "--verbose", "--friendly")
|
||||
stdio := fakeIO(inv)
|
||||
err := inv.Run()
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Equal(t, "hello --verbose --friendly", stdio.Stdout.String())
|
||||
}
|
||||
|
||||
func TestCommand_HyphenHyphen(t *testing.T) {
|
||||
t.Parallel()
|
||||
cmd := &clibase.Cmd{
|
||||
Handler: (func(i *clibase.Invocation) error {
|
||||
i.Stdout.Write([]byte(strings.Join(i.Args, " ")))
|
||||
return nil
|
||||
}),
|
||||
}
|
||||
|
||||
inv := cmd.Invoke("--", "--verbose", "--friendly")
|
||||
stdio := fakeIO(inv)
|
||||
err := inv.Run()
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Equal(t, "--verbose --friendly", stdio.Stdout.String())
|
||||
}
|
||||
|
||||
func TestCommand_ContextCancels(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var gotCtx context.Context
|
||||
|
||||
cmd := &clibase.Cmd{
|
||||
Handler: (func(i *clibase.Invocation) error {
|
||||
gotCtx = i.Context()
|
||||
if err := gotCtx.Err(); err != nil {
|
||||
return xerrors.Errorf("unexpected context error: %w", i.Context().Err())
|
||||
}
|
||||
return nil
|
||||
}),
|
||||
}
|
||||
|
||||
err := cmd.Invoke().Run()
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Error(t, gotCtx.Err())
|
||||
}
|
||||
|
||||
func TestCommand_Help(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cmd := func() *clibase.Cmd {
|
||||
return &clibase.Cmd{
|
||||
Use: "root",
|
||||
HelpHandler: (func(i *clibase.Invocation) error {
|
||||
i.Stdout.Write([]byte("abdracadabra"))
|
||||
return nil
|
||||
}),
|
||||
Handler: (func(i *clibase.Invocation) error {
|
||||
return xerrors.New("should not be called")
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("NoHandler", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
c := cmd()
|
||||
c.HelpHandler = nil
|
||||
err := c.Invoke("--help").Run()
|
||||
require.Error(t, err)
|
||||
})
|
||||
|
||||
t.Run("Long", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
inv := cmd().Invoke("--help")
|
||||
stdio := fakeIO(inv)
|
||||
err := inv.Run()
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Contains(t, stdio.Stdout.String(), "abdracadabra")
|
||||
})
|
||||
|
||||
t.Run("Short", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
inv := cmd().Invoke("-h")
|
||||
stdio := fakeIO(inv)
|
||||
err := inv.Run()
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Contains(t, stdio.Stdout.String(), "abdracadabra")
|
||||
})
|
||||
}
|
||||
|
||||
func TestCommand_SliceFlags(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cmd := func(want ...string) *clibase.Cmd {
|
||||
var got []string
|
||||
return &clibase.Cmd{
|
||||
Use: "root",
|
||||
Options: clibase.OptionSet{
|
||||
{
|
||||
Name: "arr",
|
||||
Flag: "arr",
|
||||
Default: "bad,bad,bad",
|
||||
Value: clibase.StringArrayOf(&got),
|
||||
},
|
||||
},
|
||||
Handler: (func(i *clibase.Invocation) error {
|
||||
require.Equal(t, want, got)
|
||||
return nil
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
err := cmd("good", "good", "good").Invoke("--arr", "good", "--arr", "good", "--arr", "good").Run()
|
||||
require.NoError(t, err)
|
||||
|
||||
err = cmd("bad", "bad", "bad").Invoke().Run()
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestCommand_EmptySlice(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cmd := func(want ...string) *clibase.Cmd {
|
||||
var got []string
|
||||
return &clibase.Cmd{
|
||||
Use: "root",
|
||||
Options: clibase.OptionSet{
|
||||
{
|
||||
Name: "arr",
|
||||
Flag: "arr",
|
||||
Default: "def,def,def",
|
||||
Env: "ARR",
|
||||
Value: clibase.StringArrayOf(&got),
|
||||
},
|
||||
},
|
||||
Handler: (func(i *clibase.Invocation) error {
|
||||
require.Equal(t, want, got)
|
||||
return nil
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
// Base-case, uses default.
|
||||
err := cmd("def", "def", "def").Invoke().Run()
|
||||
require.NoError(t, err)
|
||||
|
||||
// Empty-env uses default, too.
|
||||
inv := cmd("def", "def", "def").Invoke()
|
||||
inv.Environ.Set("ARR", "")
|
||||
require.NoError(t, err)
|
||||
|
||||
// Reset to nothing at all via flag.
|
||||
inv = cmd().Invoke("--arr", "")
|
||||
inv.Environ.Set("ARR", "cant see")
|
||||
err = inv.Run()
|
||||
require.NoError(t, err)
|
||||
|
||||
// Reset to a specific value with flag.
|
||||
inv = cmd("great").Invoke("--arr", "great")
|
||||
inv.Environ.Set("ARR", "")
|
||||
err = inv.Run()
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestCommand_DefaultsOverride(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
test := func(name string, want string, fn func(t *testing.T, inv *clibase.Invocation)) {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var (
|
||||
got string
|
||||
config clibase.YAMLConfigPath
|
||||
)
|
||||
cmd := &clibase.Cmd{
|
||||
Options: clibase.OptionSet{
|
||||
{
|
||||
Name: "url",
|
||||
Flag: "url",
|
||||
Default: "def.com",
|
||||
Env: "URL",
|
||||
Value: clibase.StringOf(&got),
|
||||
YAML: "url",
|
||||
},
|
||||
{
|
||||
Name: "config",
|
||||
Flag: "config",
|
||||
Default: "",
|
||||
Value: &config,
|
||||
},
|
||||
},
|
||||
Handler: (func(i *clibase.Invocation) error {
|
||||
_, _ = fmt.Fprintf(i.Stdout, "%s", got)
|
||||
return nil
|
||||
}),
|
||||
}
|
||||
|
||||
inv := cmd.Invoke()
|
||||
stdio := fakeIO(inv)
|
||||
fn(t, inv)
|
||||
err := inv.Run()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, want, stdio.Stdout.String())
|
||||
})
|
||||
}
|
||||
|
||||
test("DefaultOverNothing", "def.com", func(t *testing.T, inv *clibase.Invocation) {})
|
||||
|
||||
test("FlagOverDefault", "good.com", func(t *testing.T, inv *clibase.Invocation) {
|
||||
inv.Args = []string{"--url", "good.com"}
|
||||
})
|
||||
|
||||
test("EnvOverDefault", "good.com", func(t *testing.T, inv *clibase.Invocation) {
|
||||
inv.Environ.Set("URL", "good.com")
|
||||
})
|
||||
|
||||
test("FlagOverEnv", "good.com", func(t *testing.T, inv *clibase.Invocation) {
|
||||
inv.Environ.Set("URL", "bad.com")
|
||||
inv.Args = []string{"--url", "good.com"}
|
||||
})
|
||||
|
||||
test("FlagOverYAML", "good.com", func(t *testing.T, inv *clibase.Invocation) {
|
||||
fi, err := os.CreateTemp(t.TempDir(), "config.yaml")
|
||||
require.NoError(t, err)
|
||||
defer fi.Close()
|
||||
|
||||
_, err = fi.WriteString("url: bad.com")
|
||||
require.NoError(t, err)
|
||||
|
||||
inv.Args = []string{"--config", fi.Name(), "--url", "good.com"}
|
||||
})
|
||||
|
||||
test("YAMLOverDefault", "good.com", func(t *testing.T, inv *clibase.Invocation) {
|
||||
fi, err := os.CreateTemp(t.TempDir(), "config.yaml")
|
||||
require.NoError(t, err)
|
||||
defer fi.Close()
|
||||
|
||||
_, err = fi.WriteString("url: good.com")
|
||||
require.NoError(t, err)
|
||||
|
||||
inv.Args = []string{"--config", fi.Name()}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package clibase
|
||||
|
||||
import "strings"
|
||||
|
||||
// name returns the name of the environment variable.
|
||||
func envName(line string) string {
|
||||
return strings.ToUpper(
|
||||
strings.SplitN(line, "=", 2)[0],
|
||||
)
|
||||
}
|
||||
|
||||
// value returns the value of the environment variable.
|
||||
func envValue(line string) string {
|
||||
tokens := strings.SplitN(line, "=", 2)
|
||||
if len(tokens) < 2 {
|
||||
return ""
|
||||
}
|
||||
return tokens[1]
|
||||
}
|
||||
|
||||
// Var represents a single environment variable of form
|
||||
// NAME=VALUE.
|
||||
type EnvVar struct {
|
||||
Name string
|
||||
Value string
|
||||
}
|
||||
|
||||
type Environ []EnvVar
|
||||
|
||||
func (e Environ) ToOS() []string {
|
||||
var env []string
|
||||
for _, v := range e {
|
||||
env = append(env, v.Name+"="+v.Value)
|
||||
}
|
||||
return env
|
||||
}
|
||||
|
||||
func (e Environ) Lookup(name string) (string, bool) {
|
||||
for _, v := range e {
|
||||
if v.Name == name {
|
||||
return v.Value, true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
func (e Environ) Get(name string) string {
|
||||
v, _ := e.Lookup(name)
|
||||
return v
|
||||
}
|
||||
|
||||
func (e *Environ) Set(name, value string) {
|
||||
for i, v := range *e {
|
||||
if v.Name == name {
|
||||
(*e)[i].Value = value
|
||||
return
|
||||
}
|
||||
}
|
||||
*e = append(*e, EnvVar{Name: name, Value: value})
|
||||
}
|
||||
|
||||
// ParseEnviron returns all environment variables starting with
|
||||
// prefix without said prefix.
|
||||
func ParseEnviron(environ []string, prefix string) Environ {
|
||||
var filtered []EnvVar
|
||||
for _, line := range environ {
|
||||
name := envName(line)
|
||||
if strings.HasPrefix(name, prefix) {
|
||||
filtered = append(filtered, EnvVar{
|
||||
Name: strings.TrimPrefix(name, prefix),
|
||||
Value: envValue(line),
|
||||
})
|
||||
}
|
||||
}
|
||||
return filtered
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package clibase_test
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
)
|
||||
|
||||
func TestFilterNamePrefix(t *testing.T) {
|
||||
t.Parallel()
|
||||
type args struct {
|
||||
environ []string
|
||||
prefix string
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
want clibase.Environ
|
||||
}{
|
||||
{"empty", args{[]string{}, "SHIRE"}, nil},
|
||||
{
|
||||
"ONE",
|
||||
args{
|
||||
[]string{
|
||||
"SHIRE_BRANDYBUCK=hmm",
|
||||
},
|
||||
"SHIRE_",
|
||||
},
|
||||
[]clibase.EnvVar{
|
||||
{Name: "BRANDYBUCK", Value: "hmm"},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
tt := tt
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
if got := clibase.ParseEnviron(tt.args.environ, tt.args.prefix); !reflect.DeepEqual(got, tt.want) {
|
||||
t.Errorf("FilterNamePrefix() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package clibase
|
||||
|
||||
import (
|
||||
"net"
|
||||
"strconv"
|
||||
|
||||
"github.com/pion/udp"
|
||||
"golang.org/x/xerrors"
|
||||
)
|
||||
|
||||
// Net abstracts CLI commands interacting with the operating system networking.
|
||||
//
|
||||
// At present, it covers opening local listening sockets, since doing this
|
||||
// in testing is a challenge without flakes, since it's hard to pick a port we
|
||||
// know a priori will be free.
|
||||
type Net interface {
|
||||
// Listen has the same semantics as `net.Listen` but also supports `udp`
|
||||
Listen(network, address string) (net.Listener, error)
|
||||
}
|
||||
|
||||
// osNet is an implementation that call the real OS for networking.
|
||||
type osNet struct{}
|
||||
|
||||
func (osNet) Listen(network, address string) (net.Listener, error) {
|
||||
switch network {
|
||||
case "tcp", "tcp4", "tcp6", "unix", "unixpacket":
|
||||
return net.Listen(network, address)
|
||||
case "udp":
|
||||
host, port, err := net.SplitHostPort(address)
|
||||
if err != nil {
|
||||
return nil, xerrors.Errorf("split %q: %w", address, err)
|
||||
}
|
||||
|
||||
var portInt int
|
||||
portInt, err = strconv.Atoi(port)
|
||||
if err != nil {
|
||||
return nil, xerrors.Errorf("parse port %v from %q as int: %w", port, address, err)
|
||||
}
|
||||
|
||||
// Use pion here so that we get a stream-style net.Conn listener, instead
|
||||
// of a packet-oriented connection that can read and write to multiple
|
||||
// addresses.
|
||||
return udp.Listen(network, &net.UDPAddr{
|
||||
IP: net.ParseIP(host),
|
||||
Port: portInt,
|
||||
})
|
||||
default:
|
||||
return nil, xerrors.Errorf("unknown listen network %q", network)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
package clibase
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/hashicorp/go-multierror"
|
||||
"github.com/spf13/pflag"
|
||||
"golang.org/x/xerrors"
|
||||
)
|
||||
|
||||
type ValueSource string
|
||||
|
||||
const (
|
||||
ValueSourceNone ValueSource = ""
|
||||
ValueSourceFlag ValueSource = "flag"
|
||||
ValueSourceEnv ValueSource = "env"
|
||||
ValueSourceYAML ValueSource = "yaml"
|
||||
ValueSourceDefault ValueSource = "default"
|
||||
)
|
||||
|
||||
// Option is a configuration option for a CLI application.
|
||||
type Option struct {
|
||||
Name string `json:"name,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
// Required means this value must be set by some means. It requires
|
||||
// `ValueSource != ValueSourceNone`
|
||||
// If `Default` is set, then `Required` is ignored.
|
||||
Required bool `json:"required,omitempty"`
|
||||
|
||||
// Flag is the long name of the flag used to configure this option. If unset,
|
||||
// flag configuring is disabled.
|
||||
Flag string `json:"flag,omitempty"`
|
||||
// FlagShorthand is the one-character shorthand for the flag. If unset, no
|
||||
// shorthand is used.
|
||||
FlagShorthand string `json:"flag_shorthand,omitempty"`
|
||||
|
||||
// Env is the environment variable used to configure this option. If unset,
|
||||
// environment configuring is disabled.
|
||||
Env string `json:"env,omitempty"`
|
||||
|
||||
// YAML is the YAML key used to configure this option. If unset, YAML
|
||||
// configuring is disabled.
|
||||
YAML string `json:"yaml,omitempty"`
|
||||
|
||||
// Default is parsed into Value if set.
|
||||
Default string `json:"default,omitempty"`
|
||||
// Value includes the types listed in values.go.
|
||||
Value pflag.Value `json:"value,omitempty"`
|
||||
|
||||
// Annotations enable extensions to clibase higher up in the stack. It's useful for
|
||||
// help formatting and documentation generation.
|
||||
Annotations Annotations `json:"annotations,omitempty"`
|
||||
|
||||
// Group is a group hierarchy that helps organize this option in help, configs
|
||||
// and other documentation.
|
||||
Group *Group `json:"group,omitempty"`
|
||||
|
||||
// UseInstead is a list of options that should be used instead of this one.
|
||||
// The field is used to generate a deprecation warning.
|
||||
UseInstead []Option `json:"use_instead,omitempty"`
|
||||
|
||||
Hidden bool `json:"hidden,omitempty"`
|
||||
|
||||
ValueSource ValueSource `json:"value_source,omitempty"`
|
||||
}
|
||||
|
||||
// optionNoMethods is just a wrapper around Option so we can defer to the
|
||||
// default json.Unmarshaler behavior.
|
||||
type optionNoMethods Option
|
||||
|
||||
func (o *Option) UnmarshalJSON(data []byte) error {
|
||||
// If an option has no values, we have no idea how to unmarshal it.
|
||||
// So just discard the json data.
|
||||
if o.Value == nil {
|
||||
o.Value = &DiscardValue
|
||||
}
|
||||
|
||||
return json.Unmarshal(data, (*optionNoMethods)(o))
|
||||
}
|
||||
|
||||
func (o Option) YAMLPath() string {
|
||||
if o.YAML == "" {
|
||||
return ""
|
||||
}
|
||||
var gs []string
|
||||
for _, g := range o.Group.Ancestry() {
|
||||
gs = append(gs, g.YAML)
|
||||
}
|
||||
return strings.Join(append(gs, o.YAML), ".")
|
||||
}
|
||||
|
||||
// OptionSet is a group of options that can be applied to a command.
|
||||
type OptionSet []Option
|
||||
|
||||
// UnmarshalJSON implements json.Unmarshaler for OptionSets. Options have an
|
||||
// interface Value type that cannot handle unmarshalling because the types cannot
|
||||
// be inferred. Since it is a slice, instantiating the Options first does not
|
||||
// help.
|
||||
//
|
||||
// However, we typically do instantiate the slice to have the correct types.
|
||||
// So this unmarshaller will attempt to find the named option in the existing
|
||||
// set, if it cannot, the value is discarded. If the option exists, the value
|
||||
// is unmarshalled into the existing option, and replaces the existing option.
|
||||
//
|
||||
// The value is discarded if it's type cannot be inferred. This behavior just
|
||||
// feels "safer", although it should never happen if the correct option set
|
||||
// is passed in. The situation where this could occur is if a client and server
|
||||
// are on different versions with different options.
|
||||
func (optSet *OptionSet) UnmarshalJSON(data []byte) error {
|
||||
dec := json.NewDecoder(bytes.NewBuffer(data))
|
||||
// Should be a json array, so consume the starting open bracket.
|
||||
t, err := dec.Token()
|
||||
if err != nil {
|
||||
return xerrors.Errorf("read array open bracket: %w", err)
|
||||
}
|
||||
if t != json.Delim('[') {
|
||||
return xerrors.Errorf("expected array open bracket, got %q", t)
|
||||
}
|
||||
|
||||
// As long as json elements exist, consume them. The counter is used for
|
||||
// better errors.
|
||||
var i int
|
||||
OptionSetDecodeLoop:
|
||||
for dec.More() {
|
||||
var opt Option
|
||||
// jValue is a placeholder value that allows us to capture the
|
||||
// raw json for the value to attempt to unmarshal later.
|
||||
var jValue jsonValue
|
||||
opt.Value = &jValue
|
||||
err := dec.Decode(&opt)
|
||||
if err != nil {
|
||||
return xerrors.Errorf("decode %d option: %w", i, err)
|
||||
}
|
||||
// This counter is used to contextualize errors to show which element of
|
||||
// the array we failed to decode. It is only used in the error above, as
|
||||
// if the above works, we can instead use the Option.Name which is more
|
||||
// descriptive and useful. So increment here for the next decode.
|
||||
i++
|
||||
|
||||
// Try to see if the option already exists in the option set.
|
||||
// If it does, just update the existing option.
|
||||
for optIndex, have := range *optSet {
|
||||
if have.Name == opt.Name {
|
||||
if jValue != nil {
|
||||
err := json.Unmarshal(jValue, &(*optSet)[optIndex].Value)
|
||||
if err != nil {
|
||||
return xerrors.Errorf("decode option %q value: %w", have.Name, err)
|
||||
}
|
||||
// Set the opt's value
|
||||
opt.Value = (*optSet)[optIndex].Value
|
||||
} else {
|
||||
// Hopefully the user passed empty values in the option set. There is no easy way
|
||||
// to tell, and if we do not do this, it breaks json.Marshal if we do it again on
|
||||
// this new option set.
|
||||
opt.Value = (*optSet)[optIndex].Value
|
||||
}
|
||||
// Override the existing.
|
||||
(*optSet)[optIndex] = opt
|
||||
// Go to the next option to decode.
|
||||
continue OptionSetDecodeLoop
|
||||
}
|
||||
}
|
||||
|
||||
// If the option doesn't exist, the value will be discarded.
|
||||
// We do this because we cannot infer the type of the value.
|
||||
opt.Value = DiscardValue
|
||||
*optSet = append(*optSet, opt)
|
||||
}
|
||||
|
||||
t, err = dec.Token()
|
||||
if err != nil {
|
||||
return xerrors.Errorf("read array close bracket: %w", err)
|
||||
}
|
||||
if t != json.Delim(']') {
|
||||
return xerrors.Errorf("expected array close bracket, got %q", t)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Add adds the given Options to the OptionSet.
|
||||
func (optSet *OptionSet) Add(opts ...Option) {
|
||||
*optSet = append(*optSet, opts...)
|
||||
}
|
||||
|
||||
// Filter will only return options that match the given filter. (return true)
|
||||
func (optSet OptionSet) Filter(filter func(opt Option) bool) OptionSet {
|
||||
cpy := make(OptionSet, 0)
|
||||
for _, opt := range optSet {
|
||||
if filter(opt) {
|
||||
cpy = append(cpy, opt)
|
||||
}
|
||||
}
|
||||
return cpy
|
||||
}
|
||||
|
||||
// FlagSet returns a pflag.FlagSet for the OptionSet.
|
||||
func (optSet *OptionSet) FlagSet() *pflag.FlagSet {
|
||||
if optSet == nil {
|
||||
return &pflag.FlagSet{}
|
||||
}
|
||||
|
||||
fs := pflag.NewFlagSet("", pflag.ContinueOnError)
|
||||
for _, opt := range *optSet {
|
||||
if opt.Flag == "" {
|
||||
continue
|
||||
}
|
||||
var noOptDefValue string
|
||||
{
|
||||
no, ok := opt.Value.(NoOptDefValuer)
|
||||
if ok {
|
||||
noOptDefValue = no.NoOptDefValue()
|
||||
}
|
||||
}
|
||||
|
||||
val := opt.Value
|
||||
if val == nil {
|
||||
val = DiscardValue
|
||||
}
|
||||
|
||||
fs.AddFlag(&pflag.Flag{
|
||||
Name: opt.Flag,
|
||||
Shorthand: opt.FlagShorthand,
|
||||
Usage: opt.Description,
|
||||
Value: val,
|
||||
DefValue: "",
|
||||
Changed: false,
|
||||
Deprecated: "",
|
||||
NoOptDefVal: noOptDefValue,
|
||||
Hidden: opt.Hidden,
|
||||
})
|
||||
}
|
||||
fs.Usage = func() {
|
||||
_, _ = os.Stderr.WriteString("Override (*FlagSet).Usage() to print help text.\n")
|
||||
}
|
||||
return fs
|
||||
}
|
||||
|
||||
// ParseEnv parses the given environment variables into the OptionSet.
|
||||
// Use EnvsWithPrefix to filter out prefixes.
|
||||
func (optSet *OptionSet) ParseEnv(vs []EnvVar) error {
|
||||
if optSet == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
var merr *multierror.Error
|
||||
|
||||
// We parse environment variables first instead of using a nested loop to
|
||||
// avoid N*M complexity when there are a lot of options and environment
|
||||
// variables.
|
||||
envs := make(map[string]string)
|
||||
for _, v := range vs {
|
||||
envs[v.Name] = v.Value
|
||||
}
|
||||
|
||||
for i, opt := range *optSet {
|
||||
if opt.Env == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
envVal, ok := envs[opt.Env]
|
||||
if !ok {
|
||||
// Homebrew strips all environment variables that do not start with `HOMEBREW_`.
|
||||
// This prevented using brew to invoke the Coder agent, because the environment
|
||||
// variables to not get passed down.
|
||||
//
|
||||
// A customer wanted to use their custom tap inside a workspace, which was failing
|
||||
// because the agent lacked the environment variables to authenticate with Git.
|
||||
envVal, ok = envs[`HOMEBREW_`+opt.Env]
|
||||
}
|
||||
// Currently, empty values are treated as if the environment variable is
|
||||
// unset. This behavior is technically not correct as there is now no
|
||||
// way for a user to change a Default value to an empty string from
|
||||
// the environment. Unfortunately, we have old configuration files
|
||||
// that rely on the faulty behavior.
|
||||
//
|
||||
// TODO: We should remove this hack in May 2023, when deployments
|
||||
// have had months to migrate to the new behavior.
|
||||
if !ok || envVal == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
(*optSet)[i].ValueSource = ValueSourceEnv
|
||||
if err := opt.Value.Set(envVal); err != nil {
|
||||
merr = multierror.Append(
|
||||
merr, xerrors.Errorf("parse %q: %w", opt.Name, err),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return merr.ErrorOrNil()
|
||||
}
|
||||
|
||||
// SetDefaults sets the default values for each Option, skipping values
|
||||
// that already have a value source.
|
||||
func (optSet *OptionSet) SetDefaults() error {
|
||||
if optSet == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
var merr *multierror.Error
|
||||
|
||||
for i, opt := range *optSet {
|
||||
// Skip values that may have already been set by the user.
|
||||
if opt.ValueSource != ValueSourceNone {
|
||||
continue
|
||||
}
|
||||
|
||||
if opt.Default == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
if opt.Value == nil {
|
||||
merr = multierror.Append(
|
||||
merr,
|
||||
xerrors.Errorf(
|
||||
"parse %q: no Value field set\nFull opt: %+v",
|
||||
opt.Name, opt,
|
||||
),
|
||||
)
|
||||
continue
|
||||
}
|
||||
(*optSet)[i].ValueSource = ValueSourceDefault
|
||||
if err := opt.Value.Set(opt.Default); err != nil {
|
||||
merr = multierror.Append(
|
||||
merr, xerrors.Errorf("parse %q: %w", opt.Name, err),
|
||||
)
|
||||
}
|
||||
}
|
||||
return merr.ErrorOrNil()
|
||||
}
|
||||
|
||||
// ByName returns the Option with the given name, or nil if no such option
|
||||
// exists.
|
||||
func (optSet *OptionSet) ByName(name string) *Option {
|
||||
for i := range *optSet {
|
||||
opt := &(*optSet)[i]
|
||||
if opt.Name == name {
|
||||
return opt
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,391 @@
|
||||
package clibase_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"regexp"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/coderd/coderdtest"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
)
|
||||
|
||||
func TestOptionSet_ParseFlags(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
t.Run("SimpleString", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var workspaceName clibase.String
|
||||
|
||||
os := clibase.OptionSet{
|
||||
clibase.Option{
|
||||
Name: "Workspace Name",
|
||||
Value: &workspaceName,
|
||||
Flag: "workspace-name",
|
||||
FlagShorthand: "n",
|
||||
},
|
||||
}
|
||||
|
||||
var err error
|
||||
err = os.FlagSet().Parse([]string{"--workspace-name", "foo"})
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, "foo", workspaceName)
|
||||
|
||||
err = os.FlagSet().Parse([]string{"-n", "f"})
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, "f", workspaceName)
|
||||
})
|
||||
|
||||
t.Run("StringArray", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var names clibase.StringArray
|
||||
|
||||
os := clibase.OptionSet{
|
||||
clibase.Option{
|
||||
Name: "name",
|
||||
Value: &names,
|
||||
Flag: "name",
|
||||
FlagShorthand: "n",
|
||||
},
|
||||
}
|
||||
|
||||
err := os.SetDefaults()
|
||||
require.NoError(t, err)
|
||||
|
||||
err = os.FlagSet().Parse([]string{"--name", "foo", "--name", "bar"})
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, []string{"foo", "bar"}, names)
|
||||
})
|
||||
|
||||
t.Run("ExtraFlags", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var workspaceName clibase.String
|
||||
|
||||
os := clibase.OptionSet{
|
||||
clibase.Option{
|
||||
Name: "Workspace Name",
|
||||
Value: &workspaceName,
|
||||
},
|
||||
}
|
||||
|
||||
err := os.FlagSet().Parse([]string{"--some-unknown", "foo"})
|
||||
require.Error(t, err)
|
||||
})
|
||||
|
||||
t.Run("RegexValid", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var regexpString clibase.Regexp
|
||||
|
||||
os := clibase.OptionSet{
|
||||
clibase.Option{
|
||||
Name: "RegexpString",
|
||||
Value: ®expString,
|
||||
Flag: "regexp-string",
|
||||
},
|
||||
}
|
||||
|
||||
err := os.FlagSet().Parse([]string{"--regexp-string", "$test^"})
|
||||
require.NoError(t, err)
|
||||
})
|
||||
|
||||
t.Run("RegexInvalid", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var regexpString clibase.Regexp
|
||||
|
||||
os := clibase.OptionSet{
|
||||
clibase.Option{
|
||||
Name: "RegexpString",
|
||||
Value: ®expString,
|
||||
Flag: "regexp-string",
|
||||
},
|
||||
}
|
||||
|
||||
err := os.FlagSet().Parse([]string{"--regexp-string", "(("})
|
||||
require.Error(t, err)
|
||||
})
|
||||
}
|
||||
|
||||
func TestOptionSet_ParseEnv(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
t.Run("SimpleString", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var workspaceName clibase.String
|
||||
|
||||
os := clibase.OptionSet{
|
||||
clibase.Option{
|
||||
Name: "Workspace Name",
|
||||
Value: &workspaceName,
|
||||
Env: "WORKSPACE_NAME",
|
||||
},
|
||||
}
|
||||
|
||||
err := os.ParseEnv([]clibase.EnvVar{
|
||||
{Name: "WORKSPACE_NAME", Value: "foo"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, "foo", workspaceName)
|
||||
})
|
||||
|
||||
t.Run("EmptyValue", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var workspaceName clibase.String
|
||||
|
||||
os := clibase.OptionSet{
|
||||
clibase.Option{
|
||||
Name: "Workspace Name",
|
||||
Value: &workspaceName,
|
||||
Default: "defname",
|
||||
Env: "WORKSPACE_NAME",
|
||||
},
|
||||
}
|
||||
|
||||
err := os.SetDefaults()
|
||||
require.NoError(t, err)
|
||||
|
||||
err = os.ParseEnv(clibase.ParseEnviron([]string{"CODER_WORKSPACE_NAME="}, "CODER_"))
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, "defname", workspaceName)
|
||||
})
|
||||
|
||||
t.Run("StringSlice", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var actual clibase.StringArray
|
||||
expected := []string{"foo", "bar", "baz"}
|
||||
|
||||
os := clibase.OptionSet{
|
||||
clibase.Option{
|
||||
Name: "name",
|
||||
Value: &actual,
|
||||
Env: "NAMES",
|
||||
},
|
||||
}
|
||||
|
||||
err := os.SetDefaults()
|
||||
require.NoError(t, err)
|
||||
|
||||
err = os.ParseEnv([]clibase.EnvVar{
|
||||
{Name: "NAMES", Value: "foo,bar,baz"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, expected, actual)
|
||||
})
|
||||
|
||||
t.Run("StructMapStringString", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var actual clibase.Struct[map[string]string]
|
||||
expected := map[string]string{"foo": "bar", "baz": "zap"}
|
||||
|
||||
os := clibase.OptionSet{
|
||||
clibase.Option{
|
||||
Name: "labels",
|
||||
Value: &actual,
|
||||
Env: "LABELS",
|
||||
},
|
||||
}
|
||||
|
||||
err := os.SetDefaults()
|
||||
require.NoError(t, err)
|
||||
|
||||
err = os.ParseEnv([]clibase.EnvVar{
|
||||
{Name: "LABELS", Value: `{"foo":"bar","baz":"zap"}`},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, expected, actual.Value)
|
||||
})
|
||||
|
||||
t.Run("Homebrew", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var agentToken clibase.String
|
||||
|
||||
os := clibase.OptionSet{
|
||||
clibase.Option{
|
||||
Name: "Agent Token",
|
||||
Value: &agentToken,
|
||||
Env: "AGENT_TOKEN",
|
||||
},
|
||||
}
|
||||
|
||||
err := os.ParseEnv([]clibase.EnvVar{
|
||||
{Name: "HOMEBREW_AGENT_TOKEN", Value: "foo"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, "foo", agentToken)
|
||||
})
|
||||
}
|
||||
|
||||
func TestOptionSet_JsonMarshal(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
// This unit test ensures if the source optionset is missing the option
|
||||
// and cannot determine the type, it will not panic. The unmarshal will
|
||||
// succeed with a best effort.
|
||||
t.Run("MissingSrcOption", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var str clibase.String = "something"
|
||||
var arr clibase.StringArray = []string{"foo", "bar"}
|
||||
opts := clibase.OptionSet{
|
||||
clibase.Option{
|
||||
Name: "StringOpt",
|
||||
Value: &str,
|
||||
},
|
||||
clibase.Option{
|
||||
Name: "ArrayOpt",
|
||||
Value: &arr,
|
||||
},
|
||||
}
|
||||
data, err := json.Marshal(opts)
|
||||
require.NoError(t, err, "marshal option set")
|
||||
|
||||
tgt := clibase.OptionSet{}
|
||||
err = json.Unmarshal(data, &tgt)
|
||||
require.NoError(t, err, "unmarshal option set")
|
||||
for i := range opts {
|
||||
compareOptionsExceptValues(t, opts[i], tgt[i])
|
||||
require.Empty(t, tgt[i].Value.String(), "unknown value types are empty")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("RegexCase", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
val := clibase.Regexp(*regexp.MustCompile(".*"))
|
||||
opts := clibase.OptionSet{
|
||||
clibase.Option{
|
||||
Name: "Regex",
|
||||
Value: &val,
|
||||
Default: ".*",
|
||||
},
|
||||
}
|
||||
data, err := json.Marshal(opts)
|
||||
require.NoError(t, err, "marshal option set")
|
||||
|
||||
var foundVal clibase.Regexp
|
||||
newOpts := clibase.OptionSet{
|
||||
clibase.Option{
|
||||
Name: "Regex",
|
||||
Value: &foundVal,
|
||||
},
|
||||
}
|
||||
err = json.Unmarshal(data, &newOpts)
|
||||
require.NoError(t, err, "unmarshal option set")
|
||||
|
||||
require.EqualValues(t, opts[0].Value.String(), newOpts[0].Value.String())
|
||||
})
|
||||
|
||||
t.Run("AllValues", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
vals := coderdtest.DeploymentValues(t)
|
||||
opts := vals.Options()
|
||||
sources := []clibase.ValueSource{
|
||||
clibase.ValueSourceNone,
|
||||
clibase.ValueSourceFlag,
|
||||
clibase.ValueSourceEnv,
|
||||
clibase.ValueSourceYAML,
|
||||
clibase.ValueSourceDefault,
|
||||
}
|
||||
for i := range opts {
|
||||
opts[i].ValueSource = sources[i%len(sources)]
|
||||
}
|
||||
|
||||
data, err := json.Marshal(opts)
|
||||
require.NoError(t, err, "marshal option set")
|
||||
|
||||
newOpts := (&codersdk.DeploymentValues{}).Options()
|
||||
err = json.Unmarshal(data, &newOpts)
|
||||
require.NoError(t, err, "unmarshal option set")
|
||||
|
||||
for i := range opts {
|
||||
exp := opts[i]
|
||||
found := newOpts[i]
|
||||
|
||||
compareOptionsExceptValues(t, exp, found)
|
||||
compareValues(t, exp, found)
|
||||
}
|
||||
|
||||
thirdOpts := (&codersdk.DeploymentValues{}).Options()
|
||||
data, err = json.Marshal(newOpts)
|
||||
require.NoError(t, err, "marshal option set")
|
||||
|
||||
err = json.Unmarshal(data, &thirdOpts)
|
||||
require.NoError(t, err, "unmarshal option set")
|
||||
// Compare to the original opts again
|
||||
for i := range opts {
|
||||
exp := opts[i]
|
||||
found := thirdOpts[i]
|
||||
|
||||
compareOptionsExceptValues(t, exp, found)
|
||||
compareValues(t, exp, found)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func compareOptionsExceptValues(t *testing.T, exp, found clibase.Option) {
|
||||
t.Helper()
|
||||
|
||||
require.Equalf(t, exp.Name, found.Name, "option name %q", exp.Name)
|
||||
require.Equalf(t, exp.Description, found.Description, "option description %q", exp.Name)
|
||||
require.Equalf(t, exp.Required, found.Required, "option required %q", exp.Name)
|
||||
require.Equalf(t, exp.Flag, found.Flag, "option flag %q", exp.Name)
|
||||
require.Equalf(t, exp.FlagShorthand, found.FlagShorthand, "option flag shorthand %q", exp.Name)
|
||||
require.Equalf(t, exp.Env, found.Env, "option env %q", exp.Name)
|
||||
require.Equalf(t, exp.YAML, found.YAML, "option yaml %q", exp.Name)
|
||||
require.Equalf(t, exp.Default, found.Default, "option default %q", exp.Name)
|
||||
require.Equalf(t, exp.ValueSource, found.ValueSource, "option value source %q", exp.Name)
|
||||
require.Equalf(t, exp.Hidden, found.Hidden, "option hidden %q", exp.Name)
|
||||
require.Equalf(t, exp.Annotations, found.Annotations, "option annotations %q", exp.Name)
|
||||
require.Equalf(t, exp.Group, found.Group, "option group %q", exp.Name)
|
||||
// UseInstead is the same comparison problem, just check the length
|
||||
require.Equalf(t, len(exp.UseInstead), len(found.UseInstead), "option use instead %q", exp.Name)
|
||||
}
|
||||
|
||||
func compareValues(t *testing.T, exp, found clibase.Option) {
|
||||
t.Helper()
|
||||
|
||||
if (exp.Value == nil || found.Value == nil) || (exp.Value.String() != found.Value.String() && found.Value.String() == "") {
|
||||
// If the string values are different, this can be a "nil" issue.
|
||||
// So only run this case if the found string is the empty string.
|
||||
// We use MarshalYAML for struct strings, and it will return an
|
||||
// empty string '""' for nil slices/maps/etc.
|
||||
// So use json to compare.
|
||||
|
||||
expJSON, err := json.Marshal(exp.Value)
|
||||
require.NoError(t, err, "marshal")
|
||||
foundJSON, err := json.Marshal(found.Value)
|
||||
require.NoError(t, err, "marshal")
|
||||
|
||||
expJSON = normalizeJSON(expJSON)
|
||||
foundJSON = normalizeJSON(foundJSON)
|
||||
assert.Equalf(t, string(expJSON), string(foundJSON), "option value %q", exp.Name)
|
||||
} else {
|
||||
assert.Equal(t,
|
||||
exp.Value.String(),
|
||||
found.Value.String(),
|
||||
"option value %q", exp.Name)
|
||||
}
|
||||
}
|
||||
|
||||
// normalizeJSON handles the fact that an empty map/slice is not the same
|
||||
// as a nil empty/slice. For our purposes, they are the same.
|
||||
func normalizeJSON(data []byte) []byte {
|
||||
if bytes.Equal(data, []byte("[]")) || bytes.Equal(data, []byte("{}")) {
|
||||
return []byte("null")
|
||||
}
|
||||
return data
|
||||
}
|
||||
@@ -0,0 +1,593 @@
|
||||
package clibase
|
||||
|
||||
import (
|
||||
"encoding/csv"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/pflag"
|
||||
"golang.org/x/xerrors"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
// NoOptDefValuer describes behavior when no
|
||||
// option is passed into the flag.
|
||||
//
|
||||
// This is useful for boolean or otherwise binary flags.
|
||||
type NoOptDefValuer interface {
|
||||
NoOptDefValue() string
|
||||
}
|
||||
|
||||
// Validator is a wrapper around a pflag.Value that allows for validation
|
||||
// of the value after or before it has been set.
|
||||
type Validator[T pflag.Value] struct {
|
||||
Value T
|
||||
// validate is called after the value is set.
|
||||
validate func(T) error
|
||||
}
|
||||
|
||||
func Validate[T pflag.Value](opt T, validate func(value T) error) *Validator[T] {
|
||||
return &Validator[T]{Value: opt, validate: validate}
|
||||
}
|
||||
|
||||
func (i *Validator[T]) String() string {
|
||||
return i.Value.String()
|
||||
}
|
||||
|
||||
func (i *Validator[T]) Set(input string) error {
|
||||
err := i.Value.Set(input)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if i.validate != nil {
|
||||
err = i.validate(i.Value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i *Validator[T]) Type() string {
|
||||
return i.Value.Type()
|
||||
}
|
||||
|
||||
func (i *Validator[T]) MarshalYAML() (interface{}, error) {
|
||||
m, ok := any(i.Value).(yaml.Marshaler)
|
||||
if !ok {
|
||||
return i.Value, nil
|
||||
}
|
||||
return m.MarshalYAML()
|
||||
}
|
||||
|
||||
func (i *Validator[T]) UnmarshalYAML(n *yaml.Node) error {
|
||||
return n.Decode(i.Value)
|
||||
}
|
||||
|
||||
func (i *Validator[T]) MarshalJSON() ([]byte, error) {
|
||||
return json.Marshal(i.Value)
|
||||
}
|
||||
|
||||
func (i *Validator[T]) UnmarshalJSON(b []byte) error {
|
||||
return json.Unmarshal(b, i.Value)
|
||||
}
|
||||
|
||||
func (i *Validator[T]) Underlying() pflag.Value { return i.Value }
|
||||
|
||||
// values.go contains a standard set of value types that can be used as
|
||||
// Option Values.
|
||||
|
||||
type Int64 int64
|
||||
|
||||
func Int64Of(i *int64) *Int64 {
|
||||
return (*Int64)(i)
|
||||
}
|
||||
|
||||
func (i *Int64) Set(s string) error {
|
||||
ii, err := strconv.ParseInt(s, 10, 64)
|
||||
*i = Int64(ii)
|
||||
return err
|
||||
}
|
||||
|
||||
func (i Int64) Value() int64 {
|
||||
return int64(i)
|
||||
}
|
||||
|
||||
func (i Int64) String() string {
|
||||
return strconv.Itoa(int(i))
|
||||
}
|
||||
|
||||
func (Int64) Type() string {
|
||||
return "int"
|
||||
}
|
||||
|
||||
type Bool bool
|
||||
|
||||
func BoolOf(b *bool) *Bool {
|
||||
return (*Bool)(b)
|
||||
}
|
||||
|
||||
func (b *Bool) Set(s string) error {
|
||||
if s == "" {
|
||||
*b = Bool(false)
|
||||
return nil
|
||||
}
|
||||
bb, err := strconv.ParseBool(s)
|
||||
*b = Bool(bb)
|
||||
return err
|
||||
}
|
||||
|
||||
func (*Bool) NoOptDefValue() string {
|
||||
return "true"
|
||||
}
|
||||
|
||||
func (b Bool) String() string {
|
||||
return strconv.FormatBool(bool(b))
|
||||
}
|
||||
|
||||
func (b Bool) Value() bool {
|
||||
return bool(b)
|
||||
}
|
||||
|
||||
func (Bool) Type() string {
|
||||
return "bool"
|
||||
}
|
||||
|
||||
type String string
|
||||
|
||||
func StringOf(s *string) *String {
|
||||
return (*String)(s)
|
||||
}
|
||||
|
||||
func (*String) NoOptDefValue() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (s *String) Set(v string) error {
|
||||
*s = String(v)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s String) String() string {
|
||||
return string(s)
|
||||
}
|
||||
|
||||
func (s String) Value() string {
|
||||
return string(s)
|
||||
}
|
||||
|
||||
func (String) Type() string {
|
||||
return "string"
|
||||
}
|
||||
|
||||
var _ pflag.SliceValue = &StringArray{}
|
||||
|
||||
// StringArray is a slice of strings that implements pflag.Value and pflag.SliceValue.
|
||||
type StringArray []string
|
||||
|
||||
func StringArrayOf(ss *[]string) *StringArray {
|
||||
return (*StringArray)(ss)
|
||||
}
|
||||
|
||||
func (s *StringArray) Append(v string) error {
|
||||
*s = append(*s, v)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *StringArray) Replace(vals []string) error {
|
||||
*s = vals
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *StringArray) GetSlice() []string {
|
||||
return *s
|
||||
}
|
||||
|
||||
func readAsCSV(v string) ([]string, error) {
|
||||
return csv.NewReader(strings.NewReader(v)).Read()
|
||||
}
|
||||
|
||||
func writeAsCSV(vals []string) string {
|
||||
var sb strings.Builder
|
||||
err := csv.NewWriter(&sb).Write(vals)
|
||||
if err != nil {
|
||||
return fmt.Sprintf("error: %s", err)
|
||||
}
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
func (s *StringArray) Set(v string) error {
|
||||
if v == "" {
|
||||
*s = nil
|
||||
return nil
|
||||
}
|
||||
ss, err := readAsCSV(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*s = append(*s, ss...)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s StringArray) String() string {
|
||||
return writeAsCSV([]string(s))
|
||||
}
|
||||
|
||||
func (s StringArray) Value() []string {
|
||||
return []string(s)
|
||||
}
|
||||
|
||||
func (StringArray) Type() string {
|
||||
return "string-array"
|
||||
}
|
||||
|
||||
type Duration time.Duration
|
||||
|
||||
func DurationOf(d *time.Duration) *Duration {
|
||||
return (*Duration)(d)
|
||||
}
|
||||
|
||||
func (d *Duration) Set(v string) error {
|
||||
dd, err := time.ParseDuration(v)
|
||||
*d = Duration(dd)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *Duration) Value() time.Duration {
|
||||
return time.Duration(*d)
|
||||
}
|
||||
|
||||
func (d *Duration) String() string {
|
||||
return time.Duration(*d).String()
|
||||
}
|
||||
|
||||
func (Duration) Type() string {
|
||||
return "duration"
|
||||
}
|
||||
|
||||
func (d *Duration) MarshalYAML() (interface{}, error) {
|
||||
return yaml.Node{
|
||||
Kind: yaml.ScalarNode,
|
||||
Value: d.String(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (d *Duration) UnmarshalYAML(n *yaml.Node) error {
|
||||
return d.Set(n.Value)
|
||||
}
|
||||
|
||||
type URL url.URL
|
||||
|
||||
func URLOf(u *url.URL) *URL {
|
||||
return (*URL)(u)
|
||||
}
|
||||
|
||||
func (u *URL) Set(v string) error {
|
||||
uu, err := url.Parse(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*u = URL(*uu)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (u *URL) String() string {
|
||||
uu := url.URL(*u)
|
||||
return uu.String()
|
||||
}
|
||||
|
||||
func (u *URL) MarshalYAML() (interface{}, error) {
|
||||
return yaml.Node{
|
||||
Kind: yaml.ScalarNode,
|
||||
Value: u.String(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (u *URL) UnmarshalYAML(n *yaml.Node) error {
|
||||
return u.Set(n.Value)
|
||||
}
|
||||
|
||||
func (u *URL) MarshalJSON() ([]byte, error) {
|
||||
return json.Marshal(u.String())
|
||||
}
|
||||
|
||||
func (u *URL) UnmarshalJSON(b []byte) error {
|
||||
var s string
|
||||
err := json.Unmarshal(b, &s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return u.Set(s)
|
||||
}
|
||||
|
||||
func (*URL) Type() string {
|
||||
return "url"
|
||||
}
|
||||
|
||||
func (u *URL) Value() *url.URL {
|
||||
return (*url.URL)(u)
|
||||
}
|
||||
|
||||
// HostPort is a host:port pair.
|
||||
type HostPort struct {
|
||||
Host string
|
||||
Port string
|
||||
}
|
||||
|
||||
func (hp *HostPort) Set(v string) error {
|
||||
if v == "" {
|
||||
return xerrors.Errorf("must not be empty")
|
||||
}
|
||||
var err error
|
||||
hp.Host, hp.Port, err = net.SplitHostPort(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (hp *HostPort) String() string {
|
||||
if hp.Host == "" && hp.Port == "" {
|
||||
return ""
|
||||
}
|
||||
// Warning: net.JoinHostPort must be used over concatenation to support
|
||||
// IPv6 addresses.
|
||||
return net.JoinHostPort(hp.Host, hp.Port)
|
||||
}
|
||||
|
||||
func (hp *HostPort) MarshalJSON() ([]byte, error) {
|
||||
return json.Marshal(hp.String())
|
||||
}
|
||||
|
||||
func (hp *HostPort) UnmarshalJSON(b []byte) error {
|
||||
var s string
|
||||
err := json.Unmarshal(b, &s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if s == "" {
|
||||
hp.Host = ""
|
||||
hp.Port = ""
|
||||
return nil
|
||||
}
|
||||
return hp.Set(s)
|
||||
}
|
||||
|
||||
func (hp *HostPort) MarshalYAML() (interface{}, error) {
|
||||
return yaml.Node{
|
||||
Kind: yaml.ScalarNode,
|
||||
Value: hp.String(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (hp *HostPort) UnmarshalYAML(n *yaml.Node) error {
|
||||
return hp.Set(n.Value)
|
||||
}
|
||||
|
||||
func (*HostPort) Type() string {
|
||||
return "host:port"
|
||||
}
|
||||
|
||||
var (
|
||||
_ yaml.Marshaler = new(Struct[struct{}])
|
||||
_ yaml.Unmarshaler = new(Struct[struct{}])
|
||||
)
|
||||
|
||||
// Struct is a special value type that encodes an arbitrary struct.
|
||||
// It implements the flag.Value interface, but in general these values should
|
||||
// only be accepted via config for ergonomics.
|
||||
//
|
||||
// The string encoding type is YAML.
|
||||
type Struct[T any] struct {
|
||||
Value T
|
||||
}
|
||||
|
||||
//nolint:revive
|
||||
func (s *Struct[T]) Set(v string) error {
|
||||
return yaml.Unmarshal([]byte(v), &s.Value)
|
||||
}
|
||||
|
||||
//nolint:revive
|
||||
func (s *Struct[T]) String() string {
|
||||
byt, err := yaml.Marshal(s.Value)
|
||||
if err != nil {
|
||||
return "decode failed: " + err.Error()
|
||||
}
|
||||
return string(byt)
|
||||
}
|
||||
|
||||
// nolint:revive
|
||||
func (s *Struct[T]) MarshalYAML() (interface{}, error) {
|
||||
var n yaml.Node
|
||||
err := n.Encode(s.Value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// nolint:revive
|
||||
func (s *Struct[T]) UnmarshalYAML(n *yaml.Node) error {
|
||||
// HACK: for compatibility with flags, we use nil slices instead of empty
|
||||
// slices. In most cases, nil slices and empty slices are treated
|
||||
// the same, so this behavior may be removed at some point.
|
||||
if typ := reflect.TypeOf(s.Value); typ.Kind() == reflect.Slice && len(n.Content) == 0 {
|
||||
reflect.ValueOf(&s.Value).Elem().Set(reflect.Zero(typ))
|
||||
return nil
|
||||
}
|
||||
return n.Decode(&s.Value)
|
||||
}
|
||||
|
||||
//nolint:revive
|
||||
func (s *Struct[T]) Type() string {
|
||||
return fmt.Sprintf("struct[%T]", s.Value)
|
||||
}
|
||||
|
||||
// nolint:revive
|
||||
func (s *Struct[T]) MarshalJSON() ([]byte, error) {
|
||||
return json.Marshal(s.Value)
|
||||
}
|
||||
|
||||
// nolint:revive
|
||||
func (s *Struct[T]) UnmarshalJSON(b []byte) error {
|
||||
return json.Unmarshal(b, &s.Value)
|
||||
}
|
||||
|
||||
// DiscardValue does nothing but implements the pflag.Value interface.
|
||||
// It's useful in cases where you want to accept an option, but access the
|
||||
// underlying value directly instead of through the Option methods.
|
||||
var DiscardValue discardValue
|
||||
|
||||
type discardValue struct{}
|
||||
|
||||
func (discardValue) Set(string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (discardValue) String() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (discardValue) Type() string {
|
||||
return "discard"
|
||||
}
|
||||
|
||||
func (discardValue) UnmarshalJSON([]byte) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// jsonValue is intentionally not exported. It is just used to store the raw JSON
|
||||
// data for a value to defer it's unmarshal. It implements the pflag.Value to be
|
||||
// usable in an Option.
|
||||
type jsonValue json.RawMessage
|
||||
|
||||
func (jsonValue) Set(string) error {
|
||||
return xerrors.Errorf("json value is read-only")
|
||||
}
|
||||
|
||||
func (jsonValue) String() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (jsonValue) Type() string {
|
||||
return "json"
|
||||
}
|
||||
|
||||
func (j *jsonValue) UnmarshalJSON(data []byte) error {
|
||||
if j == nil {
|
||||
return xerrors.New("json.RawMessage: UnmarshalJSON on nil pointer")
|
||||
}
|
||||
*j = append((*j)[0:0], data...)
|
||||
return nil
|
||||
}
|
||||
|
||||
var _ pflag.Value = (*Enum)(nil)
|
||||
|
||||
type Enum struct {
|
||||
Choices []string
|
||||
Value *string
|
||||
}
|
||||
|
||||
func EnumOf(v *string, choices ...string) *Enum {
|
||||
return &Enum{
|
||||
Choices: choices,
|
||||
Value: v,
|
||||
}
|
||||
}
|
||||
|
||||
func (e *Enum) Set(v string) error {
|
||||
for _, c := range e.Choices {
|
||||
if v == c {
|
||||
*e.Value = v
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return xerrors.Errorf("invalid choice: %s, should be one of %v", v, e.Choices)
|
||||
}
|
||||
|
||||
func (e *Enum) Type() string {
|
||||
return fmt.Sprintf("enum[%v]", strings.Join(e.Choices, "\\|"))
|
||||
}
|
||||
|
||||
func (e *Enum) String() string {
|
||||
return *e.Value
|
||||
}
|
||||
|
||||
type Regexp regexp.Regexp
|
||||
|
||||
func (r *Regexp) MarshalJSON() ([]byte, error) {
|
||||
return json.Marshal(r.String())
|
||||
}
|
||||
|
||||
func (r *Regexp) UnmarshalJSON(data []byte) error {
|
||||
var source string
|
||||
err := json.Unmarshal(data, &source)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
exp, err := regexp.Compile(source)
|
||||
if err != nil {
|
||||
return xerrors.Errorf("invalid regex expression: %w", err)
|
||||
}
|
||||
*r = Regexp(*exp)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Regexp) MarshalYAML() (interface{}, error) {
|
||||
return yaml.Node{
|
||||
Kind: yaml.ScalarNode,
|
||||
Value: r.String(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *Regexp) UnmarshalYAML(n *yaml.Node) error {
|
||||
return r.Set(n.Value)
|
||||
}
|
||||
|
||||
func (r *Regexp) Set(v string) error {
|
||||
exp, err := regexp.Compile(v)
|
||||
if err != nil {
|
||||
return xerrors.Errorf("invalid regex expression: %w", err)
|
||||
}
|
||||
*r = Regexp(*exp)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r Regexp) String() string {
|
||||
return r.Value().String()
|
||||
}
|
||||
|
||||
func (r *Regexp) Value() *regexp.Regexp {
|
||||
if r == nil {
|
||||
return nil
|
||||
}
|
||||
return (*regexp.Regexp)(r)
|
||||
}
|
||||
|
||||
func (Regexp) Type() string {
|
||||
return "regexp"
|
||||
}
|
||||
|
||||
var _ pflag.Value = (*YAMLConfigPath)(nil)
|
||||
|
||||
// YAMLConfigPath is a special value type that encodes a path to a YAML
|
||||
// configuration file where options are read from.
|
||||
type YAMLConfigPath string
|
||||
|
||||
func (p *YAMLConfigPath) Set(v string) error {
|
||||
*p = YAMLConfigPath(v)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *YAMLConfigPath) String() string {
|
||||
return string(*p)
|
||||
}
|
||||
|
||||
func (*YAMLConfigPath) Type() string {
|
||||
return "yaml-config-path"
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
package clibase
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/mitchellh/go-wordwrap"
|
||||
"github.com/spf13/pflag"
|
||||
"golang.org/x/xerrors"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
var (
|
||||
_ yaml.Marshaler = new(OptionSet)
|
||||
_ yaml.Unmarshaler = new(OptionSet)
|
||||
)
|
||||
|
||||
// deepMapNode returns the mapping node at the given path,
|
||||
// creating it if it doesn't exist.
|
||||
func deepMapNode(n *yaml.Node, path []string, headComment string) *yaml.Node {
|
||||
if len(path) == 0 {
|
||||
return n
|
||||
}
|
||||
|
||||
// Name is every two nodes.
|
||||
for i := 0; i < len(n.Content)-1; i += 2 {
|
||||
if n.Content[i].Value == path[0] {
|
||||
// Found matching name, recurse.
|
||||
return deepMapNode(n.Content[i+1], path[1:], headComment)
|
||||
}
|
||||
}
|
||||
|
||||
// Not found, create it.
|
||||
nameNode := yaml.Node{
|
||||
Kind: yaml.ScalarNode,
|
||||
Value: path[0],
|
||||
HeadComment: headComment,
|
||||
}
|
||||
valueNode := yaml.Node{
|
||||
Kind: yaml.MappingNode,
|
||||
}
|
||||
n.Content = append(n.Content, &nameNode)
|
||||
n.Content = append(n.Content, &valueNode)
|
||||
return deepMapNode(&valueNode, path[1:], headComment)
|
||||
}
|
||||
|
||||
// MarshalYAML converts the option set to a YAML node, that can be
|
||||
// converted into bytes via yaml.Marshal.
|
||||
//
|
||||
// The node is returned to enable post-processing higher up in
|
||||
// the stack.
|
||||
//
|
||||
// It is isomorphic with FromYAML.
|
||||
func (optSet *OptionSet) MarshalYAML() (any, error) {
|
||||
root := yaml.Node{
|
||||
Kind: yaml.MappingNode,
|
||||
}
|
||||
|
||||
for _, opt := range *optSet {
|
||||
if opt.YAML == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
defValue := opt.Default
|
||||
if defValue == "" {
|
||||
defValue = "<unset>"
|
||||
}
|
||||
comment := wordwrap.WrapString(
|
||||
fmt.Sprintf("%s\n(default: %s, type: %s)", opt.Description, defValue, opt.Value.Type()),
|
||||
80,
|
||||
)
|
||||
nameNode := yaml.Node{
|
||||
Kind: yaml.ScalarNode,
|
||||
Value: opt.YAML,
|
||||
HeadComment: comment,
|
||||
}
|
||||
|
||||
_, isValidator := opt.Value.(interface{ Underlying() pflag.Value })
|
||||
var valueNode yaml.Node
|
||||
if opt.Value == nil {
|
||||
valueNode = yaml.Node{
|
||||
Kind: yaml.ScalarNode,
|
||||
Value: "null",
|
||||
}
|
||||
} else if m, ok := opt.Value.(yaml.Marshaler); ok && !isValidator {
|
||||
// Validators do a wrap, and should be handled by the else statement.
|
||||
v, err := m.MarshalYAML()
|
||||
if err != nil {
|
||||
return nil, xerrors.Errorf(
|
||||
"marshal %q: %w", opt.Name, err,
|
||||
)
|
||||
}
|
||||
valueNode, ok = v.(yaml.Node)
|
||||
if !ok {
|
||||
return nil, xerrors.Errorf(
|
||||
"marshal %q: unexpected underlying type %T",
|
||||
opt.Name, v,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
// The all-other types case.
|
||||
//
|
||||
// A bit of a hack, we marshal and then unmarshal to get
|
||||
// the underlying node.
|
||||
byt, err := yaml.Marshal(opt.Value)
|
||||
if err != nil {
|
||||
return nil, xerrors.Errorf(
|
||||
"marshal %q: %w", opt.Name, err,
|
||||
)
|
||||
}
|
||||
|
||||
var docNode yaml.Node
|
||||
err = yaml.Unmarshal(byt, &docNode)
|
||||
if err != nil {
|
||||
return nil, xerrors.Errorf(
|
||||
"unmarshal %q: %w", opt.Name, err,
|
||||
)
|
||||
}
|
||||
if len(docNode.Content) != 1 {
|
||||
return nil, xerrors.Errorf(
|
||||
"unmarshal %q: expected one node, got %d",
|
||||
opt.Name, len(docNode.Content),
|
||||
)
|
||||
}
|
||||
|
||||
valueNode = *docNode.Content[0]
|
||||
}
|
||||
var group []string
|
||||
for _, g := range opt.Group.Ancestry() {
|
||||
if g.YAML == "" {
|
||||
return nil, xerrors.Errorf(
|
||||
"group yaml name is empty for %q, groups: %+v",
|
||||
opt.Name,
|
||||
opt.Group,
|
||||
)
|
||||
}
|
||||
group = append(group, g.YAML)
|
||||
}
|
||||
var groupDesc string
|
||||
if opt.Group != nil {
|
||||
groupDesc = wordwrap.WrapString(opt.Group.Description, 80)
|
||||
}
|
||||
parentValueNode := deepMapNode(
|
||||
&root, group,
|
||||
groupDesc,
|
||||
)
|
||||
parentValueNode.Content = append(
|
||||
parentValueNode.Content,
|
||||
&nameNode,
|
||||
&valueNode,
|
||||
)
|
||||
}
|
||||
return &root, nil
|
||||
}
|
||||
|
||||
// mapYAMLNodes converts parent into a map with keys of form "group.subgroup.option"
|
||||
// and values as the corresponding YAML nodes.
|
||||
func mapYAMLNodes(parent *yaml.Node) (map[string]*yaml.Node, error) {
|
||||
if parent.Kind != yaml.MappingNode {
|
||||
return nil, xerrors.Errorf("expected mapping node, got type %v", parent.Kind)
|
||||
}
|
||||
if len(parent.Content)%2 != 0 {
|
||||
return nil, xerrors.Errorf("expected an even number of k/v pairs, got %d", len(parent.Content))
|
||||
}
|
||||
var (
|
||||
key string
|
||||
m = make(map[string]*yaml.Node, len(parent.Content)/2)
|
||||
merr error
|
||||
)
|
||||
for i, child := range parent.Content {
|
||||
if i%2 == 0 {
|
||||
if child.Kind != yaml.ScalarNode {
|
||||
// We immediately because the rest of the code is bound to fail
|
||||
// if we don't know to expect a key or a value.
|
||||
return nil, xerrors.Errorf("expected scalar node for key, got type %v", child.Kind)
|
||||
}
|
||||
key = child.Value
|
||||
continue
|
||||
}
|
||||
|
||||
// We don't know if this is a grouped simple option or complex option,
|
||||
// so we store both "key" and "group.key". Since we're storing pointers,
|
||||
// the additional memory is of little concern.
|
||||
m[key] = child
|
||||
if child.Kind != yaml.MappingNode {
|
||||
continue
|
||||
}
|
||||
|
||||
sub, err := mapYAMLNodes(child)
|
||||
if err != nil {
|
||||
merr = errors.Join(merr, xerrors.Errorf("mapping node %q: %w", key, err))
|
||||
continue
|
||||
}
|
||||
for k, v := range sub {
|
||||
m[key+"."+k] = v
|
||||
}
|
||||
}
|
||||
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func (o *Option) setFromYAMLNode(n *yaml.Node) error {
|
||||
o.ValueSource = ValueSourceYAML
|
||||
if um, ok := o.Value.(yaml.Unmarshaler); ok {
|
||||
return um.UnmarshalYAML(n)
|
||||
}
|
||||
|
||||
switch n.Kind {
|
||||
case yaml.ScalarNode:
|
||||
return o.Value.Set(n.Value)
|
||||
case yaml.SequenceNode:
|
||||
// We treat empty values as nil for consistency with other option
|
||||
// mechanisms.
|
||||
if len(n.Content) == 0 {
|
||||
o.Value = nil
|
||||
return nil
|
||||
}
|
||||
return n.Decode(o.Value)
|
||||
case yaml.MappingNode:
|
||||
return xerrors.Errorf("mapping nodes must implement yaml.Unmarshaler")
|
||||
default:
|
||||
return xerrors.Errorf("unexpected node kind %v", n.Kind)
|
||||
}
|
||||
}
|
||||
|
||||
// UnmarshalYAML converts the given YAML node into the option set.
|
||||
// It is isomorphic with ToYAML.
|
||||
func (optSet *OptionSet) UnmarshalYAML(rootNode *yaml.Node) error {
|
||||
// The rootNode will be a DocumentNode if it's read from a file. We do
|
||||
// not support multiple documents in a single file.
|
||||
if rootNode.Kind == yaml.DocumentNode {
|
||||
if len(rootNode.Content) != 1 {
|
||||
return xerrors.Errorf("expected one node in document, got %d", len(rootNode.Content))
|
||||
}
|
||||
rootNode = rootNode.Content[0]
|
||||
}
|
||||
|
||||
yamlNodes, err := mapYAMLNodes(rootNode)
|
||||
if err != nil {
|
||||
return xerrors.Errorf("mapping nodes: %w", err)
|
||||
}
|
||||
|
||||
matchedNodes := make(map[string]*yaml.Node, len(yamlNodes))
|
||||
|
||||
var merr error
|
||||
for i := range *optSet {
|
||||
opt := &(*optSet)[i]
|
||||
if opt.YAML == "" {
|
||||
continue
|
||||
}
|
||||
var group []string
|
||||
for _, g := range opt.Group.Ancestry() {
|
||||
if g.YAML == "" {
|
||||
return xerrors.Errorf(
|
||||
"group yaml name is empty for %q, groups: %+v",
|
||||
opt.Name,
|
||||
opt.Group,
|
||||
)
|
||||
}
|
||||
group = append(group, g.YAML)
|
||||
delete(yamlNodes, strings.Join(group, "."))
|
||||
}
|
||||
|
||||
key := strings.Join(append(group, opt.YAML), ".")
|
||||
node, ok := yamlNodes[key]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
matchedNodes[key] = node
|
||||
if opt.ValueSource != ValueSourceNone {
|
||||
continue
|
||||
}
|
||||
if err := opt.setFromYAMLNode(node); err != nil {
|
||||
merr = errors.Join(merr, xerrors.Errorf("setting %q: %w", opt.YAML, err))
|
||||
}
|
||||
}
|
||||
|
||||
// Remove all matched nodes and their descendants from yamlNodes so we
|
||||
// can accurately report unknown options.
|
||||
for k := range yamlNodes {
|
||||
var key string
|
||||
for _, part := range strings.Split(k, ".") {
|
||||
if key != "" {
|
||||
key += "."
|
||||
}
|
||||
key += part
|
||||
if _, ok := matchedNodes[key]; ok {
|
||||
delete(yamlNodes, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
for k := range yamlNodes {
|
||||
merr = errors.Join(merr, xerrors.Errorf("unknown option %q", k))
|
||||
}
|
||||
|
||||
return merr
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package clibase_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/pflag"
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/exp/slices"
|
||||
"gopkg.in/yaml.v3"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
)
|
||||
|
||||
func TestOptionSet_YAML(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
t.Run("RequireKey", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
var workspaceName clibase.String
|
||||
os := clibase.OptionSet{
|
||||
clibase.Option{
|
||||
Name: "Workspace Name",
|
||||
Value: &workspaceName,
|
||||
Default: "billie",
|
||||
},
|
||||
}
|
||||
|
||||
node, err := os.MarshalYAML()
|
||||
require.NoError(t, err)
|
||||
require.Len(t, node.(*yaml.Node).Content, 0)
|
||||
})
|
||||
|
||||
t.Run("SimpleString", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var workspaceName clibase.String
|
||||
|
||||
os := clibase.OptionSet{
|
||||
clibase.Option{
|
||||
Name: "Workspace Name",
|
||||
Value: &workspaceName,
|
||||
Default: "billie",
|
||||
Description: "The workspace's name.",
|
||||
Group: &clibase.Group{YAML: "names"},
|
||||
YAML: "workspaceName",
|
||||
},
|
||||
}
|
||||
|
||||
err := os.SetDefaults()
|
||||
require.NoError(t, err)
|
||||
|
||||
n, err := os.MarshalYAML()
|
||||
require.NoError(t, err)
|
||||
// Visually inspect for now.
|
||||
byt, err := yaml.Marshal(n)
|
||||
require.NoError(t, err)
|
||||
t.Logf("Raw YAML:\n%s", string(byt))
|
||||
})
|
||||
}
|
||||
|
||||
func TestOptionSet_YAMLUnknownOptions(t *testing.T) {
|
||||
t.Parallel()
|
||||
os := clibase.OptionSet{
|
||||
{
|
||||
Name: "Workspace Name",
|
||||
Default: "billie",
|
||||
Description: "The workspace's name.",
|
||||
YAML: "workspaceName",
|
||||
Value: new(clibase.String),
|
||||
},
|
||||
}
|
||||
|
||||
const yamlDoc = `something: else`
|
||||
err := yaml.Unmarshal([]byte(yamlDoc), &os)
|
||||
require.Error(t, err)
|
||||
require.Empty(t, os[0].Value.String())
|
||||
|
||||
os[0].YAML = "something"
|
||||
|
||||
err = yaml.Unmarshal([]byte(yamlDoc), &os)
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Equal(t, "else", os[0].Value.String())
|
||||
}
|
||||
|
||||
// TestOptionSet_YAMLIsomorphism tests that the YAML representations of an
|
||||
// OptionSet converts to the same OptionSet when read back in.
|
||||
func TestOptionSet_YAMLIsomorphism(t *testing.T) {
|
||||
t.Parallel()
|
||||
// This is used to form a generic.
|
||||
//nolint:unused
|
||||
type kid struct {
|
||||
Name string `yaml:"name"`
|
||||
Age int `yaml:"age"`
|
||||
}
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
os clibase.OptionSet
|
||||
zeroValue func() pflag.Value
|
||||
}{
|
||||
{
|
||||
name: "SimpleString",
|
||||
os: clibase.OptionSet{
|
||||
{
|
||||
Name: "Workspace Name",
|
||||
Default: "billie",
|
||||
Description: "The workspace's name.",
|
||||
Group: &clibase.Group{YAML: "names"},
|
||||
YAML: "workspaceName",
|
||||
},
|
||||
},
|
||||
zeroValue: func() pflag.Value {
|
||||
return clibase.StringOf(new(string))
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Array",
|
||||
os: clibase.OptionSet{
|
||||
{
|
||||
YAML: "names",
|
||||
Default: "jill,jack,joan",
|
||||
},
|
||||
},
|
||||
zeroValue: func() pflag.Value {
|
||||
return clibase.StringArrayOf(&[]string{})
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "ComplexObject",
|
||||
os: clibase.OptionSet{
|
||||
{
|
||||
YAML: "kids",
|
||||
Default: `- name: jill
|
||||
age: 12
|
||||
- name: jack
|
||||
age: 13`,
|
||||
},
|
||||
},
|
||||
zeroValue: func() pflag.Value {
|
||||
return &clibase.Struct[[]kid]{}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "DeepGroup",
|
||||
os: clibase.OptionSet{
|
||||
{
|
||||
YAML: "names",
|
||||
Default: "jill,jack,joan",
|
||||
Group: &clibase.Group{YAML: "kids", Parent: &clibase.Group{YAML: "family"}},
|
||||
},
|
||||
},
|
||||
zeroValue: func() pflag.Value {
|
||||
return clibase.StringArrayOf(&[]string{})
|
||||
},
|
||||
},
|
||||
} {
|
||||
tc := tc
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
// Set initial values.
|
||||
for i := range tc.os {
|
||||
tc.os[i].Value = tc.zeroValue()
|
||||
}
|
||||
err := tc.os.SetDefaults()
|
||||
require.NoError(t, err)
|
||||
|
||||
y, err := tc.os.MarshalYAML()
|
||||
require.NoError(t, err)
|
||||
|
||||
toByt, err := yaml.Marshal(y)
|
||||
require.NoError(t, err)
|
||||
|
||||
t.Logf("Raw YAML:\n%s", string(toByt))
|
||||
|
||||
var y2 yaml.Node
|
||||
err = yaml.Unmarshal(toByt, &y2)
|
||||
require.NoError(t, err)
|
||||
|
||||
os2 := slices.Clone(tc.os)
|
||||
for i := range os2 {
|
||||
os2[i].Value = tc.zeroValue()
|
||||
os2[i].ValueSource = clibase.ValueSourceNone
|
||||
}
|
||||
|
||||
// os2 values should be zeroed whereas tc.os should be
|
||||
// set to defaults.
|
||||
// This check makes sure we aren't mixing pointers.
|
||||
require.NotEqual(t, tc.os, os2)
|
||||
err = os2.UnmarshalYAML(&y2)
|
||||
require.NoError(t, err)
|
||||
|
||||
want := tc.os
|
||||
for i := range want {
|
||||
want[i].ValueSource = clibase.ValueSourceYAML
|
||||
}
|
||||
|
||||
require.Equal(t, tc.os, os2)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -14,9 +14,9 @@ import (
|
||||
"cdr.dev/slog/sloggers/sloghuman"
|
||||
"cdr.dev/slog/sloggers/slogjson"
|
||||
"cdr.dev/slog/sloggers/slogstackdriver"
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/coderd/tracing"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
type (
|
||||
@@ -86,7 +86,7 @@ func FromDeploymentValues(vals *codersdk.DeploymentValues) Option {
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Builder) Build(inv *serpent.Invocation) (log slog.Logger, closeLog func(), err error) {
|
||||
func (b *Builder) Build(inv *clibase.Invocation) (log slog.Logger, closeLog func(), err error) {
|
||||
var (
|
||||
sinks = []slog.Sink{}
|
||||
closers = []func() error{}
|
||||
|
||||
+14
-14
@@ -8,10 +8,10 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/cli/clilog"
|
||||
"github.com/coder/coder/v2/coderd/coderdtest"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/serpent"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
@@ -23,7 +23,7 @@ func TestBuilder(t *testing.T) {
|
||||
t.Run("NoConfiguration", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cmd := &serpent.Command{
|
||||
cmd := &clibase.Cmd{
|
||||
Use: "test",
|
||||
Handler: testHandler(t),
|
||||
}
|
||||
@@ -35,7 +35,7 @@ func TestBuilder(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tempFile := filepath.Join(t.TempDir(), "test.log")
|
||||
cmd := &serpent.Command{
|
||||
cmd := &clibase.Cmd{
|
||||
Use: "test",
|
||||
Handler: testHandler(t,
|
||||
clilog.WithHuman(tempFile),
|
||||
@@ -51,7 +51,7 @@ func TestBuilder(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tempFile := filepath.Join(t.TempDir(), "test.log")
|
||||
cmd := &serpent.Command{
|
||||
cmd := &clibase.Cmd{
|
||||
Use: "test",
|
||||
Handler: testHandler(t,
|
||||
clilog.WithHuman(tempFile),
|
||||
@@ -68,7 +68,7 @@ func TestBuilder(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tempFile := filepath.Join(t.TempDir(), "test.log")
|
||||
cmd := &serpent.Command{
|
||||
cmd := &clibase.Cmd{
|
||||
Use: "test",
|
||||
Handler: testHandler(t, clilog.WithHuman(tempFile)),
|
||||
}
|
||||
@@ -81,7 +81,7 @@ func TestBuilder(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tempFile := filepath.Join(t.TempDir(), "test.log")
|
||||
cmd := &serpent.Command{
|
||||
cmd := &clibase.Cmd{
|
||||
Use: "test",
|
||||
Handler: testHandler(t, clilog.WithJSON(tempFile), clilog.WithVerbose()),
|
||||
}
|
||||
@@ -107,7 +107,7 @@ func TestBuilder(t *testing.T) {
|
||||
|
||||
// Use the default deployment values.
|
||||
dv := coderdtest.DeploymentValues(t)
|
||||
cmd := &serpent.Command{
|
||||
cmd := &clibase.Cmd{
|
||||
Use: "test",
|
||||
Handler: testHandler(t, clilog.FromDeploymentValues(dv)),
|
||||
}
|
||||
@@ -127,15 +127,15 @@ func TestBuilder(t *testing.T) {
|
||||
dv := &codersdk.DeploymentValues{
|
||||
Logging: codersdk.LoggingConfig{
|
||||
Filter: []string{"foo", "baz"},
|
||||
Human: serpent.String(tempFile),
|
||||
JSON: serpent.String(tempJSON),
|
||||
Human: clibase.String(tempFile),
|
||||
JSON: clibase.String(tempJSON),
|
||||
},
|
||||
Verbose: true,
|
||||
Trace: codersdk.TraceConfig{
|
||||
Enable: true,
|
||||
},
|
||||
}
|
||||
cmd := &serpent.Command{
|
||||
cmd := &clibase.Cmd{
|
||||
Use: "test",
|
||||
Handler: testHandler(t, clilog.FromDeploymentValues(dv)),
|
||||
}
|
||||
@@ -150,9 +150,9 @@ func TestBuilder(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tempFile := filepath.Join(t.TempDir(), "doesnotexist", "test.log")
|
||||
cmd := &serpent.Command{
|
||||
cmd := &clibase.Cmd{
|
||||
Use: "test",
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
logger, closeLog, err := clilog.New(
|
||||
clilog.WithFilter("foo", "baz"),
|
||||
clilog.WithHuman(tempFile),
|
||||
@@ -181,10 +181,10 @@ var (
|
||||
filterLog = "this is an important debug message you want to see"
|
||||
)
|
||||
|
||||
func testHandler(t testing.TB, opts ...clilog.Option) serpent.HandlerFunc {
|
||||
func testHandler(t testing.TB, opts ...clilog.Option) clibase.HandlerFunc {
|
||||
t.Helper()
|
||||
|
||||
return func(inv *serpent.Invocation) error {
|
||||
return func(inv *clibase.Invocation) error {
|
||||
logger, closeLog, err := clilog.New(opts...).Build(inv)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -20,16 +20,16 @@ import (
|
||||
"cdr.dev/slog"
|
||||
"cdr.dev/slog/sloggers/slogtest"
|
||||
"github.com/coder/coder/v2/cli"
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/cli/config"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/coder/v2/provisioner/echo"
|
||||
"github.com/coder/coder/v2/testutil"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
// New creates a CLI instance with a configuration pointed to a
|
||||
// temporary testing directory.
|
||||
func New(t testing.TB, args ...string) (*serpent.Invocation, config.Root) {
|
||||
func New(t testing.TB, args ...string) (*clibase.Invocation, config.Root) {
|
||||
var root cli.RootCmd
|
||||
|
||||
cmd, err := root.Command(root.AGPL())
|
||||
@@ -56,15 +56,15 @@ func (l *logWriter) Write(p []byte) (n int, err error) {
|
||||
}
|
||||
|
||||
func NewWithCommand(
|
||||
t testing.TB, cmd *serpent.Command, args ...string,
|
||||
) (*serpent.Invocation, config.Root) {
|
||||
t testing.TB, cmd *clibase.Cmd, args ...string,
|
||||
) (*clibase.Invocation, config.Root) {
|
||||
configDir := config.Root(t.TempDir())
|
||||
// I really would like to fail test on error logs, but realistically, turning on by default
|
||||
// in all our CLI tests is going to create a lot of flaky noise.
|
||||
logger := slogtest.Make(t, &slogtest.Options{IgnoreErrors: true}).
|
||||
Leveled(slog.LevelDebug).
|
||||
Named("cli")
|
||||
i := &serpent.Invocation{
|
||||
i := &clibase.Invocation{
|
||||
Command: cmd,
|
||||
Args: append([]string{"--global-config", string(configDir)}, args...),
|
||||
Stdin: io.LimitReader(nil, 0),
|
||||
@@ -140,11 +140,11 @@ func extractTar(t *testing.T, data []byte, directory string) {
|
||||
|
||||
// Start runs the command in a goroutine and cleans it up when the test
|
||||
// completed.
|
||||
func Start(t *testing.T, inv *serpent.Invocation) {
|
||||
func Start(t *testing.T, inv *clibase.Invocation) {
|
||||
StartWithAssert(t, inv, nil)
|
||||
}
|
||||
|
||||
func StartWithAssert(t *testing.T, inv *serpent.Invocation, assertCallback func(t *testing.T, err error)) { //nolint:revive
|
||||
func StartWithAssert(t *testing.T, inv *clibase.Invocation, assertCallback func(t *testing.T, err error)) { //nolint:revive
|
||||
t.Helper()
|
||||
|
||||
closeCh := make(chan struct{})
|
||||
@@ -175,7 +175,7 @@ func StartWithAssert(t *testing.T, inv *serpent.Invocation, assertCallback func(
|
||||
}
|
||||
|
||||
// Run runs the command and asserts that there is no error.
|
||||
func Run(t *testing.T, inv *serpent.Invocation) {
|
||||
func Run(t *testing.T, inv *clibase.Invocation) {
|
||||
t.Helper()
|
||||
|
||||
err := inv.Run()
|
||||
@@ -228,7 +228,7 @@ func (w *ErrorWaiter) RequireAs(want interface{}) {
|
||||
|
||||
// StartWithWaiter runs the command in a goroutine but returns the error instead
|
||||
// of asserting it. This is useful for testing error cases.
|
||||
func StartWithWaiter(t *testing.T, inv *serpent.Invocation) *ErrorWaiter {
|
||||
func StartWithWaiter(t *testing.T, inv *clibase.Invocation) *ErrorWaiter {
|
||||
t.Helper()
|
||||
|
||||
var (
|
||||
|
||||
+31
-36
@@ -13,12 +13,12 @@ import (
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/cli/config"
|
||||
"github.com/coder/coder/v2/coderd/coderdtest"
|
||||
"github.com/coder/coder/v2/coderd/database/dbtestutil"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/coder/v2/testutil"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
// UpdateGoldenFiles indicates golden files should be updated.
|
||||
@@ -48,7 +48,7 @@ func DefaultCases() []CommandHelpCase {
|
||||
|
||||
// TestCommandHelp will test the help output of the given commands
|
||||
// using golden files.
|
||||
func TestCommandHelp(t *testing.T, getRoot func(t *testing.T) *serpent.Command, cases []CommandHelpCase) {
|
||||
func TestCommandHelp(t *testing.T, getRoot func(t *testing.T) *clibase.Cmd, cases []CommandHelpCase) {
|
||||
t.Parallel()
|
||||
rootClient, replacements := prepareTestData(t)
|
||||
|
||||
@@ -87,45 +87,40 @@ ExtractCommandPathsLoop:
|
||||
|
||||
StartWithWaiter(t, inv.WithContext(ctx)).RequireSuccess()
|
||||
|
||||
TestGoldenFile(t, tt.Name, outBuf.Bytes(), replacements)
|
||||
actual := outBuf.Bytes()
|
||||
if len(actual) == 0 {
|
||||
t.Fatal("no output")
|
||||
}
|
||||
|
||||
for k, v := range replacements {
|
||||
actual = bytes.ReplaceAll(actual, []byte(k), []byte(v))
|
||||
}
|
||||
|
||||
actual = NormalizeGoldenFile(t, actual)
|
||||
goldenPath := filepath.Join("testdata", strings.Replace(tt.Name, " ", "_", -1)+".golden")
|
||||
if *UpdateGoldenFiles {
|
||||
t.Logf("update golden file for: %q: %s", tt.Name, goldenPath)
|
||||
err := os.WriteFile(goldenPath, actual, 0o600)
|
||||
require.NoError(t, err, "update golden file")
|
||||
}
|
||||
|
||||
expected, err := os.ReadFile(goldenPath)
|
||||
require.NoError(t, err, "read golden file, run \"make update-golden-files\" and commit the changes")
|
||||
|
||||
expected = NormalizeGoldenFile(t, expected)
|
||||
require.Equal(
|
||||
t, string(expected), string(actual),
|
||||
"golden file mismatch: %s, run \"make update-golden-files\", verify and commit the changes",
|
||||
goldenPath,
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestGoldenFile will test the given bytes slice input against the
|
||||
// golden file with the given file name, optionally using the given replacements.
|
||||
func TestGoldenFile(t *testing.T, fileName string, actual []byte, replacements map[string]string) {
|
||||
if len(actual) == 0 {
|
||||
t.Fatal("no output")
|
||||
}
|
||||
|
||||
for k, v := range replacements {
|
||||
actual = bytes.ReplaceAll(actual, []byte(k), []byte(v))
|
||||
}
|
||||
|
||||
actual = normalizeGoldenFile(t, actual)
|
||||
goldenPath := filepath.Join("testdata", strings.ReplaceAll(fileName, " ", "_")+".golden")
|
||||
if *UpdateGoldenFiles {
|
||||
t.Logf("update golden file for: %q: %s", fileName, goldenPath)
|
||||
err := os.WriteFile(goldenPath, actual, 0o600)
|
||||
require.NoError(t, err, "update golden file")
|
||||
}
|
||||
|
||||
expected, err := os.ReadFile(goldenPath)
|
||||
require.NoError(t, err, "read golden file, run \"make update-golden-files\" and commit the changes")
|
||||
|
||||
expected = normalizeGoldenFile(t, expected)
|
||||
require.Equal(
|
||||
t, string(expected), string(actual),
|
||||
"golden file mismatch: %s, run \"make update-golden-files\", verify and commit the changes",
|
||||
goldenPath,
|
||||
)
|
||||
}
|
||||
|
||||
// normalizeGoldenFile replaces any strings that are system or timing dependent
|
||||
// NormalizeGoldenFile replaces any strings that are system or timing dependent
|
||||
// with a placeholder so that the golden files can be compared with a simple
|
||||
// equality check.
|
||||
func normalizeGoldenFile(t *testing.T, byt []byte) []byte {
|
||||
func NormalizeGoldenFile(t *testing.T, byt []byte) []byte {
|
||||
// Replace any timestamps with a placeholder.
|
||||
byt = timestampRegex.ReplaceAll(byt, []byte("[timestamp]"))
|
||||
|
||||
@@ -153,7 +148,7 @@ func normalizeGoldenFile(t *testing.T, byt []byte) []byte {
|
||||
return byt
|
||||
}
|
||||
|
||||
func extractVisibleCommandPaths(cmdPath []string, cmds []*serpent.Command) [][]string {
|
||||
func extractVisibleCommandPaths(cmdPath []string, cmds []*clibase.Cmd) [][]string {
|
||||
var cmdPaths [][]string
|
||||
for _, c := range cmds {
|
||||
if c.Hidden {
|
||||
|
||||
@@ -3,7 +3,7 @@ package clitest
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/coder/serpent"
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
)
|
||||
|
||||
// HandlersOK asserts that all commands have a handler.
|
||||
@@ -11,11 +11,11 @@ import (
|
||||
// non-root commands (like 'groups' or 'users'), a handler is required.
|
||||
// These handlers are likely just the 'help' handler, but this must be
|
||||
// explicitly set.
|
||||
func HandlersOK(t *testing.T, cmd *serpent.Command) {
|
||||
cmd.Walk(func(cmd *serpent.Command) {
|
||||
func HandlersOK(t *testing.T, cmd *clibase.Cmd) {
|
||||
cmd.Walk(func(cmd *clibase.Cmd) {
|
||||
if cmd.Handler == nil {
|
||||
// If you see this error, make the Handler a helper invoker.
|
||||
// Handler: func(inv *serpent.Invocation) error {
|
||||
// Handler: func(inv *clibase.Invocation) error {
|
||||
// return inv.Command.HelpHandler(inv)
|
||||
// },
|
||||
t.Errorf("command %q has no handler, change to a helper invoker using: 'inv.Command.HelpHandler(inv)'", cmd.Name())
|
||||
|
||||
+3
-3
@@ -212,13 +212,13 @@ func Agent(ctx context.Context, writer io.Writer, agentID uuid.UUID, opts AgentO
|
||||
sw.Fail(stage, safeDuration(sw, agent.ReadyAt, agent.StartedAt))
|
||||
// Use zero time (omitted) to separate these from the startup logs.
|
||||
sw.Log(time.Time{}, codersdk.LogLevelWarn, "Warning: A startup script exited with an error and your workspace may be incomplete.")
|
||||
sw.Log(time.Time{}, codersdk.LogLevelWarn, troubleshootingMessage(agent, "https://coder.com/docs/v2/latest/templates/troubleshooting#startup-script-exited-with-an-error"))
|
||||
sw.Log(time.Time{}, codersdk.LogLevelWarn, troubleshootingMessage(agent, "https://coder.com/docs/v2/latest/templates#startup-script-exited-with-an-error"))
|
||||
default:
|
||||
switch {
|
||||
case agent.LifecycleState.Starting():
|
||||
// Use zero time (omitted) to separate these from the startup logs.
|
||||
sw.Log(time.Time{}, codersdk.LogLevelWarn, "Notice: The startup scripts are still running and your workspace may be incomplete.")
|
||||
sw.Log(time.Time{}, codersdk.LogLevelWarn, troubleshootingMessage(agent, "https://coder.com/docs/v2/latest/templates/troubleshooting#your-workspace-may-be-incomplete"))
|
||||
sw.Log(time.Time{}, codersdk.LogLevelWarn, troubleshootingMessage(agent, "https://coder.com/docs/v2/latest/templates#your-workspace-may-be-incomplete"))
|
||||
// Note: We don't complete or fail the stage here, it's
|
||||
// intentionally left open to indicate this stage didn't
|
||||
// complete.
|
||||
@@ -240,7 +240,7 @@ func Agent(ctx context.Context, writer io.Writer, agentID uuid.UUID, opts AgentO
|
||||
stage := "The workspace agent lost connection"
|
||||
sw.Start(stage)
|
||||
sw.Log(time.Now(), codersdk.LogLevelWarn, "Wait for it to reconnect or restart your workspace.")
|
||||
sw.Log(time.Now(), codersdk.LogLevelWarn, troubleshootingMessage(agent, "https://coder.com/docs/v2/latest/templates/troubleshooting#agent-connection-issues"))
|
||||
sw.Log(time.Now(), codersdk.LogLevelWarn, troubleshootingMessage(agent, "https://coder.com/docs/v2/latest/templates#agent-connection-issues"))
|
||||
|
||||
disconnectedAt := agent.DisconnectedAt
|
||||
for agent.Status == codersdk.WorkspaceAgentDisconnected {
|
||||
|
||||
@@ -18,13 +18,13 @@ import (
|
||||
"golang.org/x/xerrors"
|
||||
"tailscale.com/tailcfg"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/cli/clitest"
|
||||
"github.com/coder/coder/v2/cli/cliui"
|
||||
"github.com/coder/coder/v2/coderd/util/ptr"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/coder/v2/tailnet"
|
||||
"github.com/coder/coder/v2/testutil"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
func TestAgent(t *testing.T) {
|
||||
@@ -382,8 +382,8 @@ func TestAgent(t *testing.T) {
|
||||
output := make(chan string, 100) // Buffered to avoid blocking, overflow is discarded.
|
||||
logs := make(chan []codersdk.WorkspaceAgentLog, 1)
|
||||
|
||||
cmd := &serpent.Command{
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
cmd := &clibase.Cmd{
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
tc.opts.Fetch = func(_ context.Context, _ uuid.UUID) (codersdk.WorkspaceAgent, error) {
|
||||
t.Log("iter", len(tc.iter))
|
||||
var err error
|
||||
@@ -450,8 +450,8 @@ func TestAgent(t *testing.T) {
|
||||
t.Parallel()
|
||||
var fetchCalled uint64
|
||||
|
||||
cmd := &serpent.Command{
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
cmd := &clibase.Cmd{
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
buf := bytes.Buffer{}
|
||||
err := cliui.Agent(inv.Context(), &buf, uuid.Nil, cliui.AgentOptions{
|
||||
FetchInterval: 10 * time.Millisecond,
|
||||
|
||||
@@ -3,13 +3,13 @@ package cliui
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/pretty"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
func DeprecationWarning(message string) serpent.MiddlewareFunc {
|
||||
return func(next serpent.HandlerFunc) serpent.HandlerFunc {
|
||||
return func(i *serpent.Invocation) error {
|
||||
func DeprecationWarning(message string) clibase.MiddlewareFunc {
|
||||
return func(next clibase.HandlerFunc) clibase.HandlerFunc {
|
||||
return func(i *clibase.Invocation) error {
|
||||
_, _ = fmt.Fprintln(i.Stdout, "\n"+pretty.Sprint(DefaultStyles.Wrap,
|
||||
pretty.Sprint(
|
||||
DefaultStyles.Warn,
|
||||
|
||||
@@ -37,9 +37,6 @@ func ExternalAuth(ctx context.Context, writer io.Writer, opts ExternalAuthOption
|
||||
if auth.Authenticated {
|
||||
return nil
|
||||
}
|
||||
if auth.Optional {
|
||||
continue
|
||||
}
|
||||
|
||||
_, _ = fmt.Fprintf(writer, "You must authenticate with %s to create a workspace with this template. Visit:\n\n\t%s\n\n", auth.DisplayName, auth.AuthenticateURL)
|
||||
|
||||
|
||||
@@ -8,11 +8,11 @@ import (
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/cli/cliui"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/coder/v2/pty/ptytest"
|
||||
"github.com/coder/coder/v2/testutil"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
func TestExternalAuth(t *testing.T) {
|
||||
@@ -22,8 +22,8 @@ func TestExternalAuth(t *testing.T) {
|
||||
defer cancel()
|
||||
|
||||
ptty := ptytest.New(t)
|
||||
cmd := &serpent.Command{
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
cmd := &clibase.Cmd{
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
var fetched atomic.Bool
|
||||
return cliui.ExternalAuth(inv.Context(), inv.Stdout, cliui.ExternalAuthOptions{
|
||||
Fetch: func(ctx context.Context) ([]codersdk.TemplateVersionExternalAuth, error) {
|
||||
|
||||
+8
-8
@@ -1,8 +1,8 @@
|
||||
package cliui
|
||||
|
||||
import (
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
var defaultQuery = "owner:me"
|
||||
@@ -11,12 +11,12 @@ var defaultQuery = "owner:me"
|
||||
// and allows easy integration to a CLI command.
|
||||
// Example usage:
|
||||
//
|
||||
// func (r *RootCmd) MyCmd() *serpent.Command {
|
||||
// func (r *RootCmd) MyCmd() *clibase.Cmd {
|
||||
// var (
|
||||
// filter cliui.WorkspaceFilter
|
||||
// ...
|
||||
// )
|
||||
// cmd := &serpent.Command{
|
||||
// cmd := &clibase.Cmd{
|
||||
// ...
|
||||
// }
|
||||
// filter.AttachOptions(&cmd.Options)
|
||||
@@ -44,20 +44,20 @@ func (w *WorkspaceFilter) Filter() codersdk.WorkspaceFilter {
|
||||
return f
|
||||
}
|
||||
|
||||
func (w *WorkspaceFilter) AttachOptions(opts *serpent.OptionSet) {
|
||||
func (w *WorkspaceFilter) AttachOptions(opts *clibase.OptionSet) {
|
||||
*opts = append(*opts,
|
||||
serpent.Option{
|
||||
clibase.Option{
|
||||
Flag: "all",
|
||||
FlagShorthand: "a",
|
||||
Description: "Specifies whether all workspaces will be listed or not.",
|
||||
|
||||
Value: serpent.BoolOf(&w.all),
|
||||
Value: clibase.BoolOf(&w.all),
|
||||
},
|
||||
serpent.Option{
|
||||
clibase.Option{
|
||||
Flag: "search",
|
||||
Description: "Search for a workspace with a query.",
|
||||
Default: defaultQuery,
|
||||
Value: serpent.StringOf(&w.searchQuery),
|
||||
Value: clibase.StringOf(&w.searchQuery),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
+11
-11
@@ -9,12 +9,12 @@ import (
|
||||
|
||||
"golang.org/x/xerrors"
|
||||
|
||||
"github.com/coder/serpent"
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
)
|
||||
|
||||
type OutputFormat interface {
|
||||
ID() string
|
||||
AttachOptions(opts *serpent.OptionSet)
|
||||
AttachOptions(opts *clibase.OptionSet)
|
||||
Format(ctx context.Context, data any) (string, error)
|
||||
}
|
||||
|
||||
@@ -49,7 +49,7 @@ func NewOutputFormatter(formats ...OutputFormat) *OutputFormatter {
|
||||
|
||||
// AttachOptions attaches the --output flag to the given command, and any
|
||||
// additional flags required by the output formatters.
|
||||
func (f *OutputFormatter) AttachOptions(opts *serpent.OptionSet) {
|
||||
func (f *OutputFormatter) AttachOptions(opts *clibase.OptionSet) {
|
||||
for _, format := range f.formats {
|
||||
format.AttachOptions(opts)
|
||||
}
|
||||
@@ -60,11 +60,11 @@ func (f *OutputFormatter) AttachOptions(opts *serpent.OptionSet) {
|
||||
}
|
||||
|
||||
*opts = append(*opts,
|
||||
serpent.Option{
|
||||
clibase.Option{
|
||||
Flag: "output",
|
||||
FlagShorthand: "o",
|
||||
Default: f.formats[0].ID(),
|
||||
Value: serpent.StringOf(&f.formatID),
|
||||
Value: clibase.StringOf(&f.formatID),
|
||||
Description: "Output format. Available formats: " + strings.Join(formatNames, ", ") + ".",
|
||||
},
|
||||
)
|
||||
@@ -129,13 +129,13 @@ func (*tableFormat) ID() string {
|
||||
}
|
||||
|
||||
// AttachOptions implements OutputFormat.
|
||||
func (f *tableFormat) AttachOptions(opts *serpent.OptionSet) {
|
||||
func (f *tableFormat) AttachOptions(opts *clibase.OptionSet) {
|
||||
*opts = append(*opts,
|
||||
serpent.Option{
|
||||
clibase.Option{
|
||||
Flag: "column",
|
||||
FlagShorthand: "c",
|
||||
Default: strings.Join(f.defaultColumns, ","),
|
||||
Value: serpent.StringArrayOf(&f.columns),
|
||||
Value: clibase.StringArrayOf(&f.columns),
|
||||
Description: "Columns to display in table output. Available columns: " + strings.Join(f.allColumns, ", ") + ".",
|
||||
},
|
||||
)
|
||||
@@ -161,7 +161,7 @@ func (jsonFormat) ID() string {
|
||||
}
|
||||
|
||||
// AttachOptions implements OutputFormat.
|
||||
func (jsonFormat) AttachOptions(_ *serpent.OptionSet) {}
|
||||
func (jsonFormat) AttachOptions(_ *clibase.OptionSet) {}
|
||||
|
||||
// Format implements OutputFormat.
|
||||
func (jsonFormat) Format(_ context.Context, data any) (string, error) {
|
||||
@@ -187,7 +187,7 @@ func (textFormat) ID() string {
|
||||
return "text"
|
||||
}
|
||||
|
||||
func (textFormat) AttachOptions(_ *serpent.OptionSet) {}
|
||||
func (textFormat) AttachOptions(_ *clibase.OptionSet) {}
|
||||
|
||||
func (textFormat) Format(_ context.Context, data any) (string, error) {
|
||||
return fmt.Sprintf("%s", data), nil
|
||||
@@ -213,7 +213,7 @@ func (d *DataChangeFormat) ID() string {
|
||||
return d.format.ID()
|
||||
}
|
||||
|
||||
func (d *DataChangeFormat) AttachOptions(opts *serpent.OptionSet) {
|
||||
func (d *DataChangeFormat) AttachOptions(opts *clibase.OptionSet) {
|
||||
d.format.AttachOptions(opts)
|
||||
}
|
||||
|
||||
|
||||
@@ -8,13 +8,13 @@ import (
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/cli/cliui"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
type format struct {
|
||||
id string
|
||||
attachOptionsFn func(opts *serpent.OptionSet)
|
||||
attachOptionsFn func(opts *clibase.OptionSet)
|
||||
formatFn func(ctx context.Context, data any) (string, error)
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ func (f *format) ID() string {
|
||||
return f.id
|
||||
}
|
||||
|
||||
func (f *format) AttachOptions(opts *serpent.OptionSet) {
|
||||
func (f *format) AttachOptions(opts *clibase.OptionSet) {
|
||||
if f.attachOptionsFn != nil {
|
||||
f.attachOptionsFn(opts)
|
||||
}
|
||||
@@ -85,12 +85,12 @@ func Test_OutputFormatter(t *testing.T) {
|
||||
cliui.JSONFormat(),
|
||||
&format{
|
||||
id: "foo",
|
||||
attachOptionsFn: func(opts *serpent.OptionSet) {
|
||||
opts.Add(serpent.Option{
|
||||
attachOptionsFn: func(opts *clibase.OptionSet) {
|
||||
opts.Add(clibase.Option{
|
||||
Name: "foo",
|
||||
Flag: "foo",
|
||||
FlagShorthand: "f",
|
||||
Value: serpent.DiscardValue,
|
||||
Value: clibase.DiscardValue,
|
||||
Description: "foo flag 1234",
|
||||
})
|
||||
},
|
||||
@@ -101,7 +101,7 @@ func Test_OutputFormatter(t *testing.T) {
|
||||
},
|
||||
)
|
||||
|
||||
cmd := &serpent.Command{}
|
||||
cmd := &clibase.Cmd{}
|
||||
f.AttachOptions(&cmd.Options)
|
||||
|
||||
fs := cmd.Options.FlagSet()
|
||||
|
||||
+5
-10
@@ -5,12 +5,12 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/pretty"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
func RichParameter(inv *serpent.Invocation, templateVersionParameter codersdk.TemplateVersionParameter, defaultOverrides map[string]string) (string, error) {
|
||||
func RichParameter(inv *clibase.Invocation, templateVersionParameter codersdk.TemplateVersionParameter) (string, error) {
|
||||
label := templateVersionParameter.Name
|
||||
if templateVersionParameter.DisplayName != "" {
|
||||
label = templateVersionParameter.DisplayName
|
||||
@@ -26,11 +26,6 @@ func RichParameter(inv *serpent.Invocation, templateVersionParameter codersdk.Te
|
||||
_, _ = fmt.Fprintln(inv.Stdout, " "+strings.TrimSpace(strings.Join(strings.Split(templateVersionParameter.DescriptionPlaintext, "\n"), "\n "))+"\n")
|
||||
}
|
||||
|
||||
defaultValue := templateVersionParameter.DefaultValue
|
||||
if v, ok := defaultOverrides[templateVersionParameter.Name]; ok {
|
||||
defaultValue = v
|
||||
}
|
||||
|
||||
var err error
|
||||
var value string
|
||||
if templateVersionParameter.Type == "list(string)" {
|
||||
@@ -63,7 +58,7 @@ func RichParameter(inv *serpent.Invocation, templateVersionParameter codersdk.Te
|
||||
var richParameterOption *codersdk.TemplateVersionParameterOption
|
||||
richParameterOption, err = RichSelect(inv, RichSelectOptions{
|
||||
Options: templateVersionParameter.Options,
|
||||
Default: defaultValue,
|
||||
Default: templateVersionParameter.DefaultValue,
|
||||
HideSearch: true,
|
||||
})
|
||||
if err == nil {
|
||||
@@ -74,7 +69,7 @@ func RichParameter(inv *serpent.Invocation, templateVersionParameter codersdk.Te
|
||||
} else {
|
||||
text := "Enter a value"
|
||||
if !templateVersionParameter.Required {
|
||||
text += fmt.Sprintf(" (default: %q)", defaultValue)
|
||||
text += fmt.Sprintf(" (default: %q)", templateVersionParameter.DefaultValue)
|
||||
}
|
||||
text += ":"
|
||||
|
||||
@@ -92,7 +87,7 @@ func RichParameter(inv *serpent.Invocation, templateVersionParameter codersdk.Te
|
||||
|
||||
// If they didn't specify anything, use the default value if set.
|
||||
if len(templateVersionParameter.Options) == 0 && value == "" {
|
||||
value = defaultValue
|
||||
value = templateVersionParameter.DefaultValue
|
||||
}
|
||||
|
||||
return value, nil
|
||||
|
||||
+5
-5
@@ -13,8 +13,8 @@ import (
|
||||
"github.com/mattn/go-isatty"
|
||||
"golang.org/x/xerrors"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/pretty"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
// PromptOptions supply a set of options to the prompt.
|
||||
@@ -30,13 +30,13 @@ const skipPromptFlag = "yes"
|
||||
|
||||
// SkipPromptOption adds a "--yes/-y" flag to the cmd that can be used to skip
|
||||
// prompts.
|
||||
func SkipPromptOption() serpent.Option {
|
||||
return serpent.Option{
|
||||
func SkipPromptOption() clibase.Option {
|
||||
return clibase.Option{
|
||||
Flag: skipPromptFlag,
|
||||
FlagShorthand: "y",
|
||||
Description: "Bypass prompts.",
|
||||
// Discard
|
||||
Value: serpent.BoolOf(new(bool)),
|
||||
Value: clibase.BoolOf(new(bool)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ const (
|
||||
)
|
||||
|
||||
// Prompt asks the user for input.
|
||||
func Prompt(inv *serpent.Invocation, opts PromptOptions) (string, error) {
|
||||
func Prompt(inv *clibase.Invocation, opts PromptOptions) (string, error) {
|
||||
// If the cmd has a "yes" flag for skipping confirm prompts, honor it.
|
||||
// If it's not a "Confirm" prompt, then don't skip. As the default value of
|
||||
// "yes" makes no sense.
|
||||
|
||||
@@ -11,11 +11,11 @@ import (
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/cli/cliui"
|
||||
"github.com/coder/coder/v2/pty"
|
||||
"github.com/coder/coder/v2/pty/ptytest"
|
||||
"github.com/coder/coder/v2/testutil"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
func TestPrompt(t *testing.T) {
|
||||
@@ -77,7 +77,7 @@ func TestPrompt(t *testing.T) {
|
||||
resp, err := newPrompt(ptty, cliui.PromptOptions{
|
||||
Text: "ShouldNotSeeThis",
|
||||
IsConfirm: true,
|
||||
}, func(inv *serpent.Invocation) {
|
||||
}, func(inv *clibase.Invocation) {
|
||||
inv.Command.Options = append(inv.Command.Options, cliui.SkipPromptOption())
|
||||
inv.Args = []string{"-y"}
|
||||
})
|
||||
@@ -145,10 +145,10 @@ func TestPrompt(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func newPrompt(ptty *ptytest.PTY, opts cliui.PromptOptions, invOpt func(inv *serpent.Invocation)) (string, error) {
|
||||
func newPrompt(ptty *ptytest.PTY, opts cliui.PromptOptions, invOpt func(inv *clibase.Invocation)) (string, error) {
|
||||
value := ""
|
||||
cmd := &serpent.Command{
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
cmd := &clibase.Cmd{
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
var err error
|
||||
value, err = cliui.Prompt(inv, opts)
|
||||
return err
|
||||
@@ -210,8 +210,8 @@ func TestPasswordTerminalState(t *testing.T) {
|
||||
|
||||
// nolint:unused
|
||||
func passwordHelper() {
|
||||
cmd := &serpent.Command{
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
cmd := &clibase.Cmd{
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
cliui.Prompt(inv, cliui.PromptOptions{
|
||||
Text: "Password:",
|
||||
Secret: true,
|
||||
|
||||
@@ -54,11 +54,6 @@ func (err *ProvisionerJobError) Error() string {
|
||||
return err.Message
|
||||
}
|
||||
|
||||
const (
|
||||
ProvisioningStateQueued = "Queued"
|
||||
ProvisioningStateRunning = "Running"
|
||||
)
|
||||
|
||||
// ProvisionerJob renders a provisioner job with interactive cancellation.
|
||||
func ProvisionerJob(ctx context.Context, wr io.Writer, opts ProvisionerJobOptions) error {
|
||||
if opts.FetchInterval == 0 {
|
||||
@@ -68,9 +63,8 @@ func ProvisionerJob(ctx context.Context, wr io.Writer, opts ProvisionerJobOption
|
||||
defer cancelFunc()
|
||||
|
||||
var (
|
||||
currentStage = ProvisioningStateQueued
|
||||
currentStage = "Queued"
|
||||
currentStageStartedAt = time.Now().UTC()
|
||||
currentQueuePos = -1
|
||||
|
||||
errChan = make(chan error, 1)
|
||||
job codersdk.ProvisionerJob
|
||||
@@ -80,20 +74,7 @@ func ProvisionerJob(ctx context.Context, wr io.Writer, opts ProvisionerJobOption
|
||||
sw := &stageWriter{w: wr, verbose: opts.Verbose, silentLogs: opts.Silent}
|
||||
|
||||
printStage := func() {
|
||||
out := currentStage
|
||||
|
||||
if currentStage == ProvisioningStateQueued && currentQueuePos > 0 {
|
||||
var queuePos string
|
||||
if currentQueuePos == 1 {
|
||||
queuePos = "next"
|
||||
} else {
|
||||
queuePos = fmt.Sprintf("position: %d", currentQueuePos)
|
||||
}
|
||||
|
||||
out = pretty.Sprintf(DefaultStyles.Warn, "%s (%s)", currentStage, queuePos)
|
||||
}
|
||||
|
||||
sw.Start(out)
|
||||
sw.Start(currentStage)
|
||||
}
|
||||
|
||||
updateStage := func(stage string, startedAt time.Time) {
|
||||
@@ -122,26 +103,15 @@ func ProvisionerJob(ctx context.Context, wr io.Writer, opts ProvisionerJobOption
|
||||
errChan <- xerrors.Errorf("fetch: %w", err)
|
||||
return
|
||||
}
|
||||
if job.QueuePosition != currentQueuePos {
|
||||
initialState := currentQueuePos == -1
|
||||
|
||||
currentQueuePos = job.QueuePosition
|
||||
// Print an update when the queue position changes, but:
|
||||
// - not initially, because the stage is printed at startup
|
||||
// - not when we're first in the queue, because it's redundant
|
||||
if !initialState && currentQueuePos != 0 {
|
||||
printStage()
|
||||
}
|
||||
}
|
||||
if job.StartedAt == nil {
|
||||
return
|
||||
}
|
||||
if currentStage != ProvisioningStateQueued {
|
||||
if currentStage != "Queued" {
|
||||
// If another stage is already running, there's no need
|
||||
// for us to notify the user we're running!
|
||||
return
|
||||
}
|
||||
updateStage(ProvisioningStateRunning, *job.StartedAt)
|
||||
updateStage("Running", *job.StartedAt)
|
||||
}
|
||||
|
||||
if opts.Cancel != nil {
|
||||
@@ -173,8 +143,8 @@ func ProvisionerJob(ctx context.Context, wr io.Writer, opts ProvisionerJobOption
|
||||
}
|
||||
|
||||
// The initial stage needs to print after the signal handler has been registered.
|
||||
updateJob()
|
||||
printStage()
|
||||
updateJob()
|
||||
|
||||
logs, closer, err := opts.Logs()
|
||||
if err != nil {
|
||||
|
||||
@@ -2,10 +2,8 @@ package cliui_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"sync"
|
||||
"testing"
|
||||
@@ -13,13 +11,11 @@ import (
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"github.com/coder/coder/v2/testutil"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/cli/cliui"
|
||||
"github.com/coder/coder/v2/coderd/database/dbtime"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/coder/v2/pty/ptytest"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
// This cannot be ran in parallel because it uses a signal.
|
||||
@@ -29,11 +25,7 @@ func TestProvisionerJob(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
test := newProvisionerJob(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitShort)
|
||||
defer cancel()
|
||||
|
||||
testutil.Go(t, func() {
|
||||
go func() {
|
||||
<-test.Next
|
||||
test.JobMutex.Lock()
|
||||
test.Job.Status = codersdk.ProvisionerJobRunning
|
||||
@@ -47,26 +39,20 @@ func TestProvisionerJob(t *testing.T) {
|
||||
test.Job.CompletedAt = &now
|
||||
close(test.Logs)
|
||||
test.JobMutex.Unlock()
|
||||
})
|
||||
testutil.Eventually(ctx, t, func(ctx context.Context) (done bool) {
|
||||
test.PTY.ExpectMatch(cliui.ProvisioningStateQueued)
|
||||
test.Next <- struct{}{}
|
||||
test.PTY.ExpectMatch(cliui.ProvisioningStateQueued)
|
||||
test.PTY.ExpectMatch(cliui.ProvisioningStateRunning)
|
||||
test.Next <- struct{}{}
|
||||
test.PTY.ExpectMatch(cliui.ProvisioningStateRunning)
|
||||
return true
|
||||
}, testutil.IntervalFast)
|
||||
}()
|
||||
test.PTY.ExpectMatch("Queued")
|
||||
test.Next <- struct{}{}
|
||||
test.PTY.ExpectMatch("Queued")
|
||||
test.PTY.ExpectMatch("Running")
|
||||
test.Next <- struct{}{}
|
||||
test.PTY.ExpectMatch("Running")
|
||||
})
|
||||
|
||||
t.Run("Stages", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
test := newProvisionerJob(t)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitShort)
|
||||
defer cancel()
|
||||
|
||||
testutil.Go(t, func() {
|
||||
go func() {
|
||||
<-test.Next
|
||||
test.JobMutex.Lock()
|
||||
test.Job.Status = codersdk.ProvisionerJobRunning
|
||||
@@ -84,86 +70,13 @@ func TestProvisionerJob(t *testing.T) {
|
||||
test.Job.CompletedAt = &now
|
||||
close(test.Logs)
|
||||
test.JobMutex.Unlock()
|
||||
})
|
||||
testutil.Eventually(ctx, t, func(ctx context.Context) (done bool) {
|
||||
test.PTY.ExpectMatch(cliui.ProvisioningStateQueued)
|
||||
test.Next <- struct{}{}
|
||||
test.PTY.ExpectMatch(cliui.ProvisioningStateQueued)
|
||||
test.PTY.ExpectMatch("Something")
|
||||
test.Next <- struct{}{}
|
||||
test.PTY.ExpectMatch("Something")
|
||||
return true
|
||||
}, testutil.IntervalFast)
|
||||
})
|
||||
|
||||
t.Run("Queue Position", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
stage := cliui.ProvisioningStateQueued
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
queuePos int
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
name: "first",
|
||||
queuePos: 0,
|
||||
expected: fmt.Sprintf("%s$", stage),
|
||||
},
|
||||
{
|
||||
name: "next",
|
||||
queuePos: 1,
|
||||
expected: fmt.Sprintf(`%s %s$`, stage, regexp.QuoteMeta("(next)")),
|
||||
},
|
||||
{
|
||||
name: "other",
|
||||
queuePos: 4,
|
||||
expected: fmt.Sprintf(`%s %s$`, stage, regexp.QuoteMeta("(position: 4)")),
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
tc := tc
|
||||
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
test := newProvisionerJob(t)
|
||||
test.JobMutex.Lock()
|
||||
test.Job.QueuePosition = tc.queuePos
|
||||
test.Job.QueueSize = tc.queuePos
|
||||
test.JobMutex.Unlock()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitShort)
|
||||
defer cancel()
|
||||
|
||||
testutil.Go(t, func() {
|
||||
<-test.Next
|
||||
test.JobMutex.Lock()
|
||||
test.Job.Status = codersdk.ProvisionerJobRunning
|
||||
now := dbtime.Now()
|
||||
test.Job.StartedAt = &now
|
||||
test.JobMutex.Unlock()
|
||||
<-test.Next
|
||||
test.JobMutex.Lock()
|
||||
test.Job.Status = codersdk.ProvisionerJobSucceeded
|
||||
now = dbtime.Now()
|
||||
test.Job.CompletedAt = &now
|
||||
close(test.Logs)
|
||||
test.JobMutex.Unlock()
|
||||
})
|
||||
testutil.Eventually(ctx, t, func(ctx context.Context) (done bool) {
|
||||
test.PTY.ExpectRegexMatch(tc.expected)
|
||||
test.Next <- struct{}{}
|
||||
test.PTY.ExpectMatch(cliui.ProvisioningStateQueued) // step completed
|
||||
test.PTY.ExpectMatch(cliui.ProvisioningStateRunning)
|
||||
test.Next <- struct{}{}
|
||||
test.PTY.ExpectMatch(cliui.ProvisioningStateRunning)
|
||||
return true
|
||||
}, testutil.IntervalFast)
|
||||
})
|
||||
}
|
||||
}()
|
||||
test.PTY.ExpectMatch("Queued")
|
||||
test.Next <- struct{}{}
|
||||
test.PTY.ExpectMatch("Queued")
|
||||
test.PTY.ExpectMatch("Something")
|
||||
test.Next <- struct{}{}
|
||||
test.PTY.ExpectMatch("Something")
|
||||
})
|
||||
|
||||
// This cannot be ran in parallel because it uses a signal.
|
||||
@@ -177,11 +90,7 @@ func TestProvisionerJob(t *testing.T) {
|
||||
}
|
||||
|
||||
test := newProvisionerJob(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitShort)
|
||||
defer cancel()
|
||||
|
||||
testutil.Go(t, func() {
|
||||
go func() {
|
||||
<-test.Next
|
||||
currentProcess, err := os.FindProcess(os.Getpid())
|
||||
assert.NoError(t, err)
|
||||
@@ -194,15 +103,12 @@ func TestProvisionerJob(t *testing.T) {
|
||||
test.Job.CompletedAt = &now
|
||||
close(test.Logs)
|
||||
test.JobMutex.Unlock()
|
||||
})
|
||||
testutil.Eventually(ctx, t, func(ctx context.Context) (done bool) {
|
||||
test.PTY.ExpectMatch(cliui.ProvisioningStateQueued)
|
||||
test.Next <- struct{}{}
|
||||
test.PTY.ExpectMatch("Gracefully canceling")
|
||||
test.Next <- struct{}{}
|
||||
test.PTY.ExpectMatch(cliui.ProvisioningStateQueued)
|
||||
return true
|
||||
}, testutil.IntervalFast)
|
||||
}()
|
||||
test.PTY.ExpectMatch("Queued")
|
||||
test.Next <- struct{}{}
|
||||
test.PTY.ExpectMatch("Gracefully canceling")
|
||||
test.Next <- struct{}{}
|
||||
test.PTY.ExpectMatch("Queued")
|
||||
})
|
||||
}
|
||||
|
||||
@@ -221,8 +127,8 @@ func newProvisionerJob(t *testing.T) provisionerJobTest {
|
||||
}
|
||||
jobLock := sync.Mutex{}
|
||||
logs := make(chan codersdk.ProvisionerJobLog, 1)
|
||||
cmd := &serpent.Command{
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
cmd := &clibase.Cmd{
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
return cliui.ProvisionerJob(inv.Context(), inv.Stdout, cliui.ProvisionerJobOptions{
|
||||
FetchInterval: time.Millisecond,
|
||||
Fetch: func() (codersdk.ProvisionerJob, error) {
|
||||
|
||||
+4
-4
@@ -10,8 +10,8 @@ import (
|
||||
"github.com/AlecAivazis/survey/v2/terminal"
|
||||
"golang.org/x/xerrors"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
func init() {
|
||||
@@ -68,7 +68,7 @@ type RichSelectOptions struct {
|
||||
}
|
||||
|
||||
// RichSelect displays a list of user options including name and description.
|
||||
func RichSelect(inv *serpent.Invocation, richOptions RichSelectOptions) (*codersdk.TemplateVersionParameterOption, error) {
|
||||
func RichSelect(inv *clibase.Invocation, richOptions RichSelectOptions) (*codersdk.TemplateVersionParameterOption, error) {
|
||||
opts := make([]string, len(richOptions.Options))
|
||||
var defaultOpt string
|
||||
for i, option := range richOptions.Options {
|
||||
@@ -102,7 +102,7 @@ func RichSelect(inv *serpent.Invocation, richOptions RichSelectOptions) (*coders
|
||||
}
|
||||
|
||||
// Select displays a list of user options.
|
||||
func Select(inv *serpent.Invocation, opts SelectOptions) (string, error) {
|
||||
func Select(inv *clibase.Invocation, opts SelectOptions) (string, error) {
|
||||
// The survey library used *always* fails when testing on Windows,
|
||||
// as it requires a live TTY (can't be a conpty). We should fork
|
||||
// this library to add a dummy fallback, that simply reads/writes
|
||||
@@ -138,7 +138,7 @@ func Select(inv *serpent.Invocation, opts SelectOptions) (string, error) {
|
||||
return value, err
|
||||
}
|
||||
|
||||
func MultiSelect(inv *serpent.Invocation, items []string) ([]string, error) {
|
||||
func MultiSelect(inv *clibase.Invocation, items []string) ([]string, error) {
|
||||
// Similar hack is applied to Select()
|
||||
if flag.Lookup("test.v") != nil {
|
||||
return items, nil
|
||||
|
||||
@@ -6,10 +6,10 @@ import (
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/cli/cliui"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/coder/v2/pty/ptytest"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
func TestSelect(t *testing.T) {
|
||||
@@ -31,8 +31,8 @@ func TestSelect(t *testing.T) {
|
||||
|
||||
func newSelect(ptty *ptytest.PTY, opts cliui.SelectOptions) (string, error) {
|
||||
value := ""
|
||||
cmd := &serpent.Command{
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
cmd := &clibase.Cmd{
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
var err error
|
||||
value, err = cliui.Select(inv, opts)
|
||||
return err
|
||||
@@ -72,8 +72,8 @@ func TestRichSelect(t *testing.T) {
|
||||
|
||||
func newRichSelect(ptty *ptytest.PTY, opts cliui.RichSelectOptions) (string, error) {
|
||||
value := ""
|
||||
cmd := &serpent.Command{
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
cmd := &clibase.Cmd{
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
richOption, err := cliui.RichSelect(inv, opts)
|
||||
if err == nil {
|
||||
value = richOption.Value
|
||||
@@ -105,8 +105,8 @@ func TestMultiSelect(t *testing.T) {
|
||||
|
||||
func newMultiSelect(ptty *ptytest.PTY, items []string) ([]string, error) {
|
||||
var values []string
|
||||
cmd := &serpent.Command{
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
cmd := &clibase.Cmd{
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
selectedItems, err := cliui.MultiSelect(inv, items)
|
||||
if err == nil {
|
||||
values = selectedItems
|
||||
|
||||
+20
-20
@@ -24,10 +24,10 @@ import (
|
||||
"golang.org/x/sync/errgroup"
|
||||
"golang.org/x/xerrors"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/cli/cliui"
|
||||
"github.com/coder/coder/v2/coderd/util/slice"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -215,7 +215,7 @@ func sshPrepareWorkspaceConfigs(ctx context.Context, client *codersdk.Client) (r
|
||||
}
|
||||
}
|
||||
|
||||
func (r *RootCmd) configSSH() *serpent.Command {
|
||||
func (r *RootCmd) configSSH() *clibase.Cmd {
|
||||
var (
|
||||
sshConfigFile string
|
||||
sshConfigOpts sshConfigOptions
|
||||
@@ -226,25 +226,25 @@ func (r *RootCmd) configSSH() *serpent.Command {
|
||||
coderCliPath string
|
||||
)
|
||||
client := new(codersdk.Client)
|
||||
cmd := &serpent.Command{
|
||||
cmd := &clibase.Cmd{
|
||||
Annotations: workspaceCommand,
|
||||
Use: "config-ssh",
|
||||
Short: "Add an SSH Host entry for your workspaces \"ssh coder.workspace\"",
|
||||
Long: FormatExamples(
|
||||
Example{
|
||||
Long: formatExamples(
|
||||
example{
|
||||
Description: "You can use -o (or --ssh-option) so set SSH options to be used for all your workspaces",
|
||||
Command: "coder config-ssh -o ForwardAgent=yes",
|
||||
},
|
||||
Example{
|
||||
example{
|
||||
Description: "You can use --dry-run (or -n) to see the changes that would be made",
|
||||
Command: "coder config-ssh --dry-run",
|
||||
},
|
||||
),
|
||||
Middleware: serpent.Chain(
|
||||
serpent.RequireNArgs(0),
|
||||
Middleware: clibase.Chain(
|
||||
clibase.RequireNArgs(0),
|
||||
r.InitClient(client),
|
||||
),
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
if sshConfigOpts.waitEnum != "auto" && skipProxyCommand {
|
||||
// The wait option is applied to the ProxyCommand. If the user
|
||||
// specifies skip-proxy-command, then wait cannot be applied.
|
||||
@@ -538,13 +538,13 @@ func (r *RootCmd) configSSH() *serpent.Command {
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Options = serpent.OptionSet{
|
||||
cmd.Options = clibase.OptionSet{
|
||||
{
|
||||
Flag: "ssh-config-file",
|
||||
Env: "CODER_SSH_CONFIG_FILE",
|
||||
Default: sshDefaultConfigFileName,
|
||||
Description: "Specifies the path to an SSH config.",
|
||||
Value: serpent.StringOf(&sshConfigFile),
|
||||
Value: clibase.StringOf(&sshConfigFile),
|
||||
},
|
||||
{
|
||||
Flag: "coder-binary-path",
|
||||
@@ -552,7 +552,7 @@ func (r *RootCmd) configSSH() *serpent.Command {
|
||||
Default: "",
|
||||
Description: "Optionally specify the absolute path to the coder binary used in ProxyCommand. " +
|
||||
"By default, the binary invoking this command ('config ssh') is used.",
|
||||
Value: serpent.Validate(serpent.StringOf(&coderCliPath), func(value *serpent.String) error {
|
||||
Value: clibase.Validate(clibase.StringOf(&coderCliPath), func(value *clibase.String) error {
|
||||
if runtime.GOOS == goosWindows {
|
||||
// For some reason filepath.IsAbs() does not work on windows.
|
||||
return nil
|
||||
@@ -569,46 +569,46 @@ func (r *RootCmd) configSSH() *serpent.Command {
|
||||
FlagShorthand: "o",
|
||||
Env: "CODER_SSH_CONFIG_OPTS",
|
||||
Description: "Specifies additional SSH options to embed in each host stanza.",
|
||||
Value: serpent.StringArrayOf(&sshConfigOpts.sshOptions),
|
||||
Value: clibase.StringArrayOf(&sshConfigOpts.sshOptions),
|
||||
},
|
||||
{
|
||||
Flag: "dry-run",
|
||||
FlagShorthand: "n",
|
||||
Env: "CODER_SSH_DRY_RUN",
|
||||
Description: "Perform a trial run with no changes made, showing a diff at the end.",
|
||||
Value: serpent.BoolOf(&dryRun),
|
||||
Value: clibase.BoolOf(&dryRun),
|
||||
},
|
||||
{
|
||||
Flag: "skip-proxy-command",
|
||||
Env: "CODER_SSH_SKIP_PROXY_COMMAND",
|
||||
Description: "Specifies whether the ProxyCommand option should be skipped. Useful for testing.",
|
||||
Value: serpent.BoolOf(&skipProxyCommand),
|
||||
Value: clibase.BoolOf(&skipProxyCommand),
|
||||
Hidden: true,
|
||||
},
|
||||
{
|
||||
Flag: "use-previous-options",
|
||||
Env: "CODER_SSH_USE_PREVIOUS_OPTIONS",
|
||||
Description: "Specifies whether or not to keep options from previous run of config-ssh.",
|
||||
Value: serpent.BoolOf(&usePreviousOpts),
|
||||
Value: clibase.BoolOf(&usePreviousOpts),
|
||||
},
|
||||
{
|
||||
Flag: "ssh-host-prefix",
|
||||
Env: "CODER_CONFIGSSH_SSH_HOST_PREFIX",
|
||||
Description: "Override the default host prefix.",
|
||||
Value: serpent.StringOf(&sshConfigOpts.userHostPrefix),
|
||||
Value: clibase.StringOf(&sshConfigOpts.userHostPrefix),
|
||||
},
|
||||
{
|
||||
Flag: "wait",
|
||||
Env: "CODER_CONFIGSSH_WAIT", // Not to be mixed with CODER_SSH_WAIT.
|
||||
Description: "Specifies whether or not to wait for the startup script to finish executing. Auto means that the agent startup script behavior configured in the workspace template is used.",
|
||||
Default: "auto",
|
||||
Value: serpent.EnumOf(&sshConfigOpts.waitEnum, "yes", "no", "auto"),
|
||||
Value: clibase.EnumOf(&sshConfigOpts.waitEnum, "yes", "no", "auto"),
|
||||
},
|
||||
{
|
||||
Flag: "disable-autostart",
|
||||
Description: "Disable starting the workspace automatically when connecting via SSH.",
|
||||
Env: "CODER_CONFIGSSH_DISABLE_AUTOSTART",
|
||||
Value: serpent.BoolOf(&sshConfigOpts.disableAutostart),
|
||||
Value: clibase.BoolOf(&sshConfigOpts.disableAutostart),
|
||||
Default: "false",
|
||||
},
|
||||
{
|
||||
@@ -617,7 +617,7 @@ func (r *RootCmd) configSSH() *serpent.Command {
|
||||
Description: "By default, 'config-ssh' uses the os path separator when writing the ssh config. " +
|
||||
"This might be an issue in Windows machine that use a unix-like shell. " +
|
||||
"This flag forces the use of unix file paths (the forward slash '/').",
|
||||
Value: serpent.BoolOf(&forceUnixSeparators),
|
||||
Value: clibase.BoolOf(&forceUnixSeparators),
|
||||
// On non-windows showing this command is useless because it is a noop.
|
||||
// Hide vs disable it though so if a command is copied from a Windows
|
||||
// machine to a unix machine it will still work and not throw an
|
||||
|
||||
@@ -25,7 +25,6 @@ import (
|
||||
"github.com/coder/coder/v2/coderd/database"
|
||||
"github.com/coder/coder/v2/coderd/database/dbfake"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/coder/v2/codersdk/workspacesdk"
|
||||
"github.com/coder/coder/v2/provisionersdk/proto"
|
||||
"github.com/coder/coder/v2/pty/ptytest"
|
||||
"github.com/coder/coder/v2/testutil"
|
||||
@@ -84,8 +83,7 @@ func TestConfigSSH(t *testing.T) {
|
||||
}).WithAgent().Do()
|
||||
_ = agenttest.New(t, client.URL, r.AgentToken)
|
||||
resources := coderdtest.AwaitWorkspaceAgents(t, client, r.Workspace.ID)
|
||||
agentConn, err := workspacesdk.New(client).
|
||||
DialAgent(context.Background(), resources[0].Agents[0].ID, nil)
|
||||
agentConn, err := client.DialWorkspaceAgent(context.Background(), resources[0].Agents[0].ID, nil)
|
||||
require.NoError(t, err)
|
||||
defer agentConn.Close()
|
||||
|
||||
|
||||
+24
-33
@@ -12,14 +12,14 @@ import (
|
||||
|
||||
"github.com/coder/pretty"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/cli/cliui"
|
||||
"github.com/coder/coder/v2/coderd/util/ptr"
|
||||
"github.com/coder/coder/v2/coderd/util/slice"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
func (r *RootCmd) create() *serpent.Command {
|
||||
func (r *RootCmd) create() *clibase.Cmd {
|
||||
var (
|
||||
templateName string
|
||||
startAt string
|
||||
@@ -31,18 +31,18 @@ func (r *RootCmd) create() *serpent.Command {
|
||||
copyParametersFrom string
|
||||
)
|
||||
client := new(codersdk.Client)
|
||||
cmd := &serpent.Command{
|
||||
cmd := &clibase.Cmd{
|
||||
Annotations: workspaceCommand,
|
||||
Use: "create [name]",
|
||||
Short: "Create a workspace",
|
||||
Long: FormatExamples(
|
||||
Example{
|
||||
Long: formatExamples(
|
||||
example{
|
||||
Description: "Create a workspace for another user (if you have permission)",
|
||||
Command: "coder create <username>/<workspace_name>",
|
||||
},
|
||||
),
|
||||
Middleware: serpent.Chain(r.InitClient(client)),
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
Middleware: clibase.Chain(r.InitClient(client)),
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
organization, err := CurrentOrganization(r, inv, client)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -165,11 +165,6 @@ func (r *RootCmd) create() *serpent.Command {
|
||||
return xerrors.Errorf("can't parse given parameter values: %w", err)
|
||||
}
|
||||
|
||||
cliBuildParameterDefaults, err := asWorkspaceBuildParameters(parameterFlags.richParameterDefaults)
|
||||
if err != nil {
|
||||
return xerrors.Errorf("can't parse given parameter defaults: %w", err)
|
||||
}
|
||||
|
||||
var sourceWorkspaceParameters []codersdk.WorkspaceBuildParameter
|
||||
if copyParametersFrom != "" {
|
||||
sourceWorkspaceParameters, err = client.WorkspaceBuildParameters(inv.Context(), sourceWorkspace.LatestBuild.ID)
|
||||
@@ -183,9 +178,8 @@ func (r *RootCmd) create() *serpent.Command {
|
||||
TemplateVersionID: templateVersionID,
|
||||
NewWorkspaceName: workspaceName,
|
||||
|
||||
RichParameterFile: parameterFlags.richParameterFile,
|
||||
RichParameters: cliBuildParameters,
|
||||
RichParameterDefaults: cliBuildParameterDefaults,
|
||||
RichParameterFile: parameterFlags.richParameterFile,
|
||||
RichParameters: cliBuildParameters,
|
||||
|
||||
SourceWorkspaceParameters: sourceWorkspaceParameters,
|
||||
})
|
||||
@@ -233,42 +227,41 @@ func (r *RootCmd) create() *serpent.Command {
|
||||
},
|
||||
}
|
||||
cmd.Options = append(cmd.Options,
|
||||
serpent.Option{
|
||||
clibase.Option{
|
||||
Flag: "template",
|
||||
FlagShorthand: "t",
|
||||
Env: "CODER_TEMPLATE_NAME",
|
||||
Description: "Specify a template name.",
|
||||
Value: serpent.StringOf(&templateName),
|
||||
Value: clibase.StringOf(&templateName),
|
||||
},
|
||||
serpent.Option{
|
||||
clibase.Option{
|
||||
Flag: "start-at",
|
||||
Env: "CODER_WORKSPACE_START_AT",
|
||||
Description: "Specify the workspace autostart schedule. Check coder schedule start --help for the syntax.",
|
||||
Value: serpent.StringOf(&startAt),
|
||||
Value: clibase.StringOf(&startAt),
|
||||
},
|
||||
serpent.Option{
|
||||
clibase.Option{
|
||||
Flag: "stop-after",
|
||||
Env: "CODER_WORKSPACE_STOP_AFTER",
|
||||
Description: "Specify a duration after which the workspace should shut down (e.g. 8h).",
|
||||
Value: serpent.DurationOf(&stopAfter),
|
||||
Value: clibase.DurationOf(&stopAfter),
|
||||
},
|
||||
serpent.Option{
|
||||
clibase.Option{
|
||||
Flag: "automatic-updates",
|
||||
Env: "CODER_WORKSPACE_AUTOMATIC_UPDATES",
|
||||
Description: "Specify automatic updates setting for the workspace (accepts 'always' or 'never').",
|
||||
Default: string(codersdk.AutomaticUpdatesNever),
|
||||
Value: serpent.StringOf(&autoUpdates),
|
||||
Value: clibase.StringOf(&autoUpdates),
|
||||
},
|
||||
serpent.Option{
|
||||
clibase.Option{
|
||||
Flag: "copy-parameters-from",
|
||||
Env: "CODER_WORKSPACE_COPY_PARAMETERS_FROM",
|
||||
Description: "Specify the source workspace name to copy parameters from.",
|
||||
Value: serpent.StringOf(©ParametersFrom),
|
||||
Value: clibase.StringOf(©ParametersFrom),
|
||||
},
|
||||
cliui.SkipPromptOption(),
|
||||
)
|
||||
cmd.Options = append(cmd.Options, parameterFlags.cliParameters()...)
|
||||
cmd.Options = append(cmd.Options, parameterFlags.cliParameterDefaults()...)
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -283,15 +276,14 @@ type prepWorkspaceBuildArgs struct {
|
||||
PromptBuildOptions bool
|
||||
BuildOptions []codersdk.WorkspaceBuildParameter
|
||||
|
||||
PromptRichParameters bool
|
||||
RichParameters []codersdk.WorkspaceBuildParameter
|
||||
RichParameterFile string
|
||||
RichParameterDefaults []codersdk.WorkspaceBuildParameter
|
||||
PromptRichParameters bool
|
||||
RichParameters []codersdk.WorkspaceBuildParameter
|
||||
RichParameterFile string
|
||||
}
|
||||
|
||||
// prepWorkspaceBuild will ensure a workspace build will succeed on the latest template version.
|
||||
// Any missing params will be prompted to the user. It supports rich parameters.
|
||||
func prepWorkspaceBuild(inv *serpent.Invocation, client *codersdk.Client, args prepWorkspaceBuildArgs) ([]codersdk.WorkspaceBuildParameter, error) {
|
||||
func prepWorkspaceBuild(inv *clibase.Invocation, client *codersdk.Client, args prepWorkspaceBuildArgs) ([]codersdk.WorkspaceBuildParameter, error) {
|
||||
ctx := inv.Context()
|
||||
|
||||
templateVersion, err := client.TemplateVersion(ctx, args.TemplateVersionID)
|
||||
@@ -319,8 +311,7 @@ func prepWorkspaceBuild(inv *serpent.Invocation, client *codersdk.Client, args p
|
||||
WithBuildOptions(args.BuildOptions).
|
||||
WithPromptRichParameters(args.PromptRichParameters).
|
||||
WithRichParameters(args.RichParameters).
|
||||
WithRichParametersFile(parameterFile).
|
||||
WithRichParametersDefaults(args.RichParameterDefaults)
|
||||
WithRichParametersFile(parameterFile)
|
||||
buildParameters, err := resolver.Resolve(inv, args.Action, templateVersionParameters)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -315,68 +315,6 @@ func TestCreateWithRichParameters(t *testing.T) {
|
||||
<-doneChan
|
||||
})
|
||||
|
||||
t.Run("ParametersDefaults", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
client := coderdtest.New(t, &coderdtest.Options{IncludeProvisionerDaemon: true})
|
||||
owner := coderdtest.CreateFirstUser(t, client)
|
||||
member, _ := coderdtest.CreateAnotherUser(t, client, owner.OrganizationID)
|
||||
version := coderdtest.CreateTemplateVersion(t, client, owner.OrganizationID, echoResponses)
|
||||
coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID)
|
||||
|
||||
template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID)
|
||||
|
||||
inv, root := clitest.New(t, "create", "my-workspace", "--template", template.Name,
|
||||
"--parameter-default", fmt.Sprintf("%s=%s", firstParameterName, firstParameterValue),
|
||||
"--parameter-default", fmt.Sprintf("%s=%s", secondParameterName, secondParameterValue),
|
||||
"--parameter-default", fmt.Sprintf("%s=%s", immutableParameterName, immutableParameterValue))
|
||||
clitest.SetupConfig(t, member, root)
|
||||
doneChan := make(chan struct{})
|
||||
pty := ptytest.New(t).Attach(inv)
|
||||
go func() {
|
||||
defer close(doneChan)
|
||||
err := inv.Run()
|
||||
assert.NoError(t, err)
|
||||
}()
|
||||
|
||||
matches := []string{
|
||||
firstParameterDescription, firstParameterValue,
|
||||
secondParameterDescription, secondParameterValue,
|
||||
immutableParameterDescription, immutableParameterValue,
|
||||
}
|
||||
for i := 0; i < len(matches); i += 2 {
|
||||
match := matches[i]
|
||||
defaultValue := matches[i+1]
|
||||
|
||||
pty.ExpectMatch(match)
|
||||
pty.ExpectMatch(`Enter a value (default: "` + defaultValue + `")`)
|
||||
pty.WriteLine("")
|
||||
}
|
||||
pty.ExpectMatch("Confirm create?")
|
||||
pty.WriteLine("yes")
|
||||
<-doneChan
|
||||
|
||||
// Verify that the expected default values were used.
|
||||
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitShort)
|
||||
defer cancel()
|
||||
|
||||
workspaces, err := client.Workspaces(ctx, codersdk.WorkspaceFilter{
|
||||
Name: "my-workspace",
|
||||
})
|
||||
require.NoError(t, err, "can't list available workspaces")
|
||||
require.Len(t, workspaces.Workspaces, 1)
|
||||
|
||||
workspaceLatestBuild := workspaces.Workspaces[0].LatestBuild
|
||||
require.Equal(t, version.ID, workspaceLatestBuild.TemplateVersionID)
|
||||
|
||||
buildParameters, err := client.WorkspaceBuildParameters(ctx, workspaceLatestBuild.ID)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, buildParameters, 3)
|
||||
require.Contains(t, buildParameters, codersdk.WorkspaceBuildParameter{Name: firstParameterName, Value: firstParameterValue})
|
||||
require.Contains(t, buildParameters, codersdk.WorkspaceBuildParameter{Name: secondParameterName, Value: secondParameterValue})
|
||||
require.Contains(t, buildParameters, codersdk.WorkspaceBuildParameter{Name: immutableParameterName, Value: immutableParameterValue})
|
||||
})
|
||||
|
||||
t.Run("RichParametersFile", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
|
||||
+8
-8
@@ -4,24 +4,24 @@ import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/cli/cliui"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
// nolint
|
||||
func (r *RootCmd) deleteWorkspace() *serpent.Command {
|
||||
func (r *RootCmd) deleteWorkspace() *clibase.Cmd {
|
||||
var orphan bool
|
||||
client := new(codersdk.Client)
|
||||
cmd := &serpent.Command{
|
||||
cmd := &clibase.Cmd{
|
||||
Annotations: workspaceCommand,
|
||||
Use: "delete <workspace>",
|
||||
Short: "Delete a workspace",
|
||||
Middleware: serpent.Chain(
|
||||
serpent.RequireNArgs(1),
|
||||
Middleware: clibase.Chain(
|
||||
clibase.RequireNArgs(1),
|
||||
r.InitClient(client),
|
||||
),
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
workspace, err := namedWorkspace(inv.Context(), client, inv.Args[0])
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -62,12 +62,12 @@ func (r *RootCmd) deleteWorkspace() *serpent.Command {
|
||||
return nil
|
||||
},
|
||||
}
|
||||
cmd.Options = serpent.OptionSet{
|
||||
cmd.Options = clibase.OptionSet{
|
||||
{
|
||||
Flag: "orphan",
|
||||
Description: "Delete a workspace without deleting its resources. This can delete a workspace in a broken state, but may also lead to unaccounted cloud resources.",
|
||||
|
||||
Value: serpent.BoolOf(&orphan),
|
||||
Value: clibase.BoolOf(&orphan),
|
||||
},
|
||||
cliui.SkipPromptOption(),
|
||||
}
|
||||
|
||||
+12
-12
@@ -15,26 +15,26 @@ import (
|
||||
|
||||
"github.com/coder/pretty"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/cli/cliui"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
func (r *RootCmd) dotfiles() *serpent.Command {
|
||||
func (r *RootCmd) dotfiles() *clibase.Cmd {
|
||||
var symlinkDir string
|
||||
var gitbranch string
|
||||
var dotfilesRepoDir string
|
||||
|
||||
cmd := &serpent.Command{
|
||||
cmd := &clibase.Cmd{
|
||||
Use: "dotfiles <git_repo_url>",
|
||||
Middleware: serpent.RequireNArgs(1),
|
||||
Middleware: clibase.RequireNArgs(1),
|
||||
Short: "Personalize your workspace by applying a canonical dotfiles repository",
|
||||
Long: FormatExamples(
|
||||
Example{
|
||||
Long: formatExamples(
|
||||
example{
|
||||
Description: "Check out and install a dotfiles repository without prompts",
|
||||
Command: "coder dotfiles --yes git@github.com:example/dotfiles.git",
|
||||
},
|
||||
),
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
var (
|
||||
gitRepo = inv.Args[0]
|
||||
cfg = r.createConfig()
|
||||
@@ -276,26 +276,26 @@ func (r *RootCmd) dotfiles() *serpent.Command {
|
||||
return nil
|
||||
},
|
||||
}
|
||||
cmd.Options = serpent.OptionSet{
|
||||
cmd.Options = clibase.OptionSet{
|
||||
{
|
||||
Flag: "symlink-dir",
|
||||
Env: "CODER_SYMLINK_DIR",
|
||||
Description: "Specifies the directory for the dotfiles symlink destinations. If empty, will use $HOME.",
|
||||
Value: serpent.StringOf(&symlinkDir),
|
||||
Value: clibase.StringOf(&symlinkDir),
|
||||
},
|
||||
{
|
||||
Flag: "branch",
|
||||
FlagShorthand: "b",
|
||||
Description: "Specifies which branch to clone. " +
|
||||
"If empty, will default to cloning the default branch or using the existing branch in the cloned repo on disk.",
|
||||
Value: serpent.StringOf(&gitbranch),
|
||||
Value: clibase.StringOf(&gitbranch),
|
||||
},
|
||||
{
|
||||
Flag: "repo-dir",
|
||||
Default: "dotfiles",
|
||||
Env: "CODER_DOTFILES_REPO_DIR",
|
||||
Description: "Specifies the directory for the dotfiles repository, relative to global config directory.",
|
||||
Value: serpent.StringOf(&dotfilesRepoDir),
|
||||
Value: clibase.StringOf(&dotfilesRepoDir),
|
||||
},
|
||||
cliui.SkipPromptOption(),
|
||||
}
|
||||
@@ -308,7 +308,7 @@ type ensureCorrectGitBranchParams struct {
|
||||
gitBranch string
|
||||
}
|
||||
|
||||
func ensureCorrectGitBranch(baseInv *serpent.Invocation, params ensureCorrectGitBranchParams) error {
|
||||
func ensureCorrectGitBranch(baseInv *clibase.Invocation, params ensureCorrectGitBranchParams) error {
|
||||
dotfileCmd := func(cmd string, args ...string) *exec.Cmd {
|
||||
c := exec.CommandContext(baseInv.Context(), cmd, args...)
|
||||
c.Dir = params.repoDir
|
||||
|
||||
+27
-23
@@ -5,18 +5,19 @@ import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
|
||||
"golang.org/x/xerrors"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
func (RootCmd) errorExample() *serpent.Command {
|
||||
errorCmd := func(use string, err error) *serpent.Command {
|
||||
return &serpent.Command{
|
||||
func (RootCmd) errorExample() *clibase.Cmd {
|
||||
errorCmd := func(use string, err error) *clibase.Cmd {
|
||||
return &clibase.Cmd{
|
||||
Use: use,
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
return err
|
||||
},
|
||||
}
|
||||
@@ -49,18 +50,18 @@ func (RootCmd) errorExample() *serpent.Command {
|
||||
apiErrorNoHelper.Helper = ""
|
||||
|
||||
// Some flags
|
||||
var magicWord serpent.String
|
||||
var magicWord clibase.String
|
||||
|
||||
cmd := &serpent.Command{
|
||||
cmd := &clibase.Cmd{
|
||||
Use: "example-error",
|
||||
Short: "Shows what different error messages look like",
|
||||
Long: "This command is pretty pointless, but without it testing errors is" +
|
||||
"difficult to visually inspect. Error message formatting is inherently" +
|
||||
"visual, so we need a way to quickly see what they look like.",
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
return inv.Command.HelpHandler(inv)
|
||||
},
|
||||
Children: []*serpent.Command{
|
||||
Children: []*clibase.Cmd{
|
||||
// Typical codersdk api error
|
||||
errorCmd("api", apiError),
|
||||
|
||||
@@ -70,7 +71,7 @@ func (RootCmd) errorExample() *serpent.Command {
|
||||
// A multi-error
|
||||
{
|
||||
Use: "multi-error",
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
return xerrors.Errorf("wrapped: %w", errors.Join(
|
||||
xerrors.Errorf("first error: %w", errorWithStackTrace()),
|
||||
xerrors.Errorf("second error: %w", errorWithStackTrace()),
|
||||
@@ -81,41 +82,44 @@ func (RootCmd) errorExample() *serpent.Command {
|
||||
{
|
||||
Use: "multi-multi-error",
|
||||
Short: "This is a multi error inside a multi error",
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
// Closing the stdin file descriptor will cause the next close
|
||||
// to fail. This is joined to the returned Command error.
|
||||
if f, ok := inv.Stdin.(*os.File); ok {
|
||||
_ = f.Close()
|
||||
}
|
||||
|
||||
return errors.Join(
|
||||
xerrors.Errorf("parent error: %w", errorWithStackTrace()),
|
||||
errors.Join(
|
||||
xerrors.Errorf("child first error: %w", errorWithStackTrace()),
|
||||
xerrors.Errorf("child second error: %w", errorWithStackTrace()),
|
||||
),
|
||||
xerrors.Errorf("first error: %w", errorWithStackTrace()),
|
||||
xerrors.Errorf("second error: %w", errorWithStackTrace()),
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
Use: "validation",
|
||||
Options: serpent.OptionSet{
|
||||
serpent.Option{
|
||||
Options: clibase.OptionSet{
|
||||
clibase.Option{
|
||||
Name: "magic-word",
|
||||
Description: "Take a good guess.",
|
||||
Required: true,
|
||||
Flag: "magic-word",
|
||||
Default: "",
|
||||
Value: serpent.Validate(&magicWord, func(value *serpent.String) error {
|
||||
Value: clibase.Validate(&magicWord, func(value *clibase.String) error {
|
||||
return xerrors.Errorf("magic word is incorrect")
|
||||
}),
|
||||
},
|
||||
},
|
||||
Handler: func(i *serpent.Invocation) error {
|
||||
Handler: func(i *clibase.Invocation) error {
|
||||
_, _ = fmt.Fprint(i.Stdout, "Try setting the --magic-word flag\n")
|
||||
return nil
|
||||
},
|
||||
},
|
||||
{
|
||||
Use: "arg-required <required>",
|
||||
Middleware: serpent.Chain(
|
||||
serpent.RequireNArgs(1),
|
||||
Middleware: clibase.Chain(
|
||||
clibase.RequireNArgs(1),
|
||||
),
|
||||
Handler: func(i *serpent.Invocation) error {
|
||||
Handler: func(i *clibase.Invocation) error {
|
||||
_, _ = fmt.Fprint(i.Stdout, "Try running this without an argument\n")
|
||||
return nil
|
||||
},
|
||||
|
||||
@@ -1,93 +0,0 @@
|
||||
package cli_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/coder/coder/v2/cli"
|
||||
"github.com/coder/coder/v2/cli/clitest"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
type commandErrorCase struct {
|
||||
Name string
|
||||
Cmd []string
|
||||
}
|
||||
|
||||
// TestErrorExamples will test the help output of the
|
||||
// coder exp example-error using golden files.
|
||||
func TestErrorExamples(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
coderRootCmd := getRoot(t)
|
||||
|
||||
var exampleErrorRootCmd *serpent.Command
|
||||
coderRootCmd.Walk(func(command *serpent.Command) {
|
||||
if command.Name() == "example-error" {
|
||||
// cannot abort early, but list is small
|
||||
exampleErrorRootCmd = command
|
||||
}
|
||||
})
|
||||
require.NotNil(t, exampleErrorRootCmd, "example-error command not found")
|
||||
|
||||
var cases []commandErrorCase
|
||||
|
||||
ExtractCommandPathsLoop:
|
||||
for _, cp := range extractCommandPaths(nil, exampleErrorRootCmd.Children) {
|
||||
cmd := append([]string{"exp", "example-error"}, cp...)
|
||||
name := fmt.Sprintf("coder %s", strings.Join(cmd, " "))
|
||||
for _, tt := range cases {
|
||||
if tt.Name == name {
|
||||
continue ExtractCommandPathsLoop
|
||||
}
|
||||
}
|
||||
cases = append(cases, commandErrorCase{Name: name, Cmd: cmd})
|
||||
}
|
||||
|
||||
for _, tt := range cases {
|
||||
tt := tt
|
||||
t.Run(tt.Name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var outBuf bytes.Buffer
|
||||
|
||||
coderRootCmd := getRoot(t)
|
||||
|
||||
inv, _ := clitest.NewWithCommand(t, coderRootCmd, tt.Cmd...)
|
||||
inv.Stderr = &outBuf
|
||||
inv.Stdout = &outBuf
|
||||
|
||||
err := inv.Run()
|
||||
|
||||
errFormatter := cli.NewPrettyErrorFormatter(&outBuf, false)
|
||||
errFormatter.Format(err)
|
||||
|
||||
clitest.TestGoldenFile(t, tt.Name, outBuf.Bytes(), nil)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func extractCommandPaths(cmdPath []string, cmds []*serpent.Command) [][]string {
|
||||
var cmdPaths [][]string
|
||||
for _, c := range cmds {
|
||||
cmdPath := append(cmdPath, c.Name())
|
||||
cmdPaths = append(cmdPaths, cmdPath)
|
||||
cmdPaths = append(cmdPaths, extractCommandPaths(cmdPath, c.Children)...)
|
||||
}
|
||||
return cmdPaths
|
||||
}
|
||||
|
||||
// Must return a fresh instance of cmds each time.
|
||||
func getRoot(t *testing.T) *serpent.Command {
|
||||
t.Helper()
|
||||
|
||||
var root cli.RootCmd
|
||||
rootCmd, err := root.Command(root.AGPL())
|
||||
require.NoError(t, err)
|
||||
|
||||
return rootCmd
|
||||
}
|
||||
+5
-5
@@ -1,16 +1,16 @@
|
||||
package cli
|
||||
|
||||
import "github.com/coder/serpent"
|
||||
import "github.com/coder/coder/v2/cli/clibase"
|
||||
|
||||
func (r *RootCmd) expCmd() *serpent.Command {
|
||||
cmd := &serpent.Command{
|
||||
func (r *RootCmd) expCmd() *clibase.Cmd {
|
||||
cmd := &clibase.Cmd{
|
||||
Use: "exp",
|
||||
Short: "Internal commands for testing and experimentation. These are prone to breaking changes with no notice.",
|
||||
Handler: func(i *serpent.Invocation) error {
|
||||
Handler: func(i *clibase.Invocation) error {
|
||||
return i.Command.HelpHandler(i)
|
||||
},
|
||||
Hidden: true,
|
||||
Children: []*serpent.Command{
|
||||
Children: []*clibase.Cmd{
|
||||
r.scaletestCmd(),
|
||||
r.errorExample(),
|
||||
},
|
||||
|
||||
+86
-80
@@ -14,6 +14,7 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
@@ -26,11 +27,11 @@ import (
|
||||
"cdr.dev/slog"
|
||||
"cdr.dev/slog/sloggers/sloghuman"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/cli/cliui"
|
||||
"github.com/coder/coder/v2/coderd/httpapi"
|
||||
"github.com/coder/coder/v2/coderd/tracing"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/coder/v2/codersdk/workspacesdk"
|
||||
"github.com/coder/coder/v2/cryptorand"
|
||||
"github.com/coder/coder/v2/scaletest/agentconn"
|
||||
"github.com/coder/coder/v2/scaletest/createworkspaces"
|
||||
@@ -39,19 +40,18 @@ import (
|
||||
"github.com/coder/coder/v2/scaletest/reconnectingpty"
|
||||
"github.com/coder/coder/v2/scaletest/workspacebuild"
|
||||
"github.com/coder/coder/v2/scaletest/workspacetraffic"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
const scaletestTracerName = "coder_scaletest"
|
||||
|
||||
func (r *RootCmd) scaletestCmd() *serpent.Command {
|
||||
cmd := &serpent.Command{
|
||||
func (r *RootCmd) scaletestCmd() *clibase.Cmd {
|
||||
cmd := &clibase.Cmd{
|
||||
Use: "scaletest",
|
||||
Short: "Run a scale test against the Coder API",
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
return inv.Command.HelpHandler(inv)
|
||||
},
|
||||
Children: []*serpent.Command{
|
||||
Children: []*clibase.Cmd{
|
||||
r.scaletestCleanup(),
|
||||
r.scaletestDashboard(),
|
||||
r.scaletestCreateWorkspaces(),
|
||||
@@ -69,32 +69,32 @@ type scaletestTracingFlags struct {
|
||||
tracePropagate bool
|
||||
}
|
||||
|
||||
func (s *scaletestTracingFlags) attach(opts *serpent.OptionSet) {
|
||||
func (s *scaletestTracingFlags) attach(opts *clibase.OptionSet) {
|
||||
*opts = append(
|
||||
*opts,
|
||||
serpent.Option{
|
||||
clibase.Option{
|
||||
Flag: "trace",
|
||||
Env: "CODER_SCALETEST_TRACE",
|
||||
Description: "Whether application tracing data is collected. It exports to a backend configured by environment variables. See: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md.",
|
||||
Value: serpent.BoolOf(&s.traceEnable),
|
||||
Value: clibase.BoolOf(&s.traceEnable),
|
||||
},
|
||||
serpent.Option{
|
||||
clibase.Option{
|
||||
Flag: "trace-coder",
|
||||
Env: "CODER_SCALETEST_TRACE_CODER",
|
||||
Description: "Whether opentelemetry traces are sent to Coder. We recommend keeping this disabled unless we advise you to enable it.",
|
||||
Value: serpent.BoolOf(&s.traceCoder),
|
||||
Value: clibase.BoolOf(&s.traceCoder),
|
||||
},
|
||||
serpent.Option{
|
||||
clibase.Option{
|
||||
Flag: "trace-honeycomb-api-key",
|
||||
Env: "CODER_SCALETEST_TRACE_HONEYCOMB_API_KEY",
|
||||
Description: "Enables trace exporting to Honeycomb.io using the provided API key.",
|
||||
Value: serpent.StringOf(&s.traceHoneycombAPIKey),
|
||||
Value: clibase.StringOf(&s.traceHoneycombAPIKey),
|
||||
},
|
||||
serpent.Option{
|
||||
clibase.Option{
|
||||
Flag: "trace-propagate",
|
||||
Env: "CODER_SCALETEST_TRACE_PROPAGATE",
|
||||
Description: "Enables trace propagation to the Coder backend, which will be used to correlate server-side spans with client-side spans. Only enable this if the server is configured with the exact same tracing configuration as the client.",
|
||||
Value: serpent.BoolOf(&s.tracePropagate),
|
||||
Value: clibase.BoolOf(&s.tracePropagate),
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -137,7 +137,7 @@ type scaletestStrategyFlags struct {
|
||||
timeoutPerJob time.Duration
|
||||
}
|
||||
|
||||
func (s *scaletestStrategyFlags) attach(opts *serpent.OptionSet) {
|
||||
func (s *scaletestStrategyFlags) attach(opts *clibase.OptionSet) {
|
||||
concurrencyLong, concurrencyEnv, concurrencyDescription := "concurrency", "CODER_SCALETEST_CONCURRENCY", "Number of concurrent jobs to run. 0 means unlimited."
|
||||
timeoutLong, timeoutEnv, timeoutDescription := "timeout", "CODER_SCALETEST_TIMEOUT", "Timeout for the entire test run. 0 means unlimited."
|
||||
jobTimeoutLong, jobTimeoutEnv, jobTimeoutDescription := "job-timeout", "CODER_SCALETEST_JOB_TIMEOUT", "Timeout per job. Jobs may take longer to complete under higher concurrency limits."
|
||||
@@ -149,26 +149,26 @@ func (s *scaletestStrategyFlags) attach(opts *serpent.OptionSet) {
|
||||
|
||||
*opts = append(
|
||||
*opts,
|
||||
serpent.Option{
|
||||
clibase.Option{
|
||||
Flag: concurrencyLong,
|
||||
Env: concurrencyEnv,
|
||||
Description: concurrencyDescription,
|
||||
Default: "1",
|
||||
Value: serpent.Int64Of(&s.concurrency),
|
||||
Value: clibase.Int64Of(&s.concurrency),
|
||||
},
|
||||
serpent.Option{
|
||||
clibase.Option{
|
||||
Flag: timeoutLong,
|
||||
Env: timeoutEnv,
|
||||
Description: timeoutDescription,
|
||||
Default: "30m",
|
||||
Value: serpent.DurationOf(&s.timeout),
|
||||
Value: clibase.DurationOf(&s.timeout),
|
||||
},
|
||||
serpent.Option{
|
||||
clibase.Option{
|
||||
Flag: jobTimeoutLong,
|
||||
Env: jobTimeoutEnv,
|
||||
Description: jobTimeoutDescription,
|
||||
Default: "5m",
|
||||
Value: serpent.DurationOf(&s.timeoutPerJob),
|
||||
Value: clibase.DurationOf(&s.timeoutPerJob),
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -244,8 +244,14 @@ func (o *scaleTestOutput) write(res harness.Results, stdout io.Writer) error {
|
||||
|
||||
// Sync the file to disk if it's a file.
|
||||
if s, ok := w.(interface{ Sync() error }); ok {
|
||||
// Best effort. If we get an error from syncing, just ignore it.
|
||||
_ = s.Sync()
|
||||
err := s.Sync()
|
||||
// On Linux, EINVAL is returned when calling fsync on /dev/stdout. We
|
||||
// can safely ignore this error.
|
||||
// On macOS, ENOTTY is returned when calling sync on /dev/stdout. We
|
||||
// can safely ignore this error.
|
||||
if err != nil && !xerrors.Is(err, syscall.EINVAL) && !xerrors.Is(err, syscall.ENOTTY) {
|
||||
return xerrors.Errorf("flush output file: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if c != nil {
|
||||
@@ -262,13 +268,13 @@ type scaletestOutputFlags struct {
|
||||
outputSpecs []string
|
||||
}
|
||||
|
||||
func (s *scaletestOutputFlags) attach(opts *serpent.OptionSet) {
|
||||
*opts = append(*opts, serpent.Option{
|
||||
func (s *scaletestOutputFlags) attach(opts *clibase.OptionSet) {
|
||||
*opts = append(*opts, clibase.Option{
|
||||
Flag: "output",
|
||||
Env: "CODER_SCALETEST_OUTPUTS",
|
||||
Description: `Output format specs in the format "<format>[:<path>]". Not specifying a path will default to stdout. Available formats: text, json.`,
|
||||
Default: "text",
|
||||
Value: serpent.StringArrayOf(&s.outputSpecs),
|
||||
Value: clibase.StringArrayOf(&s.outputSpecs),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -325,21 +331,21 @@ type scaletestPrometheusFlags struct {
|
||||
Wait time.Duration
|
||||
}
|
||||
|
||||
func (s *scaletestPrometheusFlags) attach(opts *serpent.OptionSet) {
|
||||
func (s *scaletestPrometheusFlags) attach(opts *clibase.OptionSet) {
|
||||
*opts = append(*opts,
|
||||
serpent.Option{
|
||||
clibase.Option{
|
||||
Flag: "scaletest-prometheus-address",
|
||||
Env: "CODER_SCALETEST_PROMETHEUS_ADDRESS",
|
||||
Default: "0.0.0.0:21112",
|
||||
Description: "Address on which to expose scaletest Prometheus metrics.",
|
||||
Value: serpent.StringOf(&s.Address),
|
||||
Value: clibase.StringOf(&s.Address),
|
||||
},
|
||||
serpent.Option{
|
||||
clibase.Option{
|
||||
Flag: "scaletest-prometheus-wait",
|
||||
Env: "CODER_SCALETEST_PROMETHEUS_WAIT",
|
||||
Default: "15s",
|
||||
Description: "How long to wait before exiting in order to allow Prometheus metrics to be scraped.",
|
||||
Value: serpent.DurationOf(&s.Wait),
|
||||
Value: clibase.DurationOf(&s.Wait),
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -392,20 +398,20 @@ func (r *userCleanupRunner) Run(ctx context.Context, _ string, _ io.Writer) erro
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *RootCmd) scaletestCleanup() *serpent.Command {
|
||||
func (r *RootCmd) scaletestCleanup() *clibase.Cmd {
|
||||
var template string
|
||||
|
||||
cleanupStrategy := &scaletestStrategyFlags{cleanup: true}
|
||||
client := new(codersdk.Client)
|
||||
|
||||
cmd := &serpent.Command{
|
||||
cmd := &clibase.Cmd{
|
||||
Use: "cleanup",
|
||||
Short: "Cleanup scaletest workspaces, then cleanup scaletest users.",
|
||||
Long: "The strategy flags will apply to each stage of the cleanup process.",
|
||||
Middleware: serpent.Chain(
|
||||
Middleware: clibase.Chain(
|
||||
r.InitClient(client),
|
||||
),
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
ctx := inv.Context()
|
||||
|
||||
me, err := requireAdmin(ctx, client)
|
||||
@@ -502,12 +508,12 @@ func (r *RootCmd) scaletestCleanup() *serpent.Command {
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Options = serpent.OptionSet{
|
||||
cmd.Options = clibase.OptionSet{
|
||||
{
|
||||
Flag: "template",
|
||||
Env: "CODER_SCALETEST_CLEANUP_TEMPLATE",
|
||||
Description: "Name or ID of the template. Only delete workspaces created from the given template.",
|
||||
Value: serpent.StringOf(&template),
|
||||
Value: clibase.StringOf(&template),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -515,7 +521,7 @@ func (r *RootCmd) scaletestCleanup() *serpent.Command {
|
||||
return cmd
|
||||
}
|
||||
|
||||
func (r *RootCmd) scaletestCreateWorkspaces() *serpent.Command {
|
||||
func (r *RootCmd) scaletestCreateWorkspaces() *clibase.Cmd {
|
||||
var (
|
||||
count int64
|
||||
retry int64
|
||||
@@ -552,12 +558,12 @@ func (r *RootCmd) scaletestCreateWorkspaces() *serpent.Command {
|
||||
|
||||
client := new(codersdk.Client)
|
||||
|
||||
cmd := &serpent.Command{
|
||||
cmd := &clibase.Cmd{
|
||||
Use: "create-workspaces",
|
||||
Short: "Creates many users, then creates a workspace for each user and waits for them finish building and fully come online. Optionally runs a command inside each workspace, and connects to the workspace over WireGuard.",
|
||||
Long: `It is recommended that all rate limits are disabled on the server before running this scaletest. This test generates many login events which will be rate limited against the (most likely single) IP.`,
|
||||
Middleware: r.InitClient(client),
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
ctx := inv.Context()
|
||||
|
||||
me, err := requireAdmin(ctx, client)
|
||||
@@ -661,7 +667,7 @@ func (r *RootCmd) scaletestCreateWorkspaces() *serpent.Command {
|
||||
if runCommand != "" {
|
||||
config.ReconnectingPTY = &reconnectingpty.Config{
|
||||
// AgentID is set by the test automatically.
|
||||
Init: workspacesdk.AgentReconnectingPTYInit{
|
||||
Init: codersdk.WorkspaceAgentReconnectingPTYInit{
|
||||
ID: uuid.Nil,
|
||||
Height: 24,
|
||||
Width: 80,
|
||||
@@ -740,98 +746,98 @@ func (r *RootCmd) scaletestCreateWorkspaces() *serpent.Command {
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Options = serpent.OptionSet{
|
||||
cmd.Options = clibase.OptionSet{
|
||||
{
|
||||
Flag: "count",
|
||||
FlagShorthand: "c",
|
||||
Env: "CODER_SCALETEST_COUNT",
|
||||
Default: "1",
|
||||
Description: "Required: Number of workspaces to create.",
|
||||
Value: serpent.Int64Of(&count),
|
||||
Value: clibase.Int64Of(&count),
|
||||
},
|
||||
{
|
||||
Flag: "retry",
|
||||
Env: "CODER_SCALETEST_RETRY",
|
||||
Default: "0",
|
||||
Description: "Number of tries to create and bring up the workspace.",
|
||||
Value: serpent.Int64Of(&retry),
|
||||
Value: clibase.Int64Of(&retry),
|
||||
},
|
||||
{
|
||||
Flag: "template",
|
||||
FlagShorthand: "t",
|
||||
Env: "CODER_SCALETEST_TEMPLATE",
|
||||
Description: "Required: Name or ID of the template to use for workspaces.",
|
||||
Value: serpent.StringOf(&template),
|
||||
Value: clibase.StringOf(&template),
|
||||
},
|
||||
{
|
||||
Flag: "no-cleanup",
|
||||
Env: "CODER_SCALETEST_NO_CLEANUP",
|
||||
Description: "Do not clean up resources after the test completes. You can cleanup manually using coder scaletest cleanup.",
|
||||
Value: serpent.BoolOf(&noCleanup),
|
||||
Value: clibase.BoolOf(&noCleanup),
|
||||
},
|
||||
{
|
||||
Flag: "no-wait-for-agents",
|
||||
Env: "CODER_SCALETEST_NO_WAIT_FOR_AGENTS",
|
||||
Description: `Do not wait for agents to start before marking the test as succeeded. This can be useful if you are running the test against a template that does not start the agent quickly.`,
|
||||
Value: serpent.BoolOf(&noWaitForAgents),
|
||||
Value: clibase.BoolOf(&noWaitForAgents),
|
||||
},
|
||||
{
|
||||
Flag: "run-command",
|
||||
Env: "CODER_SCALETEST_RUN_COMMAND",
|
||||
Description: "Command to run inside each workspace using reconnecting-pty (i.e. web terminal protocol). " + "If not specified, no command will be run.",
|
||||
Value: serpent.StringOf(&runCommand),
|
||||
Value: clibase.StringOf(&runCommand),
|
||||
},
|
||||
{
|
||||
Flag: "run-timeout",
|
||||
Env: "CODER_SCALETEST_RUN_TIMEOUT",
|
||||
Default: "5s",
|
||||
Description: "Timeout for the command to complete.",
|
||||
Value: serpent.DurationOf(&runTimeout),
|
||||
Value: clibase.DurationOf(&runTimeout),
|
||||
},
|
||||
{
|
||||
Flag: "run-expect-timeout",
|
||||
Env: "CODER_SCALETEST_RUN_EXPECT_TIMEOUT",
|
||||
|
||||
Description: "Expect the command to timeout." + " If the command does not finish within the given --run-timeout, it will be marked as succeeded." + " If the command finishes before the timeout, it will be marked as failed.",
|
||||
Value: serpent.BoolOf(&runExpectTimeout),
|
||||
Value: clibase.BoolOf(&runExpectTimeout),
|
||||
},
|
||||
{
|
||||
Flag: "run-expect-output",
|
||||
Env: "CODER_SCALETEST_RUN_EXPECT_OUTPUT",
|
||||
Description: "Expect the command to output the given string (on a single line). " + "If the command does not output the given string, it will be marked as failed.",
|
||||
Value: serpent.StringOf(&runExpectOutput),
|
||||
Value: clibase.StringOf(&runExpectOutput),
|
||||
},
|
||||
{
|
||||
Flag: "run-log-output",
|
||||
Env: "CODER_SCALETEST_RUN_LOG_OUTPUT",
|
||||
Description: "Log the output of the command to the test logs. " + "This should be left off unless you expect small amounts of output. " + "Large amounts of output will cause high memory usage.",
|
||||
Value: serpent.BoolOf(&runLogOutput),
|
||||
Value: clibase.BoolOf(&runLogOutput),
|
||||
},
|
||||
{
|
||||
Flag: "connect-url",
|
||||
Env: "CODER_SCALETEST_CONNECT_URL",
|
||||
Description: "URL to connect to inside the the workspace over WireGuard. " + "If not specified, no connections will be made over WireGuard.",
|
||||
Value: serpent.StringOf(&connectURL),
|
||||
Value: clibase.StringOf(&connectURL),
|
||||
},
|
||||
{
|
||||
Flag: "connect-mode",
|
||||
Env: "CODER_SCALETEST_CONNECT_MODE",
|
||||
Default: "derp",
|
||||
Description: "Mode to use for connecting to the workspace.",
|
||||
Value: serpent.EnumOf(&connectMode, "derp", "direct"),
|
||||
Value: clibase.EnumOf(&connectMode, "derp", "direct"),
|
||||
},
|
||||
{
|
||||
Flag: "connect-hold",
|
||||
Env: "CODER_SCALETEST_CONNECT_HOLD",
|
||||
Default: "30s",
|
||||
Description: "How long to hold the WireGuard connection open for.",
|
||||
Value: serpent.DurationOf(&connectHold),
|
||||
Value: clibase.DurationOf(&connectHold),
|
||||
},
|
||||
{
|
||||
Flag: "connect-interval",
|
||||
Env: "CODER_SCALETEST_CONNECT_INTERVAL",
|
||||
Default: "1s",
|
||||
Value: serpent.DurationOf(&connectInterval),
|
||||
Value: clibase.DurationOf(&connectInterval),
|
||||
Description: "How long to wait between making requests to the --connect-url once the connection is established.",
|
||||
},
|
||||
{
|
||||
@@ -839,14 +845,14 @@ func (r *RootCmd) scaletestCreateWorkspaces() *serpent.Command {
|
||||
Env: "CODER_SCALETEST_CONNECT_TIMEOUT",
|
||||
Default: "5s",
|
||||
Description: "Timeout for each request to the --connect-url.",
|
||||
Value: serpent.DurationOf(&connectTimeout),
|
||||
Value: clibase.DurationOf(&connectTimeout),
|
||||
},
|
||||
{
|
||||
Flag: "use-host-login",
|
||||
Env: "CODER_SCALETEST_USE_HOST_LOGIN",
|
||||
Default: "false",
|
||||
Description: "Use the user logged in on the host machine, instead of creating users.",
|
||||
Value: serpent.BoolOf(&useHostUser),
|
||||
Value: clibase.BoolOf(&useHostUser),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -858,7 +864,7 @@ func (r *RootCmd) scaletestCreateWorkspaces() *serpent.Command {
|
||||
return cmd
|
||||
}
|
||||
|
||||
func (r *RootCmd) scaletestWorkspaceTraffic() *serpent.Command {
|
||||
func (r *RootCmd) scaletestWorkspaceTraffic() *clibase.Cmd {
|
||||
var (
|
||||
tickInterval time.Duration
|
||||
bytesPerTick int64
|
||||
@@ -875,13 +881,13 @@ func (r *RootCmd) scaletestWorkspaceTraffic() *serpent.Command {
|
||||
prometheusFlags = &scaletestPrometheusFlags{}
|
||||
)
|
||||
|
||||
cmd := &serpent.Command{
|
||||
cmd := &clibase.Cmd{
|
||||
Use: "workspace-traffic",
|
||||
Short: "Generate traffic to scaletest workspaces through coderd",
|
||||
Middleware: serpent.Chain(
|
||||
Middleware: clibase.Chain(
|
||||
r.InitClient(client),
|
||||
),
|
||||
Handler: func(inv *serpent.Invocation) (err error) {
|
||||
Handler: func(inv *clibase.Invocation) (err error) {
|
||||
ctx := inv.Context()
|
||||
|
||||
notifyCtx, stop := signal.NotifyContext(ctx, StopSignals...) // Checked later.
|
||||
@@ -1050,47 +1056,47 @@ func (r *RootCmd) scaletestWorkspaceTraffic() *serpent.Command {
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Options = []serpent.Option{
|
||||
cmd.Options = []clibase.Option{
|
||||
{
|
||||
Flag: "template",
|
||||
FlagShorthand: "t",
|
||||
Env: "CODER_SCALETEST_TEMPLATE",
|
||||
Description: "Name or ID of the template. Traffic generation will be limited to workspaces created from this template.",
|
||||
Value: serpent.StringOf(&template),
|
||||
Value: clibase.StringOf(&template),
|
||||
},
|
||||
{
|
||||
Flag: "target-workspaces",
|
||||
Env: "CODER_SCALETEST_TARGET_WORKSPACES",
|
||||
Description: "Target a specific range of workspaces in the format [START]:[END] (exclusive). Example: 0:10 will target the 10 first alphabetically sorted workspaces (0-9).",
|
||||
Value: serpent.StringOf(&targetWorkspaces),
|
||||
Value: clibase.StringOf(&targetWorkspaces),
|
||||
},
|
||||
{
|
||||
Flag: "bytes-per-tick",
|
||||
Env: "CODER_SCALETEST_WORKSPACE_TRAFFIC_BYTES_PER_TICK",
|
||||
Default: "1024",
|
||||
Description: "How much traffic to generate per tick.",
|
||||
Value: serpent.Int64Of(&bytesPerTick),
|
||||
Value: clibase.Int64Of(&bytesPerTick),
|
||||
},
|
||||
{
|
||||
Flag: "tick-interval",
|
||||
Env: "CODER_SCALETEST_WORKSPACE_TRAFFIC_TICK_INTERVAL",
|
||||
Default: "100ms",
|
||||
Description: "How often to send traffic.",
|
||||
Value: serpent.DurationOf(&tickInterval),
|
||||
Value: clibase.DurationOf(&tickInterval),
|
||||
},
|
||||
{
|
||||
Flag: "ssh",
|
||||
Env: "CODER_SCALETEST_WORKSPACE_TRAFFIC_SSH",
|
||||
Default: "",
|
||||
Description: "Send traffic over SSH, cannot be used with --app.",
|
||||
Value: serpent.BoolOf(&ssh),
|
||||
Value: clibase.BoolOf(&ssh),
|
||||
},
|
||||
{
|
||||
Flag: "app",
|
||||
Env: "CODER_SCALETEST_WORKSPACE_TRAFFIC_APP",
|
||||
Default: "",
|
||||
Description: "Send WebSocket traffic to a workspace app (proxied via coderd), cannot be used with --ssh.",
|
||||
Value: serpent.StringOf(&app),
|
||||
Value: clibase.StringOf(&app),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -1103,7 +1109,7 @@ func (r *RootCmd) scaletestWorkspaceTraffic() *serpent.Command {
|
||||
return cmd
|
||||
}
|
||||
|
||||
func (r *RootCmd) scaletestDashboard() *serpent.Command {
|
||||
func (r *RootCmd) scaletestDashboard() *clibase.Cmd {
|
||||
var (
|
||||
interval time.Duration
|
||||
jitter time.Duration
|
||||
@@ -1119,13 +1125,13 @@ func (r *RootCmd) scaletestDashboard() *serpent.Command {
|
||||
prometheusFlags = &scaletestPrometheusFlags{}
|
||||
)
|
||||
|
||||
cmd := &serpent.Command{
|
||||
cmd := &clibase.Cmd{
|
||||
Use: "dashboard",
|
||||
Short: "Generate traffic to the HTTP API to simulate use of the dashboard.",
|
||||
Middleware: serpent.Chain(
|
||||
Middleware: clibase.Chain(
|
||||
r.InitClient(client),
|
||||
),
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
if !(interval > 0) {
|
||||
return xerrors.Errorf("--interval must be greater than zero")
|
||||
}
|
||||
@@ -1255,40 +1261,40 @@ func (r *RootCmd) scaletestDashboard() *serpent.Command {
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Options = []serpent.Option{
|
||||
cmd.Options = []clibase.Option{
|
||||
{
|
||||
Flag: "target-users",
|
||||
Env: "CODER_SCALETEST_DASHBOARD_TARGET_USERS",
|
||||
Description: "Target a specific range of users in the format [START]:[END] (exclusive). Example: 0:10 will target the 10 first alphabetically sorted users (0-9).",
|
||||
Value: serpent.StringOf(&targetUsers),
|
||||
Value: clibase.StringOf(&targetUsers),
|
||||
},
|
||||
{
|
||||
Flag: "interval",
|
||||
Env: "CODER_SCALETEST_DASHBOARD_INTERVAL",
|
||||
Default: "10s",
|
||||
Description: "Interval between actions.",
|
||||
Value: serpent.DurationOf(&interval),
|
||||
Value: clibase.DurationOf(&interval),
|
||||
},
|
||||
{
|
||||
Flag: "jitter",
|
||||
Env: "CODER_SCALETEST_DASHBOARD_JITTER",
|
||||
Default: "5s",
|
||||
Description: "Jitter between actions.",
|
||||
Value: serpent.DurationOf(&jitter),
|
||||
Value: clibase.DurationOf(&jitter),
|
||||
},
|
||||
{
|
||||
Flag: "headless",
|
||||
Env: "CODER_SCALETEST_DASHBOARD_HEADLESS",
|
||||
Default: "true",
|
||||
Description: "Controls headless mode. Setting to false is useful for debugging.",
|
||||
Value: serpent.BoolOf(&headless),
|
||||
Value: clibase.BoolOf(&headless),
|
||||
},
|
||||
{
|
||||
Flag: "rand-seed",
|
||||
Env: "CODER_SCALETEST_DASHBOARD_RAND_SEED",
|
||||
Default: "0",
|
||||
Description: "Seed for the random number generator.",
|
||||
Value: serpent.Int64Of(&randSeed),
|
||||
Value: clibase.Int64Of(&randSeed),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
|
||||
package cli
|
||||
|
||||
import "github.com/coder/serpent"
|
||||
import "github.com/coder/coder/v2/cli/clibase"
|
||||
|
||||
func (r *RootCmd) scaletestCmd() *serpent.Command {
|
||||
cmd := &serpent.Command{
|
||||
func (r *RootCmd) scaletestCmd() *clibase.Cmd {
|
||||
cmd := &clibase.Cmd{
|
||||
Use: "scaletest",
|
||||
Short: "Run a scale test against the Coder API",
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
SlimUnsupported(inv.Stderr, "exp scaletest")
|
||||
return nil
|
||||
},
|
||||
|
||||
+15
-22
@@ -2,41 +2,39 @@ package cli
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"golang.org/x/xerrors"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/cli/cliui"
|
||||
"github.com/coder/coder/v2/codersdk/agentsdk"
|
||||
"github.com/coder/pretty"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
func (r *RootCmd) externalAuth() *serpent.Command {
|
||||
return &serpent.Command{
|
||||
func (r *RootCmd) externalAuth() *clibase.Cmd {
|
||||
return &clibase.Cmd{
|
||||
Use: "external-auth",
|
||||
Short: "Manage external authentication",
|
||||
Long: "Authenticate with external services inside of a workspace.",
|
||||
Handler: func(i *serpent.Invocation) error {
|
||||
Handler: func(i *clibase.Invocation) error {
|
||||
return i.Command.HelpHandler(i)
|
||||
},
|
||||
Children: []*serpent.Command{
|
||||
Children: []*clibase.Cmd{
|
||||
r.externalAuthAccessToken(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (r *RootCmd) externalAuthAccessToken() *serpent.Command {
|
||||
func (r *RootCmd) externalAuthAccessToken() *clibase.Cmd {
|
||||
var extra string
|
||||
return &serpent.Command{
|
||||
return &clibase.Cmd{
|
||||
Use: "access-token <provider>",
|
||||
Short: "Print auth for an external provider",
|
||||
Long: "Print an access-token for an external auth provider. " +
|
||||
"The access-token will be validated and sent to stdout with exit code 0. " +
|
||||
"If a valid access-token cannot be obtained, the URL to authenticate will be sent to stdout with exit code 1\n" + FormatExamples(
|
||||
Example{
|
||||
"If a valid access-token cannot be obtained, the URL to authenticate will be sent to stdout with exit code 1\n" + formatExamples(
|
||||
example{
|
||||
Description: "Ensure that the user is authenticated with GitHub before cloning.",
|
||||
Command: `#!/usr/bin/env sh
|
||||
|
||||
@@ -49,32 +47,27 @@ else
|
||||
fi
|
||||
`,
|
||||
},
|
||||
Example{
|
||||
example{
|
||||
Description: "Obtain an extra property of an access token for additional metadata.",
|
||||
Command: "coder external-auth access-token slack --extra \"authed_user.id\"",
|
||||
},
|
||||
),
|
||||
Middleware: serpent.Chain(
|
||||
serpent.RequireNArgs(1),
|
||||
Middleware: clibase.Chain(
|
||||
clibase.RequireNArgs(1),
|
||||
),
|
||||
Options: serpent.OptionSet{{
|
||||
Options: clibase.OptionSet{{
|
||||
Name: "Extra",
|
||||
Flag: "extra",
|
||||
Description: "Extract a field from the \"extra\" properties of the OAuth token.",
|
||||
Value: serpent.StringOf(&extra),
|
||||
Value: clibase.StringOf(&extra),
|
||||
}},
|
||||
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
ctx := inv.Context()
|
||||
|
||||
ctx, stop := inv.SignalNotifyContext(ctx, StopSignals...)
|
||||
defer stop()
|
||||
|
||||
if r.agentToken == "" {
|
||||
_, _ = fmt.Fprint(inv.Stderr, pretty.Sprintf(headLineStyle(), "No agent token found, this command must be run from inside a running workspace.\n"))
|
||||
return xerrors.Errorf("agent token not found")
|
||||
}
|
||||
|
||||
client, err := r.createAgentClient()
|
||||
if err != nil {
|
||||
return xerrors.Errorf("create agent client: %w", err)
|
||||
|
||||
@@ -24,7 +24,7 @@ func TestExternalAuth(t *testing.T) {
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
url := srv.URL
|
||||
inv, _ := clitest.New(t, "--agent-url", url, "--agent-token", "foo", "external-auth", "access-token", "github")
|
||||
inv, _ := clitest.New(t, "--agent-url", url, "external-auth", "access-token", "github")
|
||||
pty := ptytest.New(t)
|
||||
inv.Stdout = pty.Output()
|
||||
waiter := clitest.StartWithWaiter(t, inv)
|
||||
@@ -40,7 +40,7 @@ func TestExternalAuth(t *testing.T) {
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
url := srv.URL
|
||||
inv, _ := clitest.New(t, "--agent-url", url, "--agent-token", "foo", "external-auth", "access-token", "github")
|
||||
inv, _ := clitest.New(t, "--agent-url", url, "external-auth", "access-token", "github")
|
||||
pty := ptytest.New(t)
|
||||
inv.Stdout = pty.Output()
|
||||
clitest.Start(t, inv)
|
||||
@@ -55,7 +55,7 @@ func TestExternalAuth(t *testing.T) {
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
url := srv.URL
|
||||
inv, _ := clitest.New(t, "--agent-url", url, "--agent-token", "foo", "external-auth", "access-token")
|
||||
inv, _ := clitest.New(t, "--agent-url", url, "external-auth", "access-token")
|
||||
watier := clitest.StartWithWaiter(t, inv)
|
||||
watier.RequireContains("wanted 1 args but got 0")
|
||||
})
|
||||
@@ -71,7 +71,7 @@ func TestExternalAuth(t *testing.T) {
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
url := srv.URL
|
||||
inv, _ := clitest.New(t, "--agent-url", url, "--agent-token", "foo", "external-auth", "access-token", "github", "--extra", "hey")
|
||||
inv, _ := clitest.New(t, "--agent-url", url, "external-auth", "access-token", "github", "--extra", "hey")
|
||||
pty := ptytest.New(t)
|
||||
inv.Stdout = pty.Output()
|
||||
clitest.Start(t, inv)
|
||||
|
||||
+11
-11
@@ -5,22 +5,22 @@ import (
|
||||
|
||||
"golang.org/x/xerrors"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
func (r *RootCmd) favorite() *serpent.Command {
|
||||
func (r *RootCmd) favorite() *clibase.Cmd {
|
||||
client := new(codersdk.Client)
|
||||
cmd := &serpent.Command{
|
||||
cmd := &clibase.Cmd{
|
||||
Aliases: []string{"fav", "favou" + "rite"},
|
||||
Annotations: workspaceCommand,
|
||||
Use: "favorite <workspace>",
|
||||
Short: "Add a workspace to your favorites",
|
||||
Middleware: serpent.Chain(
|
||||
serpent.RequireNArgs(1),
|
||||
Middleware: clibase.Chain(
|
||||
clibase.RequireNArgs(1),
|
||||
r.InitClient(client),
|
||||
),
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
ws, err := namedWorkspace(inv.Context(), client, inv.Args[0])
|
||||
if err != nil {
|
||||
return xerrors.Errorf("get workspace: %w", err)
|
||||
@@ -36,18 +36,18 @@ func (r *RootCmd) favorite() *serpent.Command {
|
||||
return cmd
|
||||
}
|
||||
|
||||
func (r *RootCmd) unfavorite() *serpent.Command {
|
||||
func (r *RootCmd) unfavorite() *clibase.Cmd {
|
||||
client := new(codersdk.Client)
|
||||
cmd := &serpent.Command{
|
||||
cmd := &clibase.Cmd{
|
||||
Aliases: []string{"unfav", "unfavou" + "rite"},
|
||||
Annotations: workspaceCommand,
|
||||
Use: "unfavorite <workspace>",
|
||||
Short: "Remove a workspace from your favorites",
|
||||
Middleware: serpent.Chain(
|
||||
serpent.RequireNArgs(1),
|
||||
Middleware: clibase.Chain(
|
||||
clibase.RequireNArgs(1),
|
||||
r.InitClient(client),
|
||||
),
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
ws, err := namedWorkspace(inv.Context(), client, inv.Args[0])
|
||||
if err != nil {
|
||||
return xerrors.Errorf("get workspace: %w", err)
|
||||
|
||||
+4
-4
@@ -8,21 +8,21 @@ import (
|
||||
|
||||
"golang.org/x/xerrors"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/cli/cliui"
|
||||
"github.com/coder/coder/v2/cli/gitauth"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/coder/v2/codersdk/agentsdk"
|
||||
"github.com/coder/retry"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
// gitAskpass is used by the Coder agent to automatically authenticate
|
||||
// with Git providers based on a hostname.
|
||||
func (r *RootCmd) gitAskpass() *serpent.Command {
|
||||
return &serpent.Command{
|
||||
func (r *RootCmd) gitAskpass() *clibase.Cmd {
|
||||
return &clibase.Cmd{
|
||||
Use: "gitaskpass",
|
||||
Hidden: true,
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
ctx := inv.Context()
|
||||
|
||||
ctx, stop := inv.SignalNotifyContext(ctx, StopSignals...)
|
||||
|
||||
+4
-4
@@ -13,17 +13,17 @@ import (
|
||||
|
||||
"golang.org/x/xerrors"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/cli/cliui"
|
||||
"github.com/coder/pretty"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
func (r *RootCmd) gitssh() *serpent.Command {
|
||||
cmd := &serpent.Command{
|
||||
func (r *RootCmd) gitssh() *clibase.Cmd {
|
||||
cmd := &clibase.Cmd{
|
||||
Use: "gitssh",
|
||||
Hidden: true,
|
||||
Short: `Wraps the "ssh" command and uses the coder gitssh key for authentication`,
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
ctx := inv.Context()
|
||||
env := os.Environ()
|
||||
|
||||
|
||||
+19
-37
@@ -4,9 +4,7 @@ import (
|
||||
"bufio"
|
||||
_ "embed"
|
||||
"fmt"
|
||||
"os"
|
||||
"regexp"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"text/tabwriter"
|
||||
@@ -17,9 +15,9 @@ import (
|
||||
"golang.org/x/xerrors"
|
||||
|
||||
"github.com/coder/coder/v2/buildinfo"
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/cli/cliui"
|
||||
"github.com/coder/pretty"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
//go:embed help.tpl
|
||||
@@ -28,7 +26,7 @@ var helpTemplateRaw string
|
||||
type optionGroup struct {
|
||||
Name string
|
||||
Description string
|
||||
Options serpent.OptionSet
|
||||
Options clibase.OptionSet
|
||||
}
|
||||
|
||||
func ttyWidth() int {
|
||||
@@ -77,9 +75,9 @@ var usageTemplate = func() *template.Template {
|
||||
headerFg.Format(txt)
|
||||
return txt.String()
|
||||
},
|
||||
"typeHelper": func(opt *serpent.Option) string {
|
||||
"typeHelper": func(opt *clibase.Option) string {
|
||||
switch v := opt.Value.(type) {
|
||||
case *serpent.Enum:
|
||||
case *clibase.Enum:
|
||||
return strings.Join(v.Choices, "|")
|
||||
default:
|
||||
return v.Type()
|
||||
@@ -109,7 +107,7 @@ var usageTemplate = func() *template.Template {
|
||||
}
|
||||
return sb.String()
|
||||
},
|
||||
"formatSubcommand": func(cmd *serpent.Command) string {
|
||||
"formatSubcommand": func(cmd *clibase.Cmd) string {
|
||||
// Minimize padding by finding the longest neighboring name.
|
||||
maxNameLength := len(cmd.Name())
|
||||
if parent := cmd.Parent; parent != nil {
|
||||
@@ -144,23 +142,23 @@ var usageTemplate = func() *template.Template {
|
||||
|
||||
return sb.String()
|
||||
},
|
||||
"envName": func(opt serpent.Option) string {
|
||||
"envName": func(opt clibase.Option) string {
|
||||
if opt.Env == "" {
|
||||
return ""
|
||||
}
|
||||
return opt.Env
|
||||
},
|
||||
"flagName": func(opt serpent.Option) string {
|
||||
"flagName": func(opt clibase.Option) string {
|
||||
return opt.Flag
|
||||
},
|
||||
|
||||
"isEnterprise": func(opt serpent.Option) bool {
|
||||
"isEnterprise": func(opt clibase.Option) bool {
|
||||
return opt.Annotations.IsSet("enterprise")
|
||||
},
|
||||
"isDeprecated": func(opt serpent.Option) bool {
|
||||
"isDeprecated": func(opt clibase.Option) bool {
|
||||
return len(opt.UseInstead) > 0
|
||||
},
|
||||
"useInstead": func(opt serpent.Option) string {
|
||||
"useInstead": func(opt clibase.Option) string {
|
||||
var sb strings.Builder
|
||||
for i, s := range opt.UseInstead {
|
||||
if i > 0 {
|
||||
@@ -191,12 +189,12 @@ var usageTemplate = func() *template.Template {
|
||||
s = wrapTTY(s)
|
||||
return s
|
||||
},
|
||||
"visibleChildren": func(cmd *serpent.Command) []*serpent.Command {
|
||||
return filterSlice(cmd.Children, func(c *serpent.Command) bool {
|
||||
"visibleChildren": func(cmd *clibase.Cmd) []*clibase.Cmd {
|
||||
return filterSlice(cmd.Children, func(c *clibase.Cmd) bool {
|
||||
return !c.Hidden
|
||||
})
|
||||
},
|
||||
"optionGroups": func(cmd *serpent.Command) []optionGroup {
|
||||
"optionGroups": func(cmd *clibase.Cmd) []optionGroup {
|
||||
groups := []optionGroup{{
|
||||
// Default group.
|
||||
Name: "",
|
||||
@@ -242,7 +240,7 @@ var usageTemplate = func() *template.Template {
|
||||
groups = append(groups, optionGroup{
|
||||
Name: groupName,
|
||||
Description: opt.Group.Description,
|
||||
Options: serpent.OptionSet{opt},
|
||||
Options: clibase.OptionSet{opt},
|
||||
})
|
||||
}
|
||||
sort.Slice(groups, func(i, j int) bool {
|
||||
@@ -320,27 +318,8 @@ var usageWantsArgRe = regexp.MustCompile(`<.*>`)
|
||||
|
||||
// helpFn returns a function that generates usage (help)
|
||||
// output for a given command.
|
||||
func helpFn() serpent.HandlerFunc {
|
||||
return func(inv *serpent.Invocation) error {
|
||||
// Check for invalid subcommands before printing help.
|
||||
if len(inv.Args) > 0 && !usageWantsArgRe.MatchString(inv.Command.Use) {
|
||||
_, _ = fmt.Fprintf(inv.Stderr, "---\nerror: unrecognized subcommand %q\n", inv.Args[0])
|
||||
}
|
||||
if len(inv.Args) > 0 {
|
||||
// Return an error so that exit status is non-zero when
|
||||
// a subcommand is not found.
|
||||
err := xerrors.Errorf("unrecognized subcommand %q", strings.Join(inv.Args, " "))
|
||||
if slices.Contains(os.Args, "--help") {
|
||||
// Subcommand error is not wrapped in RunCommandErr if command
|
||||
// is invoked with --help with no HelpHandler
|
||||
return &serpent.RunCommandError{
|
||||
Cmd: inv.Command,
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func helpFn() clibase.HandlerFunc {
|
||||
return func(inv *clibase.Invocation) error {
|
||||
// We use stdout for help and not stderr since there's no straightforward
|
||||
// way to distinguish between a user error and a help request.
|
||||
//
|
||||
@@ -361,6 +340,9 @@ func helpFn() serpent.HandlerFunc {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(inv.Args) > 0 && !usageWantsArgRe.MatchString(inv.Command.Use) {
|
||||
_, _ = fmt.Fprintf(inv.Stderr, "---\nerror: unknown subcommand %q\n", inv.Args[0])
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
+6
-6
@@ -8,10 +8,10 @@ import (
|
||||
|
||||
"golang.org/x/xerrors"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/cli/cliui"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/pretty"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
// workspaceListRow is the type provided to the OutputFormatter. This is a bit
|
||||
@@ -70,7 +70,7 @@ func workspaceListRowFromWorkspace(now time.Time, workspace codersdk.Workspace)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *RootCmd) list() *serpent.Command {
|
||||
func (r *RootCmd) list() *clibase.Cmd {
|
||||
var (
|
||||
filter cliui.WorkspaceFilter
|
||||
formatter = cliui.NewOutputFormatter(
|
||||
@@ -92,16 +92,16 @@ func (r *RootCmd) list() *serpent.Command {
|
||||
)
|
||||
)
|
||||
client := new(codersdk.Client)
|
||||
cmd := &serpent.Command{
|
||||
cmd := &clibase.Cmd{
|
||||
Annotations: workspaceCommand,
|
||||
Use: "list",
|
||||
Short: "List workspaces",
|
||||
Aliases: []string{"ls"},
|
||||
Middleware: serpent.Chain(
|
||||
serpent.RequireNArgs(0),
|
||||
Middleware: clibase.Chain(
|
||||
clibase.RequireNArgs(0),
|
||||
r.InitClient(client),
|
||||
),
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
res, err := queryConvertWorkspaces(inv.Context(), client, filter.Filter(), workspaceListRowFromWorkspace)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
+28
-18
@@ -18,10 +18,11 @@ import (
|
||||
|
||||
"github.com/coder/pretty"
|
||||
|
||||
"github.com/coder/coder/v2/buildinfo"
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/cli/cliui"
|
||||
"github.com/coder/coder/v2/coderd/userpassword"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -39,7 +40,7 @@ func init() {
|
||||
browser.Stdout = io.Discard
|
||||
}
|
||||
|
||||
func promptFirstUsername(inv *serpent.Invocation) (string, error) {
|
||||
func promptFirstUsername(inv *clibase.Invocation) (string, error) {
|
||||
currentUser, err := user.Current()
|
||||
if err != nil {
|
||||
return "", xerrors.Errorf("get current user: %w", err)
|
||||
@@ -58,7 +59,7 @@ func promptFirstUsername(inv *serpent.Invocation) (string, error) {
|
||||
return username, nil
|
||||
}
|
||||
|
||||
func promptFirstPassword(inv *serpent.Invocation) (string, error) {
|
||||
func promptFirstPassword(inv *clibase.Invocation) (string, error) {
|
||||
retry:
|
||||
password, err := cliui.Prompt(inv, cliui.PromptOptions{
|
||||
Text: "Enter a " + pretty.Sprint(cliui.DefaultStyles.Field, "password") + ":",
|
||||
@@ -88,7 +89,7 @@ retry:
|
||||
}
|
||||
|
||||
func (r *RootCmd) loginWithPassword(
|
||||
inv *serpent.Invocation,
|
||||
inv *clibase.Invocation,
|
||||
client *codersdk.Client,
|
||||
email, password string,
|
||||
) error {
|
||||
@@ -124,7 +125,7 @@ func (r *RootCmd) loginWithPassword(
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *RootCmd) login() *serpent.Command {
|
||||
func (r *RootCmd) login() *clibase.Cmd {
|
||||
const firstUserTrialEnv = "CODER_FIRST_USER_TRIAL"
|
||||
|
||||
var (
|
||||
@@ -134,11 +135,11 @@ func (r *RootCmd) login() *serpent.Command {
|
||||
trial bool
|
||||
useTokenForSession bool
|
||||
)
|
||||
cmd := &serpent.Command{
|
||||
cmd := &clibase.Cmd{
|
||||
Use: "login [<url>]",
|
||||
Short: "Authenticate with Coder deployment",
|
||||
Middleware: serpent.RequireRangeArgs(0, 1),
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
Middleware: clibase.RequireRangeArgs(0, 1),
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
ctx := inv.Context()
|
||||
rawURL := ""
|
||||
var urlSource string
|
||||
@@ -179,11 +180,21 @@ func (r *RootCmd) login() *serpent.Command {
|
||||
serverURL.Scheme = "https"
|
||||
}
|
||||
|
||||
client, err := r.createUnauthenticatedClient(ctx, serverURL, inv)
|
||||
client, err := r.createUnauthenticatedClient(ctx, serverURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Try to check the version of the server prior to logging in.
|
||||
// It may be useful to warn the user if they are trying to login
|
||||
// on a very old client.
|
||||
err = r.checkVersions(inv, client, buildinfo.Version())
|
||||
if err != nil {
|
||||
// Checking versions isn't a fatal error so we print a warning
|
||||
// and proceed.
|
||||
_, _ = fmt.Fprintln(inv.Stderr, pretty.Sprint(cliui.DefaultStyles.Warn, err.Error()))
|
||||
}
|
||||
|
||||
hasFirstUser, err := client.HasFirstUser(ctx)
|
||||
if err != nil {
|
||||
return xerrors.Errorf("Failed to check server %q for first user, is the URL correct and is coder accessible from your browser? Error - has initial user: %w", serverURL.String(), err)
|
||||
@@ -287,8 +298,7 @@ func (r *RootCmd) login() *serpent.Command {
|
||||
}
|
||||
|
||||
sessionToken, err = cliui.Prompt(inv, cliui.PromptOptions{
|
||||
Text: "Paste your token here:",
|
||||
Secret: true,
|
||||
Text: "Paste your token here:",
|
||||
Validate: func(token string) error {
|
||||
client.SetSessionToken(token)
|
||||
_, err := client.User(ctx, codersdk.Me)
|
||||
@@ -340,35 +350,35 @@ func (r *RootCmd) login() *serpent.Command {
|
||||
return nil
|
||||
},
|
||||
}
|
||||
cmd.Options = serpent.OptionSet{
|
||||
cmd.Options = clibase.OptionSet{
|
||||
{
|
||||
Flag: "first-user-email",
|
||||
Env: "CODER_FIRST_USER_EMAIL",
|
||||
Description: "Specifies an email address to use if creating the first user for the deployment.",
|
||||
Value: serpent.StringOf(&email),
|
||||
Value: clibase.StringOf(&email),
|
||||
},
|
||||
{
|
||||
Flag: "first-user-username",
|
||||
Env: "CODER_FIRST_USER_USERNAME",
|
||||
Description: "Specifies a username to use if creating the first user for the deployment.",
|
||||
Value: serpent.StringOf(&username),
|
||||
Value: clibase.StringOf(&username),
|
||||
},
|
||||
{
|
||||
Flag: "first-user-password",
|
||||
Env: "CODER_FIRST_USER_PASSWORD",
|
||||
Description: "Specifies a password to use if creating the first user for the deployment.",
|
||||
Value: serpent.StringOf(&password),
|
||||
Value: clibase.StringOf(&password),
|
||||
},
|
||||
{
|
||||
Flag: "first-user-trial",
|
||||
Env: firstUserTrialEnv,
|
||||
Description: "Specifies whether a trial license should be provisioned for the Coder deployment or not.",
|
||||
Value: serpent.BoolOf(&trial),
|
||||
Value: clibase.BoolOf(&trial),
|
||||
},
|
||||
{
|
||||
Flag: "use-token-as-session",
|
||||
Description: "By default, the CLI will generate a new session token when logging in. This flag will instead use the provided token as the session token.",
|
||||
Value: serpent.BoolOf(&useTokenForSession),
|
||||
Value: clibase.BoolOf(&useTokenForSession),
|
||||
},
|
||||
}
|
||||
return cmd
|
||||
@@ -387,7 +397,7 @@ func isWSL() (bool, error) {
|
||||
}
|
||||
|
||||
// openURL opens the provided URL via user's default browser
|
||||
func openURL(inv *serpent.Invocation, urlToOpen string) error {
|
||||
func openURL(inv *clibase.Invocation, urlToOpen string) error {
|
||||
noOpen, err := inv.ParsedFlags().GetBool(varNoOpen)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
|
||||
+5
-5
@@ -7,20 +7,20 @@ import (
|
||||
|
||||
"golang.org/x/xerrors"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/cli/cliui"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
func (r *RootCmd) logout() *serpent.Command {
|
||||
func (r *RootCmd) logout() *clibase.Cmd {
|
||||
client := new(codersdk.Client)
|
||||
cmd := &serpent.Command{
|
||||
cmd := &clibase.Cmd{
|
||||
Use: "logout",
|
||||
Short: "Unauthenticate your local session",
|
||||
Middleware: serpent.Chain(
|
||||
Middleware: clibase.Chain(
|
||||
r.InitClient(client),
|
||||
),
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
var errors []error
|
||||
|
||||
config := r.createConfig()
|
||||
|
||||
@@ -97,6 +97,33 @@ func TestLogout(t *testing.T) {
|
||||
|
||||
<-logoutChan
|
||||
})
|
||||
t.Run("NoSessionFile", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
pty := ptytest.New(t)
|
||||
config := login(t, pty)
|
||||
|
||||
// Ensure session files exist.
|
||||
require.FileExists(t, string(config.URL()))
|
||||
require.FileExists(t, string(config.Session()))
|
||||
|
||||
err := os.Remove(string(config.Session()))
|
||||
require.NoError(t, err)
|
||||
|
||||
logoutChan := make(chan struct{})
|
||||
logout, _ := clitest.New(t, "logout", "--global-config", string(config))
|
||||
|
||||
logout.Stdin = pty.Input()
|
||||
logout.Stdout = pty.Output()
|
||||
|
||||
go func() {
|
||||
defer close(logoutChan)
|
||||
err = logout.Run()
|
||||
assert.ErrorContains(t, err, "You are not logged in. Try logging in using 'coder login'.")
|
||||
}()
|
||||
|
||||
<-logoutChan
|
||||
})
|
||||
t.Run("CannotDeleteFiles", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
|
||||
+7
-8
@@ -8,26 +8,25 @@ import (
|
||||
|
||||
"golang.org/x/xerrors"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/coderd/healthcheck/derphealth"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/coder/v2/codersdk/workspacesdk"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
func (r *RootCmd) netcheck() *serpent.Command {
|
||||
func (r *RootCmd) netcheck() *clibase.Cmd {
|
||||
client := new(codersdk.Client)
|
||||
|
||||
cmd := &serpent.Command{
|
||||
cmd := &clibase.Cmd{
|
||||
Use: "netcheck",
|
||||
Short: "Print network debug information for DERP and STUN",
|
||||
Middleware: serpent.Chain(
|
||||
Middleware: clibase.Chain(
|
||||
r.InitClient(client),
|
||||
),
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
ctx, cancel := context.WithTimeout(inv.Context(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
connInfo, err := workspacesdk.New(client).AgentConnectionInfoGeneric(ctx)
|
||||
connInfo, err := client.WorkspaceAgentConnectionInfoGeneric(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -57,6 +56,6 @@ func (r *RootCmd) netcheck() *serpent.Command {
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Options = serpent.OptionSet{}
|
||||
cmd.Options = clibase.OptionSet{}
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clitest"
|
||||
"github.com/coder/coder/v2/codersdk/healthsdk"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/coder/v2/pty/ptytest"
|
||||
)
|
||||
|
||||
@@ -27,7 +27,7 @@ func TestNetcheck(t *testing.T) {
|
||||
|
||||
b := out.Bytes()
|
||||
t.Log(string(b))
|
||||
var report healthsdk.DERPHealthReport
|
||||
var report codersdk.DERPHealthReport
|
||||
require.NoError(t, json.Unmarshal(b, &report))
|
||||
|
||||
assert.True(t, report.Healthy)
|
||||
|
||||
+14
-14
@@ -12,19 +12,19 @@ import (
|
||||
"github.com/skratchdot/open-golang/open"
|
||||
"golang.org/x/xerrors"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/cli/cliui"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
func (r *RootCmd) open() *serpent.Command {
|
||||
cmd := &serpent.Command{
|
||||
func (r *RootCmd) open() *clibase.Cmd {
|
||||
cmd := &clibase.Cmd{
|
||||
Use: "open",
|
||||
Short: "Open a workspace",
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
return inv.Command.HelpHandler(inv)
|
||||
},
|
||||
Children: []*serpent.Command{
|
||||
Children: []*clibase.Cmd{
|
||||
r.openVSCode(),
|
||||
},
|
||||
}
|
||||
@@ -33,22 +33,22 @@ func (r *RootCmd) open() *serpent.Command {
|
||||
|
||||
const vscodeDesktopName = "VS Code Desktop"
|
||||
|
||||
func (r *RootCmd) openVSCode() *serpent.Command {
|
||||
func (r *RootCmd) openVSCode() *clibase.Cmd {
|
||||
var (
|
||||
generateToken bool
|
||||
testOpenError bool
|
||||
)
|
||||
|
||||
client := new(codersdk.Client)
|
||||
cmd := &serpent.Command{
|
||||
cmd := &clibase.Cmd{
|
||||
Annotations: workspaceCommand,
|
||||
Use: "vscode <workspace> [<directory in workspace>]",
|
||||
Short: fmt.Sprintf("Open a workspace in %s", vscodeDesktopName),
|
||||
Middleware: serpent.Chain(
|
||||
serpent.RequireRangeArgs(1, 2),
|
||||
Middleware: clibase.Chain(
|
||||
clibase.RequireRangeArgs(1, 2),
|
||||
r.InitClient(client),
|
||||
),
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
ctx, cancel := context.WithCancel(inv.Context())
|
||||
defer cancel()
|
||||
|
||||
@@ -64,7 +64,7 @@ func (r *RootCmd) openVSCode() *serpent.Command {
|
||||
// need to wait for the agent to start.
|
||||
workspaceQuery := inv.Args[0]
|
||||
autostart := true
|
||||
workspace, workspaceAgent, err := getWorkspaceAndAgent(ctx, inv, client, autostart, workspaceQuery)
|
||||
workspace, workspaceAgent, err := getWorkspaceAndAgent(ctx, inv, client, autostart, codersdk.Me, workspaceQuery)
|
||||
if err != nil {
|
||||
return xerrors.Errorf("get workspace and agent: %w", err)
|
||||
}
|
||||
@@ -186,7 +186,7 @@ func (r *RootCmd) openVSCode() *serpent.Command {
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Options = serpent.OptionSet{
|
||||
cmd.Options = clibase.OptionSet{
|
||||
{
|
||||
Flag: "generate-token",
|
||||
Env: "CODER_OPEN_VSCODE_GENERATE_TOKEN",
|
||||
@@ -195,12 +195,12 @@ func (r *RootCmd) openVSCode() *serpent.Command {
|
||||
"This flag does not need to be specified when running this command on a local machine unless automatic open fails.",
|
||||
vscodeDesktopName,
|
||||
),
|
||||
Value: serpent.BoolOf(&generateToken),
|
||||
Value: clibase.BoolOf(&generateToken),
|
||||
},
|
||||
{
|
||||
Flag: "test.open-error",
|
||||
Description: "Don't run the open command.",
|
||||
Value: serpent.BoolOf(&testOpenError),
|
||||
Value: clibase.BoolOf(&testOpenError),
|
||||
Hidden: true, // This is for testing!
|
||||
},
|
||||
}
|
||||
|
||||
+23
-24
@@ -9,57 +9,56 @@ import (
|
||||
|
||||
"golang.org/x/xerrors"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/cli/cliui"
|
||||
"github.com/coder/coder/v2/cli/config"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/pretty"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
func (r *RootCmd) organizations() *serpent.Command {
|
||||
cmd := &serpent.Command{
|
||||
func (r *RootCmd) organizations() *clibase.Cmd {
|
||||
cmd := &clibase.Cmd{
|
||||
Annotations: workspaceCommand,
|
||||
Use: "organizations [subcommand]",
|
||||
Short: "Organization related commands",
|
||||
Aliases: []string{"organization", "org", "orgs"},
|
||||
Hidden: true, // Hidden until these commands are complete.
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
return inv.Command.HelpHandler(inv)
|
||||
},
|
||||
Children: []*serpent.Command{
|
||||
Children: []*clibase.Cmd{
|
||||
r.currentOrganization(),
|
||||
r.switchOrganization(),
|
||||
r.createOrganization(),
|
||||
r.organizationRoles(),
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Options = serpent.OptionSet{}
|
||||
cmd.Options = clibase.OptionSet{}
|
||||
return cmd
|
||||
}
|
||||
|
||||
func (r *RootCmd) switchOrganization() *serpent.Command {
|
||||
func (r *RootCmd) switchOrganization() *clibase.Cmd {
|
||||
client := new(codersdk.Client)
|
||||
|
||||
cmd := &serpent.Command{
|
||||
cmd := &clibase.Cmd{
|
||||
Use: "set <organization name | ID>",
|
||||
Short: "set the organization used by the CLI. Pass an empty string to reset to the default organization.",
|
||||
Long: "set the organization used by the CLI. Pass an empty string to reset to the default organization.\n" + FormatExamples(
|
||||
Example{
|
||||
Long: "set the organization used by the CLI. Pass an empty string to reset to the default organization.\n" + formatExamples(
|
||||
example{
|
||||
Description: "Remove the current organization and defer to the default.",
|
||||
Command: "coder organizations set ''",
|
||||
},
|
||||
Example{
|
||||
example{
|
||||
Description: "Switch to a custom organization.",
|
||||
Command: "coder organizations set my-org",
|
||||
},
|
||||
),
|
||||
Middleware: serpent.Chain(
|
||||
Middleware: clibase.Chain(
|
||||
r.InitClient(client),
|
||||
serpent.RequireRangeArgs(0, 1),
|
||||
clibase.RequireRangeArgs(0, 1),
|
||||
),
|
||||
Options: serpent.OptionSet{},
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
Options: clibase.OptionSet{},
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
conf := r.createConfig()
|
||||
orgs, err := client.OrganizationsByUser(inv.Context(), codersdk.Me)
|
||||
if err != nil {
|
||||
@@ -139,7 +138,7 @@ func (r *RootCmd) switchOrganization() *serpent.Command {
|
||||
|
||||
// promptUserSelectOrg will prompt the user to select an organization from a list
|
||||
// of their organizations.
|
||||
func promptUserSelectOrg(inv *serpent.Invocation, conf config.Root, orgs []codersdk.Organization) (string, error) {
|
||||
func promptUserSelectOrg(inv *clibase.Invocation, conf config.Root, orgs []codersdk.Organization) (string, error) {
|
||||
// Default choice
|
||||
var defaultOrg string
|
||||
// Comes from config file
|
||||
@@ -207,7 +206,7 @@ func orgNames(orgs []codersdk.Organization) []string {
|
||||
return names
|
||||
}
|
||||
|
||||
func (r *RootCmd) currentOrganization() *serpent.Command {
|
||||
func (r *RootCmd) currentOrganization() *clibase.Cmd {
|
||||
var (
|
||||
stringFormat func(orgs []codersdk.Organization) (string, error)
|
||||
client = new(codersdk.Client)
|
||||
@@ -225,23 +224,23 @@ func (r *RootCmd) currentOrganization() *serpent.Command {
|
||||
)
|
||||
onlyID = false
|
||||
)
|
||||
cmd := &serpent.Command{
|
||||
cmd := &clibase.Cmd{
|
||||
Use: "show [current|me|uuid]",
|
||||
Short: "Show the organization, if no argument is given, the organization currently in use will be shown.",
|
||||
Middleware: serpent.Chain(
|
||||
Middleware: clibase.Chain(
|
||||
r.InitClient(client),
|
||||
serpent.RequireRangeArgs(0, 1),
|
||||
clibase.RequireRangeArgs(0, 1),
|
||||
),
|
||||
Options: serpent.OptionSet{
|
||||
Options: clibase.OptionSet{
|
||||
{
|
||||
Name: "only-id",
|
||||
Description: "Only print the organization ID.",
|
||||
Required: false,
|
||||
Flag: "only-id",
|
||||
Value: serpent.BoolOf(&onlyID),
|
||||
Value: clibase.BoolOf(&onlyID),
|
||||
},
|
||||
},
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
orgArg := "current"
|
||||
if len(inv.Args) >= 1 {
|
||||
orgArg = inv.Args[0]
|
||||
|
||||
@@ -1,14 +1,8 @@
|
||||
package cli_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clitest"
|
||||
@@ -22,38 +16,6 @@ import (
|
||||
func TestCurrentOrganization(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
// This test emulates 2 cases:
|
||||
// 1. The user is not a part of the default organization, but only belongs to one.
|
||||
// 2. The user is connecting to an older Coder instance.
|
||||
t.Run("no-default", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
orgID := uuid.New()
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
json.NewEncoder(w).Encode([]codersdk.Organization{
|
||||
{
|
||||
ID: orgID,
|
||||
Name: "not-default",
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
IsDefault: false,
|
||||
},
|
||||
})
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
client := codersdk.New(must(url.Parse(srv.URL)))
|
||||
inv, root := clitest.New(t, "organizations", "show", "current")
|
||||
clitest.SetupConfig(t, client, root)
|
||||
pty := ptytest.New(t).Attach(inv)
|
||||
errC := make(chan error)
|
||||
go func() {
|
||||
errC <- inv.Run()
|
||||
}()
|
||||
require.NoError(t, <-errC)
|
||||
pty.ExpectMatch(orgID.String())
|
||||
})
|
||||
|
||||
t.Run("OnlyID", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
ownerClient := coderdtest.New(t, nil)
|
||||
@@ -146,10 +108,3 @@ func TestOrganizationSwitch(t *testing.T) {
|
||||
pty.ExpectMatch(exp.ID.String())
|
||||
})
|
||||
}
|
||||
|
||||
func must[V any](v V, err error) V {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
@@ -6,28 +6,28 @@ import (
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/xerrors"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/cli/cliui"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/pretty"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
func (r *RootCmd) createOrganization() *serpent.Command {
|
||||
func (r *RootCmd) createOrganization() *clibase.Cmd {
|
||||
client := new(codersdk.Client)
|
||||
|
||||
cmd := &serpent.Command{
|
||||
cmd := &clibase.Cmd{
|
||||
Use: "create <organization name>",
|
||||
Short: "Create a new organization.",
|
||||
// This action is currently irreversible, so it's hidden until we have a way to delete organizations.
|
||||
Hidden: true,
|
||||
Middleware: serpent.Chain(
|
||||
Middleware: clibase.Chain(
|
||||
r.InitClient(client),
|
||||
serpent.RequireNArgs(1),
|
||||
clibase.RequireNArgs(1),
|
||||
),
|
||||
Options: serpent.OptionSet{
|
||||
Options: clibase.OptionSet{
|
||||
cliui.SkipPromptOption(),
|
||||
},
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
orgName := inv.Args[0]
|
||||
|
||||
// This check is not perfect since not all users can read all organizations.
|
||||
|
||||
@@ -1,113 +0,0 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/xerrors"
|
||||
|
||||
"github.com/coder/coder/v2/cli/cliui"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
func (r *RootCmd) organizationRoles() *serpent.Command {
|
||||
cmd := &serpent.Command{
|
||||
Use: "roles",
|
||||
Short: "Manage organization roles.",
|
||||
Aliases: []string{"role"},
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
return inv.Command.HelpHandler(inv)
|
||||
},
|
||||
Hidden: true,
|
||||
Children: []*serpent.Command{
|
||||
r.showOrganizationRoles(),
|
||||
},
|
||||
}
|
||||
return cmd
|
||||
}
|
||||
|
||||
func (r *RootCmd) showOrganizationRoles() *serpent.Command {
|
||||
formatter := cliui.NewOutputFormatter(
|
||||
cliui.ChangeFormatterData(
|
||||
cliui.TableFormat([]assignableRolesTableRow{}, []string{"name", "display_name", "built_in", "site_permissions", "org_permissions", "user_permissions"}),
|
||||
func(data any) (any, error) {
|
||||
input, ok := data.([]codersdk.AssignableRoles)
|
||||
if !ok {
|
||||
return nil, xerrors.Errorf("expected []codersdk.AssignableRoles got %T", data)
|
||||
}
|
||||
rows := make([]assignableRolesTableRow, 0, len(input))
|
||||
for _, role := range input {
|
||||
rows = append(rows, assignableRolesTableRow{
|
||||
Name: role.Name,
|
||||
DisplayName: role.DisplayName,
|
||||
SitePermissions: fmt.Sprintf("%d permissions", len(role.SitePermissions)),
|
||||
OrganizationPermissions: fmt.Sprintf("%d organizations", len(role.OrganizationPermissions)),
|
||||
UserPermissions: fmt.Sprintf("%d permissions", len(role.UserPermissions)),
|
||||
Assignable: role.Assignable,
|
||||
BuiltIn: role.BuiltIn,
|
||||
})
|
||||
}
|
||||
return rows, nil
|
||||
},
|
||||
),
|
||||
cliui.JSONFormat(),
|
||||
)
|
||||
|
||||
client := new(codersdk.Client)
|
||||
cmd := &serpent.Command{
|
||||
Use: "show [role_names ...]",
|
||||
Short: "Show role(s)",
|
||||
Middleware: serpent.Chain(
|
||||
r.InitClient(client),
|
||||
),
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
ctx := inv.Context()
|
||||
org, err := CurrentOrganization(r, inv, client)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
roles, err := client.ListOrganizationRoles(ctx, org.ID)
|
||||
if err != nil {
|
||||
return xerrors.Errorf("listing roles: %w", err)
|
||||
}
|
||||
|
||||
if len(inv.Args) > 0 {
|
||||
// filter roles
|
||||
filtered := make([]codersdk.AssignableRoles, 0)
|
||||
for _, role := range roles {
|
||||
if slices.ContainsFunc(inv.Args, func(s string) bool {
|
||||
return strings.EqualFold(s, role.Name)
|
||||
}) {
|
||||
filtered = append(filtered, role)
|
||||
}
|
||||
}
|
||||
roles = filtered
|
||||
}
|
||||
|
||||
out, err := formatter.Format(inv.Context(), roles)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = fmt.Fprintln(inv.Stdout, out)
|
||||
return err
|
||||
},
|
||||
}
|
||||
formatter.AttachOptions(&cmd.Options)
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
type assignableRolesTableRow struct {
|
||||
Name string `table:"name,default_sort"`
|
||||
DisplayName string `table:"display_name"`
|
||||
SitePermissions string ` table:"site_permissions"`
|
||||
// map[<org_id>] -> Permissions
|
||||
OrganizationPermissions string `table:"org_permissions"`
|
||||
UserPermissions string `table:"user_permissions"`
|
||||
Assignable bool `table:"assignable"`
|
||||
BuiltIn bool `table:"built_in"`
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
package cli_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clitest"
|
||||
"github.com/coder/coder/v2/coderd/coderdtest"
|
||||
"github.com/coder/coder/v2/coderd/database"
|
||||
"github.com/coder/coder/v2/coderd/database/dbgen"
|
||||
"github.com/coder/coder/v2/coderd/rbac"
|
||||
"github.com/coder/coder/v2/testutil"
|
||||
)
|
||||
|
||||
func TestShowOrganizationRoles(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
t.Run("OK", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ownerClient, db := coderdtest.NewWithDatabase(t, &coderdtest.Options{})
|
||||
owner := coderdtest.CreateFirstUser(t, ownerClient)
|
||||
client, _ := coderdtest.CreateAnotherUser(t, ownerClient, owner.OrganizationID, rbac.RoleUserAdmin())
|
||||
|
||||
const expectedRole = "test-role"
|
||||
dbgen.CustomRole(t, db, database.CustomRole{
|
||||
Name: expectedRole,
|
||||
DisplayName: "Expected",
|
||||
SitePermissions: nil,
|
||||
OrgPermissions: nil,
|
||||
UserPermissions: nil,
|
||||
OrganizationID: uuid.NullUUID{
|
||||
UUID: owner.OrganizationID,
|
||||
Valid: true,
|
||||
},
|
||||
})
|
||||
|
||||
ctx := testutil.Context(t, testutil.WaitMedium)
|
||||
inv, root := clitest.New(t, "organization", "roles", "show")
|
||||
clitest.SetupConfig(t, client, root)
|
||||
|
||||
buf := new(bytes.Buffer)
|
||||
inv.Stdout = buf
|
||||
err := inv.WithContext(ctx).Run()
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, buf.String(), expectedRole)
|
||||
})
|
||||
}
|
||||
+17
-30
@@ -9,8 +9,8 @@ import (
|
||||
"golang.org/x/xerrors"
|
||||
"gopkg.in/yaml.v3"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
// workspaceParameterFlags are used by commands processing rich parameters and/or build options.
|
||||
@@ -18,68 +18,55 @@ type workspaceParameterFlags struct {
|
||||
promptBuildOptions bool
|
||||
buildOptions []string
|
||||
|
||||
richParameterFile string
|
||||
richParameters []string
|
||||
richParameterDefaults []string
|
||||
richParameterFile string
|
||||
richParameters []string
|
||||
|
||||
promptRichParameters bool
|
||||
}
|
||||
|
||||
func (wpf *workspaceParameterFlags) allOptions() []serpent.Option {
|
||||
func (wpf *workspaceParameterFlags) allOptions() []clibase.Option {
|
||||
options := append(wpf.cliBuildOptions(), wpf.cliParameters()...)
|
||||
options = append(options, wpf.cliParameterDefaults()...)
|
||||
return append(options, wpf.alwaysPrompt())
|
||||
}
|
||||
|
||||
func (wpf *workspaceParameterFlags) cliBuildOptions() []serpent.Option {
|
||||
return serpent.OptionSet{
|
||||
func (wpf *workspaceParameterFlags) cliBuildOptions() []clibase.Option {
|
||||
return clibase.OptionSet{
|
||||
{
|
||||
Flag: "build-option",
|
||||
Env: "CODER_BUILD_OPTION",
|
||||
Description: `Build option value in the format "name=value".`,
|
||||
Value: serpent.StringArrayOf(&wpf.buildOptions),
|
||||
Value: clibase.StringArrayOf(&wpf.buildOptions),
|
||||
},
|
||||
{
|
||||
Flag: "build-options",
|
||||
Description: "Prompt for one-time build options defined with ephemeral parameters.",
|
||||
Value: serpent.BoolOf(&wpf.promptBuildOptions),
|
||||
Value: clibase.BoolOf(&wpf.promptBuildOptions),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (wpf *workspaceParameterFlags) cliParameters() []serpent.Option {
|
||||
return serpent.OptionSet{
|
||||
serpent.Option{
|
||||
func (wpf *workspaceParameterFlags) cliParameters() []clibase.Option {
|
||||
return clibase.OptionSet{
|
||||
clibase.Option{
|
||||
Flag: "parameter",
|
||||
Env: "CODER_RICH_PARAMETER",
|
||||
Description: `Rich parameter value in the format "name=value".`,
|
||||
Value: serpent.StringArrayOf(&wpf.richParameters),
|
||||
Value: clibase.StringArrayOf(&wpf.richParameters),
|
||||
},
|
||||
serpent.Option{
|
||||
clibase.Option{
|
||||
Flag: "rich-parameter-file",
|
||||
Env: "CODER_RICH_PARAMETER_FILE",
|
||||
Description: "Specify a file path with values for rich parameters defined in the template.",
|
||||
Value: serpent.StringOf(&wpf.richParameterFile),
|
||||
Value: clibase.StringOf(&wpf.richParameterFile),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (wpf *workspaceParameterFlags) cliParameterDefaults() []serpent.Option {
|
||||
return serpent.OptionSet{
|
||||
serpent.Option{
|
||||
Flag: "parameter-default",
|
||||
Env: "CODER_RICH_PARAMETER_DEFAULT",
|
||||
Description: `Rich parameter default values in the format "name=value".`,
|
||||
Value: serpent.StringArrayOf(&wpf.richParameterDefaults),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (wpf *workspaceParameterFlags) alwaysPrompt() serpent.Option {
|
||||
return serpent.Option{
|
||||
func (wpf *workspaceParameterFlags) alwaysPrompt() clibase.Option {
|
||||
return clibase.Option{
|
||||
Flag: "always-prompt",
|
||||
Description: "Always prompt all parameters. Does not pull parameter values from existing workspace.",
|
||||
Value: serpent.BoolOf(&wpf.promptRichParameters),
|
||||
Value: clibase.BoolOf(&wpf.promptRichParameters),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,11 +6,11 @@ import (
|
||||
|
||||
"golang.org/x/xerrors"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/cli/cliui"
|
||||
"github.com/coder/coder/v2/cli/cliutil/levenshtein"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/pretty"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
type WorkspaceCLIAction int
|
||||
@@ -26,10 +26,9 @@ type ParameterResolver struct {
|
||||
lastBuildParameters []codersdk.WorkspaceBuildParameter
|
||||
sourceWorkspaceParameters []codersdk.WorkspaceBuildParameter
|
||||
|
||||
richParameters []codersdk.WorkspaceBuildParameter
|
||||
richParametersDefaults map[string]string
|
||||
richParametersFile map[string]string
|
||||
buildOptions []codersdk.WorkspaceBuildParameter
|
||||
richParameters []codersdk.WorkspaceBuildParameter
|
||||
richParametersFile map[string]string
|
||||
buildOptions []codersdk.WorkspaceBuildParameter
|
||||
|
||||
promptRichParameters bool
|
||||
promptBuildOptions bool
|
||||
@@ -60,16 +59,6 @@ func (pr *ParameterResolver) WithRichParametersFile(fileMap map[string]string) *
|
||||
return pr
|
||||
}
|
||||
|
||||
func (pr *ParameterResolver) WithRichParametersDefaults(params []codersdk.WorkspaceBuildParameter) *ParameterResolver {
|
||||
if pr.richParametersDefaults == nil {
|
||||
pr.richParametersDefaults = make(map[string]string)
|
||||
}
|
||||
for _, p := range params {
|
||||
pr.richParametersDefaults[p.Name] = p.Value
|
||||
}
|
||||
return pr
|
||||
}
|
||||
|
||||
func (pr *ParameterResolver) WithPromptRichParameters(promptRichParameters bool) *ParameterResolver {
|
||||
pr.promptRichParameters = promptRichParameters
|
||||
return pr
|
||||
@@ -80,7 +69,7 @@ func (pr *ParameterResolver) WithPromptBuildOptions(promptBuildOptions bool) *Pa
|
||||
return pr
|
||||
}
|
||||
|
||||
func (pr *ParameterResolver) Resolve(inv *serpent.Invocation, action WorkspaceCLIAction, templateVersionParameters []codersdk.TemplateVersionParameter) ([]codersdk.WorkspaceBuildParameter, error) {
|
||||
func (pr *ParameterResolver) Resolve(inv *clibase.Invocation, action WorkspaceCLIAction, templateVersionParameters []codersdk.TemplateVersionParameter) ([]codersdk.WorkspaceBuildParameter, error) {
|
||||
var staged []codersdk.WorkspaceBuildParameter
|
||||
var err error
|
||||
|
||||
@@ -220,7 +209,7 @@ func (pr *ParameterResolver) verifyConstraints(resolved []codersdk.WorkspaceBuil
|
||||
return nil
|
||||
}
|
||||
|
||||
func (pr *ParameterResolver) resolveWithInput(resolved []codersdk.WorkspaceBuildParameter, inv *serpent.Invocation, action WorkspaceCLIAction, templateVersionParameters []codersdk.TemplateVersionParameter) ([]codersdk.WorkspaceBuildParameter, error) {
|
||||
func (pr *ParameterResolver) resolveWithInput(resolved []codersdk.WorkspaceBuildParameter, inv *clibase.Invocation, action WorkspaceCLIAction, templateVersionParameters []codersdk.TemplateVersionParameter) ([]codersdk.WorkspaceBuildParameter, error) {
|
||||
for _, tvp := range templateVersionParameters {
|
||||
p := findWorkspaceBuildParameter(tvp.Name, resolved)
|
||||
if p != nil {
|
||||
@@ -238,7 +227,7 @@ func (pr *ParameterResolver) resolveWithInput(resolved []codersdk.WorkspaceBuild
|
||||
(action == WorkspaceUpdate && tvp.Mutable && tvp.Required) ||
|
||||
(action == WorkspaceUpdate && !tvp.Mutable && firstTimeUse) ||
|
||||
(tvp.Mutable && !tvp.Ephemeral && pr.promptRichParameters) {
|
||||
parameterValue, err := cliui.RichParameter(inv, tvp, pr.richParametersDefaults)
|
||||
parameterValue, err := cliui.RichParameter(inv, tvp)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
+17
-17
@@ -12,13 +12,12 @@ import (
|
||||
|
||||
"github.com/coder/pretty"
|
||||
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/cli/cliui"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/coder/v2/codersdk/workspacesdk"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
func (r *RootCmd) ping() *serpent.Command {
|
||||
func (r *RootCmd) ping() *clibase.Cmd {
|
||||
var (
|
||||
pingNum int64
|
||||
pingTimeout time.Duration
|
||||
@@ -26,15 +25,15 @@ func (r *RootCmd) ping() *serpent.Command {
|
||||
)
|
||||
|
||||
client := new(codersdk.Client)
|
||||
cmd := &serpent.Command{
|
||||
cmd := &clibase.Cmd{
|
||||
Annotations: workspaceCommand,
|
||||
Use: "ping <workspace>",
|
||||
Short: "Ping a workspace",
|
||||
Middleware: serpent.Chain(
|
||||
serpent.RequireNArgs(1),
|
||||
Middleware: clibase.Chain(
|
||||
clibase.RequireNArgs(1),
|
||||
r.InitClient(client),
|
||||
),
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
ctx, cancel := context.WithCancel(inv.Context())
|
||||
defer cancel()
|
||||
|
||||
@@ -42,23 +41,24 @@ func (r *RootCmd) ping() *serpent.Command {
|
||||
_, workspaceAgent, err := getWorkspaceAndAgent(
|
||||
ctx, inv, client,
|
||||
false, // Do not autostart for a ping.
|
||||
workspaceName,
|
||||
codersdk.Me, workspaceName,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
opts := &workspacesdk.DialAgentOptions{}
|
||||
|
||||
logger := inv.Logger
|
||||
if r.verbose {
|
||||
opts.Logger = inv.Logger.AppendSinks(sloghuman.Sink(inv.Stdout)).Leveled(slog.LevelDebug)
|
||||
logger = logger.AppendSinks(sloghuman.Sink(inv.Stdout)).Leveled(slog.LevelDebug)
|
||||
}
|
||||
|
||||
if r.disableDirect {
|
||||
_, _ = fmt.Fprintln(inv.Stderr, "Direct connections disabled.")
|
||||
opts.BlockEndpoints = true
|
||||
}
|
||||
conn, err := workspacesdk.New(client).DialAgent(ctx, workspaceAgent.ID, opts)
|
||||
conn, err := client.DialWorkspaceAgent(ctx, workspaceAgent.ID, &codersdk.DialWorkspaceAgentOptions{
|
||||
Logger: logger,
|
||||
BlockEndpoints: r.disableDirect,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -143,26 +143,26 @@ func (r *RootCmd) ping() *serpent.Command {
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Options = serpent.OptionSet{
|
||||
cmd.Options = clibase.OptionSet{
|
||||
{
|
||||
Flag: "wait",
|
||||
Description: "Specifies how long to wait between pings.",
|
||||
Default: "1s",
|
||||
Value: serpent.DurationOf(&pingWait),
|
||||
Value: clibase.DurationOf(&pingWait),
|
||||
},
|
||||
{
|
||||
Flag: "timeout",
|
||||
FlagShorthand: "t",
|
||||
Default: "5s",
|
||||
Description: "Specifies how long to wait for a ping to complete.",
|
||||
Value: serpent.DurationOf(&pingTimeout),
|
||||
Value: clibase.DurationOf(&pingTimeout),
|
||||
},
|
||||
{
|
||||
Flag: "num",
|
||||
FlagShorthand: "n",
|
||||
Default: "10",
|
||||
Description: "Specifies the number of pings to perform.",
|
||||
Value: serpent.Int64Of(&pingNum),
|
||||
Value: clibase.Int64Of(&pingNum),
|
||||
},
|
||||
}
|
||||
return cmd
|
||||
|
||||
+28
-28
@@ -18,50 +18,49 @@ import (
|
||||
"cdr.dev/slog/sloggers/sloghuman"
|
||||
|
||||
"github.com/coder/coder/v2/agent/agentssh"
|
||||
"github.com/coder/coder/v2/cli/clibase"
|
||||
"github.com/coder/coder/v2/cli/cliui"
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
"github.com/coder/coder/v2/codersdk/workspacesdk"
|
||||
"github.com/coder/serpent"
|
||||
)
|
||||
|
||||
func (r *RootCmd) portForward() *serpent.Command {
|
||||
func (r *RootCmd) portForward() *clibase.Cmd {
|
||||
var (
|
||||
tcpForwards []string // <port>:<port>
|
||||
udpForwards []string // <port>:<port>
|
||||
disableAutostart bool
|
||||
)
|
||||
client := new(codersdk.Client)
|
||||
cmd := &serpent.Command{
|
||||
cmd := &clibase.Cmd{
|
||||
Use: "port-forward <workspace>",
|
||||
Short: `Forward ports from a workspace to the local machine. For reverse port forwarding, use "coder ssh -R".`,
|
||||
Aliases: []string{"tunnel"},
|
||||
Long: FormatExamples(
|
||||
Example{
|
||||
Long: formatExamples(
|
||||
example{
|
||||
Description: "Port forward a single TCP port from 1234 in the workspace to port 5678 on your local machine",
|
||||
Command: "coder port-forward <workspace> --tcp 5678:1234",
|
||||
},
|
||||
Example{
|
||||
example{
|
||||
Description: "Port forward a single UDP port from port 9000 to port 9000 on your local machine",
|
||||
Command: "coder port-forward <workspace> --udp 9000",
|
||||
},
|
||||
Example{
|
||||
example{
|
||||
Description: "Port forward multiple TCP ports and a UDP port",
|
||||
Command: "coder port-forward <workspace> --tcp 8080:8080 --tcp 9000:3000 --udp 5353:53",
|
||||
},
|
||||
Example{
|
||||
example{
|
||||
Description: "Port forward multiple ports (TCP or UDP) in condensed syntax",
|
||||
Command: "coder port-forward <workspace> --tcp 8080,9000:3000,9090-9092,10000-10002:10010-10012",
|
||||
},
|
||||
Example{
|
||||
example{
|
||||
Description: "Port forward specifying the local address to bind to",
|
||||
Command: "coder port-forward <workspace> --tcp 1.2.3.4:8080:8080",
|
||||
},
|
||||
),
|
||||
Middleware: serpent.Chain(
|
||||
serpent.RequireNArgs(1),
|
||||
Middleware: clibase.Chain(
|
||||
clibase.RequireNArgs(1),
|
||||
r.InitClient(client),
|
||||
),
|
||||
Handler: func(inv *serpent.Invocation) error {
|
||||
Handler: func(inv *clibase.Invocation) error {
|
||||
ctx, cancel := context.WithCancel(inv.Context())
|
||||
defer cancel()
|
||||
|
||||
@@ -70,10 +69,14 @@ func (r *RootCmd) portForward() *serpent.Command {
|
||||
return xerrors.Errorf("parse port-forward specs: %w", err)
|
||||
}
|
||||
if len(specs) == 0 {
|
||||
err = inv.Command.HelpHandler(inv)
|
||||
if err != nil {
|
||||
return xerrors.Errorf("generate help output: %w", err)
|
||||
}
|
||||
return xerrors.New("no port-forwards requested")
|
||||
}
|
||||
|
||||
workspace, workspaceAgent, err := getWorkspaceAndAgent(ctx, inv, client, !disableAutostart, inv.Args[0])
|
||||
workspace, workspaceAgent, err := getWorkspaceAndAgent(ctx, inv, client, !disableAutostart, codersdk.Me, inv.Args[0])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -95,18 +98,18 @@ func (r *RootCmd) portForward() *serpent.Command {
|
||||
return xerrors.Errorf("await agent: %w", err)
|
||||
}
|
||||
|
||||
opts := &workspacesdk.DialAgentOptions{}
|
||||
|
||||
logger := inv.Logger
|
||||
if r.verbose {
|
||||
opts.Logger = logger.AppendSinks(sloghuman.Sink(inv.Stdout)).Leveled(slog.LevelDebug)
|
||||
logger = logger.AppendSinks(sloghuman.Sink(inv.Stdout)).Leveled(slog.LevelDebug)
|
||||
}
|
||||
|
||||
if r.disableDirect {
|
||||
_, _ = fmt.Fprintln(inv.Stderr, "Direct connections disabled.")
|
||||
opts.BlockEndpoints = true
|
||||
}
|
||||
conn, err := workspacesdk.New(client).DialAgent(ctx, workspaceAgent.ID, opts)
|
||||
conn, err := client.DialWorkspaceAgent(ctx, workspaceAgent.ID, &codersdk.DialWorkspaceAgentOptions{
|
||||
Logger: logger,
|
||||
BlockEndpoints: r.disableDirect,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -137,8 +140,6 @@ func (r *RootCmd) portForward() *serpent.Command {
|
||||
listeners[i] = l
|
||||
}
|
||||
|
||||
stopUpdating := client.UpdateWorkspaceUsageContext(ctx, workspace.ID)
|
||||
|
||||
// Wait for the context to be canceled or for a signal and close
|
||||
// all listeners.
|
||||
var closeErr error
|
||||
@@ -159,7 +160,6 @@ func (r *RootCmd) portForward() *serpent.Command {
|
||||
}
|
||||
|
||||
cancel()
|
||||
stopUpdating()
|
||||
closeAllListeners()
|
||||
}()
|
||||
|
||||
@@ -171,21 +171,21 @@ func (r *RootCmd) portForward() *serpent.Command {
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Options = serpent.OptionSet{
|
||||
cmd.Options = clibase.OptionSet{
|
||||
{
|
||||
Flag: "tcp",
|
||||
FlagShorthand: "p",
|
||||
Env: "CODER_PORT_FORWARD_TCP",
|
||||
Description: "Forward TCP port(s) from the workspace to the local machine.",
|
||||
Value: serpent.StringArrayOf(&tcpForwards),
|
||||
Value: clibase.StringArrayOf(&tcpForwards),
|
||||
},
|
||||
{
|
||||
Flag: "udp",
|
||||
Env: "CODER_PORT_FORWARD_UDP",
|
||||
Description: "Forward UDP port(s) from the workspace to the local machine. The UDP connection has TCP-like semantics to support stateful UDP protocols.",
|
||||
Value: serpent.StringArrayOf(&udpForwards),
|
||||
Value: clibase.StringArrayOf(&udpForwards),
|
||||
},
|
||||
sshDisableAutostartOption(serpent.BoolOf(&disableAutostart)),
|
||||
sshDisableAutostartOption(clibase.BoolOf(&disableAutostart)),
|
||||
}
|
||||
|
||||
return cmd
|
||||
@@ -193,8 +193,8 @@ func (r *RootCmd) portForward() *serpent.Command {
|
||||
|
||||
func listenAndPortForward(
|
||||
ctx context.Context,
|
||||
inv *serpent.Invocation,
|
||||
conn *workspacesdk.AgentConn,
|
||||
inv *clibase.Invocation,
|
||||
conn *codersdk.WorkspaceAgentConn,
|
||||
wg *sync.WaitGroup,
|
||||
spec portForwardSpec,
|
||||
logger slog.Logger,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user