├── .release ├── images ├── infracloud.png ├── kbrew-logo.png ├── rook-demo.gif ├── kbrew-remove.png └── kbrew-install.png ├── .gitignore ├── .mergify.yml ├── .golangci.yaml ├── .github └── workflows │ ├── codeql.yaml │ └── go.yml ├── pkg ├── log │ ├── log_test.go │ ├── status_test.go │ ├── logger_test.go │ ├── logger.go │ └── status.go ├── version │ └── version.go ├── util │ └── util.go ├── yaml │ ├── eval.go │ └── eval_test.go ├── update │ └── updater.go ├── engine │ ├── engine.go │ ├── engine_test.go │ └── funcs.go ├── kube │ └── kube.go ├── apps │ ├── helm │ │ └── helm.go │ ├── apps.go │ └── raw │ │ └── raw.go ├── config │ └── config.go ├── events │ └── events.go └── registry │ └── registry.go ├── .goreleaser.yml ├── Makefile ├── go.mod ├── docs └── analytics.md ├── cmd └── cli │ └── main.go ├── install.sh ├── LICENSE ├── CHANGELOG.md └── README.md /.release: -------------------------------------------------------------------------------- 1 | release=v0.1.0 2 | -------------------------------------------------------------------------------- /images/infracloud.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kbrew-dev/kbrew/HEAD/images/infracloud.png -------------------------------------------------------------------------------- /images/kbrew-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kbrew-dev/kbrew/HEAD/images/kbrew-logo.png -------------------------------------------------------------------------------- /images/rook-demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kbrew-dev/kbrew/HEAD/images/rook-demo.gif -------------------------------------------------------------------------------- /images/kbrew-remove.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kbrew-dev/kbrew/HEAD/images/kbrew-remove.png -------------------------------------------------------------------------------- /images/kbrew-install.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kbrew-dev/kbrew/HEAD/images/kbrew-install.png -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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/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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /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/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/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/engine/engine.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 | "bytes" 19 | "fmt" 20 | "strings" 21 | "text/template" 22 | 23 | "github.com/pkg/errors" 24 | "helm.sh/helm/v3/pkg/engine" 25 | "k8s.io/client-go/rest" 26 | ) 27 | 28 | const renderErr = "Error rendering value" 29 | 30 | // Engine provides functionalities to evaluate and render templates. 31 | type Engine struct { 32 | config *rest.Config 33 | fmap template.FuncMap 34 | template *template.Template 35 | } 36 | 37 | // NewEngine returns an initialized Engine 38 | func NewEngine(config *rest.Config) *Engine { 39 | return &Engine{ 40 | template: template.New("gotpl"), 41 | config: config, 42 | } 43 | } 44 | 45 | // Render resolves values of a string template. 46 | func (e *Engine) Render(arg string) (string, error) { 47 | 48 | if len(e.fmap) == 0 { 49 | e.initFuncMap() 50 | } 51 | 52 | _, err := e.template.Parse(arg) 53 | if err != nil { 54 | return "", errors.Wrapf(err, renderErr) 55 | } 56 | 57 | var tpl bytes.Buffer 58 | err = e.template.Execute(&tpl, "") 59 | if err != nil { 60 | return "", errors.Wrapf(err, renderErr) 61 | } 62 | 63 | return tpl.String(), nil 64 | } 65 | 66 | func (e *Engine) initFuncMap() { 67 | 68 | includedNames := make(map[string]int) 69 | 70 | e.fmap = funcMap() 71 | 72 | e.fmap["include"] = func(name string, data interface{}) (string, error) { 73 | var buf strings.Builder 74 | if v, ok := includedNames[name]; ok { 75 | if v > 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/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/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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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/apps/helm/helm.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 helm 16 | 17 | import ( 18 | "context" 19 | "fmt" 20 | "os/exec" 21 | "strings" 22 | 23 | "github.com/pkg/errors" 24 | corev1 "k8s.io/api/core/v1" 25 | 26 | "github.com/kbrew-dev/kbrew/pkg/apps/raw" 27 | "github.com/kbrew-dev/kbrew/pkg/config" 28 | "github.com/kbrew-dev/kbrew/pkg/log" 29 | ) 30 | 31 | type method string 32 | 33 | const ( 34 | installMethod method = "install" 35 | statusMethod method = "status" 36 | uninstallMethod method = "delete" 37 | // getManifestMethod method = "get manifest" // unused 38 | ) 39 | 40 | // App holds helm app details 41 | type App struct { 42 | app config.App 43 | log *log.Logger 44 | } 45 | 46 | // New returns Helm App 47 | func New(c config.App, log *log.Logger) *App { 48 | return &App{ 49 | app: c, 50 | log: log, 51 | } 52 | } 53 | 54 | // Install installs the application specified by name, version and namespace. 55 | func (ha *App) Install(ctx context.Context, name, namespace, version string, options map[string]string) error { 56 | //TODO: Resolve Deps 57 | // Validate and install chart 58 | // TODO(@prasad): Use go sdks 59 | // Needs helm3 60 | if _, err := ha.addRepo(ctx); err != nil { 61 | return err 62 | } 63 | if err := ha.resolveArgs(); err != nil { 64 | return err 65 | } 66 | _, err := helmCommand(ctx, statusMethod, name, "", namespace, "", nil) 67 | if err == nil { 68 | // helm release already exists, return from here 69 | ha.log.Warnf("helm app %s/%s already exists in %s namespace. Skipping...\n", ha.app.Repository.Name, name, namespace) 70 | return nil 71 | } 72 | 73 | out, err := helmCommand(ctx, installMethod, name, version, namespace, fmt.Sprintf("%s/%s", ha.app.Repository.Name, name), ha.app.Args) 74 | ha.log.Debug(out) 75 | return err 76 | } 77 | 78 | // Uninstall uninstalls the application specified by name and namespace. 79 | func (ha *App) Uninstall(ctx context.Context, name, namespace string) error { 80 | //TODO: Resolve Deps 81 | // Validate and install chart 82 | // TODO(@prasad): Use go sdks 83 | out, err := helmCommand(ctx, uninstallMethod, name, "", namespace, "", nil) 84 | ha.log.Debug(out) 85 | return err 86 | } 87 | 88 | func (ha *App) resolveArgs() error { 89 | if len(ha.app.Args) != 0 { 90 | for arg, value := range ha.app.Args { 91 | if value == nil { 92 | ha.app.Args[arg] = "" 93 | } 94 | } 95 | } 96 | return nil 97 | } 98 | 99 | func (ha *App) addRepo(ctx context.Context) (string, error) { 100 | // Needs helm 3.2+ 101 | c := exec.CommandContext(ctx, "helm", "repo", "add", ha.app.Repository.Name, ha.app.Repository.URL) 102 | if out, err := c.CombinedOutput(); err != nil { 103 | return string(out), err 104 | } 105 | return ha.updateRepo(ctx) 106 | } 107 | 108 | func (ha *App) updateRepo(ctx context.Context) (string, error) { 109 | // Needs helm 3.2+ 110 | c := exec.CommandContext(ctx, "helm", "repo", "update") 111 | out, err := c.CombinedOutput() 112 | return string(out), err 113 | } 114 | 115 | func (ha *App) getManifests(ctx context.Context, namespace string) (string, error) { 116 | c := exec.CommandContext(ctx, "helm", "get", "manifest", ha.app.Name, "--namespace", namespace) 117 | out, err := c.CombinedOutput() 118 | return string(out), err 119 | } 120 | 121 | // Search searches the name passed in helm repo 122 | func (ha *App) Search(ctx context.Context, name string) (string, error) { 123 | // Needs helm 3.2+ 124 | if out, err := ha.addRepo(ctx); err != nil { 125 | return out, err 126 | } 127 | c := exec.CommandContext(ctx, "helm", "search", "repo", fmt.Sprintf("%s/%s", ha.app.Repository.Name, name)) 128 | out, err := c.CombinedOutput() 129 | if err != nil { 130 | return string(out), err 131 | } 132 | if strings.Contains(string(out), "No results found") { 133 | return string(out), errors.New("No results found") 134 | } 135 | return string(out), err 136 | } 137 | 138 | // Workloads returns K8s workload object reference list for the helm app 139 | func (ha *App) Workloads(ctx context.Context, namespace string) ([]corev1.ObjectReference, error) { 140 | manifest, err := ha.getManifests(ctx, namespace) 141 | if err != nil { 142 | return nil, errors.Wrap(err, "Failed to get helm chart manifests") 143 | } 144 | return raw.ParseManifestYAML(manifest, namespace) 145 | } 146 | 147 | func helmCommand(ctx context.Context, m method, name, version, namespace, chart string, chartArgs map[string]interface{}) (string, error) { 148 | // Needs helm 3.2+ 149 | c := exec.CommandContext(ctx, "helm", string(m), name, "--namespace", namespace) 150 | if chart != "" { 151 | c.Args = append(c.Args, chart) 152 | } 153 | if version != "" { 154 | c.Args = append(c.Args, "--version", version) 155 | } 156 | if m == installMethod { 157 | // Add extra time to wait arg so that context will be timeout out before helm command failure 158 | // This is for catching timeout through context instead of parsing helm command output 159 | // This might change once we switch to SDKs 160 | c.Args = append(c.Args, "--wait", "--timeout", "5h0m", "--create-namespace") 161 | } 162 | 163 | if len(chartArgs) != 0 { 164 | c.Args = append(c.Args, appendChartArgs(chartArgs)...) 165 | } 166 | 167 | out, err := c.CombinedOutput() 168 | return string(out), err 169 | } 170 | 171 | func appendChartArgs(args map[string]interface{}) []string { 172 | var s []string 173 | for k, v := range args { 174 | s = append(s, "--set", k+"="+fmt.Sprintf("%s", v)) 175 | } 176 | return s 177 | } 178 | -------------------------------------------------------------------------------- /pkg/config/config.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 config 16 | 17 | import ( 18 | "fmt" 19 | "io/ioutil" 20 | "os" 21 | "path/filepath" 22 | 23 | "github.com/kbrew-dev/kbrew/pkg/engine" 24 | homedir "github.com/mitchellh/go-homedir" 25 | "github.com/pkg/errors" 26 | uuid "github.com/satori/go.uuid" 27 | "github.com/spf13/cobra" 28 | "github.com/spf13/viper" 29 | "gopkg.in/yaml.v2" 30 | "k8s.io/client-go/tools/clientcmd" 31 | ) 32 | 33 | // RepoType describes the type of kbrew app repository 34 | type RepoType string 35 | 36 | // ConfigDir represents dir path of kbrew config 37 | var ConfigDir string 38 | 39 | const ( 40 | // Raw repo type means the apps in the repo are raw apps 41 | Raw RepoType = "raw" 42 | // Helm repo means the apps in the repo are helm apps 43 | Helm RepoType = "helm" 44 | // RegistriesDirName represents the dir name within ConfigDir holding all the kbrew registries 45 | RegistriesDirName = "registries" 46 | 47 | // Analytics setting flags 48 | 49 | // AnalyticsUUID represents unique ID used as customer ID 50 | AnalyticsUUID = "analyticsUUID" 51 | // AnalyticsEnabled to toggle GA event collection 52 | AnalyticsEnabled = "analyticsEnabled" 53 | ) 54 | 55 | // KbrewConfig is a kbrew config stored at CONFIG_DIR/config.yaml 56 | type KbrewConfig struct { 57 | AnalyticsUUID string `yaml:"analyticsUUID"` 58 | AnalyticsEnabled bool `yaml:"analyticsEnabled"` 59 | } 60 | 61 | // AppConfig is the kbrew recipe configuration 62 | type AppConfig struct { 63 | APIVersion string `yaml:"apiVersion"` 64 | Kind string `yaml:"kind"` 65 | App App `yaml:"app"` 66 | } 67 | 68 | // App hold app details set in kbrew recipe 69 | type App struct { 70 | Args map[string]interface{} `yaml:"args,omitempty"` 71 | Repository Repository `yaml:"repository"` 72 | Name string `yaml:"name,omitempty"` 73 | Namespace string `yaml:"namespace,omitempty"` 74 | URL string `yaml:"url,omitempty"` 75 | SHA256 string `yaml:"sha256,omitempty"` 76 | Version string `yaml:"version,omitempty"` 77 | PreInstall []PreInstall `yaml:"pre_install,omitempty"` 78 | PostInstall []PostInstall `yaml:"post_install,omitempty"` 79 | PreCleanup AppCleanup `yaml:"pre_cleanup,omitempty"` 80 | PostCleanup AppCleanup `yaml:"post_cleanup,omitempty"` 81 | } 82 | 83 | // Repository is the repo for kbrew app 84 | type Repository struct { 85 | Name string `yaml:"name"` 86 | URL string `yaml:"url"` 87 | Type RepoType `yaml:"type"` 88 | } 89 | 90 | // PreInstall contains Apps and Steps that need to be installed/executed before installing the main app 91 | type PreInstall struct { 92 | Apps []string `yaml:"apps,omitempty"` 93 | Steps []string `yaml:"steps,omitempty"` 94 | } 95 | 96 | // PostInstall contains Apps and Steps that need to be installed/executed after installing the main app 97 | type PostInstall struct { 98 | Apps []string `yaml:"apps,omitempty"` 99 | Steps []string `yaml:"steps,omitempty"` 100 | } 101 | 102 | // AppCleanup contains steps to be executed before uninstalling applications 103 | type AppCleanup struct { 104 | Steps []string `yaml:"steps,omitempty"` 105 | } 106 | 107 | // NewApp parses kbrew recipe configuration and returns AppConfig instance 108 | func NewApp(name, path string) (*AppConfig, error) { 109 | c := &AppConfig{} 110 | configFile, err := os.Open(path) 111 | defer func() { 112 | err := configFile.Close() 113 | if err != nil { 114 | fmt.Printf("Error closing file :%v", err) 115 | } 116 | }() 117 | 118 | if err != nil { 119 | return nil, err 120 | } 121 | 122 | b, err := ioutil.ReadAll(configFile) 123 | if err != nil { 124 | return nil, err 125 | } 126 | 127 | k8sconfig, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig( 128 | clientcmd.NewDefaultClientConfigLoadingRules(), 129 | &clientcmd.ConfigOverrides{}, 130 | ).ClientConfig() 131 | if err != nil { 132 | return nil, errors.Wrapf(err, "Failed to load Kubernetes config") 133 | } 134 | 135 | e := engine.NewEngine(k8sconfig) 136 | v, err := e.Render(string(b)) 137 | if err != nil { 138 | return nil, err 139 | } 140 | 141 | if len(b) != 0 { 142 | err = yaml.Unmarshal([]byte(v), c) 143 | if err != nil { 144 | return nil, err 145 | } 146 | } 147 | c.App.Name = name 148 | return c, nil 149 | } 150 | 151 | // NewKbrew parses Kbrew config and returns KbrewConfig struct object 152 | func NewKbrew() (*KbrewConfig, error) { 153 | kc := &KbrewConfig{} 154 | err := viper.Unmarshal(kc) 155 | if err != nil { 156 | return nil, errors.Wrap(err, "Failed to read kbrew config") 157 | } 158 | return kc, nil 159 | } 160 | 161 | // InitConfig initializes ConfigDir. 162 | // If ConfigDir does not exists, create it 163 | func InitConfig() { 164 | if ConfigDir != "" { 165 | return 166 | } 167 | // Find home directory. 168 | home, err := homedir.Dir() 169 | cobra.CheckErr(err) 170 | 171 | // Generate default config file path 172 | ConfigDir = filepath.Join(home, ".kbrew") 173 | if _, err := os.Stat(ConfigDir); os.IsNotExist(err) { 174 | err := os.MkdirAll(ConfigDir, os.ModePerm) 175 | cobra.CheckErr(err) 176 | } 177 | 178 | // Create kbrew config yaml 179 | viper.SetConfigName("config") 180 | viper.SetConfigType("yaml") 181 | viper.AddConfigPath(ConfigDir) 182 | if err := viper.ReadInConfig(); err != nil { 183 | if _, ok := err.(viper.ConfigFileNotFoundError); ok { 184 | // Create config file 185 | viper.Set(AnalyticsUUID, uuid.NewV4().String()) 186 | viper.Set(AnalyticsEnabled, true) 187 | cobra.CheckErr(viper.SafeWriteConfig()) 188 | } else { 189 | cobra.CheckErr(err) 190 | } 191 | } 192 | } 193 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /pkg/apps/apps.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 apps 16 | 17 | import ( 18 | "context" 19 | "fmt" 20 | "os" 21 | "os/exec" 22 | "path/filepath" 23 | 24 | "github.com/spf13/viper" 25 | corev1 "k8s.io/api/core/v1" 26 | 27 | "github.com/kbrew-dev/kbrew/pkg/apps/helm" 28 | "github.com/kbrew-dev/kbrew/pkg/apps/raw" 29 | "github.com/kbrew-dev/kbrew/pkg/config" 30 | "github.com/kbrew-dev/kbrew/pkg/events" 31 | "github.com/kbrew-dev/kbrew/pkg/log" 32 | ) 33 | 34 | // Method defines operation performed on the apps 35 | type Method string 36 | 37 | const ( 38 | // Install method to install the app 39 | Install Method = "install" 40 | // Uninstall method to uninstall the app 41 | Uninstall Method = "uninstall" 42 | ) 43 | 44 | // App represents a K8s applications than can be managed with kbrew recipes 45 | type App interface { 46 | Install(ctx context.Context, name, namespace string, version string, opt map[string]string) error 47 | Uninstall(ctx context.Context, name, namespace string) error 48 | Search(ctx context.Context, name string) (string, error) 49 | Workloads(ctx context.Context, namespace string) ([]corev1.ObjectReference, error) 50 | } 51 | 52 | type AppRunner struct { 53 | operation Method 54 | log *log.Logger 55 | status *log.Status 56 | } 57 | 58 | func NewAppRunner(op Method, log *log.Logger, status *log.Status) *AppRunner { 59 | return &AppRunner{ 60 | operation: op, 61 | log: log, 62 | status: status, 63 | } 64 | } 65 | 66 | // Run fetches recipe from registry for the app and performs given operation 67 | func (r *AppRunner) Run(ctx context.Context, appName, namespace, appConfigPath string) error { 68 | c, err := config.NewApp(appName, appConfigPath) 69 | if err != nil { 70 | return err 71 | } 72 | var app App 73 | 74 | switch c.App.Repository.Type { 75 | case config.Helm: 76 | app = helm.New(c.App, r.log) 77 | case config.Raw: 78 | app, err = raw.New(c.App, r.log) 79 | if err != nil { 80 | return err 81 | } 82 | default: 83 | return fmt.Errorf("unsupported app type %s", c.App.Repository.Type) 84 | } 85 | 86 | // Check if entry exists in config 87 | if c.App.Name != appName { 88 | // Check if app exists in repo 89 | if _, err := app.Search(ctx, appName); err != nil { 90 | return err 91 | } 92 | } 93 | 94 | // Override if default namespace is set 95 | if c.App.Namespace != "" { 96 | namespace = c.App.Namespace 97 | } 98 | if c.App.Namespace == "-" { 99 | namespace = "" 100 | } 101 | 102 | switch r.operation { 103 | case Install: 104 | return r.runInstall(ctx, app, c, appName, namespace, appConfigPath) 105 | case Uninstall: 106 | return r.runUninstall(ctx, app, c, appName, namespace, appConfigPath) 107 | default: 108 | err = fmt.Errorf("unsupported method %s", r.operation) 109 | } 110 | return err 111 | } 112 | 113 | func (r *AppRunner) runInstall(ctx context.Context, app App, c *config.AppConfig, appName, namespace, appConfigPath string) error { 114 | // Event report 115 | event := events.NewKbrewEvent(c) 116 | 117 | // Run preinstall 118 | r.status.Start(fmt.Sprintf("Setting up pre-install dependencies for %s", appName)) 119 | for _, phase := range c.App.PreInstall { 120 | for _, a := range phase.Apps { 121 | if err := r.Run(ctx, a, namespace, filepath.Join(filepath.Dir(appConfigPath), a+".yaml")); err != nil { 122 | return r.handleInstallError(ctx, err, event, app, appName, namespace) 123 | } 124 | } 125 | for _, a := range phase.Steps { 126 | out, err := r.execCommand(ctx, a) 127 | if err != nil { 128 | return r.handleInstallError(ctx, err, event, app, appName, namespace) 129 | } 130 | r.log.Debug(out) 131 | } 132 | } 133 | r.status.Stop() 134 | 135 | // Run install 136 | r.status.Start(fmt.Sprintf("Installing app %s in %s namespace", appName, namespace)) 137 | if err := app.Install(ctx, appName, namespace, c.App.Version, nil); err != nil { 138 | return r.handleInstallError(ctx, err, event, app, appName, namespace) 139 | } 140 | r.status.Success() 141 | 142 | // Run postinstall 143 | r.status.Start(fmt.Sprintf("Setting up post-install dependencies for %s", appName)) 144 | for _, phase := range c.App.PostInstall { 145 | for _, a := range phase.Apps { 146 | if err := r.Run(ctx, a, namespace, filepath.Join(filepath.Dir(appConfigPath), a+".yaml")); err != nil { 147 | return r.handleInstallError(ctx, err, event, app, appName, namespace) 148 | } 149 | } 150 | for _, a := range phase.Steps { 151 | out, err := r.execCommand(ctx, a) 152 | if err != nil { 153 | return r.handleInstallError(ctx, err, event, app, appName, namespace) 154 | } 155 | r.log.Debug(out) 156 | } 157 | } 158 | r.status.Stop() 159 | if viper.GetBool(config.AnalyticsEnabled) { 160 | if err1 := event.Report(context.TODO(), events.ECInstallSuccess, nil, nil); err1 != nil { 161 | r.log.Debugf("Failed to report event. %s", err1.Error()) 162 | } 163 | } 164 | return nil 165 | } 166 | 167 | func (r *AppRunner) runUninstall(ctx context.Context, app App, c *config.AppConfig, appName, namespace, appConfigPath string) error { 168 | // Event report 169 | event := events.NewKbrewEvent(c) 170 | 171 | r.status.Start(fmt.Sprintf("Executing up pre-cleanup steps for %s", appName)) 172 | // Execute precleanup steps 173 | for _, a := range c.App.PreCleanup.Steps { 174 | out, err := r.execCommand(ctx, a) 175 | if err != nil { 176 | return r.handleUninstallError(ctx, err, event, appName, namespace) 177 | } 178 | r.log.Debug(out) 179 | } 180 | r.status.Stop() 181 | 182 | // Delete postinstall apps 183 | for _, phase := range c.App.PostInstall { 184 | for _, a := range phase.Apps { 185 | if err := r.Run(ctx, a, namespace, filepath.Join(filepath.Dir(appConfigPath), a+".yaml")); err != nil { 186 | return r.handleUninstallError(ctx, err, event, appName, namespace) 187 | } 188 | } 189 | } 190 | 191 | // Run uninstall 192 | r.status.Start(fmt.Sprintf("Removing app %s from %s namespace", appName, namespace)) 193 | if err := app.Uninstall(ctx, appName, namespace); err != nil { 194 | return r.handleUninstallError(ctx, err, event, appName, namespace) 195 | } 196 | r.status.Success() 197 | 198 | // Delete preinstall apps 199 | for _, phase := range c.App.PreInstall { 200 | for _, a := range phase.Apps { 201 | if err := r.Run(ctx, a, namespace, filepath.Join(filepath.Dir(appConfigPath), a+".yaml")); err != nil { 202 | return r.handleUninstallError(ctx, err, event, appName, namespace) 203 | } 204 | } 205 | } 206 | 207 | // Execute postcleanup steps 208 | r.status.Start(fmt.Sprintf("Executing up post-cleanup steps for %s", appName)) 209 | for _, a := range c.App.PostCleanup.Steps { 210 | out, err := r.execCommand(ctx, a) 211 | if err != nil { 212 | return r.handleUninstallError(ctx, err, event, appName, namespace) 213 | } 214 | r.log.Debug(out) 215 | } 216 | r.status.Stop() 217 | 218 | if viper.GetBool(config.AnalyticsEnabled) { 219 | if err1 := event.Report(context.TODO(), events.ECUninstallSuccess, nil, nil); err1 != nil { 220 | r.log.Debugf("Failed to report event. %s", err1.Error()) 221 | } 222 | } 223 | return nil 224 | } 225 | 226 | func (r *AppRunner) handleInstallError(ctx context.Context, err error, event *events.KbrewEvent, app App, appName, namespace string) error { 227 | if err == nil { 228 | return nil 229 | } 230 | defer r.status.Error() 231 | 232 | eventType := events.ECInstallFail 233 | if ctx.Err() != nil && ctx.Err() == context.DeadlineExceeded { 234 | r.log.Errorf("Timed out while installing %s app in %s namespace\n", appName, namespace) 235 | eventType = events.ECInstallTimeout 236 | } 237 | 238 | if !viper.GetBool(config.AnalyticsEnabled) { 239 | return err 240 | } 241 | 242 | wkl, err1 := app.Workloads(context.TODO(), namespace) 243 | if err1 != nil { 244 | r.log.Debugf("Failed to report event. %s", err.Error()) 245 | } 246 | if err1 := event.Report(context.TODO(), eventType, err, nil); err1 != nil { 247 | r.log.Debugf("Failed to report event. %s", err1.Error()) 248 | } 249 | if err1 := event.ReportK8sEvents(context.TODO(), err, wkl); err1 != nil { 250 | r.log.Debugf("Failed to report event. %s", err1.Error()) 251 | } 252 | return err 253 | } 254 | 255 | func (r *AppRunner) handleUninstallError(ctx context.Context, err error, event *events.KbrewEvent, appName, namespace string) error { 256 | if err == nil { 257 | return nil 258 | } 259 | defer r.status.Error() 260 | r.log.Warnf("Error encountered while uninstalling app - %s.\nYou need to cleanup few resources manually. App: %s, Namespace: %s\n", err, appName, namespace) 261 | if !viper.GetBool(config.AnalyticsEnabled) { 262 | return err 263 | } 264 | 265 | if ctx.Err() != nil && ctx.Err() == context.DeadlineExceeded { 266 | if err1 := event.Report(context.TODO(), events.ECUninstallTimeout, err, nil); err1 != nil { 267 | r.log.Debugf("Failed to report event. %s", err1.Error()) 268 | } 269 | return err 270 | } 271 | if err1 := event.Report(context.TODO(), events.ECUninstallFail, err, nil); err1 != nil { 272 | r.log.Debugf("Failed to report event. %s", err1.Error()) 273 | } 274 | return err 275 | } 276 | 277 | func (r *AppRunner) execCommand(ctx context.Context, cmd string) (string, error) { 278 | c := exec.CommandContext(ctx, "sh", "-c", cmd) 279 | c.Stderr = os.Stderr 280 | output, err := c.Output() 281 | return string(output), err 282 | } 283 | -------------------------------------------------------------------------------- /pkg/apps/raw/raw.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 raw 16 | 17 | import ( 18 | "bytes" 19 | "context" 20 | "fmt" 21 | "io/ioutil" 22 | "net/http" 23 | "os" 24 | "os/exec" 25 | "regexp" 26 | "strings" 27 | "text/tabwriter" 28 | 29 | osappsv1 "github.com/openshift/api/apps/v1" 30 | osversioned "github.com/openshift/client-go/apps/clientset/versioned" 31 | "github.com/pkg/errors" 32 | appsv1 "k8s.io/api/apps/v1" 33 | corev1 "k8s.io/api/core/v1" 34 | k8sErrors "k8s.io/apimachinery/pkg/api/errors" 35 | "k8s.io/client-go/kubernetes" 36 | "k8s.io/client-go/kubernetes/scheme" 37 | 38 | // Load all auth plugins 39 | _ "k8s.io/client-go/plugin/pkg/client/auth" 40 | "k8s.io/client-go/tools/clientcmd" 41 | 42 | "github.com/kbrew-dev/kbrew/pkg/config" 43 | "github.com/kbrew-dev/kbrew/pkg/kube" 44 | "github.com/kbrew-dev/kbrew/pkg/log" 45 | "github.com/kbrew-dev/kbrew/pkg/yaml" 46 | ) 47 | 48 | type method string 49 | 50 | const ( 51 | install method = "apply" 52 | uninstall method = "delete" 53 | // upgrade method = "apply" // unused 54 | 55 | evalExpression = `select(.kind == "%s" and .metadata.name == "%s").%s |= %v` 56 | ) 57 | 58 | var yamlDelimiter = regexp.MustCompile(`(?m)^---$`) 59 | 60 | // App represents K8s app defined with plain YAML manifests 61 | type App struct { 62 | app config.App 63 | log *log.Logger 64 | kubeCli kubernetes.Interface 65 | osAppCli osversioned.Interface 66 | } 67 | 68 | // New returns new instance of raw App 69 | func New(c config.App, log *log.Logger) (*App, error) { 70 | cfg, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig( 71 | clientcmd.NewDefaultClientConfigLoadingRules(), 72 | &clientcmd.ConfigOverrides{}, 73 | ).ClientConfig() 74 | if err != nil { 75 | return nil, errors.Wrapf(err, "Failed to load Kubernetes config") 76 | } 77 | 78 | cli, err := kubernetes.NewForConfig(cfg) 79 | if err != nil { 80 | return nil, errors.Wrapf(err, "Failed to create Kubernetes client") 81 | } 82 | osCli, err := osversioned.NewForConfig(cfg) 83 | if err != nil { 84 | return nil, errors.Wrapf(err, "Failed to create OpenShift client") 85 | } 86 | 87 | rApp := &App{ 88 | app: c, 89 | log: log, 90 | kubeCli: cli, 91 | osAppCli: osCli, 92 | } 93 | return rApp, nil 94 | } 95 | 96 | // Install installs the app specified by name, version and namespace. 97 | func (r *App) Install(ctx context.Context, name, namespace, version string, options map[string]string) error { 98 | manifest, err := getManifest(r.app.Repository.URL) 99 | if err != nil { 100 | return err 101 | } 102 | 103 | patchedManifest, err := patchManifest(manifest, r.app.Args) 104 | if err != nil { 105 | return err 106 | } 107 | 108 | if err := kube.CreateNamespace(ctx, r.kubeCli, namespace); err != nil && !k8sErrors.IsAlreadyExists(err) { 109 | return err 110 | } 111 | 112 | // TODO(@prasad): Use go sdks 113 | out, err := kubectlCommand(ctx, install, name, namespace, patchedManifest) 114 | if err != nil { 115 | r.log.Debug(out) 116 | return err 117 | } 118 | r.log.Debug(out) 119 | r.log.Debugf("Waiting for components to be ready for %s", name) 120 | return r.waitForReady(ctx, namespace) 121 | } 122 | 123 | // Uninstall uninstalls the app specified by name and namespace. 124 | func (r *App) Uninstall(ctx context.Context, name, namespace string) error { 125 | // TODO(@prasad): Use go sdks 126 | out, err := kubectlCommand(ctx, uninstall, name, namespace, r.app.Repository.URL) 127 | r.log.Debug(out) 128 | return err 129 | } 130 | 131 | // Search searches the app specified by name. 132 | func (r *App) Search(ctx context.Context, name string) (string, error) { 133 | return printList(r.app), nil 134 | } 135 | 136 | func kubectlCommand(ctx context.Context, m method, name, namespace, manifest string) (string, error) { 137 | var c *exec.Cmd 138 | switch m { 139 | case install: 140 | c = exec.CommandContext(ctx, "kubectl", string(m), "-f", "-") 141 | // Pass the manifest on STDIN 142 | c.Stdin = strings.NewReader(manifest) 143 | default: 144 | c = exec.CommandContext(ctx, "kubectl", string(m), "-f", manifest) 145 | } 146 | 147 | if namespace != "" { 148 | c.Args = append(c.Args, "--namespace", namespace) 149 | } 150 | c.Stderr = os.Stderr 151 | output, err := c.Output() 152 | return string(output), err 153 | } 154 | 155 | // Workloads returns K8s workload object reference list for the raw app 156 | func (r *App) Workloads(ctx context.Context, namespace string) ([]corev1.ObjectReference, error) { 157 | resp, err := http.Get(r.app.Repository.URL) 158 | if err != nil { 159 | return nil, errors.Wrap(err, "Failed to read resource manifest from URL") 160 | } 161 | defer resp.Body.Close() 162 | 163 | data, err := ioutil.ReadAll(resp.Body) 164 | if err != nil { 165 | return nil, errors.Wrap(err, "Failed to read resource manifest from URL") 166 | } 167 | return ParseManifestYAML(string(data), namespace) 168 | } 169 | 170 | func (r *App) waitForReady(ctx context.Context, namespace string) error { 171 | workloads, err := r.Workloads(ctx, namespace) 172 | if err != nil { 173 | return err 174 | } 175 | for _, wRef := range workloads { 176 | switch wRef.Kind { 177 | case "Pod": 178 | if err := kube.WaitForPodReady(ctx, r.kubeCli, wRef.Namespace, wRef.Name); err != nil { 179 | return errors.Wrap(err, fmt.Sprintf("Pod not in ready state. Namespace: %s, Name: %s", wRef.Namespace, wRef.Name)) 180 | } 181 | 182 | case "Deployment": 183 | if err := kube.WaitForDeploymentReady(ctx, r.kubeCli, wRef.Namespace, wRef.Name); err != nil { 184 | return errors.Wrap(err, fmt.Sprintf("Deployment not in ready state. Namespace: %s, Name: %s", wRef.Namespace, wRef.Name)) 185 | } 186 | 187 | case "StatefulSet": 188 | if err := kube.WaitForStatefulSetReady(ctx, r.kubeCli, wRef.Namespace, wRef.Name); err != nil { 189 | return errors.Wrap(err, fmt.Sprintf("StatefulSet not in ready state. Namespace: %s, Name: %s", wRef.Namespace, wRef.Name)) 190 | } 191 | 192 | case "DeploymentConfig": 193 | if err := kube.WaitForDeploymentConfigReady(ctx, r.osAppCli, r.kubeCli, wRef.Namespace, wRef.Name); err != nil { 194 | return errors.Wrap(err, fmt.Sprintf("DeploymentConfig not in ready state. Namespace: %s, Name: %s", wRef.Namespace, wRef.Name)) 195 | } 196 | } 197 | } 198 | return nil 199 | } 200 | 201 | // ParseManifestYAML splits yaml manifests with multiple K8s object specs and returns list of workload object references 202 | func ParseManifestYAML(manifest, namespace string) ([]corev1.ObjectReference, error) { 203 | decode := scheme.Codecs.UniversalDeserializer().Decode 204 | objRefs := []corev1.ObjectReference{} 205 | for _, spec := range yamlDelimiter.Split(manifest, -1) { 206 | if len(spec) == 0 { 207 | continue 208 | } 209 | obj, _, err := decode([]byte(spec), nil, nil) 210 | if err != nil { 211 | continue 212 | } 213 | 214 | // Set default namespace if empty 215 | if namespace == "" { 216 | namespace = "default" 217 | } 218 | 219 | switch w := obj.(type) { 220 | case *corev1.Pod: 221 | if w.GetNamespace() != "" { 222 | namespace = w.GetNamespace() 223 | } 224 | objRefs = append(objRefs, corev1.ObjectReference{Name: w.GetName(), Namespace: namespace, Kind: "Pod"}) 225 | 226 | case *appsv1.Deployment: 227 | if w.GetNamespace() != "" { 228 | namespace = w.GetNamespace() 229 | } 230 | objRefs = append(objRefs, corev1.ObjectReference{Name: w.GetName(), Namespace: namespace, Kind: "Deployment"}) 231 | 232 | case *appsv1.StatefulSet: 233 | if w.GetNamespace() != "" { 234 | namespace = w.GetNamespace() 235 | } 236 | objRefs = append(objRefs, corev1.ObjectReference{Name: w.GetName(), Namespace: namespace, Kind: "StatefulSet"}) 237 | 238 | case *osappsv1.DeploymentConfig: 239 | if w.GetNamespace() != "" { 240 | namespace = w.GetNamespace() 241 | } 242 | objRefs = append(objRefs, corev1.ObjectReference{Name: w.GetName(), Namespace: namespace, Kind: "DeploymentConfig"}) 243 | } 244 | 245 | } 246 | return objRefs, nil 247 | } 248 | 249 | func printList(app config.App) string { 250 | var b bytes.Buffer 251 | w := tabwriter.NewWriter(&b, 0, 0, 1, ' ', tabwriter.TabIndent) 252 | fmt.Fprintln(w, "NAME\tVERSION\tTYPE") 253 | fmt.Fprintf(w, "%s\t%s\t%s", app.Name, app.Version, app.Repository.Type) 254 | w.Flush() 255 | return b.String() 256 | } 257 | 258 | func patchManifest(manifest string, patches map[string]interface{}) (string, error) { 259 | e := yaml.NewEvaluator() 260 | patchedManifest := manifest 261 | var err error 262 | for _, expression := range createExpressions(patches) { 263 | patchedManifest, err = e.Eval(patchedManifest, expression) 264 | if err != nil { 265 | return "", err 266 | } 267 | } 268 | return patchedManifest, nil 269 | } 270 | 271 | func getManifest(url string) (string, error) { 272 | resp, err := http.Get(url) 273 | if err != nil { 274 | return "", errors.Wrap(err, "Error fetching from app URL") 275 | } 276 | 277 | defer resp.Body.Close() 278 | 279 | manifest, err := ioutil.ReadAll(resp.Body) 280 | if err != nil { 281 | return "", errors.Wrap(err, "Error fetching from app URL") 282 | } 283 | return string(manifest), nil 284 | } 285 | 286 | func createExpressions(patches map[string]interface{}) []string { 287 | var expressions []string 288 | 289 | for k, v := range patches { 290 | // Type assertion is necessary for yq, strings without quotes result in error 291 | switch v.(type) { 292 | case string: 293 | v = fmt.Sprintf("\"%s\"", v) 294 | default: 295 | } 296 | 297 | keys := strings.Split(k, ".") 298 | // keys[0] - kind 299 | // keys[1] - metadata.name 300 | // keys[2:] - path of the field 301 | e := fmt.Sprintf(evalExpression, keys[0], keys[1], strings.Join(keys[2:], "."), v) 302 | expressions = append(expressions, e) 303 | } 304 | return expressions 305 | } 306 | -------------------------------------------------------------------------------- /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 < 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 | --------------------------------------------------------------------------------