├── .github └── workflows │ ├── codeql.yaml │ └── go.yml ├── .gitignore ├── .golangci.yaml ├── .goreleaser.yml ├── .mergify.yml ├── .release ├── CHANGELOG.md ├── LICENSE ├── Makefile ├── README.md ├── build └── release.sh ├── cmd └── cli │ └── main.go ├── docs └── analytics.md ├── go.mod ├── go.sum ├── images ├── infracloud.png ├── kbrew-install.png ├── kbrew-logo.png ├── kbrew-remove.png └── rook-demo.gif ├── install.sh └── pkg ├── apps ├── apps.go ├── helm │ └── helm.go └── raw │ └── raw.go ├── config └── config.go ├── engine ├── engine.go ├── engine_test.go └── funcs.go ├── events └── events.go ├── kube └── kube.go ├── log ├── log_test.go ├── logger.go ├── logger_test.go ├── status.go └── status_test.go ├── registry └── registry.go ├── update └── updater.go ├── util └── util.go ├── version └── version.go └── yaml ├── eval.go └── eval_test.go /.github/workflows/codeql.yaml: -------------------------------------------------------------------------------- 1 | name: Code Scanning 2 | 3 | on: 4 | push: 5 | pull_request: 6 | schedule: 7 | - cron: "0 0 * * 0" 8 | 9 | jobs: 10 | CodeQL-Build: 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - name: Check out code 15 | uses: actions/checkout@v2 16 | 17 | - name: Initialize CodeQL 18 | uses: github/codeql-action/init@v1 19 | with: 20 | languages: go 21 | 22 | - name: Perform CodeQL Analysis 23 | uses: github/codeql-action/analyze@v1 24 | -------------------------------------------------------------------------------- /.github/workflows/go.yml: -------------------------------------------------------------------------------- 1 | name: Go 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | jobs: 10 | 11 | build: 12 | runs-on: ubuntu-latest 13 | env: 14 | GO111MODULE: on 15 | GOPATH: /home/runner/work/kbrew 16 | GOBIN: /home/runner/work/kbrew/bin 17 | steps: 18 | - uses: actions/checkout@v2 19 | 20 | - name: Set up Go 21 | uses: actions/setup-go@v2 22 | with: 23 | go-version: 1.16 24 | 25 | - uses: actions/cache@v2 26 | with: 27 | path: ~/go/pkg/mod 28 | key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} 29 | restore-keys: | 30 | ${{ runner.os }}-go- 31 | 32 | - name: Verify dependencies 33 | run: | 34 | go mod verify 35 | go mod download 36 | LINT_VERSION=1.41.1 37 | curl -fsSL https://github.com/golangci/golangci-lint/releases/download/v${LINT_VERSION}/golangci-lint-${LINT_VERSION}-linux-amd64.tar.gz | \ 38 | tar xz --strip-components 1 --wildcards \*/golangci-lint 39 | mkdir -p bin && mv golangci-lint bin/ 40 | 41 | - name: Run checks 42 | run: | 43 | STATUS=0 44 | assert-nothing-changed() { 45 | local diff 46 | "$@" >/dev/null || return 1 47 | if ! diff="$(git diff -U1 --color --exit-code)"; then 48 | printf '\e[31mError: running `\e[1m%s\e[22m` results in modifications that you must check into version control:\e[0m\n%s\n\n' "$*" "$diff" >&2 49 | git checkout -- . 50 | STATUS=1 51 | fi 52 | } 53 | assert-nothing-changed go fmt ./... 54 | assert-nothing-changed go mod tidy 55 | bin/golangci-lint run --out-format=github-actions --timeout=5m || STATUS=$? 56 | exit $STATUS 57 | 58 | - name: Build 59 | run: go build -v ./... 60 | 61 | - name: Test 62 | run: go test -v ./... 63 | 64 | - name: Run GoReleaser 65 | uses: goreleaser/goreleaser-action@v2 66 | with: 67 | version: latest 68 | args: release --rm-dist 69 | env: 70 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 71 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, built with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | # Dependency directories (remove the comment below to include it) 15 | # vendor/ 16 | -------------------------------------------------------------------------------- /.golangci.yaml: -------------------------------------------------------------------------------- 1 | linters: 2 | enable: 3 | - deadcode 4 | - errcheck 5 | - gofmt 6 | - goimports 7 | - gosimple 8 | - govet 9 | - ineffassign 10 | - misspell 11 | - nakedret 12 | - revive 13 | - staticcheck 14 | - structcheck 15 | - typecheck 16 | - unconvert 17 | - varcheck 18 | goimports: 19 | # put imports beginning with prefix after 3rd-party packages; 20 | # it's a comma-separated list of prefixes 21 | local-prefixes: github.com/kbrew-dev/kbrew 22 | -------------------------------------------------------------------------------- /.goreleaser.yml: -------------------------------------------------------------------------------- 1 | before: 2 | hooks: 3 | - go mod download 4 | builds: 5 | - id: kbrew 6 | binary: kbrew 7 | main: cmd/cli/main.go 8 | ldflags: &ldflags 9 | - -s -w 10 | -X github.com/kbrew-dev/kbrew/pkg/version.Version={{.Tag}} 11 | -X github.com/kbrew-dev/kbrew/pkg/version.GitCommitID={{.Commit}} 12 | -X github.com/kbrew-dev/kbrew/pkg/version.BuildDate={{.Date}} 13 | env: 14 | - CGO_ENABLED=0 15 | goos: 16 | - linux 17 | - darwin 18 | - windows 19 | goarch: 20 | - 386 21 | - amd64 22 | - arm 23 | - arm64 24 | archives: 25 | - replacements: 26 | darwin: Darwin 27 | linux: Linux 28 | windows: Windows 29 | 386: i386 30 | amd64: x86_64 31 | checksum: 32 | name_template: 'checksums.txt' 33 | snapshot: 34 | name_template: "{{ .Tag }}" 35 | changelog: 36 | sort: asc 37 | filters: 38 | exclude: 39 | - '^docs:' 40 | - '^test:' 41 | 42 | -------------------------------------------------------------------------------- /.mergify.yml: -------------------------------------------------------------------------------- 1 | pull_request_rules: 2 | - name: Automatic merge on approval 3 | conditions: 4 | - base=main 5 | - "#approved-reviews-by>=1" 6 | - label!=hold-off-merging 7 | - label=ready-to-merge 8 | - status-success=build 9 | actions: 10 | merge: 11 | method: squash 12 | commit_message: title+body 13 | strict: smart 14 | -------------------------------------------------------------------------------- /.release: -------------------------------------------------------------------------------- 1 | release=v0.1.0 2 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## [v0.1.0](https://github.com/kbrew-dev/kbrew/tree/v0.1.0) (2021-08-03) 4 | 5 | [Full Changelog](https://github.com/kbrew-dev/kbrew/compare/v0.0.8...v0.1.0) 6 | 7 | **Merged pull requests:** 8 | 9 | - Fix install demo gif [\#112](https://github.com/kbrew-dev/kbrew/pull/112) ([PrasadG193](https://github.com/PrasadG193)) 10 | - Analytics documentation [\#111](https://github.com/kbrew-dev/kbrew/pull/111) ([PrasadG193](https://github.com/PrasadG193)) 11 | - Update CLI description [\#109](https://github.com/kbrew-dev/kbrew/pull/109) ([PrasadG193](https://github.com/PrasadG193)) 12 | - Update README [\#102](https://github.com/kbrew-dev/kbrew/pull/102) ([vishal-biyani](https://github.com/vishal-biyani)) 13 | 14 | ## [v0.0.8](https://github.com/kbrew-dev/kbrew/tree/v0.0.8) (2021-08-02) 15 | 16 | [Full Changelog](https://github.com/kbrew-dev/kbrew/compare/v0.0.7...v0.0.8) 17 | 18 | **Closed issues:** 19 | 20 | - Raw args with int values are not working [\#94](https://github.com/kbrew-dev/kbrew/issues/94) 21 | 22 | **Merged pull requests:** 23 | 24 | - Correct binary install link in README [\#108](https://github.com/kbrew-dev/kbrew/pull/108) ([PrasadG193](https://github.com/PrasadG193)) 25 | - Add license to code files [\#106](https://github.com/kbrew-dev/kbrew/pull/106) ([gauravgahlot](https://github.com/gauravgahlot)) 26 | - Add Mergify integration to automatically merge PRs on approval [\#104](https://github.com/kbrew-dev/kbrew/pull/104) ([PrasadG193](https://github.com/PrasadG193)) 27 | - Switch release repo to kbrew [\#103](https://github.com/kbrew-dev/kbrew/pull/103) ([PrasadG193](https://github.com/PrasadG193)) 28 | - Bump helm.sh/helm/v3 from 3.5.4 to 3.6.1 [\#101](https://github.com/kbrew-dev/kbrew/pull/101) ([dependabot[bot]](https://github.com/apps/dependabot)) 29 | - Enable code scan with CodeQL for Go source [\#89](https://github.com/kbrew-dev/kbrew/pull/89) ([sanketsudake](https://github.com/sanketsudake)) 30 | 31 | ## [v0.0.7](https://github.com/kbrew-dev/kbrew/tree/v0.0.7) (2021-07-26) 32 | 33 | [Full Changelog](https://github.com/kbrew-dev/kbrew/compare/v0.0.6...v0.0.7) 34 | 35 | **Closed issues:** 36 | 37 | - kbrew remove doesn't delete resources from pre-install steps [\#74](https://github.com/kbrew-dev/kbrew/issues/74) 38 | - kbrew info command for information on packages [\#22](https://github.com/kbrew-dev/kbrew/issues/22) 39 | 40 | **Merged pull requests:** 41 | 42 | - render templates before unmarshalling [\#100](https://github.com/kbrew-dev/kbrew/pull/100) ([sahil-lakhwani](https://github.com/sahil-lakhwani)) 43 | - Use golangci-lint run for linting [\#95](https://github.com/kbrew-dev/kbrew/pull/95) ([sanketsudake](https://github.com/sanketsudake)) 44 | - Logging framework [\#93](https://github.com/kbrew-dev/kbrew/pull/93) ([PrasadG193](https://github.com/PrasadG193)) 45 | 46 | ## [v0.0.6](https://github.com/kbrew-dev/kbrew/tree/v0.0.6) (2021-07-01) 47 | 48 | [Full Changelog](https://github.com/kbrew-dev/kbrew/compare/v0.0.5...v0.0.6) 49 | 50 | **Closed issues:** 51 | 52 | - Create namespace if does not exist for raw apps [\#80](https://github.com/kbrew-dev/kbrew/issues/80) 53 | - Installation should continue if any dependency app already exists [\#79](https://github.com/kbrew-dev/kbrew/issues/79) 54 | 55 | **Merged pull requests:** 56 | 57 | - Silence usage and error print [\#92](https://github.com/kbrew-dev/kbrew/pull/92) ([sahil-lakhwani](https://github.com/sahil-lakhwani)) 58 | - Skip namespace creation if name is nil [\#91](https://github.com/kbrew-dev/kbrew/pull/91) ([PrasadG193](https://github.com/PrasadG193)) 59 | - Use correct reference while creating namespace [\#90](https://github.com/kbrew-dev/kbrew/pull/90) ([PrasadG193](https://github.com/PrasadG193)) 60 | - add info and args command [\#88](https://github.com/kbrew-dev/kbrew/pull/88) ([sahil-lakhwani](https://github.com/sahil-lakhwani)) 61 | - App cleanup improvements [\#87](https://github.com/kbrew-dev/kbrew/pull/87) ([PrasadG193](https://github.com/PrasadG193)) 62 | - Skip helm app installation if already exists [\#85](https://github.com/kbrew-dev/kbrew/pull/85) ([PrasadG193](https://github.com/PrasadG193)) 63 | - Fix incorrect exit codes [\#84](https://github.com/kbrew-dev/kbrew/pull/84) ([PrasadG193](https://github.com/PrasadG193)) 64 | - create namespace if it doesn't exist [\#83](https://github.com/kbrew-dev/kbrew/pull/83) ([mahendrabagul](https://github.com/mahendrabagul)) 65 | 66 | ## [v0.0.5](https://github.com/kbrew-dev/kbrew/tree/v0.0.5) (2021-06-02) 67 | 68 | [Full Changelog](https://github.com/kbrew-dev/kbrew/compare/v0.0.4...v0.0.5) 69 | 70 | **Closed issues:** 71 | 72 | - Add a flag to set custom wait for ready timeout [\#75](https://github.com/kbrew-dev/kbrew/issues/75) 73 | - Collect events for analytics [\#65](https://github.com/kbrew-dev/kbrew/issues/65) 74 | - Support for helm functions in recipe yaml [\#64](https://github.com/kbrew-dev/kbrew/issues/64) 75 | - Add support for passing args to the kbrew app [\#63](https://github.com/kbrew-dev/kbrew/issues/63) 76 | - Add support for kbrew help command [\#57](https://github.com/kbrew-dev/kbrew/issues/57) 77 | 78 | **Merged pull requests:** 79 | 80 | - Support helm functions on raw app args [\#81](https://github.com/kbrew-dev/kbrew/pull/81) ([PrasadG193](https://github.com/PrasadG193)) 81 | - Add autocomplete support for kbrew CLI [\#78](https://github.com/kbrew-dev/kbrew/pull/78) ([sanketsudake](https://github.com/sanketsudake)) 82 | - Collect events for analytics [\#77](https://github.com/kbrew-dev/kbrew/pull/77) ([PrasadG193](https://github.com/PrasadG193)) 83 | - Support custom wait-for-ready timeout [\#76](https://github.com/kbrew-dev/kbrew/pull/76) ([PrasadG193](https://github.com/PrasadG193)) 84 | - \[CI\] Fix go vet failures [\#72](https://github.com/kbrew-dev/kbrew/pull/72) ([PrasadG193](https://github.com/PrasadG193)) 85 | - Support for raw app args [\#71](https://github.com/kbrew-dev/kbrew/pull/71) ([sahil-lakhwani](https://github.com/sahil-lakhwani)) 86 | - change args value to empty interface [\#70](https://github.com/kbrew-dev/kbrew/pull/70) ([sahil-lakhwani](https://github.com/sahil-lakhwani)) 87 | - yaml evaluator [\#69](https://github.com/kbrew-dev/kbrew/pull/69) ([sahil-lakhwani](https://github.com/sahil-lakhwani)) 88 | - Enhanced version command to check for latest version and warn user [\#68](https://github.com/kbrew-dev/kbrew/pull/68) ([vishal-biyani](https://github.com/vishal-biyani)) 89 | 90 | ## [v0.0.4](https://github.com/kbrew-dev/kbrew/tree/v0.0.4) (2021-05-13) 91 | 92 | [Full Changelog](https://github.com/kbrew-dev/kbrew/compare/v0.0.3...v0.0.4) 93 | 94 | **Closed issues:** 95 | 96 | - Add Go lint checks in CI [\#37](https://github.com/kbrew-dev/kbrew/issues/37) 97 | 98 | **Merged pull requests:** 99 | 100 | - Args templating engine [\#67](https://github.com/kbrew-dev/kbrew/pull/67) ([sahil-lakhwani](https://github.com/sahil-lakhwani)) 101 | - arguments to helm app [\#66](https://github.com/kbrew-dev/kbrew/pull/66) ([sahil-lakhwani](https://github.com/sahil-lakhwani)) 102 | - Remove stale recipes dir [\#61](https://github.com/kbrew-dev/kbrew/pull/61) ([PrasadG193](https://github.com/PrasadG193)) 103 | - Added link to registry [\#53](https://github.com/kbrew-dev/kbrew/pull/53) ([vishal-biyani](https://github.com/vishal-biyani)) 104 | - Add go lint checks [\#52](https://github.com/kbrew-dev/kbrew/pull/52) ([mahendrabagul](https://github.com/mahendrabagul)) 105 | - fix exact match for registry [\#51](https://github.com/kbrew-dev/kbrew/pull/51) ([sahil-lakhwani](https://github.com/sahil-lakhwani)) 106 | 107 | ## [v0.0.3](https://github.com/kbrew-dev/kbrew/tree/v0.0.3) (2021-04-05) 108 | 109 | [Full Changelog](https://github.com/kbrew-dev/kbrew/compare/v0.0.2...v0.0.3) 110 | 111 | **Closed issues:** 112 | 113 | - Install script does not support Mac [\#49](https://github.com/kbrew-dev/kbrew/issues/49) 114 | 115 | **Merged pull requests:** 116 | 117 | - Add support of Mac build [\#50](https://github.com/kbrew-dev/kbrew/pull/50) ([PrasadG193](https://github.com/PrasadG193)) 118 | 119 | ## [v0.0.2](https://github.com/kbrew-dev/kbrew/tree/v0.0.2) (2021-04-05) 120 | 121 | [Full Changelog](https://github.com/kbrew-dev/kbrew/compare/v0.0.1...v0.0.2) 122 | 123 | **Merged pull requests:** 124 | 125 | - \[README\] Update installation steps and command structs [\#48](https://github.com/kbrew-dev/kbrew/pull/48) ([PrasadG193](https://github.com/PrasadG193)) 126 | - Add support to update kbrew registries [\#47](https://github.com/kbrew-dev/kbrew/pull/47) ([PrasadG193](https://github.com/PrasadG193)) 127 | - Install kbrew in existing exec bin dir during update [\#46](https://github.com/kbrew-dev/kbrew/pull/46) ([PrasadG193](https://github.com/PrasadG193)) 128 | 129 | ## [v0.0.1](https://github.com/kbrew-dev/kbrew/tree/v0.0.1) (2021-04-04) 130 | 131 | [Full Changelog](https://github.com/kbrew-dev/kbrew/compare/55e699e0ef038af0f8e29bbca6b3697752e1fe77...v0.0.1) 132 | 133 | **Closed issues:** 134 | 135 | - Add release process/script [\#39](https://github.com/kbrew-dev/kbrew/issues/39) 136 | - Host and fetch recipes at runtime [\#28](https://github.com/kbrew-dev/kbrew/issues/28) 137 | - Recipe: Rook + Ceph [\#21](https://github.com/kbrew-dev/kbrew/issues/21) 138 | - Trial/Recipe: Longhorn [\#20](https://github.com/kbrew-dev/kbrew/issues/20) 139 | - Trial/Recipe: OpenEBS [\#19](https://github.com/kbrew-dev/kbrew/issues/19) 140 | - Add GitHub actions CI to run build and test [\#11](https://github.com/kbrew-dev/kbrew/issues/11) 141 | - Add preinstall/postinstall hooks in installation workflow [\#6](https://github.com/kbrew-dev/kbrew/issues/6) 142 | - Wait resources to be ready after install/upgrade [\#5](https://github.com/kbrew-dev/kbrew/issues/5) 143 | - Add support for repository in config [\#4](https://github.com/kbrew-dev/kbrew/issues/4) 144 | 145 | **Merged pull requests:** 146 | 147 | - Add update command to upgrade kbrew [\#45](https://github.com/kbrew-dev/kbrew/pull/45) ([PrasadG193](https://github.com/PrasadG193)) 148 | - Add kbrew version command [\#44](https://github.com/kbrew-dev/kbrew/pull/44) ([PrasadG193](https://github.com/PrasadG193)) 149 | - Publish releases to kbrew-release repo [\#43](https://github.com/kbrew-dev/kbrew/pull/43) ([PrasadG193](https://github.com/PrasadG193)) 150 | - Add release process [\#42](https://github.com/kbrew-dev/kbrew/pull/42) ([PrasadG193](https://github.com/PrasadG193)) 151 | - Add support for kbrew registries [\#35](https://github.com/kbrew-dev/kbrew/pull/35) ([PrasadG193](https://github.com/PrasadG193)) 152 | - Cleanup - remove redundant files [\#34](https://github.com/kbrew-dev/kbrew/pull/34) ([PrasadG193](https://github.com/PrasadG193)) 153 | - Change repo owner to kbrew-dev [\#33](https://github.com/kbrew-dev/kbrew/pull/33) ([PrasadG193](https://github.com/PrasadG193)) 154 | - Revert "Add Mergify integration to automatically merge PRs on approval" [\#32](https://github.com/kbrew-dev/kbrew/pull/32) ([PrasadG193](https://github.com/PrasadG193)) 155 | - Add Mergify integration to automatically merge PRs on approval [\#31](https://github.com/kbrew-dev/kbrew/pull/31) ([PrasadG193](https://github.com/PrasadG193)) 156 | - Fix resource name in WaitForReady methods [\#30](https://github.com/kbrew-dev/kbrew/pull/30) ([PrasadG193](https://github.com/PrasadG193)) 157 | - Added details to readme such as instructions and usage commands [\#26](https://github.com/kbrew-dev/kbrew/pull/26) ([vishal-biyani](https://github.com/vishal-biyani)) 158 | - Set app/chart versions in the recipes [\#18](https://github.com/kbrew-dev/kbrew/pull/18) ([PrasadG193](https://github.com/PrasadG193)) 159 | - Add recipe for kafka operator installation [\#17](https://github.com/kbrew-dev/kbrew/pull/17) ([PrasadG193](https://github.com/PrasadG193)) 160 | - Add support for shell command in install hooks [\#15](https://github.com/kbrew-dev/kbrew/pull/15) ([PrasadG193](https://github.com/PrasadG193)) 161 | - Add support for pre/post install hooks [\#14](https://github.com/kbrew-dev/kbrew/pull/14) ([PrasadG193](https://github.com/PrasadG193)) 162 | - Remove redundant file [\#13](https://github.com/kbrew-dev/kbrew/pull/13) ([PrasadG193](https://github.com/PrasadG193)) 163 | - Added a simple workflow to build and test code [\#12](https://github.com/kbrew-dev/kbrew/pull/12) ([vishal-biyani](https://github.com/vishal-biyani)) 164 | - Update imports to point to infracloudio repo [\#10](https://github.com/kbrew-dev/kbrew/pull/10) ([PrasadG193](https://github.com/PrasadG193)) 165 | - Wait for workloads to be ready after install [\#9](https://github.com/kbrew-dev/kbrew/pull/9) ([PrasadG193](https://github.com/PrasadG193)) 166 | - Add support for app repository [\#7](https://github.com/kbrew-dev/kbrew/pull/7) ([PrasadG193](https://github.com/PrasadG193)) 167 | - Add support to pass and parse config [\#3](https://github.com/kbrew-dev/kbrew/pull/3) ([PrasadG193](https://github.com/PrasadG193)) 168 | - Add support to install, remove and search apps [\#2](https://github.com/kbrew-dev/kbrew/pull/2) ([PrasadG193](https://github.com/PrasadG193)) 169 | 170 | 171 | 172 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .DEFAULT_GOAL := build 2 | .PHONY: build pre-build system-check cli 3 | 4 | #Build the binary 5 | build: pre-build 6 | @cd cmd/cli;GOOS_VAL=$(shell go env GOOS) GOARCH_VAL=$(shell go env GOARCH) go build -o $(shell go env GOPATH)/bin/kbrew 7 | @echo "Build completed successfully" 8 | 9 | cli: 10 | @cd cmd/cli;GOOS_VAL=$(shell go env GOOS) GOARCH_VAL=$(shell go env GOARCH) go build -o $(shell go env GOPATH)/bin/kbrew 11 | @echo "cli generated successfully" 12 | 13 | #system checks 14 | system-check: 15 | @echo "Checking system information" 16 | @if [ -z "$(shell go env GOOS)" ] || [ -z "$(shell go env GOARCH)" ] ; \ 17 | then \ 18 | echo 'ERROR: Could not determine the system architecture.' && exit 1 ; \ 19 | else \ 20 | echo 'GOOS: $(shell go env GOOS)' ; \ 21 | echo 'GOARCH: $(shell go env GOARCH)' ; \ 22 | echo 'System information checks passed.'; \ 23 | fi ; 24 | 25 | #Pre-build checks 26 | pre-build: system-check 27 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # kbrew 2 | 3 | [![CI](https://github.com/kbrew-dev/kbrew/actions/workflows/go.yml/badge.svg)](https://github.com/kbrew-dev/kbrew/actions/workflows/go.yml) [![Go Report Card](https://goreportcard.com/badge/github.com/kbrew-dev/kbrew)](https://goreportcard.com/report/github.com/kbrew-dev/kbrew) 4 | [![Release Version](https://img.shields.io/github/v/release/kbrew-dev/kbrew?label=kbrew)](https://github.com/kbrew-dev/kbrew/releases/latest) 5 | [![License](https://img.shields.io/github/license/kbrew-dev/kbrew?color=light%20green&logo=github)](https://github.com/kbrew-dev/kbrew/blob/main/LICENSE) 6 | 7 | 8 | 9 | ![kbrew-logo](./images/kbrew-logo.png) 10 | 11 | 12 | kbrew is a CLI tool for Kubernetes which makes installing any complex stack easy in `one step` (And yes we are definitely inspired by Homebrew from MacOS) 13 | 14 | Let's take the example of installing Kafka on a Kubernetes cluster. If you are a developer trying this on a non-prod environment, you want a quick and simple way to set it up. But a typical process looks like this: 15 | 16 | - You need a cert-manager, Zookeeper & kube-prometheus-stack for monitoring installed. 17 | - Zookeeper is an operator so you need to create a CR of the Zookeeper cluster after installation of the operator is done. 18 | - Then you have to install Kafka operator. 19 | - Finally, you have to create a CR of Kafka and wait for everything to stabilize. 20 | - And lastly, create a ServiceMonitor resource to enable Prometheus scraping. 21 | 22 | With kbrew, all of this happens with a "one step": 23 | 24 | ``` 25 | kbrew install kafka-operator 26 | ``` 27 | 28 | Similarly when you install a Rook Ceph cluster - it makes it a `one step easy`: 29 | 30 | ![](./images/rook-demo.gif) 31 | 32 | > Any engineering is not without tradeoffs and we are not claiming that this is a silver bullet. Please refer to the Goals and FAQ sections for details. 33 | 34 | Table of Contents 35 | ================= 36 | 37 | * [Goals](#goals) 38 | * [One step Easy for users](#one-step-easy-for-users) 39 | * [Fully Configured & functional](#fully-configured--functional) 40 | * [Recipe - abstracts complexity!](#recipe---abstracts-complexity) 41 | * [Installation](#installation) 42 | * [Install the pre-compiled binary](#install-the-pre-compiled-binary) 43 | * [Compiling from source](#compiling-from-source) 44 | * [Step 1: Clone the repo](#step-1-clone-the-repo) 45 | * [Step 2: Build binary using make](#step-2-build-binary-using-make) 46 | * [CLI Usage](#cli-usage) 47 | * [Commonly used commands](#commonly-used-commands) 48 | * [kbrew search](#kbrew-search) 49 | * [kbrew info](#kbrew-info) 50 | * [kbrew install](#kbrew-install) 51 | * [kbrew update](#kbrew-update) 52 | * [kbrew remove](#kbrew-remove) 53 | * [Recipes](#recipes) 54 | * [Recipe structure](#recipe-structure) 55 | * [Application](#application) 56 | * [Arguments](#arguments) 57 | * [Pre & Post Install](#pre--post-install) 58 | * [Pre and Post Cleanup](#pre-and-post-cleanup) 59 | * [FAQ](#faq) 60 | * [How is kbrew different than Helm or Kubernetes Operator?](https://github.com/kbrew-dev/kbrew#how-is-kbrew-different-than-helm-or-kubernetes-operator) 61 | * [Should I use kbrew for installing applications in a production environment?](#should-i-use-kbrew-for-installing-applications-in-a-production-environment) 62 | * [How can I contribute recipes for a project/tool?](#how-can-i-contribute-recipes-for-a-projecttool) 63 | * [How is analytics used?](#how-is-analytics-used) 64 | * [What data is collected for analytics?](#what-data-is-collected-for-analytics) 65 | * [Who is developing kbrew?](#who-is-developing-kbrew) 66 | 67 | Created by [gh-md-toc](https://github.com/ekalinin/github-markdown-toc) 68 | 69 | ## Goals 70 | 71 | ### `One step` Easy for users 72 | 73 | We are basically optimizing for `one step` install easy for developers. You end up installing applications in dev/tinkering environments multiple times and it should not be this hard. Also, you should not have to write `glue code` or shell scripts to make it work! 74 | 75 | ### Fully Configured & functional 76 | 77 | `One step` would not be true to its promise if you had to `configure` things such as StorageClass or verify the version of Kubernetes etc. It should work and be fully functional to use right after installation. 78 | 79 | ### Recipe - abstracts complexity! 80 | 81 | While we are making it easy for users to install any application in one step, we are pushing the complexity to the recipe. This means the recipe authors have to understand and write recipes that just work! 82 | 83 | ## Installation 84 | 85 |
86 | (Click to expand) 87 | 88 | ### Install the pre-compiled binary 89 | 90 | ```bash 91 | export BINDIR=/usr/local/bin 92 | curl -sfL https://raw.githubusercontent.com/kbrew-dev/kbrew/main/install.sh | sh 93 | ``` 94 | 95 | ### Compiling from source 96 | 97 | #### Step 1: Clone the repo 98 | 99 | ```bash 100 | git clone https://github.com/kbrew-dev/kbrew.git 101 | ``` 102 | 103 | #### Step 2: Build binary using make 104 | 105 | ```bash 106 | make 107 | ``` 108 |
109 | 110 | ## CLI Usage 111 | 112 |
113 | (Click to expand) 114 | 115 | ``` 116 | $ kbrew --help 117 | A CLI tool for Kubernetes which makes installing any complex stack easy in one step. 118 | 119 | Usage: 120 | kbrew [command] 121 | 122 | Available Commands: 123 | analytics Manage analytics setting 124 | completion Output shell completion code for the specified shell 125 | help Help about any command 126 | info Describe application 127 | install Install application 128 | remove Remove application 129 | search Search application 130 | update Update kbrew and recipe registries 131 | version Print version information 132 | 133 | Flags: 134 | -c, --config string config file (default is $HOME/.kbrew.yaml) 135 | --config-dir string config dir (default is $HOME/.kbrew) 136 | --debug enable debug logs 137 | -h, --help help for kbrew 138 | -n, --namespace string namespace 139 | 140 | Use "kbrew [command] --help" for more information about a command. 141 | ``` 142 | 143 | ### Commonly used commands 144 | 145 | #### kbrew search 146 | 147 | Searches for a recipe for the given application. Lists all the available recipes if no application name is passed. 148 | 149 | #### kbrew info 150 | 151 | Prints applications details including registry and dependency information. 152 | 153 | #### kbrew install 154 | 155 | Installs a recipe in your cluster with all pre & posts steps and applications. 156 | 157 | #### kbrew update 158 | 159 | Checks for kbrew updates and upgrades automatically if a newer version is available. Fetches updates for all the kbrew recipe registries 160 | 161 | #### kbrew remove 162 | 163 | Uninstalls the application and its dependencies. 164 | 165 |
166 | 167 | ## Recipes 168 | 169 | A kbrew recipe is a YAML file that declares the installation process of a Kubernetes app. It allows to *brew* Helm charts or vanilla Kubernetes manifests with scripts, also managing dependencies with other recipes. 170 | 171 | Recipes can be grouped in a structured directory called `Registry`. kbrew uses the [kbrew-registry](https://github.com/kbrew-dev/kbrew-registry/) by default. 172 | 173 | ### Recipe structure 174 | 175 | The process of how kbrew manages the installation of an app according to the recipe specification is depicted below. As can be seen, kbrew takes care of the order of pre/post actions. 176 | 177 | ![kbrew-install](./images/kbrew-install.png) 178 | 179 | 180 | Similarly, while removing an app, kbrew takes care of the order of removal of the dependent apps and the cleanup steps specified via `pre/post_cleanup` in the recipe. 181 | 182 | ![kbrew-install](./images/kbrew-remove.png) 183 | 184 | A bare-bones structure of a recipe is a composition of pre-install steps, install and post-install steps. Each step could have another application being installed or a further set of steps. 185 | 186 | ``` 187 | apiVersion: v1 188 | kind: kbrew 189 | app: 190 | repository: 191 | url: https://raw.githubusercontent.com/repo/manifest.yaml 192 | type: raw 193 | args: 194 | Deployment.nginx.spec.replicas: 4 195 | namespace: default 196 | version: v0.17.0 197 | pre_install: 198 | - apps: 199 | - OtherApp 200 | - steps: 201 | - echo "installing app" 202 | post_install: 203 | - steps: 204 | - echo "done installing" 205 | pre_cleanup: 206 | - steps 207 | - echo "deleting prerequisite" 208 | post_cleanup: 209 | - steps: 210 | - echo "app deleted" 211 | ``` 212 | 213 | #### Application 214 | 215 | - `app` is the declaration of how a Kubernetes application - a Helm chart or a YAML manifest - will get installed. 216 | * `repository`: defines the source of the app 217 | - `url`: location of a Helm chart or a Kubernetes YAML manifest 218 | - `type`: can be `helm` or `raw` 219 | 220 | For example for the Kafka recipe, we will use the Helm chart from Banzaicloud and point to the Helm repo where the chart is available. 221 | 222 | ``` 223 | app: 224 | repository: 225 | name: banzaicloud-stable 226 | url: https://kubernetes-charts.banzaicloud.com 227 | type: helm 228 | ``` 229 | 230 | ##### Arguments 231 | 232 | kbrew allows you to modify the app via arguments that can modify the Helm chart values or manifest field values. kbrew supports passing arguments to recipes as [Go templates](https://pkg.go.dev/text/template). 233 | 234 | All the functions from the [Sprig library](http://masterminds.github.io/sprig/) and the [lookup](https://helm.sh/docs/chart_template_guide/functions_and_pipelines/#using-the-lookup-function) & [include](https://helm.sh/docs/howto/charts_tips_and_tricks/#using-the-include-function) functions from Helm are supported. 235 | 236 | **Helm app**: Arguments to a helm app can be the key-value pairs offered by the chart in its values.yaml file. 237 | 238 | **Raw app**: These arguments patch the manifest of a raw app and can be specified in the format: `..: `. For example, to change `spec.replicas` of a `Deployment` named `nginx`, specify `Deployment.nginx.spec.replicas` 239 | 240 | For example for [Nginx Ingress recipe](https://github.com/kbrew-dev/kbrew-registry/blob/19d9cd3ae269265c1e3147918a3a2287fc006bda/recipes/ingress-nginx.yaml) we configure an annotation if the application is being installed in AWS EKS or Digital Ocean. 241 | 242 | ``` 243 | app: 244 | args: 245 | # annotation for EKS 246 | controller.service.annotations."service\.beta\.kubernetes\.io/aws-load-balancer-type": '{{ $providerID := (index (lookup "v1" "Node" "" "").items 0).spec.providerID }}{{ if hasPrefix "aws" $providerID }}nlb{{end}}' 247 | # annotations for Digital Ocean 248 | controller.service.annotations."service\.beta\.kubernetes\.io/do-loadbalancer-enable-proxy-protocol": '{{ $providerID := (index (lookup "v1" "Node" "" "").items 0).spec.providerID }}{{ if hasPrefix "digitalocean" $providerID }}true{{end}}' 249 | ``` 250 | 251 | * `namespace`: Kubernetes namespace where the app should be installed. If not specified, `default` is used for installation. 252 | 253 | #### Pre & Post Install 254 | 255 | Pre and post-install sections allow the recipe author to do steps needed before or after the installation of the core application. This could be for example: 256 | 257 | - Checking for compatibility of cluster or the environment-specific things such as `StorageClass`. 258 | - Install another dependency application by using the recipe of that application. 259 | - After installation wait for setup to be ready and fully functional. 260 | - Create CRs of a specific application so that it is fully functional and ready to use. 261 | 262 | Let's look at some examples. In the RookCeph recipe, we install the operator as a dependency application: 263 | 264 | ``` 265 | pre_install: 266 | - apps: 267 | - rook-ceph-operator 268 | ``` 269 | 270 | In the Minio recipe, we check the version of Kubernetes so that only compatible versions of Kubernetes are used for rest of the install 271 | 272 | ``` 273 | pre_install: 274 | - steps: 275 | - | 276 | # Prerequisites 277 | # https://github.com/minio/operator#prerequisites 278 | minK8sVersion="v1.19.0" 279 | expected=$(echo $minK8sVersion | sed 's/v//g' | sed 's/\.//g') 280 | k8sVersion=$(kubectl version --short=true --output json | jq -r ".serverVersion.gitVersion" | sed 's/-.*//g' | sed 's/v//g' | sed 's/\.//g') 281 | if [ $expected -gt $k8sVersion ] 282 | then 283 | echo "The cluster does not meet requirements." 284 | echo "Kubernetes version v1.19.0 or later required." 285 | exit 1 286 | fi 287 | ``` 288 | 289 | Or for example, in case of Minio, the `StorageClass` should have the value of `volumeBindingMode` as `WaitForFirstConsumer` - and is one of the prerequisites for the installation: 290 | 291 | ``` 292 | pre_install: 293 | - steps: 294 | - | 295 | # Prerequisites - The StorageClass must have volumeBindingMode: WaitForFirstConsumer 296 | # https://github.com/minio/operator#prerequisites 297 | scList=$(kubectl get storageclass -o jsonpath='{.items[?(@.volumeBindingMode=="WaitForFirstConsumer")].metadata.name}') 298 | if [ -z "$scList" ] 299 | then 300 | echo "The cluster does not meet requirements." 301 | echo "Atleast 1 StorageClass should have WaitForFirstConsumer volumeBindingMode." 302 | exit 1 303 | fi 304 | ``` 305 | 306 | #### Pre and Post Cleanup 307 | 308 | The `pre_cleanup` and `post_cleanup` are very similar to the `pre_install` and `post_install` steps but are used in the uninstall lifecycle. 309 | 310 | ## FAQ 311 | 312 | ##### How is kbrew different than Helm or Kubernetes Operator? 313 | 314 | kbrew uses Helm charts and operators both under the hood. kbrew acts as a `glue code` that makes combination of installing a Helm chart, creating a manifest CR etc. into a single command that also tries to make some decisions such as StorageClass configuration etc. It is great for developers who wants to just get something running fast and fully working! 315 | 316 | ##### Should I use kbrew for installing applications in a production environment? 317 | 318 | At this point, kbrew is not meant to install applications in production. It makes installing applications easy for developers and anyone tinkering and installing frequently 319 | 320 | ##### How can I contribute recipes for a project/tool? 321 | 322 | The recipes are maintained in [kbrew registry](https://github.com/kbrew-dev/kbrew-registry), and if a recipe does not exist then please raise an issue and you can contribute to the registry. 323 | 324 | ##### How is analytics used? 325 | 326 | The analytics is anonymized and used in aggregate to determine the failure/success rate of recipes and to improve user experience. 327 | 328 | ##### What data is collected for analytics? 329 | 330 | Please check [analytics](docs/analytics.md) for details. 331 | 332 | ##### Who is developing kbrew? 333 | 334 | The team at [InfraCloud](https://www.infracloud.io/) is supporting kbrew's development with love! But we love contributions from the community. 335 | -------------------------------------------------------------------------------- /build/release.sh: -------------------------------------------------------------------------------- 1 | # Copyright 2021 The kbrew Authors. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | set -e 16 | 17 | version=$(cut -d'=' -f2- .release) 18 | if [[ -z ${version} ]]; then 19 | echo "Invalid version set in .release" 20 | exit 1 21 | fi 22 | 23 | 24 | if [[ -z ${GITHUB_TOKEN} ]]; then 25 | echo "GITHUB_TOKEN not set. Usage: GITHUB_TOKEN= ./hack/release.sh" 26 | exit 1 27 | fi 28 | 29 | echo "Publishing release ${version}" 30 | 31 | generate_changelog() { 32 | local version=$1 33 | 34 | # generate changelog from github 35 | github_changelog_generator --user kbrew-dev --project kbrew -t ${GITHUB_TOKEN} --future-release ${version} -o CHANGELOG.md 36 | sed -i '$d' CHANGELOG.md 37 | } 38 | 39 | git_tag() { 40 | local version=$1 41 | echo "Creating a git tag" 42 | git add .release CHANGELOG.md 43 | git commit -m "Release ${version}" 44 | git tag ${version} 45 | git push --tags origin main 46 | echo 'Git tag pushed successfully' 47 | } 48 | 49 | make_release() { 50 | goreleaser release --rm-dist --debug 51 | } 52 | 53 | generate_changelog $version 54 | git_tag $version 55 | make_release 56 | 57 | echo "=========================== Done =============================" 58 | echo "Congratulations!! Release ${version} published." 59 | echo "Don't forget to add changelog in the release description." 60 | echo "==============================================================" 61 | -------------------------------------------------------------------------------- /cmd/cli/main.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 The kbrew Authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package main 16 | 17 | import ( 18 | "context" 19 | "fmt" 20 | "os" 21 | "strings" 22 | "time" 23 | 24 | "github.com/pkg/errors" 25 | "github.com/spf13/cobra" 26 | "github.com/spf13/viper" 27 | "gopkg.in/yaml.v2" 28 | 29 | "github.com/kbrew-dev/kbrew/pkg/apps" 30 | "github.com/kbrew-dev/kbrew/pkg/config" 31 | "github.com/kbrew-dev/kbrew/pkg/log" 32 | "github.com/kbrew-dev/kbrew/pkg/registry" 33 | "github.com/kbrew-dev/kbrew/pkg/update" 34 | "github.com/kbrew-dev/kbrew/pkg/version" 35 | ) 36 | 37 | const defaultTimeout = "15m0s" 38 | 39 | var ( 40 | configFile string 41 | namespace string 42 | timeout string 43 | debug bool 44 | 45 | rootCmd = &cobra.Command{ 46 | Use: "kbrew", 47 | Short: "A CLI tool for Kubernetes which makes installing any complex stack easy in one step.", 48 | SilenceErrors: true, 49 | SilenceUsage: true, 50 | } 51 | 52 | versionCmd = &cobra.Command{ 53 | Use: "version", 54 | Short: "Print version information", 55 | Run: func(cmd *cobra.Command, args []string) { 56 | fmt.Println(version.Long()) 57 | release, err := update.IsAvailable(context.Background()) 58 | if err != nil { 59 | fmt.Printf("Error getting latest version of kbrew from GiThub: %s", err) 60 | } 61 | if release != "" { 62 | fmt.Printf("There is a new version of kbrew available: %s, please run 'kbrew update' command to upgrade.\n", release) 63 | } 64 | }, 65 | } 66 | 67 | installCmd = &cobra.Command{ 68 | Use: "install [NAME]", 69 | Short: "Install application", 70 | Args: cobra.MinimumNArgs(1), 71 | RunE: func(cmd *cobra.Command, args []string) error { 72 | return manageApp(apps.Install, args) 73 | }, 74 | } 75 | 76 | removeCmd = &cobra.Command{ 77 | Use: "remove [NAME]", 78 | Short: "Remove application", 79 | Args: cobra.MinimumNArgs(1), 80 | RunE: func(cmd *cobra.Command, args []string) error { 81 | return manageApp(apps.Uninstall, args) 82 | }, 83 | } 84 | 85 | searchCmd = &cobra.Command{ 86 | Use: "search [NAME]", 87 | Short: "Search application", 88 | RunE: func(cmd *cobra.Command, args []string) error { 89 | appName := "" 90 | if len(args) != 0 { 91 | appName = args[0] 92 | } 93 | reg, err := registry.New(config.ConfigDir) 94 | if err != nil { 95 | return err 96 | } 97 | appList, err := reg.Search(appName, false) 98 | if err != nil { 99 | return err 100 | } 101 | if len(appList) == 0 { 102 | fmt.Printf("No recipe found for %s.\n", appName) 103 | return nil 104 | } 105 | fmt.Println("Available recipes:") 106 | for _, app := range appList { 107 | fmt.Println(app.Name) 108 | } 109 | return nil 110 | }, 111 | } 112 | 113 | updateCmd = &cobra.Command{ 114 | Use: "update", 115 | Short: "Update kbrew and recipe registries", 116 | RunE: func(cmd *cobra.Command, args []string) error { 117 | // Upgrade kbrew 118 | if err := update.CheckRelease(context.Background()); err != nil { 119 | return err 120 | } 121 | // Update kbrew registries 122 | reg, err := registry.New(config.ConfigDir) 123 | if err != nil { 124 | return err 125 | } 126 | return reg.Update() 127 | }, 128 | } 129 | 130 | analyticsCmd = &cobra.Command{ 131 | Use: "analytics [on|off|status]", 132 | Short: "Manage analytics setting", 133 | RunE: func(cmd *cobra.Command, args []string) error { 134 | return manageAnalytics(args) 135 | }, 136 | } 137 | 138 | completionCmd = &cobra.Command{ 139 | Use: "completion [SHELL]", 140 | Short: "Output shell completion code for the specified shell", 141 | ValidArgs: []string{"bash", "zsh", "fish", "powershell"}, 142 | Args: cobra.ExactValidArgs(1), 143 | RunE: func(cmd *cobra.Command, args []string) (err error) { 144 | switch args[0] { 145 | case "bash": 146 | err = cmd.Root().GenBashCompletion(os.Stdout) 147 | case "zsh": 148 | err = cmd.Root().GenZshCompletion(os.Stdout) 149 | case "fish": 150 | err = cmd.Root().GenFishCompletion(os.Stdout, true) 151 | case "powershell": 152 | err = cmd.Root().GenPowerShellCompletionWithDesc(os.Stdout) 153 | } 154 | return err 155 | }, 156 | } 157 | 158 | infoCmd = &cobra.Command{ 159 | Use: "info [NAME]", 160 | Short: "Describe application", 161 | Args: cobra.MinimumNArgs(1), 162 | RunE: func(cmd *cobra.Command, args []string) error { 163 | reg, err := registry.New(config.ConfigDir) 164 | if err != nil { 165 | return err 166 | } 167 | s, err := reg.Info(args[0]) 168 | if err != nil { 169 | return err 170 | } 171 | fmt.Println(s) 172 | return nil 173 | }, 174 | } 175 | 176 | argsCmd = &cobra.Command{ 177 | Use: "args [NAME]", 178 | Short: "Get arguments for an application", 179 | Args: cobra.MinimumNArgs(1), 180 | RunE: func(cmd *cobra.Command, args []string) error { 181 | reg, err := registry.New(config.ConfigDir) 182 | if err != nil { 183 | return err 184 | } 185 | appArgs, err := reg.Args(args[0]) 186 | if err != nil { 187 | return err 188 | } 189 | 190 | bytes, err := yaml.Marshal(appArgs) 191 | if err != nil { 192 | return err 193 | } 194 | fmt.Println(string(bytes)) 195 | return nil 196 | }, 197 | } 198 | ) 199 | 200 | func init() { 201 | cobra.OnInitialize(config.InitConfig) 202 | rootCmd.PersistentFlags().StringVarP(&configFile, "config", "c", "", "config file (default is $HOME/.kbrew.yaml)") 203 | rootCmd.PersistentFlags().StringVarP(&config.ConfigDir, "config-dir", "", "", "config dir (default is $HOME/.kbrew)") 204 | rootCmd.PersistentFlags().StringVarP(&namespace, "namespace", "n", "", "namespace") 205 | rootCmd.PersistentFlags().BoolVarP(&debug, "debug", "", false, "enable debug logs") 206 | 207 | rootCmd.AddCommand(versionCmd) 208 | rootCmd.AddCommand(installCmd) 209 | rootCmd.AddCommand(removeCmd) 210 | rootCmd.AddCommand(searchCmd) 211 | rootCmd.AddCommand(updateCmd) 212 | rootCmd.AddCommand(analyticsCmd) 213 | rootCmd.AddCommand(completionCmd) 214 | rootCmd.AddCommand(infoCmd) 215 | 216 | infoCmd.AddCommand(argsCmd) 217 | 218 | installCmd.PersistentFlags().StringVarP(&timeout, "timeout", "t", "", "time to wait for app components to be in a ready state (default 15m0s)") 219 | } 220 | 221 | func main() { 222 | Execute() 223 | } 224 | 225 | // Execute executes the main command 226 | func Execute() { 227 | if err := rootCmd.Execute(); err != nil { 228 | fmt.Fprintln(os.Stderr, err) 229 | os.Exit(1) 230 | } 231 | } 232 | 233 | func manageApp(m apps.Method, args []string) error { 234 | ctx := context.Background() 235 | if timeout == "" { 236 | timeout = defaultTimeout 237 | } 238 | timeoutDur, err := time.ParseDuration(timeout) 239 | if err != nil { 240 | return err 241 | } 242 | for _, a := range args { 243 | reg, err := registry.New(config.ConfigDir) 244 | if err != nil { 245 | return err 246 | } 247 | configFile, err := reg.FetchRecipe(strings.ToLower(a)) 248 | if err != nil { 249 | return err 250 | } 251 | logger := log.NewLogger(debug) 252 | runner := apps.NewAppRunner(m, logger, log.NewStatus(logger)) 253 | c, err := config.NewApp(strings.ToLower(a), configFile) 254 | if err != nil { 255 | return err 256 | } 257 | printDetails(logger, strings.ToLower(a), m, c) 258 | ctxTimeout, cancel := context.WithTimeout(ctx, timeoutDur) 259 | defer cancel() 260 | if err := runner.Run(ctxTimeout, strings.ToLower(a), namespace, configFile); err != nil { 261 | return err 262 | } 263 | } 264 | return nil 265 | } 266 | 267 | func printDetails(log *log.Logger, appName string, m apps.Method, c *config.AppConfig) { 268 | switch m { 269 | case apps.Install: 270 | log.Infof("🚀 Installing %s app...", appName) 271 | log.InfoMap("Version", c.App.Version) 272 | log.InfoMap("Pre-install dependencies", "") 273 | for _, pre := range c.App.PreInstall { 274 | for _, app := range pre.Apps { 275 | log.Infof(" - %s", app) 276 | } 277 | } 278 | log.InfoMap("Post-install dependencies", "") 279 | for _, post := range c.App.PostInstall { 280 | for _, app := range post.Apps { 281 | log.Infof(" - %s", app) 282 | } 283 | } 284 | log.Info("---") 285 | case apps.Uninstall: 286 | log.Infof("🧹 Uninstalling %s app and its dependencies...", appName) 287 | log.InfoMap("Dependencies", "") 288 | for _, pre := range c.App.PreInstall { 289 | for _, app := range pre.Apps { 290 | log.Infof(" - %s", app) 291 | } 292 | } 293 | for _, post := range c.App.PostInstall { 294 | for _, app := range post.Apps { 295 | log.Infof(" - %s", app) 296 | } 297 | } 298 | log.Info("---") 299 | } 300 | 301 | } 302 | 303 | func manageAnalytics(args []string) error { 304 | if len(args) == 0 { 305 | return errors.New("Missing subcommand") 306 | } 307 | switch args[0] { 308 | case "on": 309 | viper.Set(config.AnalyticsEnabled, true) 310 | return viper.WriteConfig() 311 | case "off": 312 | viper.Set(config.AnalyticsEnabled, false) 313 | return viper.WriteConfig() 314 | case "status": 315 | kc, err := config.NewKbrew() 316 | if err != nil { 317 | return err 318 | } 319 | fmt.Println("Analytics enabled:", kc.AnalyticsEnabled) 320 | default: 321 | return errors.New("Invalid subcommand") 322 | } 323 | return nil 324 | } 325 | -------------------------------------------------------------------------------- /docs/analytics.md: -------------------------------------------------------------------------------- 1 | # Anonymous Aggregate Analytics 2 | 3 | kbrew gathers anonymous aggregate analytics using Google Analytics. The analytics are enabled by default but you can always [opt out](analytics.md#opting-out) and continue using kbrew without ever sending analytics data. 4 | 5 | ## Why? 6 | The analytics is anonymized and used in aggregate to determine the failure/success rate of recipes and to improve user experience. It helps us understand how the tool is getting used and what we can do to make it even better. Anonymous aggregate user analytics allows us to prioritize bug fixes, plan new features and design the roadmap. In the future, once we have enough data, we are planning to make the failure and success rates of the app installations public so that users can do install with confidence. 7 | 8 | ## What? 9 | 10 | kbrew records the following events 11 | (ref: https://github.com/kbrew-dev/kbrew/blob/main/pkg/events/events.go#L97) 12 | 13 | | s/r | event | example | 14 | | --- |-------- | -------- | 15 | | 1 | kbrew [application name](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#an) | `kbrew` | 16 | | 2 | kbrew [application version](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#av) | `v0.0.8` | 17 | | 3 | [Google Analytics version](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#v) | `1` | 18 | | 4 | kbrew [analytics tracking ID](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#tid) | `UA-xxxxxxx-1` | 19 | | 5 | kbrew [analytics user ID](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#cid) | `c47d1a81-6cbe-4179-bdd1-4918e3be9768` (generated and stored after installation. See note for the details) | 20 | | 6 | [Google Analytics anonymous IP setting](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#aip) | `1` (enabled) 21 | | 7 | kbrew [analytics hit type](h8tps://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#t) | `event` | 22 | | 8 | K8s version of the cluster (on which kbrew installs app) | `v1.20.1` | 23 | | 9 | kbrew app name | `kafka` | 24 | | 10 | kbrew recipe args | `Deployment.nginx.spec.replicas: 4` | 25 | | 11 | kbrew error message | `Error rendering value: template: gotpl:1: unexpected {{end}}` | 26 | | 12 | kbrew event category | `install-fail` | 27 | 28 | **NOTE:** 29 | 30 | `kbrew analytics user ID` is generated by UUID generator when first time kbrew command is executed on a system and stored in the kbrew config `(${HOME}/.kbrew/config.yaml)` `analyticsuuid`. This does not allow us to track individual users but does enable us to accurately measure user counts versus event counts. The ID is specific to kbrew installation and does not permit kbrew maintainers to track anything else. 31 | 32 | On failures, kbrew also collects [the Kubernetes failure events](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.19/#event-v1-core) generated for the recipe components. kbrew does not collect events on any other resources which are not created as a part of the installation. Kubernetes failure events help us tuning the recipes if it is not working in a specific environment. 33 | - K8s failure event reason 34 | - K8s failure event message 35 | - K8s failure event action 36 | - K8s failure event involvedObject 37 | 38 | kbrew's analytics records the following different events: 39 | (ref: https://github.com/kbrew-dev/kbrew/blob/main/pkg/events/events.go#L45) 40 | 41 | - `install-success`: installation successful 42 | - `install-fail`: installation failed 43 | - `install-timeout`: installation timed out 44 | - `uninstall-success`: uninstallation successful 45 | - `uninstall-fail`: uninstallation failed 46 | - `uninstall-timeout`: uninstallation timed out 47 | - `k8s-event`: Kubernetes failure events sent after `install-fail` or `install-timeout` event 48 | 49 | 50 | It's practically impossible to map randomly generated user ID (UUID) with any particular event. So you don't have to worry about being tracked for the activity. 51 | 52 | ## When/Where? 53 | kbrew analytics are sent throughout kbrew's execution to Google Analytics over HTTPS. 54 | 55 | ## Opting out 56 | We appreciate keeping analytics on which helps us keep kbrew improving. But if you decided to opt-out of kbrew analytics, it can be disabled with 57 | 58 | ```sh 59 | kbrew analytics off 60 | ``` 61 | The kbrew analytics status can be checked with 62 | 63 | ```sh 64 | kbrew analytics status 65 | ``` 66 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/kbrew-dev/kbrew 2 | 3 | go 1.16 4 | 5 | replace github.com/graymeta/stow => github.com/kastenhq/stow v0.2.6-kasten.1 6 | 7 | require ( 8 | github.com/BurntSushi/toml v0.3.1 9 | github.com/Masterminds/sprig/v3 v3.2.2 10 | github.com/briandowns/spinner v1.16.0 11 | github.com/go-git/go-git/v5 v5.2.0 12 | github.com/google/go-cmp v0.5.4 13 | github.com/google/go-github v17.0.0+incompatible 14 | github.com/google/go-querystring v1.0.0 // indirect 15 | github.com/kanisterio/kanister v0.0.0-20210224062123-08e898f3dbf3 16 | github.com/mikefarah/yq/v4 v4.9.0 17 | github.com/mitchellh/go-homedir v1.1.0 18 | github.com/openshift/api v0.0.0-20200526144822-34f54f12813a 19 | github.com/openshift/client-go v0.0.0-20200521150516-05eb9880269c 20 | github.com/pkg/errors v0.9.1 21 | github.com/satori/go.uuid v1.2.0 22 | github.com/spf13/cobra v1.1.3 23 | github.com/spf13/viper v1.7.1 24 | golang.org/x/net v0.0.0-20210510120150-4163338589ed // indirect 25 | golang.org/x/sys v0.0.0-20210514084401-e8d321eab015 // indirect 26 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c 27 | gopkg.in/op/go-logging.v1 v1.0.0-20160211212156-b2cb9fa56473 28 | gopkg.in/yaml.v2 v2.4.0 29 | helm.sh/helm/v3 v3.6.1 30 | k8s.io/api v0.21.0 31 | k8s.io/apimachinery v0.21.0 32 | k8s.io/client-go v0.21.0 33 | sigs.k8s.io/yaml v1.2.0 34 | ) 35 | 36 | replace ( 37 | github.com/docker/distribution => github.com/docker/distribution v0.0.0-20191216044856-a8371794149d 38 | github.com/docker/docker => github.com/moby/moby v17.12.0-ce-rc1.0.20200618181300-9dc6525e6118+incompatible 39 | ) 40 | -------------------------------------------------------------------------------- /images/infracloud.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kbrew-dev/kbrew/e418f0eadc88452eff3a75f56a5dc33e5b5932a9/images/infracloud.png -------------------------------------------------------------------------------- /images/kbrew-install.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kbrew-dev/kbrew/e418f0eadc88452eff3a75f56a5dc33e5b5932a9/images/kbrew-install.png -------------------------------------------------------------------------------- /images/kbrew-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kbrew-dev/kbrew/e418f0eadc88452eff3a75f56a5dc33e5b5932a9/images/kbrew-logo.png -------------------------------------------------------------------------------- /images/kbrew-remove.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kbrew-dev/kbrew/e418f0eadc88452eff3a75f56a5dc33e5b5932a9/images/kbrew-remove.png -------------------------------------------------------------------------------- /images/rook-demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kbrew-dev/kbrew/e418f0eadc88452eff3a75f56a5dc33e5b5932a9/images/rook-demo.gif -------------------------------------------------------------------------------- /install.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | set -e 3 | # Code generated by godownloader on 2021-07-28T09:07:28Z. DO NOT EDIT. 4 | # 5 | 6 | usage() { 7 | this=$1 8 | cat </dev/null 135 | } 136 | echoerr() { 137 | echo "$@" 1>&2 138 | } 139 | log_prefix() { 140 | echo "$0" 141 | } 142 | _logp=6 143 | log_set_priority() { 144 | _logp="$1" 145 | } 146 | log_priority() { 147 | if test -z "$1"; then 148 | echo "$_logp" 149 | return 150 | fi 151 | [ "$1" -le "$_logp" ] 152 | } 153 | log_tag() { 154 | case $1 in 155 | 0) echo "emerg" ;; 156 | 1) echo "alert" ;; 157 | 2) echo "crit" ;; 158 | 3) echo "err" ;; 159 | 4) echo "warning" ;; 160 | 5) echo "notice" ;; 161 | 6) echo "info" ;; 162 | 7) echo "debug" ;; 163 | *) echo "$1" ;; 164 | esac 165 | } 166 | log_debug() { 167 | log_priority 7 || return 0 168 | echoerr "$(log_prefix)" "$(log_tag 7)" "$@" 169 | } 170 | log_info() { 171 | log_priority 6 || return 0 172 | echoerr "$(log_prefix)" "$(log_tag 6)" "$@" 173 | } 174 | log_err() { 175 | log_priority 3 || return 0 176 | echoerr "$(log_prefix)" "$(log_tag 3)" "$@" 177 | } 178 | log_crit() { 179 | log_priority 2 || return 0 180 | echoerr "$(log_prefix)" "$(log_tag 2)" "$@" 181 | } 182 | uname_os() { 183 | os=$(uname -s | tr '[:upper:]' '[:lower:]') 184 | case "$os" in 185 | cygwin_nt*) os="windows" ;; 186 | mingw*) os="windows" ;; 187 | msys_nt*) os="windows" ;; 188 | esac 189 | echo "$os" 190 | } 191 | uname_arch() { 192 | arch=$(uname -m) 193 | case $arch in 194 | x86_64) arch="amd64" ;; 195 | x86) arch="386" ;; 196 | i686) arch="386" ;; 197 | i386) arch="386" ;; 198 | aarch64) arch="arm64" ;; 199 | armv5*) arch="armv5" ;; 200 | armv6*) arch="armv6" ;; 201 | armv7*) arch="armv7" ;; 202 | esac 203 | echo ${arch} 204 | } 205 | uname_os_check() { 206 | os=$(uname_os) 207 | case "$os" in 208 | darwin) return 0 ;; 209 | dragonfly) return 0 ;; 210 | freebsd) return 0 ;; 211 | linux) return 0 ;; 212 | android) return 0 ;; 213 | nacl) return 0 ;; 214 | netbsd) return 0 ;; 215 | openbsd) return 0 ;; 216 | plan9) return 0 ;; 217 | solaris) return 0 ;; 218 | windows) return 0 ;; 219 | esac 220 | log_crit "uname_os_check '$(uname -s)' got converted to '$os' which is not a GOOS value. Please file bug at https://github.com/client9/shlib" 221 | return 1 222 | } 223 | uname_arch_check() { 224 | arch=$(uname_arch) 225 | case "$arch" in 226 | 386) return 0 ;; 227 | amd64) return 0 ;; 228 | arm64) return 0 ;; 229 | armv5) return 0 ;; 230 | armv6) return 0 ;; 231 | armv7) return 0 ;; 232 | ppc64) return 0 ;; 233 | ppc64le) return 0 ;; 234 | mips) return 0 ;; 235 | mipsle) return 0 ;; 236 | mips64) return 0 ;; 237 | mips64le) return 0 ;; 238 | s390x) return 0 ;; 239 | amd64p32) return 0 ;; 240 | esac 241 | log_crit "uname_arch_check '$(uname -m)' got converted to '$arch' which is not a GOARCH value. Please file bug report at https://github.com/client9/shlib" 242 | return 1 243 | } 244 | untar() { 245 | tarball=$1 246 | case "${tarball}" in 247 | *.tar.gz | *.tgz) tar --no-same-owner -xzf "${tarball}" ;; 248 | *.tar) tar --no-same-owner -xf "${tarball}" ;; 249 | *.zip) unzip "${tarball}" ;; 250 | *) 251 | log_err "untar unknown archive format for ${tarball}" 252 | return 1 253 | ;; 254 | esac 255 | } 256 | http_download_curl() { 257 | local_file=$1 258 | source_url=$2 259 | header=$3 260 | if [ -z "$header" ]; then 261 | code=$(curl -w '%{http_code}' -sL -o "$local_file" "$source_url") 262 | else 263 | code=$(curl -w '%{http_code}' -sL -H "$header" -o "$local_file" "$source_url") 264 | fi 265 | if [ "$code" != "200" ]; then 266 | log_debug "http_download_curl received HTTP status $code" 267 | return 1 268 | fi 269 | return 0 270 | } 271 | http_download_wget() { 272 | local_file=$1 273 | source_url=$2 274 | header=$3 275 | if [ -z "$header" ]; then 276 | wget -q -O "$local_file" "$source_url" 277 | else 278 | wget -q --header "$header" -O "$local_file" "$source_url" 279 | fi 280 | } 281 | http_download() { 282 | log_debug "http_download $2" 283 | if is_command curl; then 284 | http_download_curl "$@" 285 | return 286 | elif is_command wget; then 287 | http_download_wget "$@" 288 | return 289 | fi 290 | log_crit "http_download unable to find wget or curl" 291 | return 1 292 | } 293 | http_copy() { 294 | tmp=$(mktemp) 295 | http_download "${tmp}" "$1" "$2" || return 1 296 | body=$(cat "$tmp") 297 | rm -f "${tmp}" 298 | echo "$body" 299 | } 300 | github_release() { 301 | owner_repo=$1 302 | version=$2 303 | test -z "$version" && version="latest" 304 | giturl="https://github.com/${owner_repo}/releases/${version}" 305 | json=$(http_copy "$giturl" "Accept:application/json") 306 | test -z "$json" && return 1 307 | version=$(echo "$json" | tr -s '\n' ' ' | sed 's/.*"tag_name":"//' | sed 's/".*//') 308 | test -z "$version" && return 1 309 | echo "$version" 310 | } 311 | hash_sha256() { 312 | TARGET=${1:-/dev/stdin} 313 | if is_command gsha256sum; then 314 | hash=$(gsha256sum "$TARGET") || return 1 315 | echo "$hash" | cut -d ' ' -f 1 316 | elif is_command sha256sum; then 317 | hash=$(sha256sum "$TARGET") || return 1 318 | echo "$hash" | cut -d ' ' -f 1 319 | elif is_command shasum; then 320 | hash=$(shasum -a 256 "$TARGET" 2>/dev/null) || return 1 321 | echo "$hash" | cut -d ' ' -f 1 322 | elif is_command openssl; then 323 | hash=$(openssl -dst openssl dgst -sha256 "$TARGET") || return 1 324 | echo "$hash" | cut -d ' ' -f a 325 | else 326 | log_crit "hash_sha256 unable to find command to compute sha-256 hash" 327 | return 1 328 | fi 329 | } 330 | hash_sha256_verify() { 331 | TARGET=$1 332 | checksums=$2 333 | if [ -z "$checksums" ]; then 334 | log_err "hash_sha256_verify checksum file not specified in arg2" 335 | return 1 336 | fi 337 | BASENAME=${TARGET##*/} 338 | want=$(grep "${BASENAME}" "${checksums}" 2>/dev/null | tr '\t' ' ' | cut -d ' ' -f 1) 339 | if [ -z "$want" ]; then 340 | log_err "hash_sha256_verify unable to find checksum for '${TARGET}' in '${checksums}'" 341 | return 1 342 | fi 343 | got=$(hash_sha256 "$TARGET") 344 | if [ "$want" != "$got" ]; then 345 | log_err "hash_sha256_verify checksum for '$TARGET' did not verify ${want} vs $got" 346 | return 1 347 | fi 348 | } 349 | cat /dev/null < 1000 { 76 | return "", errors.Wrapf(fmt.Errorf("unable to execute template"), "rendering template has a nested reference name: %s", name) 77 | } 78 | includedNames[name]++ 79 | } else { 80 | includedNames[name] = 1 81 | } 82 | err := e.template.ExecuteTemplate(&buf, name, data) 83 | includedNames[name]-- 84 | return buf.String(), err 85 | } 86 | 87 | if e.config != nil { 88 | e.fmap["lookup"] = engine.NewLookupFunction(e.config) 89 | } 90 | 91 | e.template.Funcs(e.fmap) 92 | } 93 | -------------------------------------------------------------------------------- /pkg/engine/engine_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 The kbrew Authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package engine 16 | 17 | import ( 18 | "testing" 19 | 20 | "github.com/google/go-cmp/cmp" 21 | "github.com/pkg/errors" 22 | ) 23 | 24 | func TestFuncMap(t *testing.T) { 25 | fns := funcMap() 26 | forbidden := []string{"env", "expandenv"} 27 | for _, f := range forbidden { 28 | if _, ok := fns[f]; ok { 29 | t.Errorf("Forbidden function %s exists in FuncMap.", f) 30 | } 31 | } 32 | 33 | // Test for Engine-specific template functions. 34 | expect := []string{"include", "required", "tpl", "toYaml", "fromYaml", "toToml", "toJson", "fromJson", "lookup"} 35 | for _, f := range expect { 36 | if _, ok := fns[f]; !ok { 37 | t.Errorf("Expected add-on function %q", f) 38 | } 39 | } 40 | } 41 | 42 | func TestRender(t *testing.T) { 43 | type want struct { 44 | result string 45 | err error 46 | } 47 | 48 | cases := map[string]struct { 49 | arg string 50 | want 51 | }{ 52 | "CheckUntil": { 53 | arg: "{{ until 5 }}", 54 | want: want{ 55 | result: "[0 1 2 3 4]", 56 | }, 57 | }, 58 | "CheckMissingFunction": { 59 | arg: "{{ foo 5 }}", 60 | want: want{ 61 | err: errors.Wrapf(errors.New("template: gotpl:1: function \"foo\" not defined"), renderErr), 62 | }, 63 | }, 64 | "CheckConstString": { 65 | arg: "SomeString", 66 | want: want{ 67 | result: "SomeString", 68 | }, 69 | }, 70 | "CheckInclude": { 71 | arg: `{{define "T1"}}{{trim .}}{{end}}{{include "T1" " hello" | upper }}`, 72 | want: want{ 73 | result: "HELLO", 74 | }, 75 | }, 76 | } 77 | 78 | for name, tc := range cases { 79 | t.Run(name, func(t *testing.T) { 80 | e := NewEngine(nil) 81 | o, err := e.Render(tc.arg) 82 | 83 | if diff := cmp.Diff(tc.want.result, o); diff != "" { 84 | t.Errorf("r: -want, +got:\n%s", diff) 85 | } 86 | 87 | if err != nil && err.Error() != tc.err.Error() { 88 | t.Errorf("Expected '%s', got %q", tc.err.Error(), err.Error()) 89 | } 90 | }) 91 | } 92 | } 93 | 94 | func TestInitMap(t *testing.T) { 95 | e := NewEngine(nil) 96 | e.initFuncMap() 97 | 98 | _, ok := e.fmap["include"] 99 | if !ok { 100 | t.Error("Expected function 'include' in funcMap") 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /pkg/engine/funcs.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 The kbrew Authors. 2 | // 3 | // Copyright The Helm Authors. 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // The following code is taken from helm, which was found here: 6 | // https://github.com/helm/helm/blob/main/pkg/engine/funcs.go 7 | 8 | package engine 9 | 10 | import ( 11 | "bytes" 12 | "encoding/json" 13 | "strings" 14 | "text/template" 15 | 16 | "github.com/BurntSushi/toml" 17 | "github.com/Masterminds/sprig/v3" 18 | "sigs.k8s.io/yaml" 19 | ) 20 | 21 | // funcMap returns a mapping of all of the functions that Engine has. 22 | // 23 | // Because some functions are late-bound (e.g. contain context-sensitive 24 | // data), the functions may not all perform identically outside of an Engine 25 | // as they will inside of an Engine. 26 | // 27 | // Known late-bound functions: 28 | // 29 | // - "include" 30 | // - "tpl" 31 | // 32 | // These are late-bound in Engine.Render(). The 33 | // version included in the FuncMap is a placeholder. 34 | // 35 | func funcMap() template.FuncMap { 36 | f := sprig.TxtFuncMap() 37 | delete(f, "env") 38 | delete(f, "expandenv") 39 | 40 | // Add some extra functionality 41 | extra := template.FuncMap{ 42 | "toToml": toTOML, 43 | "toYaml": toYAML, 44 | "fromYaml": fromYAML, 45 | "fromYamlArray": fromYAMLArray, 46 | "toJson": toJSON, 47 | "fromJson": fromJSON, 48 | "fromJsonArray": fromJSONArray, 49 | 50 | // This is a placeholder for the "include" function, which is 51 | // late-bound to a template. By declaring it here, we preserve the 52 | // integrity of the linter. 53 | "include": func(string, interface{}) string { return "not implemented" }, 54 | "tpl": func(string, interface{}) interface{} { return "not implemented" }, 55 | "required": func(string, interface{}) (interface{}, error) { return "not implemented", nil }, 56 | // Provide a placeholder for the "lookup" function, which requires a kubernetes 57 | // connection. 58 | "lookup": func(string, string, string, string) (map[string]interface{}, error) { 59 | return map[string]interface{}{}, nil 60 | }, 61 | } 62 | 63 | for k, v := range extra { 64 | f[k] = v 65 | } 66 | 67 | return f 68 | } 69 | 70 | // toYAML takes an interface, marshals it to yaml, and returns a string. It will 71 | // always return a string, even on marshal error (empty string). 72 | // 73 | // This is designed to be called from a template. 74 | func toYAML(v interface{}) string { 75 | data, err := yaml.Marshal(v) 76 | if err != nil { 77 | // Swallow errors inside of a template. 78 | return "" 79 | } 80 | return strings.TrimSuffix(string(data), "\n") 81 | } 82 | 83 | // fromYAML converts a YAML document into a map[string]interface{}. 84 | // 85 | // This is not a general-purpose YAML parser, and will not parse all valid 86 | // YAML documents. Additionally, because its intended use is within templates 87 | // it tolerates errors. It will insert the returned error message string into 88 | // m["Error"] in the returned map. 89 | func fromYAML(str string) map[string]interface{} { 90 | m := map[string]interface{}{} 91 | 92 | if err := yaml.Unmarshal([]byte(str), &m); err != nil { 93 | m["Error"] = err.Error() 94 | } 95 | return m 96 | } 97 | 98 | // fromYAMLArray converts a YAML array into a []interface{}. 99 | // 100 | // This is not a general-purpose YAML parser, and will not parse all valid 101 | // YAML documents. Additionally, because its intended use is within templates 102 | // it tolerates errors. It will insert the returned error message string as 103 | // the first and only item in the returned array. 104 | func fromYAMLArray(str string) []interface{} { 105 | a := []interface{}{} 106 | 107 | if err := yaml.Unmarshal([]byte(str), &a); err != nil { 108 | a = []interface{}{err.Error()} 109 | } 110 | return a 111 | } 112 | 113 | // toTOML takes an interface, marshals it to toml, and returns a string. It will 114 | // always return a string, even on marshal error (empty string). 115 | // 116 | // This is designed to be called from a template. 117 | func toTOML(v interface{}) string { 118 | b := bytes.NewBuffer(nil) 119 | e := toml.NewEncoder(b) 120 | err := e.Encode(v) 121 | if err != nil { 122 | return err.Error() 123 | } 124 | return b.String() 125 | } 126 | 127 | // toJSON takes an interface, marshals it to json, and returns a string. It will 128 | // always return a string, even on marshal error (empty string). 129 | // 130 | // This is designed to be called from a template. 131 | func toJSON(v interface{}) string { 132 | data, err := json.Marshal(v) 133 | if err != nil { 134 | // Swallow errors inside of a template. 135 | return "" 136 | } 137 | return string(data) 138 | } 139 | 140 | // fromJSON converts a JSON document into a map[string]interface{}. 141 | // 142 | // This is not a general-purpose JSON parser, and will not parse all valid 143 | // JSON documents. Additionally, because its intended use is within templates 144 | // it tolerates errors. It will insert the returned error message string into 145 | // m["Error"] in the returned map. 146 | func fromJSON(str string) map[string]interface{} { 147 | m := make(map[string]interface{}) 148 | 149 | if err := json.Unmarshal([]byte(str), &m); err != nil { 150 | m["Error"] = err.Error() 151 | } 152 | return m 153 | } 154 | 155 | // fromJSONArray converts a JSON array into a []interface{}. 156 | // 157 | // This is not a general-purpose JSON parser, and will not parse all valid 158 | // JSON documents. Additionally, because its intended use is within templates 159 | // it tolerates errors. It will insert the returned error message string as 160 | // the first and only item in the returned array. 161 | func fromJSONArray(str string) []interface{} { 162 | a := []interface{}{} 163 | 164 | if err := json.Unmarshal([]byte(str), &a); err != nil { 165 | a = []interface{}{err.Error()} 166 | } 167 | return a 168 | } 169 | -------------------------------------------------------------------------------- /pkg/events/events.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 The kbrew Authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package events 16 | 17 | import ( 18 | "bytes" 19 | "context" 20 | "fmt" 21 | "net/http" 22 | "net/url" 23 | "time" 24 | 25 | "github.com/spf13/viper" 26 | corev1 "k8s.io/api/core/v1" 27 | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 28 | "k8s.io/apimachinery/pkg/labels" 29 | 30 | "github.com/kbrew-dev/kbrew/pkg/config" 31 | "github.com/kbrew-dev/kbrew/pkg/kube" 32 | "github.com/kbrew-dev/kbrew/pkg/version" 33 | ) 34 | 35 | // EventCategory is the Google Analytics Event category 36 | type EventCategory string 37 | 38 | const ( 39 | kbrewTrackingID = "UA-195717361-1" 40 | gaCollectURL = "https://www.google-analytics.com/collect" 41 | httpTimeout = 5 * time.Second 42 | ) 43 | 44 | var ( 45 | // ECInstallSuccess represents install success event category 46 | ECInstallSuccess EventCategory = "install-success" 47 | // ECInstallFail represents install failure event category 48 | ECInstallFail EventCategory = "install-fail" 49 | // ECInstallTimeout represents install timeout event category 50 | ECInstallTimeout EventCategory = "install-timeout" 51 | 52 | // ECUninstallSuccess represents uninstall success event category 53 | ECUninstallSuccess EventCategory = "uninstall-success" 54 | // ECUninstallFail represents uninstall failure event category 55 | ECUninstallFail EventCategory = "uninstall-fail" 56 | // ECUninstallTimeout represents uninstall timeout event category 57 | ECUninstallTimeout EventCategory = "uninstall-timeout" 58 | 59 | // ECK8sEvent represents k8s events event category 60 | ECK8sEvent EventCategory = "k8s-event" 61 | ) 62 | 63 | type k8sEvent struct { 64 | Reason string 65 | Message string 66 | Object string 67 | Action string 68 | } 69 | 70 | // KbrewEvent contains information to report Event to Google Analytics 71 | type KbrewEvent struct { 72 | gaVersion string 73 | gaType string 74 | gaTID string 75 | gaCID string 76 | gaAIP string 77 | gaAppName string 78 | gaAppVersion string 79 | // gaEvCategory string 80 | gaEvAction string 81 | gaEvLabel string 82 | gaKbrewArgs string 83 | } 84 | 85 | // String returns string representation of Event Category 86 | func (ec EventCategory) String() string { 87 | return string(ec) 88 | } 89 | 90 | // NewKbrewEvent return new KbrewEvent 91 | func NewKbrewEvent(appConfig *config.AppConfig) *KbrewEvent { 92 | k8sVersion, err := kube.GetK8sVersion() 93 | if err != nil { 94 | fmt.Printf("ERROR: Failed to fetch K8s version, %s\n", err.Error()) 95 | k8sVersion = "NA" 96 | } 97 | return &KbrewEvent{ 98 | gaVersion: "1", 99 | gaType: "event", 100 | gaTID: kbrewTrackingID, 101 | gaCID: viper.GetString(config.AnalyticsUUID), 102 | gaAIP: "1", 103 | gaAppName: "kbrew", 104 | gaAppVersion: version.Short(), 105 | gaEvLabel: fmt.Sprintf("k8s %s", k8sVersion), 106 | gaEvAction: appConfig.App.Name, 107 | gaKbrewArgs: labels.FormatLabels(argsToLabels(appConfig.App.Args)), 108 | } 109 | } 110 | 111 | // Report sends event to Google Analytics 112 | func (kv *KbrewEvent) Report(ctx context.Context, ec EventCategory, err error, k8sEvent *k8sEvent) error { 113 | v := url.Values{ 114 | "v": {kv.gaVersion}, 115 | "tid": {kv.gaTID}, 116 | "cid": {kv.gaCID}, 117 | "aip": {kv.gaAIP}, 118 | "t": {kv.gaType}, 119 | "ec": {ec.String()}, 120 | "ea": {kv.gaEvAction}, 121 | "el": {kv.gaEvLabel}, 122 | "an": {kv.gaAppName}, 123 | "av": {kv.gaAppVersion}, 124 | "cd1": {}, 125 | "cd2": {}, 126 | "cd3": {}, 127 | "cd4": {}, 128 | "cd5": {}, 129 | "cd6": {kv.gaKbrewArgs}, 130 | } 131 | 132 | if err != nil { 133 | // Set kbrew message 134 | v.Set("cd5", err.Error()) 135 | } 136 | 137 | if k8sEvent != nil { 138 | // Set k8s_reason 139 | v.Set("cd1", k8sEvent.Reason) 140 | // Set k8s_message 141 | v.Set("cd2", k8sEvent.Message) 142 | // Set k8s_action 143 | v.Set("cd3", k8sEvent.Action) 144 | // Set k8s_object 145 | v.Set("cd4", k8sEvent.Object) 146 | } 147 | 148 | buf := bytes.NewBufferString(v.Encode()) 149 | req, err1 := http.NewRequest("POST", gaCollectURL, buf) 150 | req.Header.Add("Content-Type", "application/x-www-form-urlencoded") 151 | req.Header.Add("User-Agent", fmt.Sprintf("kbrew/%s", version.Short())) 152 | if err1 != nil { 153 | return err1 154 | } 155 | ctx, cancel := context.WithTimeout(ctx, httpTimeout) 156 | defer cancel() 157 | 158 | req = req.WithContext(ctx) 159 | 160 | client := http.DefaultClient 161 | resp, err1 := client.Do(req) 162 | if err1 != nil { 163 | return err1 164 | } 165 | if resp.StatusCode != http.StatusOK { 166 | return fmt.Errorf("analytics report failed with status code %d", resp.StatusCode) 167 | } 168 | defer resp.Body.Close() 169 | return err1 170 | } 171 | 172 | // ReportK8sEvents sends kbrew events with K8s events to Google Analytics 173 | func (kv *KbrewEvent) ReportK8sEvents(ctx context.Context, err error, workloads []corev1.ObjectReference) error { 174 | k8sEvents, err1 := getPodEvents(ctx, workloads) 175 | if err1 != nil { 176 | return err1 177 | } 178 | for _, event := range k8sEvents { 179 | err1 := kv.Report(ctx, ECK8sEvent, err, &event) 180 | if err1 != nil { 181 | return err1 182 | } 183 | } 184 | return nil 185 | } 186 | 187 | func getPodEvents(ctx context.Context, workloads []corev1.ObjectReference) ([]k8sEvent, error) { 188 | notRunningPods, err := kube.FetchNonRunningPods(ctx, workloads) 189 | if err != nil { 190 | return nil, err 191 | } 192 | events := []k8sEvent{} 193 | for _, pod := range notRunningPods { 194 | ks8Events, err := getK8sEvents(ctx, corev1.ObjectReference{Name: pod.GetName(), Namespace: pod.GetNamespace(), UID: pod.GetUID(), Kind: "Pod"}) 195 | if err != nil { 196 | return nil, err 197 | } 198 | events = append(events, ks8Events...) 199 | } 200 | return events, nil 201 | } 202 | 203 | func prepareObjectSelector(objReference corev1.ObjectReference) string { 204 | return labels.Set{ 205 | "involvedObject.name": objReference.Name, 206 | "involvedObject.namespace": objReference.Namespace, 207 | "involvedObject.uid": string(objReference.UID), 208 | "involvedObject.kind": objReference.Kind, 209 | "type": "Warning", 210 | }.String() 211 | } 212 | 213 | func getK8sEvents(ctx context.Context, objReference corev1.ObjectReference) ([]k8sEvent, error) { 214 | clis, err := kube.NewClient() 215 | if err != nil { 216 | return nil, err 217 | } 218 | objSelector := prepareObjectSelector(objReference) 219 | eventList, err := clis.KubeCli.CoreV1().Events(objReference.Namespace).List(ctx, metav1.ListOptions{FieldSelector: objSelector}) 220 | if err != nil { 221 | return nil, err 222 | } 223 | retEventList := []k8sEvent{} 224 | for _, event := range eventList.Items { 225 | objRef := corev1.ObjectReference{ 226 | Name: event.InvolvedObject.Name, 227 | Namespace: event.InvolvedObject.Namespace, 228 | Kind: event.InvolvedObject.Kind, 229 | } 230 | retEventList = append(retEventList, k8sEvent{ 231 | Reason: event.Reason, 232 | Message: event.Message, 233 | Object: objRef.String(), 234 | Action: event.Action, 235 | }) 236 | } 237 | return retEventList, nil 238 | } 239 | 240 | func argsToLabels(args map[string]interface{}) map[string]string { 241 | labels := make(map[string]string) 242 | for k, v := range args { 243 | labels[k] = fmt.Sprintf("%v", v) 244 | } 245 | return labels 246 | } 247 | -------------------------------------------------------------------------------- /pkg/kube/kube.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 The kbrew Authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package kube 16 | 17 | import ( 18 | "context" 19 | "os" 20 | "path/filepath" 21 | 22 | "github.com/kanisterio/kanister/pkg/kube" 23 | osversioned "github.com/openshift/client-go/apps/clientset/versioned" 24 | corev1 "k8s.io/api/core/v1" 25 | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 26 | "k8s.io/client-go/discovery" 27 | "k8s.io/client-go/kubernetes" 28 | "k8s.io/client-go/rest" 29 | "k8s.io/client-go/tools/clientcmd" 30 | "k8s.io/client-go/util/homedir" 31 | ) 32 | 33 | var k8sVersion string 34 | 35 | // Client contains Kubernetes clients to call APIs 36 | type Client struct { 37 | KubeCli kubernetes.Interface 38 | OSCli osversioned.Interface 39 | DiscoveryCli discovery.DiscoveryInterface 40 | } 41 | 42 | // WaitForPodReady waits till the pod gets ready 43 | func WaitForPodReady(ctx context.Context, kubeCli kubernetes.Interface, namespace string, name string) error { 44 | return kube.WaitForPodReady(ctx, kubeCli, namespace, name) 45 | } 46 | 47 | // WaitForDeploymentReady waits till the deployment gets ready 48 | func WaitForDeploymentReady(ctx context.Context, kubeCli kubernetes.Interface, namespace string, name string) error { 49 | return kube.WaitOnDeploymentReady(ctx, kubeCli, namespace, name) 50 | } 51 | 52 | // WaitForStatefulSetReady waits till the statefulset gets ready 53 | func WaitForStatefulSetReady(ctx context.Context, kubeCli kubernetes.Interface, namespace string, name string) error { 54 | return kube.WaitOnStatefulSetReady(ctx, kubeCli, namespace, name) 55 | } 56 | 57 | // CreateNamespace creates namespace 58 | func CreateNamespace(ctx context.Context, kubeCli kubernetes.Interface, namespace string) error { 59 | if namespace == "" { 60 | return nil 61 | } 62 | nsName := &corev1.Namespace{ 63 | ObjectMeta: metav1.ObjectMeta{ 64 | Name: namespace, 65 | }, 66 | } 67 | _, err := kubeCli.CoreV1().Namespaces().Create(ctx, nsName, metav1.CreateOptions{}) 68 | return err 69 | } 70 | 71 | // WaitForDeploymentConfigReady waits till the deployment config gets ready 72 | func WaitForDeploymentConfigReady(ctx context.Context, osCli osversioned.Interface, kubeCli kubernetes.Interface, namespace string, name string) error { 73 | return kube.WaitOnDeploymentConfigReady(ctx, osCli, kubeCli, namespace, name) 74 | } 75 | 76 | // FetchNonRunningPods returns list of non running Pods owned by the workloads 77 | func FetchNonRunningPods(ctx context.Context, workloads []corev1.ObjectReference) ([]corev1.Pod, error) { 78 | clis, err := NewClient() 79 | if err != nil { 80 | return nil, err 81 | } 82 | 83 | pods := []corev1.Pod{} 84 | for _, wRef := range workloads { 85 | switch wRef.Kind { 86 | case "Pod": 87 | pod, err := clis.KubeCli.CoreV1().Pods(wRef.Namespace).Get(ctx, wRef.Name, metav1.GetOptions{}) 88 | if err != nil { 89 | return nil, err 90 | } 91 | if pod.Status.Phase != corev1.PodRunning { 92 | pods = append(pods, *pod) 93 | } 94 | 95 | case "Deployment": 96 | _, notRunningPods, err := kube.DeploymentPods(ctx, clis.KubeCli, wRef.Namespace, wRef.Name) 97 | if err != nil { 98 | return nil, err 99 | } 100 | pods = append(pods, notRunningPods...) 101 | case "StatefulSet": 102 | _, notRunningPods, err := kube.StatefulSetPods(ctx, clis.KubeCli, wRef.Namespace, wRef.Name) 103 | if err != nil { 104 | return nil, err 105 | } 106 | pods = append(pods, notRunningPods...) 107 | 108 | case "DeploymentConfig": 109 | _, notRunningPods, err := kube.DeploymentConfigPods(ctx, clis.OSCli, clis.KubeCli, wRef.Namespace, wRef.Name) 110 | if err != nil { 111 | return nil, err 112 | } 113 | pods = append(pods, notRunningPods...) 114 | } 115 | } 116 | return pods, nil 117 | } 118 | 119 | func newConfig() (*rest.Config, error) { 120 | kubeConfig, err := rest.InClusterConfig() 121 | if err == nil { 122 | return kubeConfig, nil 123 | } 124 | kubeconfig, ok := os.LookupEnv("KUBECONFIG") 125 | if !ok { 126 | kubeconfig = filepath.Join(homedir.HomeDir(), ".kube", "config") 127 | } 128 | 129 | return clientcmd.BuildConfigFromFlags("", kubeconfig) 130 | } 131 | 132 | // NewClient initializes and returns client object 133 | func NewClient() (*Client, error) { 134 | kubeConfig, err := newConfig() 135 | if err != nil { 136 | return nil, err 137 | } 138 | disClient, err := discovery.NewDiscoveryClientForConfig(kubeConfig) 139 | if err != nil { 140 | return nil, err 141 | } 142 | kubeCli, err := kubernetes.NewForConfig(kubeConfig) 143 | if err != nil { 144 | return nil, err 145 | } 146 | osCli, err := osversioned.NewForConfig(kubeConfig) 147 | if err != nil { 148 | return nil, err 149 | } 150 | return &Client{ 151 | KubeCli: kubeCli, 152 | DiscoveryCli: disClient, 153 | OSCli: osCli, 154 | }, nil 155 | } 156 | 157 | // GetK8sVersion returns Kubernetes server version 158 | func GetK8sVersion() (string, error) { 159 | if k8sVersion != "" { 160 | return k8sVersion, nil 161 | } 162 | clis, err := NewClient() 163 | if err != nil { 164 | return "", err 165 | } 166 | versionInfo, err := clis.DiscoveryCli.ServerVersion() 167 | if err != nil { 168 | return "", err 169 | } 170 | // Store the version in a global var to avoid repeatitive API calls 171 | k8sVersion = versionInfo.String() 172 | return k8sVersion, nil 173 | } 174 | -------------------------------------------------------------------------------- /pkg/log/log_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 The kbrew Authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package log 16 | 17 | import ( 18 | "testing" 19 | 20 | . "gopkg.in/check.v1" 21 | ) 22 | 23 | // Hook up gocheck into the "go test" runner. 24 | func Test(t *testing.T) { TestingT(t) } 25 | -------------------------------------------------------------------------------- /pkg/log/logger.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 The kbrew Authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package log 16 | 17 | import ( 18 | "fmt" 19 | "io" 20 | "os" 21 | ) 22 | 23 | const ( 24 | errorPrefix = "\x1b[31mERROR:\x1b[0m " 25 | warnPrefix = "\x1b[33mWARN:\x1b[0m " 26 | debugPrefix = "DEBUG: " 27 | 28 | infoMapKeyFormat = "\x1b[32m%s:\x1b[0m " 29 | ) 30 | 31 | type Logger struct { 32 | DebugLevel bool 33 | Writer io.Writer 34 | } 35 | 36 | func NewLogger(debug bool) *Logger { 37 | return &Logger{ 38 | DebugLevel: debug, 39 | Writer: os.Stdout, 40 | } 41 | } 42 | 43 | func (l *Logger) SetWriter(writer io.Writer) { 44 | l.Writer = writer 45 | } 46 | 47 | func (l *Logger) Info(message ...interface{}) { 48 | l.print("", message...) 49 | } 50 | 51 | func (l *Logger) Infof(format string, message ...interface{}) { 52 | l.print("", fmt.Sprintf(format, message...)) 53 | } 54 | 55 | func (l *Logger) Debug(message ...interface{}) { 56 | if !l.DebugLevel { 57 | return 58 | } 59 | l.print(debugPrefix, message...) 60 | } 61 | 62 | func (l *Logger) Debugf(format string, message ...interface{}) { 63 | if !l.DebugLevel { 64 | return 65 | } 66 | l.print(debugPrefix, fmt.Sprintf(format, message...)) 67 | } 68 | 69 | func (l *Logger) Error(message ...interface{}) { 70 | l.print(errorPrefix, message...) 71 | } 72 | 73 | func (l *Logger) Errorf(format string, message ...interface{}) { 74 | l.print(errorPrefix, fmt.Sprintf(format, message...)) 75 | } 76 | 77 | func (l *Logger) Warn(message ...interface{}) { 78 | l.print(warnPrefix, message...) 79 | } 80 | 81 | func (l *Logger) Warnf(format string, message ...interface{}) { 82 | l.print(warnPrefix, fmt.Sprintf(format, message...)) 83 | } 84 | 85 | func (l *Logger) InfoMap(key, value string) { 86 | l.print(fmt.Sprintf(infoMapKeyFormat, key), value) 87 | } 88 | 89 | func (l *Logger) print(prefix string, message ...interface{}) { 90 | fmt.Fprint(l.Writer, "\r") 91 | fmt.Fprint(l.Writer, prefix) 92 | fmt.Fprintln(l.Writer, message...) 93 | } 94 | -------------------------------------------------------------------------------- /pkg/log/logger_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 The kbrew Authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package log 16 | 17 | import ( 18 | "bytes" 19 | 20 | . "gopkg.in/check.v1" 21 | ) 22 | 23 | type LoggerTestSuite struct{} 24 | 25 | var _ = Suite(&LoggerTestSuite{}) 26 | 27 | func (l *LoggerTestSuite) TestLogger(c *C) { 28 | var buf bytes.Buffer 29 | log := NewLogger(true) 30 | log.SetWriter(&buf) 31 | 32 | log.Info("info log", "app=app1") 33 | c.Assert(buf.String(), Equals, "\rinfo log app=app1\n") 34 | 35 | buf.Reset() 36 | log.Infof("info log app=%s, namespace=%s", "app1", "appns") 37 | c.Assert(buf.String(), Equals, "\rinfo log app=app1, namespace=appns\n") 38 | 39 | buf.Reset() 40 | log.Debug("debug log", "app=app1") 41 | c.Assert(buf.String(), Equals, "\rDEBUG: debug log app=app1\n") 42 | 43 | buf.Reset() 44 | log.Debugf("debug log app=%s, namespace=%s", "app1", "appns") 45 | c.Assert(buf.String(), Equals, "\rDEBUG: debug log app=app1, namespace=appns\n") 46 | 47 | buf.Reset() 48 | log.Warn("warn log", "app=app1") 49 | c.Assert(buf.String(), Equals, "\r\x1b[33mWARN:\x1b[0m warn log app=app1\n") 50 | 51 | buf.Reset() 52 | log.Warnf("warn log app=%s, namespace=%s", "app1", "appns") 53 | c.Assert(buf.String(), Equals, "\r\x1b[33mWARN:\x1b[0m warn log app=app1, namespace=appns\n") 54 | 55 | buf.Reset() 56 | log.Error("error log", "app=app1") 57 | c.Assert(buf.String(), Equals, "\r\x1b[31mERROR:\x1b[0m error log app=app1\n") 58 | 59 | buf.Reset() 60 | log.Errorf("error log app=%s, namespace=%s", "app1", "appns") 61 | c.Assert(buf.String(), Equals, "\r\x1b[31mERROR:\x1b[0m error log app=app1, namespace=appns\n") 62 | 63 | buf.Reset() 64 | log.InfoMap("app", "app1") 65 | c.Assert(buf.String(), Equals, "\r\x1b[32mapp:\x1b[0m app1\n") 66 | 67 | buf.Reset() 68 | log.InfoMap("namespace", "appns") 69 | c.Assert(buf.String(), Equals, "\r\x1b[32mnamespace:\x1b[0m appns\n") 70 | } 71 | -------------------------------------------------------------------------------- /pkg/log/status.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 The kbrew Authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package log 16 | 17 | import ( 18 | "fmt" 19 | "os" 20 | "strings" 21 | "time" 22 | 23 | "github.com/briandowns/spinner" 24 | ) 25 | 26 | const ( 27 | successStatusFormat = " \x1b[32m✓\x1b[0m %s" 28 | failureStatusFormat = " \x1b[31m✗\x1b[0m %s" 29 | ) 30 | 31 | var ( 32 | defaultCharSet = []string{"⣾", "⣽", "⣻", "⢿", "⡿", "⣟", "⣯", "⣷"} 33 | defaultDelay = 100 * time.Millisecond 34 | ) 35 | 36 | type Status struct { 37 | spinner *spinner.Spinner 38 | message string 39 | logger *Logger 40 | 41 | successStatusFormat string 42 | failureStatusFormat string 43 | } 44 | 45 | func NewStatus(logger *Logger) *Status { 46 | return &Status{ 47 | logger: logger, 48 | spinner: spinner.New(defaultCharSet, defaultDelay, spinner.WithWriter(os.Stdout)), 49 | successStatusFormat: successStatusFormat, 50 | failureStatusFormat: failureStatusFormat, 51 | } 52 | } 53 | 54 | func (s *Status) Start(msg string) { 55 | s.Stop() 56 | s.message = msg 57 | if s.spinner != nil { 58 | s.spinner.Suffix = fmt.Sprintf(" %s ", s.message) 59 | s.spinner.Start() 60 | } 61 | } 62 | 63 | func (s *Status) Success(msg ...string) { 64 | if !s.spinner.Active() { 65 | return 66 | } 67 | if s.spinner != nil { 68 | s.spinner.Stop() 69 | } 70 | if msg != nil { 71 | s.logger.Infof(s.successStatusFormat, strings.Join(msg, " ")) 72 | return 73 | } 74 | s.logger.Infof(s.successStatusFormat, s.message) 75 | s.message = "" 76 | } 77 | 78 | func (s *Status) Error(msg ...string) { 79 | if !s.spinner.Active() { 80 | return 81 | } 82 | if s.spinner != nil { 83 | s.spinner.Stop() 84 | } 85 | if msg != nil { 86 | s.logger.Infof(s.failureStatusFormat, strings.Join(msg, " ")) 87 | return 88 | } 89 | s.logger.Infof(s.failureStatusFormat, s.message) 90 | s.message = "" 91 | } 92 | 93 | func (s *Status) Stop() { 94 | if !s.spinner.Active() { 95 | return 96 | } 97 | if s.spinner != nil { 98 | fmt.Fprint(s.logger.Writer, "\r") 99 | s.spinner.Stop() 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /pkg/log/status_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 The kbrew Authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package log 16 | 17 | import ( 18 | "testing" 19 | "time" 20 | ) 21 | 22 | func TestSuccessMessage(t *testing.T) { 23 | l := NewLogger(true) 24 | s := NewStatus(l) 25 | l.Info("Initializing") 26 | s.Start("Setting up deps") 27 | time.Sleep(2 * time.Second) 28 | l.Debug("Waiting for pods to be ready!!") 29 | time.Sleep(time.Second) 30 | s.Stop() 31 | s.Start("Installing app2") 32 | time.Sleep(2 * time.Second) 33 | s.Success("Install successful", "app=app2") 34 | s.Start("Setting up post install deps") 35 | time.Sleep(2 * time.Second) 36 | s.Start("Installing app3") 37 | time.Sleep(2 * time.Second) 38 | s.Success() 39 | s.Start("Installing app4") 40 | time.Sleep(2 * time.Second) 41 | l.Error("Timed out while waiting for pods to be ready!!") 42 | s.Error("App4 Installation failed!") 43 | } 44 | -------------------------------------------------------------------------------- /pkg/registry/registry.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 The kbrew Authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package registry 16 | 17 | import ( 18 | "fmt" 19 | "io/fs" 20 | "io/ioutil" 21 | "os" 22 | "path/filepath" 23 | "regexp" 24 | "strings" 25 | 26 | "github.com/go-git/go-git/v5" 27 | "github.com/mitchellh/go-homedir" 28 | "github.com/pkg/errors" 29 | "github.com/spf13/cobra" 30 | "gopkg.in/yaml.v2" 31 | 32 | "github.com/kbrew-dev/kbrew/pkg/config" 33 | ) 34 | 35 | const ( 36 | registriesDirName = "registries" 37 | 38 | defaultRegistryUserName = "kbrew-dev" 39 | defaultRegistryRepoName = "kbrew-registry" 40 | ghRegistryURLFormat = "https://github.com/%s/%s.git" 41 | kbrewDir = ".kbrew" 42 | ) 43 | 44 | // recipeFilenamePattern regex pattern to search recipe files within a registry 45 | var recipeFilenamePattern = regexp.MustCompile(`(?m)recipes\/(.*)\.yaml`) 46 | 47 | // KbrewRegistry is the collection of kbrew recipes 48 | type KbrewRegistry struct { 49 | path string 50 | } 51 | 52 | // Info holds recipe name and path for an app 53 | type Info struct { 54 | Name string 55 | Path string 56 | } 57 | 58 | // New initializes KbrewRegistry, creates or clones default registry if not exists 59 | func New(configDir string) (*KbrewRegistry, error) { 60 | r := &KbrewRegistry{ 61 | path: filepath.Join(configDir), 62 | } 63 | return r, r.init() 64 | } 65 | 66 | // init creates config dir and clones default registry if not exists 67 | func (kr *KbrewRegistry) init() error { 68 | home, err := homedir.Dir() 69 | cobra.CheckErr(err) 70 | 71 | registriesDir := filepath.Join(home, kbrewDir, registriesDirName) 72 | 73 | // Check if default kbrew-registry exists, clone if not added already 74 | if _, err := os.Stat(filepath.Join(registriesDir, defaultRegistryUserName, defaultRegistryRepoName)); os.IsNotExist(err) { 75 | return kr.Add(defaultRegistryUserName, defaultRegistryRepoName, registriesDir) 76 | } 77 | return nil 78 | } 79 | 80 | // Add clones given kbrew registry in the config dir 81 | func (kr *KbrewRegistry) Add(user, repo, path string) error { 82 | fmt.Printf("Adding %s/%s registry to %s\n", user, repo, path) 83 | r, err := git.PlainClone(filepath.Join(path, user, repo), false, &git.CloneOptions{ 84 | URL: fmt.Sprintf(ghRegistryURLFormat, user, repo), 85 | RecurseSubmodules: git.DefaultSubmoduleRecursionDepth, 86 | }) 87 | if err != nil { 88 | return err 89 | } 90 | head, err := r.Head() 91 | if err != nil { 92 | return err 93 | } 94 | fmt.Printf("Registry %s/%s head at %s\n", user, repo, head) 95 | return err 96 | } 97 | 98 | // FetchRecipe iterates over all the kbrew recipes and returns path of the app recipe file 99 | func (kr *KbrewRegistry) FetchRecipe(appName string) (string, error) { 100 | // Iterate over all the registries 101 | info, err := kr.Search(appName, true) 102 | if err != nil { 103 | return "", err 104 | } 105 | if len(info) == 0 { 106 | return "", fmt.Errorf("no recipe found for %s", appName) 107 | } 108 | return info[0].Path, nil 109 | } 110 | 111 | // Search returns app Info for give app 112 | func (kr *KbrewRegistry) Search(appName string, exactMatch bool) ([]Info, error) { 113 | result := []Info{} 114 | appList, err := kr.ListApps() 115 | if err != nil { 116 | return nil, err 117 | } 118 | for _, app := range appList { 119 | if exactMatch { 120 | if app.Name == appName { 121 | return []Info{app}, nil 122 | } 123 | continue 124 | } 125 | if strings.HasPrefix(app.Name, appName) { 126 | result = append(result, app) 127 | } 128 | } 129 | return result, nil 130 | } 131 | 132 | // ListApps return Info list of all the apps 133 | func (kr *KbrewRegistry) ListApps() ([]Info, error) { 134 | infoList := []Info{} 135 | err := filepath.WalkDir(kr.path, func(path string, d fs.DirEntry, err error) error { 136 | if err != nil { 137 | return err 138 | } 139 | if d.IsDir() && d.Name() == ".git" { 140 | return filepath.SkipDir 141 | 142 | } 143 | if d.IsDir() { 144 | return nil 145 | } 146 | for _, match := range recipeFilenamePattern.FindAllStringSubmatch(path, -1) { 147 | if len(match) != 2 { 148 | continue 149 | } 150 | infoList = append(infoList, Info{Name: match[1], Path: path}) 151 | } 152 | return nil 153 | }) 154 | return infoList, err 155 | } 156 | 157 | // List returns list of registries 158 | func (kr *KbrewRegistry) List() ([]string, error) { 159 | registries := []string{} 160 | 161 | // Registries are placed at - CONFIG_DIR/GITHUB_USER/GITHUB_REPO path 162 | // Interate over all the GITHUB_USERS dirs to find the list of all kbrew registries 163 | dirs, err := ioutil.ReadDir(kr.path) 164 | if err != nil { 165 | return nil, err 166 | } 167 | for _, user := range dirs { 168 | if !user.IsDir() { 169 | continue 170 | } 171 | subDirs, err := ioutil.ReadDir(filepath.Join(kr.path, user.Name())) 172 | if err != nil { 173 | return nil, err 174 | } 175 | for _, repo := range subDirs { 176 | if !repo.IsDir() { 177 | continue 178 | } 179 | registries = append(registries, fmt.Sprintf("%s/%s", user.Name(), repo.Name())) 180 | } 181 | } 182 | return registries, nil 183 | } 184 | 185 | // Update pull latest commits from registry repos 186 | func (kr *KbrewRegistry) Update() error { 187 | registries, err := kr.List() 188 | if err != nil { 189 | return err 190 | } 191 | for _, r := range registries { 192 | if err := fetchUpdates(kr.path, r); err != nil { 193 | return err 194 | } 195 | } 196 | return nil 197 | } 198 | 199 | // Info returns information about a recipe 200 | func (kr *KbrewRegistry) Info(appName string) (string, error) { 201 | c, err := kr.FetchRecipe(appName) 202 | if err != nil { 203 | return "", err 204 | } 205 | a, err := config.NewApp(appName, c) 206 | if err != nil { 207 | return "", err 208 | } 209 | bytes, err := yaml.Marshal(buildAppInfo(a.App)) 210 | if err != nil { 211 | return "", err 212 | } 213 | return string(bytes), nil 214 | } 215 | 216 | // Args returns the arguments declared for a recipe 217 | func (kr *KbrewRegistry) Args(appName string) (map[string]interface{}, error) { 218 | c, err := kr.FetchRecipe(appName) 219 | if err != nil { 220 | return nil, err 221 | } 222 | a, err := config.NewApp(appName, c) 223 | if err != nil { 224 | return nil, err 225 | } 226 | 227 | return a.App.Args, nil 228 | } 229 | 230 | func fetchUpdates(rootDir, repo string) error { 231 | gitRegistry, err := git.PlainOpen(filepath.Join(rootDir, repo)) 232 | if err != nil { 233 | if err == git.ErrRepositoryNotExists { 234 | return nil 235 | } 236 | return errors.Wrapf(err, "failed to init git repo %s", repo) 237 | } 238 | fmt.Printf("Fetching updates for registry %s\n", repo) 239 | wt, err := gitRegistry.Worktree() 240 | if err != nil { 241 | return errors.Wrapf(err, "failed to fetch updates for %s repo", repo) 242 | } 243 | err = wt.Pull(&git.PullOptions{}) 244 | if err != nil && err != git.NoErrAlreadyUpToDate { 245 | return errors.Wrapf(err, "failed to fetch updates for %s repo", repo) 246 | } 247 | head, err := gitRegistry.Head() 248 | if err != nil { 249 | return errors.Wrapf(err, "failed to find head of %s repo", repo) 250 | } 251 | fmt.Printf("Registry %s head is set to %s\n", repo, head) 252 | return nil 253 | } 254 | 255 | func buildAppInfo(a config.App) config.App { 256 | app := config.App{ 257 | Version: a.Version, 258 | Args: a.Args, 259 | Repository: config.Repository{ 260 | Name: a.Repository.Name, 261 | Type: a.Repository.Type, 262 | URL: a.Repository.URL, 263 | }, 264 | } 265 | preinstalls := []config.PreInstall{} 266 | for _, p := range a.PreInstall { 267 | if len(p.Apps) != 0 { 268 | preinstalls = append(preinstalls, config.PreInstall{ 269 | Apps: p.Apps, 270 | }) 271 | } 272 | } 273 | app.PreInstall = preinstalls 274 | postinstalls := []config.PostInstall{} 275 | for _, p := range a.PostInstall { 276 | if len(p.Apps) != 0 { 277 | postinstalls = append(postinstalls, config.PostInstall{ 278 | Apps: p.Apps, 279 | }) 280 | } 281 | } 282 | app.PostInstall = postinstalls 283 | return app 284 | } 285 | -------------------------------------------------------------------------------- /pkg/update/updater.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 The kbrew Authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package update 16 | 17 | import ( 18 | "context" 19 | "fmt" 20 | "os" 21 | "os/exec" 22 | "path/filepath" 23 | 24 | "github.com/kbrew-dev/kbrew/pkg/util" 25 | "github.com/kbrew-dev/kbrew/pkg/version" 26 | 27 | "github.com/pkg/errors" 28 | ) 29 | 30 | const ( 31 | upgradeCmd = "curl -sfL https://raw.githubusercontent.com/kbrew-dev/kbrew/main/install.sh | sh" 32 | ) 33 | 34 | func getBinDir() (string, error) { 35 | path, err := os.Executable() 36 | if err != nil { 37 | return "", err 38 | } 39 | return filepath.Dir(path), nil 40 | } 41 | 42 | // IsAvailable checks if a new version of GitHub release available 43 | func IsAvailable(ctx context.Context) (string, error) { 44 | release, err := util.GetLatestVersion(ctx) 45 | if err != nil { 46 | return "", errors.Wrap(err, "failed to check for kbrew updates") 47 | } 48 | if version.Version != *release.TagName { 49 | return *release.TagName, nil 50 | } 51 | return "", nil 52 | } 53 | 54 | // CheckRelease checks for the latest release 55 | func CheckRelease(ctx context.Context) error { 56 | release, err := IsAvailable(ctx) 57 | if err != nil { 58 | return errors.Wrap(err, "failed to check for kbrew updates") 59 | } 60 | if release == "" { 61 | return nil 62 | } 63 | fmt.Printf("kbrew %s is available, upgrading...\n", release) 64 | return upgradeKbrew(ctx) 65 | } 66 | 67 | func upgradeKbrew(ctx context.Context) error { 68 | dir, err := getBinDir() 69 | if err != nil { 70 | return errors.Wrap(err, "failed to get executable dir") 71 | } 72 | os.Setenv("BINDIR", dir) 73 | defer os.Unsetenv("BINDIR") 74 | return execCommand(ctx, upgradeCmd) 75 | } 76 | 77 | func execCommand(ctx context.Context, cmd string) error { 78 | c := exec.CommandContext(ctx, "sh", "-c", cmd) 79 | c.Stdout = os.Stdout 80 | c.Stderr = os.Stderr 81 | return c.Run() 82 | } 83 | -------------------------------------------------------------------------------- /pkg/util/util.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 The kbrew Authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package util 16 | 17 | import ( 18 | "context" 19 | 20 | "github.com/google/go-github/github" 21 | "github.com/pkg/errors" 22 | ) 23 | 24 | const ( 25 | releaseRepoOwner = "kbrew-dev" 26 | releaseRepoName = "kbrew" 27 | ) 28 | 29 | // GetLatestVersion returns latest published release version on GitHub 30 | func GetLatestVersion(ctx context.Context) (*github.RepositoryRelease, error) { 31 | client := github.NewClient(nil) 32 | release, _, err := client.Repositories.GetLatestRelease(ctx, releaseRepoOwner, releaseRepoName) 33 | if err != nil { 34 | return nil, errors.Wrap(err, "failed to check for kbrew updates") 35 | } 36 | if release == nil || release.TagName == nil { 37 | return nil, errors.Errorf("") 38 | } 39 | return release, nil 40 | } 41 | -------------------------------------------------------------------------------- /pkg/version/version.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 The kbrew Authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package version 16 | 17 | import "fmt" 18 | 19 | // Version The below variables are overridden using the build process 20 | // name of the release 21 | var Version = "dev" 22 | 23 | // GitCommitID git commit id of the release 24 | var GitCommitID = "none" 25 | 26 | // BuildDate date for the release 27 | var BuildDate = "unknown" 28 | 29 | const versionLongFmt = `{"Version": "%s", "GitCommit": "%s", "BuildDate": "%s"}` 30 | 31 | // Long long version of the release 32 | func Long() string { 33 | return fmt.Sprintf(versionLongFmt, Version, GitCommitID, BuildDate) 34 | } 35 | 36 | // Short short version of the release 37 | func Short() string { 38 | return Version 39 | } 40 | -------------------------------------------------------------------------------- /pkg/yaml/eval.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 The kbrew Authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package yaml 16 | 17 | import ( 18 | "bytes" 19 | "strings" 20 | 21 | "github.com/mikefarah/yq/v4/pkg/yqlib" 22 | "github.com/pkg/errors" 23 | logging "gopkg.in/op/go-logging.v1" 24 | ) 25 | 26 | // Evaluator parses yaml documents and patches them by applying given expressions 27 | type Evaluator interface { 28 | Eval(manifest string, expresssion string) (string, error) 29 | } 30 | 31 | type evaluator struct { 32 | s yqlib.StreamEvaluator 33 | } 34 | 35 | // NewEvaluator returns a new wrapped streamevaluator 36 | func NewEvaluator() Evaluator { 37 | // TODO(@sahil-lakhwani): check if there's a better way of avoiding yq debug logs 38 | logging.SetLevel(logging.CRITICAL, "yq-lib") 39 | return &evaluator{s: yqlib.NewStreamEvaluator()} 40 | } 41 | 42 | func (e *evaluator) Eval(manifest string, expresssion string) (string, error) { 43 | 44 | node, err := yqlib.NewExpressionParser().ParseExpression(expresssion) 45 | if err != nil { 46 | return "", errors.Wrap(err, "Error evaluating expression") 47 | } 48 | 49 | reader := strings.NewReader(manifest) 50 | 51 | var buf bytes.Buffer 52 | printer := yqlib.NewPrinter(&buf, false, true, false, 2, true) 53 | 54 | err = e.s.Evaluate("", reader, node, printer) 55 | if err != nil { 56 | return "", errors.Wrap(err, "Failed to evaluate") 57 | } 58 | 59 | return buf.String(), nil 60 | } 61 | -------------------------------------------------------------------------------- /pkg/yaml/eval_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 The kbrew Authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package yaml 16 | 17 | import ( 18 | "testing" 19 | 20 | "github.com/google/go-cmp/cmp" 21 | "github.com/pkg/errors" 22 | ) 23 | 24 | var ( 25 | sampleYaml = `apiVersion: networking.k8s.io/v1 26 | kind: NetworkPolicy 27 | metadata: 28 | name: allow-scraping 29 | ` 30 | badYaml = `apiVersion: networking.k8s.io/v1 31 | kind: NetworkPolicy 32 | metadata: 33 | name: allow-scraping 34 | ` 35 | apiVersionYaml = `apiVersion: networking.k8s.io/v1beta1 36 | kind: NetworkPolicy 37 | metadata: 38 | name: allow-scraping 39 | ` 40 | rootExpression = "." 41 | 42 | apiVersionExpression = `select(.kind == "NetworkPolicy" and .metadata.name == "allow-scraping").apiVersion |= "networking.k8s.io/v1beta1"` 43 | ) 44 | 45 | func TestEval(t *testing.T) { 46 | 47 | type arg struct { 48 | manifest string 49 | expression string 50 | } 51 | 52 | type want struct { 53 | result string 54 | err error 55 | } 56 | 57 | cases := map[string]struct { 58 | arg 59 | want 60 | }{ 61 | "CheckSimpleYaml": { 62 | arg: arg{ 63 | manifest: sampleYaml, 64 | expression: rootExpression, 65 | }, 66 | want: want{ 67 | result: sampleYaml, 68 | }, 69 | }, 70 | "CheckApiVersionChange": { 71 | arg: arg{ 72 | manifest: sampleYaml, 73 | expression: apiVersionExpression, 74 | }, 75 | want: want{ 76 | result: apiVersionYaml, 77 | }, 78 | }, 79 | "CheckBadYaml": { 80 | arg: arg{ 81 | manifest: badYaml, 82 | expression: rootExpression, 83 | }, 84 | want: want{ 85 | err: errors.Wrap(errors.New("yaml: line 4: found character that cannot start any token"), "Failed to evaluate"), 86 | }, 87 | }, 88 | } 89 | 90 | for name, tc := range cases { 91 | t.Run(name, func(t *testing.T) { 92 | e := NewEvaluator() 93 | o, err := e.Eval(tc.arg.manifest, tc.arg.expression) 94 | 95 | if diff := cmp.Diff(tc.want.result, o); diff != "" { 96 | t.Errorf("r: -want, +got:\n%s", diff) 97 | } 98 | 99 | if err != nil && err.Error() != tc.err.Error() { 100 | t.Errorf("Expected '%s', got %q", tc.err.Error(), err.Error()) 101 | } 102 | }) 103 | } 104 | } 105 | --------------------------------------------------------------------------------