├── .envrc ├── .gitignore ├── Makefile ├── README.md ├── cmd └── kni │ └── main.go ├── go.mod ├── hack ├── build-binaries.sh ├── build.sh └── test.sh ├── pkg ├── cmd │ ├── cmd.go │ ├── config_changes.go │ ├── core │ │ ├── config.go │ │ ├── core.go │ │ └── deps.go │ ├── flags │ │ ├── flags_factory.go │ │ ├── kubeconfig_flags.go │ │ └── namespace_flags.go │ ├── inspect.go │ ├── kube_version.go │ ├── logs.go │ ├── ui │ │ ├── diff_view.go │ │ └── tree_view.go │ └── version.go ├── inspect │ ├── config │ │ ├── configs.go │ │ └── logger.go │ ├── ksvc │ │ ├── inspector.go │ │ └── ksvc.go │ ├── logs │ │ ├── dump.go │ │ └── logs.go │ └── version │ │ └── kube_version.go └── resources │ ├── conditions.go │ └── resource_search.go └── tests ├── buffer_reader.go ├── e2e.go ├── env.go ├── inspect_test.go ├── kni.go ├── kube_version_test.go ├── kubectl.go └── version_test.go /.envrc: -------------------------------------------------------------------------------- 1 | export GO111MODULE=on 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | go.sum 2 | kni* 3 | !cmd/kni 4 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | test-integration: 2 | ./hack/build.sh 3 | ./hack/test.sh 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Knative Inspect 2 | 3 | A light-weight debugging tool for Knative's system components which is heavily 4 | influenced by [github.com/k14s/kapp](https://github.com/k14s/kapp). It assumes 5 | Kubernetes as the backend for Knative. 6 | 7 | ``` 8 | Usage: 9 | kni [flags] 10 | kni [command] 11 | 12 | Available Commands: 13 | config-changes Changes to Knative ConfigMaps 14 | help Help about any command 15 | inspect Inspect Knative services 16 | kube-version Print Kubernetes version 17 | logs Knative Component Logs 18 | version Print version 19 | 20 | Flags: 21 | -h, --help help for kni 22 | ``` 23 | 24 | ## Inspect Services 25 | 26 | ``` 27 | ± |master ✓ | → ./kni inspect -s echo 28 | Resources in echo 29 | 30 | Namespace Name Kind Ready Reason 31 | default echo Service True 32 | default echo ├─ Configuration True 33 | default echo-7llk5 │ └─ Revision True 34 | default echo-7llk5-deployment │ ├─ Deployment - 35 | default echo-7llk5-deployment-7d5d85d567 │ │ └─ ReplicaSet - 36 | default echo-7llk5-cache │ ├─ Image - 37 | default echo-7llk5 │ └─ PodAutoscaler True 38 | default echo-7llk5-metrics │ ├─ Service - 39 | default echo-7llk5 │ ├─ Metric True 40 | default echo-7llk5 │ └─ ServerlessService Unknown NoHealthyBackends 41 | default echo-7llk5-private │ ├─ Service - 42 | default echo-7llk5 │ ├─ Service - 43 | default echo-7llk5 │ └─ Endpoints - 44 | default echo └─ Route True 45 | default echo ├─ Service - 46 | default echo └─ Ingress True 47 | default echo-mesh ├─ VirtualService - 48 | default echo └─ VirtualService - 49 | 50 | 19 resources 51 | ``` 52 | 53 | ## Inspect Changes in ConfigMaps 54 | ```diff 55 | ± |master ✓ | → ./kni config-changes 56 | Changes in Knative ConfigMaps 57 | 58 | * config-defaults 59 | - *.MaxRevisionTimeoutSeconds(1) 600 60 | + *.MaxRevisionTimeoutSeconds(1) 660 61 | 62 | * config-domain 63 | - *.Domains(0){example.com} 64 | + *.Domains(0){nk-eirini-new5.us-south.containers.appdomain.cloud} &{map[]} 65 | ``` 66 | 67 | ## Component Logs 68 | 69 | ``` 70 | ± |master ✓ | → ./kni logs -p activator --lines 100 --filter error 71 | 2019/08/07 14:07:02 activator-64cb466d55-bmb57 > activator | {"level":"error","ts":"2019-08-07T06:26:03.757Z","logger":"activator","caller":"activator/throttler.go:253","msg":"updating capacity failed","knative.dev/controller":"activator","knative.dev/key":"kni-test/testapp-k5qjs","error":"revision.serving.knative.dev \"testapp-k5qjs\" not found","stacktrace":"github.com/knative/serving/pkg/activator.(*Throttler).endpointsUpdated\n\t/home/prow/go/src/github.com/knative/serving/pkg/activator/throttler.go:253\ngithub.com/knative/serving/vendor/github.com/knative/pkg/controller.PassNew.func1\n\t/home/prow/go/src/github.com/knative/serving/vendor/github.com/knative/pkg/controller/controller.go:69\ngithub.com/knative/serving/vendor/k8s.io/client-go/tools/cache.ResourceEventHandlerFuncs.OnUpdate\n\t/home/prow/go/src/github.com/knative/serving/vendor/k8s.io/client-go/tools/cache/controller.go:202\ngithub.com/knative/serving/vendor/k8s.io/client-go/tools/cache.FilteringResourceEventHandler.OnUpdate\n\t/home/prow/go/src/github.com/knative/serving/vendor/k8s.io/client-go/tools/cache/controller.go:236\ngithub.com/knative/serving/vendor/k8s.io/client-go/tools/cache.(*processorListener).run.func1.1\n\t/home/prow/go/src/github.com/knative/serving/vendor/k8s.io/client-go/tools/cache/shared_informer.go:552\ngithub.com/knative/serving/vendor/k8s.io/apimachinery/pkg/util/wait.ExponentialBackoff\n\t/home/prow/go/src/github.com/knative/serving/vendor/k8s.io/apimachinery/pkg/util/wait/wait.go:203\ngithub.com/knative/serving/vendor/k8s.io/client-go/tools/cache.(*processorListener).run.func1\n\t/home/prow/go/src/github.com/knative/serving/vendor/k8s.io/client-go/tools/cache/shared_informer.go:548\ngithub.com/knative/serving/vendor/k8s.io/apimachinery/pkg/util/wait.JitterUntil.func1\n\t/home/prow/go/src/github.com/knative/serving/vendor/k8s.io/apimachinery/pkg/util/wait/wait.go:133\ngithub.com/knative/serving/vendor/k8s.io/apimachinery/pkg/util/wait.JitterUntil\n\t/home/prow/go/src/github.com/knative/serving/vendor/k8s.io/apimachinery/pkg/util/wait/wait.go:134\ngithub.com/knative/serving/vendor/k8s.io/apimachinery/pkg/util/wait.Until\n\t/home/prow/go/src/github.com/knative/serving/vendor/k8s.io/apimachinery/pkg/util/wait/wait.go:88\ngithub.com/knative/serving/vendor/k8s.io/client-go/tools/cache.(*processorListener).run\n\t/home/prow/go/src/github.com/knative/serving/vendor/k8s.io/client-go/tools/cache/shared_informer.go:546\ngithub.com/knative/serving/vendor/k8s.io/apimachinery/pkg/util/wait.(*Group).Start.func1\n\t/home/prow/go/src/github.com/knative/serving/vendor/k8s.io/apimachinery/pkg/util/wait/wait.go:71"} 72 | 2019/08/07 14:07:02 activator-64cb466d55-bmb57 > activator | {"level":"error","ts":"2019-08-07T06:26:41.988Z","logger":"activator","caller":"activator/throttler.go:253","msg":"updating capacity failed","knative.dev/controller":"activator","knative.dev/key":"kni-test/testapp-p8mc5","error":"revision.serving.knative.dev \"testapp-p8mc5\" not found","stacktrace":"github.com/knative/serving/pkg/activator.(*Throttler).endpointsUpdated\n\t/home/prow/go/src/github.com/knative/serving/pkg/activator/throttler.go:253\ngithub.com/knative/serving/vendor/github.com/knative/pkg/controller.PassNew.func1\n\t/home/prow/go/src/github.com/knative/serving/vendor/github.com/knative/pkg/controller/controller.go:69\ngithub.com/knative/serving/vendor/k8s.io/client-go/tools/cache.ResourceEventHandlerFuncs.OnUpdate\n\t/home/prow/go/src/github.com/knative/serving/vendor/k8s.io/client-go/tools/cache/controller.go:202\ngithub.com/knative/serving/vendor/k8s.io/client-go/tools/cache.FilteringResourceEventHandler.OnUpdate\n\t/home/prow/go/src/github.com/knative/serving/vendor/k8s.io/client-go/tools/cache/controller.go:236\ngithub.com/knative/serving/vendor/k8s.io/client-go/tools/cache.(*processorListener).run.func1.1\n\t/home/prow/go/src/github.com/knative/serving/vendor/k8s.io/client-go/tools/cache/shared_informer.go:552\ngithub.com/knative/serving/vendor/k8s.io/apimachinery/pkg/util/wait.ExponentialBackoff\n\t/home/prow/go/src/github.com/knative/serving/vendor/k8s.io/apimachinery/pkg/util/wait/wait.go:203\ngithub.com/knative/serving/vendor/k8s.io/client-go/tools/cache.(*processorListener).run.func1\n\t/home/prow/go/src/github.com/knative/serving/vendor/k8s.io/client-go/tools/cache/shared_informer.go:548\ngithub.com/knative/serving/vendor/k8s.io/apimachinery/pkg/util/wait.JitterUntil.func1\n\t/home/prow/go/src/github.com/knative/serving/vendor/k8s.io/apimachinery/pkg/util/wait/wait.go:133\ngithub.com/knative/serving/vendor/k8s.io/apimachinery/pkg/util/wait.JitterUntil\n\t/home/prow/go/src/github.com/knative/serving/vendor/k8s.io/apimachinery/pkg/util/wait/wait.go:134\ngithub.com/knative/serving/vendor/k8s.io/apimachinery/pkg/util/wait.Until\n\t/home/prow/go/src/github.com/knative/serving/vendor/k8s.io/apimachinery/pkg/util/wait/wait.go:88\ngithub.com/knative/serving/vendor/k8s.io/client-go/tools/cache.(*processorListener).run\n\t/home/prow/go/src/github.com/knative/serving/vendor/k8s.io/client-go/tools/cache/shared_informer.go:546\ngithub.com/knative/serving/vendor/k8s.io/apimachinery/pkg/util/wait.(*Group).Start.func1\n\t/home/prow/go/src/github.com/knative/serving/vendor/k8s.io/apimachinery/pkg/util/wait/wait.go:71"} 73 | 2019/08/07 14:07:02 activator-64cb466d55-bmb57 > activator | {"level":"error","ts":"2019-08-07T06:26:42.018Z","logger":"activator","caller":"activator/throttler.go:253","msg":"updating capacity failed","knative.dev/controller":"activator","knative.dev/key":"kni-test/testapp-p8mc5","error":"revision.serving.knative.dev \"testapp-p8mc5\" not found","stacktrace":"github.com/knative/serving/pkg/activator.(*Throttler).endpointsUpdated\n\t/home/prow/go/src/github.com/knative/serving/pkg/activator/throttler.go:253\ngithub.com/knative/serving/vendor/github.com/knative/pkg/controller.PassNew.func1\n\t/home/prow/go/src/github.com/knative/serving/vendor/github.com/knative/pkg/controller/controller.go:69\ngithub.com/knative/serving/vendor/k8s.io/client-go/tools/cache.ResourceEventHandlerFuncs.OnUpdate\n\t/home/prow/go/src/github.com/knative/serving/vendor/k8s.io/client-go/tools/cache/controller.go:202\ngithub.com/knative/serving/vendor/k8s.io/client-go/tools/cache.FilteringResourceEventHandler.OnUpdate\n\t/home/prow/go/src/github.com/knative/serving/vendor/k8s.io/client-go/tools/cache/controller.go:236\ngithub.com/knative/serving/vendor/k8s.io/client-go/tools/cache.(*processorListener).run.func1.1\n\t/home/prow/go/src/github.com/knative/serving/vendor/k8s.io/client-go/tools/cache/shared_informer.go:552\ngithub.com/knative/serving/vendor/k8s.io/apimachinery/pkg/util/wait.ExponentialBackoff\n\t/home/prow/go/src/github.com/knative/serving/vendor/k8s.io/apimachinery/pkg/util/wait/wait.go:203\ngithub.com/knative/serving/vendor/k8s.io/client-go/tools/cache.(*processorListener).run.func1\n\t/home/prow/go/src/github.com/knative/serving/vendor/k8s.io/client-go/tools/cache/shared_informer.go:548\ngithub.com/knative/serving/vendor/k8s.io/apimachinery/pkg/util/wait.JitterUntil.func1\n\t/home/prow/go/src/github.com/knative/serving/vendor/k8s.io/apimachinery/pkg/util/wait/wait.go:133\ngithub.com/knative/serving/vendor/k8s.io/apimachinery/pkg/util/wait.JitterUntil\n\t/home/prow/go/src/github.com/knative/serving/vendor/k8s.io/apimachinery/pkg/util/wait/wait.go:134\ngithub.com/knative/serving/vendor/k8s.io/apimachinery/pkg/util/wait.Until\n\t/home/prow/go/src/github.com/knative/serving/vendor/k8s.io/apimachinery/pkg/util/wait/wait.go:88\ngithub.com/knative/serving/vendor/k8s.io/client-go/tools/cache.(*processorListener).run\n\t/home/prow/go/src/github.com/knative/serving/vendor/k8s.io/client-go/tools/cache/shared_informer.go:546\ngithub.com/knative/serving/vendor/k8s.io/apimachinery/pkg/util/wait.(*Group).Start.func1\n\t/home/prow/go/src/github.com/knative/serving/vendor/k8s.io/apimachinery/pkg/util/wait/wait.go:71"} 74 | ``` 75 | -------------------------------------------------------------------------------- /cmd/kni/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math/rand" 6 | "os" 7 | "time" 8 | 9 | "github.com/cppforlife/go-cli-ui/ui" 10 | "github.com/nimakaviani/knative-inspect/pkg/cmd" 11 | 12 | _ "k8s.io/client-go/plugin/pkg/client/auth" 13 | ) 14 | 15 | func main() { 16 | rand.Seed(time.Now().UTC().UnixNano()) 17 | 18 | confUI := ui.NewConfUI(ui.NewNoopLogger()) 19 | defer confUI.Flush() 20 | 21 | command := cmd.NewDefaultCmd(confUI) 22 | 23 | err := command.Execute() 24 | if err != nil { 25 | fmt.Fprintf(os.Stderr, "Error: %v\n", err) 26 | os.Exit(1) 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/nimakaviani/knative-inspect 2 | 3 | go 1.12 4 | 5 | require ( 6 | bitbucket.org/ww/goautoneg v0.0.0-20120707110453-75cd24fc2f2c // indirect 7 | contrib.go.opencensus.io/exporter/prometheus v0.1.0 // indirect 8 | contrib.go.opencensus.io/exporter/stackdriver v0.12.4 // indirect 9 | github.com/Azure/go-autorest v10.14.0+incompatible // indirect 10 | github.com/cppforlife/cobrautil v0.0.0-20180924214100-a39a1714c920 11 | github.com/cppforlife/go-cli-ui v0.0.0-20181113222104-5a69326440e8 12 | github.com/dgrijalva/jwt-go v3.2.0+incompatible // indirect 13 | github.com/emicklei/go-restful v2.9.6+incompatible // indirect 14 | github.com/evanphx/json-patch v4.5.0+incompatible // indirect 15 | github.com/fatih/color v1.7.0 16 | github.com/ghodss/yaml v1.0.0 // indirect 17 | github.com/gogo/protobuf v1.2.1 // indirect 18 | github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6 // indirect 19 | github.com/google/go-containerregistry v0.0.0-20190729175742-ef12d49c8daf // indirect 20 | github.com/google/gofuzz v1.0.0 // indirect 21 | github.com/google/uuid v1.1.1 // indirect 22 | github.com/googleapis/gnostic v0.3.0 // indirect 23 | github.com/gophercloud/gophercloud v0.3.0 // indirect 24 | github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79 // indirect 25 | github.com/hashicorp/golang-lru v0.5.3 // indirect 26 | github.com/imdario/mergo v0.3.7 // indirect 27 | github.com/jetstack/cert-manager v0.6.1 // indirect 28 | github.com/k14s/kapp v0.10.0 // indirect 29 | github.com/kr/pty v1.1.8 // indirect 30 | github.com/kubernetes-incubator/custom-metrics-apiserver v0.0.0-20190116221620-b7016fc85e1c // indirect 31 | github.com/mattbaird/jsonpatch v0.0.0-20171005235357-81af80346b1a // indirect 32 | github.com/mattn/go-colorable v0.1.2 // indirect 33 | github.com/nimakaviani/kapp v0.0.0-20190807210239-9460cd5b6da8 34 | github.com/nimakaviani/ytt v0.1.0 35 | github.com/onsi/ginkgo v1.8.0 // indirect 36 | github.com/onsi/gomega v1.5.0 // indirect 37 | github.com/pborman/uuid v1.2.0 // indirect 38 | github.com/peterbourgon/diskv v2.0.1+incompatible // indirect 39 | github.com/prometheus/common v0.6.0 // indirect 40 | github.com/spf13/cobra v0.0.5 41 | github.com/spf13/pflag v1.0.3 42 | github.com/vito/go-interact v1.0.0 // indirect 43 | github.com/walmartlabs/object-diff v0.0.0-20190802100942-57273a9bdebb 44 | go.uber.org/atomic v1.4.0 // indirect 45 | go.uber.org/multierr v1.1.0 // indirect 46 | go.uber.org/zap v1.10.0 // indirect 47 | golang.org/x/net v0.0.0-20190724013045-ca1201d0de80 // indirect 48 | gopkg.in/inf.v0 v0.9.1 // indirect 49 | k8s.io/api v0.0.0-20190528110122-9ad12a4af326 50 | k8s.io/apimachinery v0.0.0-20190221084156-01f179d85dbc 51 | k8s.io/apiserver v0.0.0-20190528110248-2d60c3dee270 // indirect 52 | k8s.io/client-go v0.0.0-20190528110200-4f3abb12cae2 53 | k8s.io/kube-openapi v0.0.0-20190228160746-b3a7cee44a30 // indirect 54 | k8s.io/metrics v0.0.0-20190528110627-05eb8901940c // indirect 55 | knative.dev/pkg v0.0.0-20190802214846-8a10634b4fa4 56 | knative.dev/serving v0.7.1-0.20190804133254-e4f3cc382140 57 | ) 58 | -------------------------------------------------------------------------------- /hack/build-binaries.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -e -x -u 4 | 5 | BUILD_VALUES= ./hack/build.sh 6 | 7 | GOOS=darwin GOARCH=amd64 go build -o kni-darwin-amd64 ./cmd/... 8 | GOOS=linux GOARCH=amd64 go build -o kni-linux-amd64 ./cmd/... 9 | GOOS=windows GOARCH=amd64 go build -o kni-windows-amd64.exe ./cmd/... 10 | 11 | shasum -a 256 ./kni-*-amd64* 12 | -------------------------------------------------------------------------------- /hack/build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -e -x -u 4 | 5 | go fmt ./cmd/... ./pkg/... 6 | 7 | # build without website assets 8 | go build -o kni ./cmd/... 9 | ./kni version 10 | -------------------------------------------------------------------------------- /hack/test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -e -u 4 | 5 | export PATH=$PATH:$PWD 6 | 7 | set -x 8 | 9 | export KNI_E2E_NAMESPACE=${1:-kni-test} 10 | 11 | go fmt ./tests/... 12 | go test ./tests/ -timeout 60m -test.v $@ 13 | 14 | echo E2E SUCCESS 15 | -------------------------------------------------------------------------------- /pkg/cmd/cmd.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | 7 | "github.com/cppforlife/cobrautil" 8 | "github.com/cppforlife/go-cli-ui/ui" 9 | core "github.com/nimakaviani/knative-inspect/pkg/cmd/core" 10 | "github.com/spf13/cobra" 11 | ) 12 | 13 | func NewDefaultCmd(ui *ui.ConfUI) *cobra.Command { 14 | config := core.NewConfig() 15 | deps := core.NewDeps(config) 16 | 17 | cmd := &cobra.Command{ 18 | Use: "kni", 19 | Short: "Knative Inspect - little debugging tool for Knative services", 20 | 21 | RunE: cobrautil.ShowHelp, 22 | 23 | // Affects children as well 24 | SilenceErrors: true, 25 | SilenceUsage: true, 26 | 27 | // Disable docs header 28 | DisableAutoGenTag: true, 29 | 30 | // TODO bash completion 31 | } 32 | 33 | cmd.SetOutput(uiBlockWriter{ui}) // setting output for cmd.Help() 34 | 35 | // TODO bash completion 36 | cmd.AddCommand(NewInspectCmd(NewInspectCmdOptions(ui, config, deps))) 37 | cmd.AddCommand(NewConfigChangeCmd(NewConfigChangeOptions(ui, config, deps))) 38 | cmd.AddCommand(NewKnativeLogsCmd(NewKnativeLogOptions(ui, config, deps))) 39 | cmd.AddCommand(NewKubeVersionCmd(NewKubeVersionOptions(ui, config, deps))) 40 | cmd.AddCommand(NewVersionCmd(NewVersionOptions(ui))) 41 | 42 | cobrautil.VisitCommands(cmd, cobrautil.WrapRunEForCmd(cobrautil.ResolveFlagsForCmd)) 43 | 44 | return cmd 45 | } 46 | 47 | func ShowHelp(cmd *cobra.Command, args []string) error { 48 | cmd.Help() 49 | return fmt.Errorf("Invalid command - see available commands/subcommands above") 50 | } 51 | 52 | type uiBlockWriter struct { 53 | ui ui.UI 54 | } 55 | 56 | var _ io.Writer = uiBlockWriter{} 57 | 58 | func (w uiBlockWriter) Write(p []byte) (n int, err error) { 59 | w.ui.PrintBlock(p) 60 | return len(p), nil 61 | } 62 | -------------------------------------------------------------------------------- /pkg/cmd/config_changes.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "time" 5 | 6 | "github.com/cppforlife/go-cli-ui/ui" 7 | "github.com/nimakaviani/knative-inspect/pkg/cmd/core" 8 | "github.com/nimakaviani/knative-inspect/pkg/cmd/flags" 9 | kiui "github.com/nimakaviani/knative-inspect/pkg/cmd/ui" 10 | cfg "github.com/nimakaviani/knative-inspect/pkg/inspect/config" 11 | "github.com/spf13/cobra" 12 | ) 13 | 14 | const ( 15 | servingNamespace = "knative-serving" 16 | ) 17 | 18 | type ConfigChangeOptions struct { 19 | ui ui.UI 20 | 21 | Debug bool 22 | opts cfg.ConfigMapChangeOpts 23 | 24 | kubeconfigFlags flags.KubeconfigFlags 25 | namespaceFlags flags.NamespaceFlags 26 | } 27 | 28 | func NewConfigChangeOptions(ui *ui.ConfUI, config core.Config, deps core.Deps) *ConfigChangeOptions { 29 | return &ConfigChangeOptions{ 30 | ui: ui, 31 | opts: cfg.ConfigMapChangeOpts{Config: config, Deps: deps}, 32 | } 33 | } 34 | 35 | func NewConfigChangeCmd(o *ConfigChangeOptions) *cobra.Command { 36 | cmd := &cobra.Command{ 37 | Use: "config-changes", 38 | Aliases: []string{"cc"}, 39 | Short: "Changes to Knative ConfigMaps", 40 | RunE: func(_ *cobra.Command, _ []string) error { return o.Run() }, 41 | } 42 | 43 | cmd.Flags().StringSliceVarP( 44 | &o.opts.ConfigMapNames, 45 | "config", "c", 46 | []string{}, 47 | "Knative config maps to check (can be specified multiple times)", 48 | ) 49 | 50 | o.kubeconfigFlags.Set(cmd) 51 | o.namespaceFlags.Set(cmd, servingNamespace) 52 | return cmd 53 | } 54 | 55 | func (o *ConfigChangeOptions) Run() error { 56 | o.opts.Config.ConfigurePathResolver(o.kubeconfigFlags.Path.Value) 57 | o.opts.Config.ConfigureContextResolver(o.kubeconfigFlags.Context.Value) 58 | 59 | ui := core.NewPlainUI(o.Debug) 60 | t1 := time.Now() 61 | 62 | defer func() { 63 | ui.Debugf("total: %s\n", time.Since(t1)) 64 | }() 65 | 66 | return o.changes() 67 | } 68 | 69 | func (o *ConfigChangeOptions) changes() error { 70 | // set the name based on whatever comes through from the flag 71 | o.opts.Namespace = o.namespaceFlags.Name 72 | 73 | diffs, err := cfg.NewConfigInspector(o.opts).Run() 74 | if err != nil { 75 | return err 76 | } 77 | 78 | kiui.DiffView{Source: "Knative ConfigMaps", ChangeSet: diffs}.Print(o.ui) 79 | return nil 80 | } 81 | -------------------------------------------------------------------------------- /pkg/cmd/core/config.go: -------------------------------------------------------------------------------- 1 | package core 2 | 3 | import ( 4 | "fmt" 5 | 6 | "k8s.io/client-go/rest" 7 | "k8s.io/client-go/tools/clientcmd" 8 | ) 9 | 10 | type Config interface { 11 | ConfigurePathResolver(func() (string, error)) 12 | ConfigureContextResolver(func() (string, error)) 13 | RESTConfig() (*rest.Config, error) 14 | DefaultNamespace() (string, error) 15 | } 16 | 17 | type ConfigImpl struct { 18 | pathResolverFunc func() (string, error) 19 | contextResolverFunc func() (string, error) 20 | } 21 | 22 | var _ Config = &ConfigImpl{} 23 | 24 | func NewConfig() Config { 25 | return &ConfigImpl{} 26 | } 27 | 28 | func (f *ConfigImpl) ConfigurePathResolver(resolverFunc func() (string, error)) { 29 | f.pathResolverFunc = resolverFunc 30 | } 31 | 32 | func (f *ConfigImpl) ConfigureContextResolver(resolverFunc func() (string, error)) { 33 | f.contextResolverFunc = resolverFunc 34 | } 35 | 36 | func (f *ConfigImpl) RESTConfig() (*rest.Config, error) { 37 | config, err := f.clientConfig() 38 | if err != nil { 39 | return nil, err 40 | } 41 | 42 | restConfig, err := config.ClientConfig() 43 | if err != nil { 44 | return nil, fmt.Errorf("building Kubernetes config: %s", err) 45 | } 46 | 47 | return restConfig, nil 48 | } 49 | 50 | func (f *ConfigImpl) DefaultNamespace() (string, error) { 51 | config, err := f.clientConfig() 52 | if err != nil { 53 | return "", err 54 | } 55 | 56 | name, _, err := config.Namespace() 57 | return name, err 58 | } 59 | 60 | func (f *ConfigImpl) clientConfig() (clientcmd.ClientConfig, error) { 61 | path, err := f.pathResolverFunc() 62 | if err != nil { 63 | return nil, fmt.Errorf("resolving config path: %s", err) 64 | } 65 | 66 | context, err := f.contextResolverFunc() 67 | if err != nil { 68 | return nil, fmt.Errorf("resolving config context: %s", err) 69 | } 70 | 71 | // Based on https://github.com/kubernetes/kubernetes/blob/30c7df5cd822067016640aa267714204ac089172/staging/src/k8s.io/cli-runtime/pkg/genericclioptions/config_flags.go#L124 72 | loadingRules := clientcmd.NewDefaultClientConfigLoadingRules() 73 | overrides := &clientcmd.ConfigOverrides{} 74 | 75 | if len(path) > 0 { 76 | loadingRules.ExplicitPath = path 77 | } 78 | if len(context) > 0 { 79 | overrides.CurrentContext = context 80 | } 81 | 82 | return clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, overrides), nil 83 | } 84 | -------------------------------------------------------------------------------- /pkg/cmd/core/core.go: -------------------------------------------------------------------------------- 1 | package core 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | "os" 7 | 8 | "github.com/nimakaviani/ytt/pkg/files" 9 | ) 10 | 11 | type PlainUI struct { 12 | debug bool 13 | } 14 | 15 | var _ files.UI = PlainUI{} 16 | 17 | func NewPlainUI(debug bool) PlainUI { return PlainUI{debug} } 18 | 19 | func (ui PlainUI) Printf(str string, args ...interface{}) { 20 | fmt.Printf(str, args...) 21 | } 22 | 23 | func (ui PlainUI) Debugf(str string, args ...interface{}) { 24 | if ui.debug { 25 | fmt.Fprintf(os.Stderr, str, args...) 26 | } 27 | } 28 | 29 | func (ui PlainUI) DebugWriter() io.Writer { 30 | if ui.debug { 31 | return os.Stderr 32 | } 33 | return noopWriter{} 34 | } 35 | 36 | type noopWriter struct{} 37 | 38 | var _ io.Writer = noopWriter{} 39 | 40 | func (w noopWriter) Write(data []byte) (int, error) { return len(data), nil } 41 | -------------------------------------------------------------------------------- /pkg/cmd/core/deps.go: -------------------------------------------------------------------------------- 1 | package core 2 | 3 | import ( 4 | "fmt" 5 | 6 | "k8s.io/client-go/discovery" 7 | "k8s.io/client-go/dynamic" 8 | "k8s.io/client-go/kubernetes" 9 | ) 10 | 11 | type Deps interface { 12 | DynamicClient() (dynamic.Interface, error) 13 | CoreClient() (kubernetes.Interface, error) 14 | DiscoveryClient() (discovery.DiscoveryInterface, error) 15 | } 16 | 17 | type DepsImpl struct { 18 | config Config 19 | } 20 | 21 | var _ Deps = &DepsImpl{} 22 | 23 | func NewDeps(config Config) Deps { 24 | return &DepsImpl{config} 25 | } 26 | 27 | func (f *DepsImpl) DynamicClient() (dynamic.Interface, error) { 28 | config, err := f.config.RESTConfig() 29 | if err != nil { 30 | return nil, err 31 | } 32 | 33 | // TODO high QPS 34 | config.QPS = 1000 35 | config.Burst = 1000 36 | 37 | clientset, err := dynamic.NewForConfig(config) 38 | if err != nil { 39 | return nil, fmt.Errorf("building Dynamic clientset: %s", err) 40 | } 41 | 42 | return clientset, nil 43 | } 44 | 45 | func (f *DepsImpl) CoreClient() (kubernetes.Interface, error) { 46 | config, err := f.config.RESTConfig() 47 | if err != nil { 48 | return nil, err 49 | } 50 | 51 | config.QPS = 1000 52 | config.Burst = 1000 53 | 54 | clientset, err := kubernetes.NewForConfig(config) 55 | if err != nil { 56 | return nil, fmt.Errorf("building Core clientset: %s", err) 57 | } 58 | 59 | return clientset, nil 60 | } 61 | 62 | func (f *DepsImpl) DiscoveryClient() (discovery.DiscoveryInterface, error) { 63 | config, err := f.config.RESTConfig() 64 | if err != nil { 65 | return nil, err 66 | } 67 | 68 | config.QPS = 1000 69 | config.Burst = 1000 70 | 71 | clientset, err := discovery.NewDiscoveryClientForConfig(config) 72 | if err != nil { 73 | return nil, fmt.Errorf("building discovery clientset: %s", err) 74 | } 75 | 76 | return clientset, nil 77 | } 78 | -------------------------------------------------------------------------------- /pkg/cmd/flags/flags_factory.go: -------------------------------------------------------------------------------- 1 | package flags 2 | 3 | import ( 4 | core "github.com/nimakaviani/knative-inspect/pkg/cmd/core" 5 | ) 6 | 7 | type FlagsFactory struct { 8 | config core.Config 9 | deps core.Deps 10 | } 11 | 12 | func NewFlagsFactory(config core.Config, depconfig core.Deps) FlagsFactory { 13 | return FlagsFactory{config, depconfig} 14 | } 15 | -------------------------------------------------------------------------------- /pkg/cmd/flags/kubeconfig_flags.go: -------------------------------------------------------------------------------- 1 | package flags 2 | 3 | import ( 4 | "os" 5 | 6 | "github.com/cppforlife/cobrautil" 7 | "github.com/spf13/cobra" 8 | "github.com/spf13/pflag" 9 | ) 10 | 11 | type KubeconfigFlags struct { 12 | Path *KubeconfigPathFlag 13 | Context *KubeconfigContextFlag 14 | } 15 | 16 | func (f *KubeconfigFlags) Set(cmd *cobra.Command) { 17 | f.Path = NewKubeconfigPathFlag() 18 | cmd.PersistentFlags().Var(f.Path, "kubeconfig", "Path to the kubeconfig file ($KUBECONFIG)") 19 | 20 | f.Context = NewKubeconfigContextFlag() 21 | cmd.PersistentFlags().Var(f.Context, "kubeconfig-context", "Kubeconfig context override ($KUBECONFIG_CONTEXT)") 22 | } 23 | 24 | type KubeconfigPathFlag struct { 25 | value string 26 | } 27 | 28 | var _ pflag.Value = &KubeconfigPathFlag{} 29 | var _ cobrautil.ResolvableFlag = &KubeconfigPathFlag{} 30 | 31 | func NewKubeconfigPathFlag() *KubeconfigPathFlag { 32 | return &KubeconfigPathFlag{} 33 | } 34 | 35 | func (s *KubeconfigPathFlag) Set(val string) error { 36 | s.value = val 37 | return nil 38 | } 39 | 40 | func (s *KubeconfigPathFlag) Type() string { return "string" } 41 | func (s *KubeconfigPathFlag) String() string { return "" } // default for usage 42 | 43 | func (s *KubeconfigPathFlag) Value() (string, error) { 44 | err := s.Resolve() 45 | if err != nil { 46 | return "", err 47 | } 48 | 49 | return s.value, nil 50 | } 51 | 52 | func (s *KubeconfigPathFlag) Resolve() error { 53 | if len(s.value) > 0 { 54 | return nil 55 | } 56 | 57 | s.value = s.resolveValue() 58 | 59 | return nil 60 | } 61 | 62 | func (s *KubeconfigPathFlag) resolveValue() string { 63 | path := os.Getenv("KUBECONFIG") 64 | if len(path) > 0 { 65 | return path 66 | } 67 | 68 | return "" 69 | } 70 | 71 | type KubeconfigContextFlag struct { 72 | value string 73 | } 74 | 75 | var _ pflag.Value = &KubeconfigContextFlag{} 76 | var _ cobrautil.ResolvableFlag = &KubeconfigPathFlag{} 77 | 78 | func NewKubeconfigContextFlag() *KubeconfigContextFlag { 79 | return &KubeconfigContextFlag{} 80 | } 81 | 82 | func (s *KubeconfigContextFlag) Set(val string) error { 83 | s.value = val 84 | return nil 85 | } 86 | 87 | func (s *KubeconfigContextFlag) Type() string { return "string" } 88 | func (s *KubeconfigContextFlag) String() string { return "" } // default for usage 89 | 90 | func (s *KubeconfigContextFlag) Value() (string, error) { 91 | err := s.Resolve() 92 | if err != nil { 93 | return "", err 94 | } 95 | 96 | return s.value, nil 97 | } 98 | 99 | func (s *KubeconfigContextFlag) Resolve() error { 100 | if len(s.value) > 0 { 101 | return nil 102 | } 103 | 104 | s.value = os.Getenv("KUBECONFIG_CONTEXT") 105 | 106 | return nil 107 | } 108 | -------------------------------------------------------------------------------- /pkg/cmd/flags/namespace_flags.go: -------------------------------------------------------------------------------- 1 | package flags 2 | 3 | import ( 4 | "github.com/spf13/cobra" 5 | ) 6 | 7 | type NamespaceFlags struct { 8 | Name string 9 | } 10 | 11 | func (s *NamespaceFlags) Set(cmd *cobra.Command, ns ...string) { 12 | if len(ns) > 1 { 13 | panic("cannot have multiple namespaces") 14 | } 15 | 16 | defaultNS := "default" 17 | if len(ns) == 1 { 18 | defaultNS = ns[0] 19 | } 20 | 21 | cmd.Flags().StringVarP(&s.Name, "namespace", "n", defaultNS, "Knative service namespace") 22 | } 23 | -------------------------------------------------------------------------------- /pkg/cmd/inspect.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "strings" 5 | "time" 6 | 7 | "github.com/cppforlife/go-cli-ui/ui" 8 | "github.com/nimakaviani/knative-inspect/pkg/cmd/core" 9 | "github.com/nimakaviani/knative-inspect/pkg/cmd/flags" 10 | kiui "github.com/nimakaviani/knative-inspect/pkg/cmd/ui" 11 | insp "github.com/nimakaviani/knative-inspect/pkg/inspect/ksvc" 12 | "github.com/spf13/cobra" 13 | ) 14 | 15 | type InspectCmdOptions struct { 16 | ui ui.UI 17 | 18 | Debug bool 19 | Verbose bool 20 | opts insp.InspectorOptions 21 | 22 | kubeconfigFlags flags.KubeconfigFlags 23 | namespaceFlags flags.NamespaceFlags 24 | } 25 | 26 | func NewInspectCmdOptions(ui *ui.ConfUI, config core.Config, deps core.Deps) *InspectCmdOptions { 27 | return &InspectCmdOptions{ui: ui, opts: insp.InspectorOptions{Config: config, Deps: deps}} 28 | } 29 | 30 | func NewInspectCmd(o *InspectCmdOptions) *cobra.Command { 31 | cmd := &cobra.Command{ 32 | Use: "inspect", 33 | Aliases: []string{"i", "insp", "ins"}, 34 | Short: "Inspect Knative services", 35 | RunE: func(_ *cobra.Command, _ []string) error { return o.Run() }, 36 | } 37 | cmd.Flags().BoolVar(&o.Debug, "debug", false, "Enable debug output") 38 | cmd.Flags().BoolVarP(&o.Verbose, "verbose", "v", false, "Show verbose output") 39 | cmd.Flags().StringSliceVarP(&o.opts.Services, "service", "s", []string{}, "Knative services to inspect (can be specified multiple times)") 40 | 41 | o.kubeconfigFlags.Set(cmd) 42 | o.namespaceFlags.Set(cmd) 43 | 44 | return cmd 45 | } 46 | 47 | func (o *InspectCmdOptions) Run() error { 48 | o.opts.Config.ConfigurePathResolver(o.kubeconfigFlags.Path.Value) 49 | o.opts.Config.ConfigureContextResolver(o.kubeconfigFlags.Context.Value) 50 | 51 | ui := core.NewPlainUI(o.Debug) 52 | t1 := time.Now() 53 | 54 | defer func() { 55 | ui.Debugf("total: %s\n", time.Since(t1)) 56 | }() 57 | 58 | return o.inspect() 59 | } 60 | 61 | func (o *InspectCmdOptions) inspect() error { 62 | result, err := insp.NewInspector(*o.opts.WithNamespace(o.namespaceFlags.Name)).Run() 63 | if err != nil { 64 | return err 65 | } 66 | 67 | kiui.TreeView{Source: strings.Join(o.opts.Services, ","), ResourceMap: result, Verbose: o.Verbose}.Print(o.ui) 68 | return nil 69 | } 70 | -------------------------------------------------------------------------------- /pkg/cmd/kube_version.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | 7 | "github.com/cppforlife/go-cli-ui/ui" 8 | "github.com/fatih/color" 9 | "github.com/nimakaviani/knative-inspect/pkg/cmd/core" 10 | "github.com/nimakaviani/knative-inspect/pkg/cmd/flags" 11 | version "github.com/nimakaviani/knative-inspect/pkg/inspect/version" 12 | "github.com/spf13/cobra" 13 | ) 14 | 15 | type KubeVersionOptions struct { 16 | ui ui.UI 17 | Debug bool 18 | 19 | kubeconfigFlags flags.KubeconfigFlags 20 | 21 | config core.Config 22 | deps core.Deps 23 | } 24 | 25 | func NewKubeVersionOptions(ui ui.UI, config core.Config, deps core.Deps) *KubeVersionOptions { 26 | return &KubeVersionOptions{ui: ui, config: config, deps: deps} 27 | } 28 | 29 | func NewKubeVersionCmd(o *KubeVersionOptions) *cobra.Command { 30 | cmd := &cobra.Command{ 31 | Use: "kube-version", 32 | Aliases: []string{"kv"}, 33 | Short: "Print Kubernetes version", 34 | RunE: func(_ *cobra.Command, _ []string) error { return o.Run() }, 35 | } 36 | 37 | o.kubeconfigFlags.Set(cmd) 38 | return cmd 39 | } 40 | 41 | func (o *KubeVersionOptions) Run() error { 42 | o.config.ConfigurePathResolver(o.kubeconfigFlags.Path.Value) 43 | o.config.ConfigureContextResolver(o.kubeconfigFlags.Context.Value) 44 | 45 | ui := core.NewPlainUI(o.Debug) 46 | t1 := time.Now() 47 | 48 | defer func() { 49 | ui.Debugf("total: %s\n", time.Since(t1)) 50 | }() 51 | 52 | return o.version() 53 | } 54 | 55 | func (o *KubeVersionOptions) version() error { 56 | version, err := version.KubeVersion(o.deps) 57 | if err != nil { 58 | return err 59 | } 60 | 61 | o.ui.PrintBlock([]byte( 62 | fmt.Sprintf( 63 | "\nKubernetes Version: %s\n", 64 | color.New(color.FgCyan).Sprintf("%s", version), 65 | ), 66 | )) 67 | return nil 68 | } 69 | -------------------------------------------------------------------------------- /pkg/cmd/logs.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "time" 5 | 6 | "github.com/cppforlife/go-cli-ui/ui" 7 | "github.com/nimakaviani/knative-inspect/pkg/cmd/core" 8 | "github.com/nimakaviani/knative-inspect/pkg/cmd/flags" 9 | "github.com/nimakaviani/knative-inspect/pkg/inspect/logs" 10 | "github.com/spf13/cobra" 11 | ) 12 | 13 | type KnativeLogOptions struct { 14 | ui ui.UI 15 | 16 | Debug bool 17 | opts *logs.LogOptions 18 | 19 | kubeconfigFlags flags.KubeconfigFlags 20 | namespaceFlags flags.NamespaceFlags 21 | } 22 | 23 | func NewKnativeLogOptions(ui *ui.ConfUI, config core.Config, deps core.Deps) *KnativeLogOptions { 24 | return &KnativeLogOptions{ 25 | ui: ui, 26 | opts: &logs.LogOptions{Config: config, Deps: deps}, 27 | } 28 | } 29 | 30 | func NewKnativeLogsCmd(o *KnativeLogOptions) *cobra.Command { 31 | cmd := &cobra.Command{ 32 | Use: "logs", 33 | Aliases: []string{"l"}, 34 | Short: "Knative Component Logs", 35 | RunE: func(_ *cobra.Command, _ []string) error { return o.Run() }, 36 | } 37 | 38 | cmd.Flags().BoolVarP(&o.opts.Follow, "follow", "f", false, "As new pods are added, new pod logs will be printed") 39 | cmd.Flags().Int64Var(&o.opts.Lines, "lines", 10, "Limit to number of lines (use -1 to remove limit)") 40 | cmd.Flags().StringVar(&o.opts.Filter, "filter", "", "Filter logs by log type (info, warn, error)") 41 | cmd.Flags().StringSliceVarP( 42 | &o.opts.Pods, 43 | "pods", "p", 44 | []string{}, 45 | "Knative component to grab logs for (can be specified multiple times, eg. activator, autoscaler)", 46 | ) 47 | 48 | o.kubeconfigFlags.Set(cmd) 49 | o.namespaceFlags.Set(cmd, servingNamespace) 50 | return cmd 51 | } 52 | 53 | func (o *KnativeLogOptions) Run() error { 54 | o.opts.Config.ConfigurePathResolver(o.kubeconfigFlags.Path.Value) 55 | o.opts.Config.ConfigureContextResolver(o.kubeconfigFlags.Context.Value) 56 | 57 | ui := core.NewPlainUI(o.Debug) 58 | t1 := time.Now() 59 | 60 | defer func() { 61 | ui.Debugf("total: %s\n", time.Since(t1)) 62 | }() 63 | 64 | return o.logs() 65 | } 66 | 67 | func (o *KnativeLogOptions) logs() error { 68 | // set the name based on whatever comes through from the flag 69 | o.opts.Namespace = o.namespaceFlags.Name 70 | 71 | return logs.NewLogs(o.opts).Run() 72 | } 73 | -------------------------------------------------------------------------------- /pkg/cmd/ui/diff_view.go: -------------------------------------------------------------------------------- 1 | package ui 2 | 3 | import ( 4 | "github.com/cppforlife/go-cli-ui/ui" 5 | "github.com/fatih/color" 6 | diff "github.com/walmartlabs/object-diff/pkg/obj_diff" 7 | ) 8 | 9 | type DiffView struct { 10 | Source string 11 | ChangeSet map[string]*diff.ChangeSet 12 | } 13 | 14 | func (v DiffView) Print(ui ui.UI) { 15 | var result []byte 16 | 17 | ui.PrintLinef("Changes in %s", v.Source) 18 | 19 | for name, changeSet := range v.ChangeSet { 20 | if len(changeSet.Changes) <= 0 { 21 | continue 22 | } 23 | 24 | result = append( 25 | result, 26 | []byte(color.New(color.FgYellow).Sprintf("* %s\n", name))..., 27 | ) 28 | 29 | for _, c := range changeSet.Changes { 30 | if c.IsDeletion() { 31 | result = append( 32 | result, 33 | []byte(color.New(color.FgRed).Sprintf("- %v\n", c.PathString()))..., 34 | ) 35 | } 36 | 37 | if c.IsAddition() { 38 | result = append( 39 | result, 40 | []byte(color.New(color.FgGreen).Sprintf("+ %v %v\n", c.PathString(), c.GetNewValue()))..., 41 | ) 42 | } 43 | 44 | if !c.IsDeletion() && !c.IsAddition() && c.GetNewValue() != c.GetOldValue() { 45 | result = append( 46 | result, 47 | []byte(color.New(color.FgRed).Sprintf("- %v %v\n", c.PathString(), c.GetOldValue()))..., 48 | ) 49 | result = append( 50 | result, 51 | []byte(color.New(color.FgGreen).Sprintf("+ %v %v\n", c.PathString(), c.GetNewValue()))..., 52 | ) 53 | } 54 | } 55 | result = append(result, []byte("\n")...) 56 | } 57 | 58 | ui.PrintBlock(result) 59 | } 60 | -------------------------------------------------------------------------------- /pkg/cmd/ui/tree_view.go: -------------------------------------------------------------------------------- 1 | package ui 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | "sort" 7 | 8 | "strings" 9 | 10 | "github.com/cppforlife/go-cli-ui/ui" 11 | uitable "github.com/cppforlife/go-cli-ui/ui/table" 12 | "github.com/fatih/color" 13 | krsc "github.com/nimakaviani/kapp/pkg/kapp/resources" 14 | "github.com/nimakaviani/knative-inspect/pkg/resources" 15 | ) 16 | 17 | const ( 18 | ServiceKind = "Service" 19 | ApiGroup = "serving.knative.dev" 20 | ) 21 | 22 | type TreeView struct { 23 | Source string 24 | ResourceMap [][]krsc.Resource 25 | Sort bool 26 | Verbose bool 27 | } 28 | 29 | func (v TreeView) Print(ui ui.UI) { 30 | groupHeader := uitable.NewHeader("Group") 31 | groupHeader.Hidden = true 32 | 33 | versionHeader := uitable.NewHeader("Version") 34 | versionHeader.Hidden = !v.Verbose 35 | 36 | table := uitable.Table{ 37 | Title: fmt.Sprintf("Resources in %s", v.Source), 38 | Content: "resources", 39 | 40 | Header: []uitable.Header{ 41 | groupHeader, 42 | uitable.NewHeader("Namespace"), 43 | uitable.NewHeader("Name"), 44 | versionHeader, 45 | uitable.NewHeader("Kind"), 46 | uitable.NewHeader("Ready"), 47 | uitable.NewHeader("Reason"), 48 | }, 49 | 50 | FillFirstColumn: true, 51 | } 52 | 53 | for _, rm := range v.ResourceMap { 54 | rt := buildResourceTree(rm) 55 | v.addRows(&table, rt, 0, "", false) 56 | v.addBlankRow(&table) 57 | } 58 | 59 | ui.PrintTable(table) 60 | } 61 | 62 | type resourceTree interface { 63 | Resource() krsc.Resource 64 | Children() []resourceTree 65 | } 66 | 67 | type resourceTreeImpl struct { 68 | root krsc.Resource 69 | children []resourceTree 70 | } 71 | 72 | func (r *resourceTreeImpl) Resource() krsc.Resource { 73 | return r.root 74 | } 75 | 76 | func (r *resourceTreeImpl) Children() []resourceTree { 77 | return r.children 78 | } 79 | 80 | type byUID []resourceTree 81 | 82 | func (a byUID) Len() int { return len(a) } 83 | func (a byUID) Swap(i, j int) { a[i], a[j] = a[j], a[i] } 84 | func (a byUID) Less(i, j int) bool { return a[i].Resource().UID() < a[j].Resource().UID() } 85 | 86 | type resourceRef struct { 87 | self krsc.Resource 88 | parent krsc.Resource 89 | } 90 | 91 | func buildResourceTree(resources []krsc.Resource) resourceTree { 92 | resourceMap := make(map[string]*resourceRef) 93 | for _, r := range resources { 94 | if r == nil { 95 | continue 96 | } 97 | 98 | resourceMap[r.UID()] = &resourceRef{self: r} 99 | } 100 | 101 | for _, r := range resources { 102 | if r == nil { 103 | continue 104 | } 105 | 106 | for _, owner := range r.OwnerRefs() { 107 | if p, ok := resourceMap[string(owner.UID)]; ok { 108 | resourceMap[r.UID()].parent = p.self 109 | } 110 | } 111 | } 112 | 113 | root := findRoot(resourceMap) 114 | return buildTree(root, resourceMap) 115 | } 116 | 117 | func findRoot(nodes map[string]*resourceRef) *resourceRef { 118 | for _, n := range nodes { 119 | if n.parent == nil && n.self.Kind() == ServiceKind && strings.Contains(n.self.APIGroup(), ApiGroup) { 120 | return n 121 | } 122 | } 123 | panic("no root found") 124 | } 125 | 126 | func findKids(r krsc.Resource, resourceMap map[string]*resourceRef) []*resourceRef { 127 | var kids []*resourceRef 128 | for _, n := range resourceMap { 129 | if n.parent == r { 130 | kids = append(kids, n) 131 | } 132 | } 133 | return kids 134 | } 135 | 136 | func buildTree(r *resourceRef, resourceMap map[string]*resourceRef) resourceTree { 137 | rt := resourceTreeImpl{ 138 | root: r.self, 139 | children: []resourceTree{}, 140 | } 141 | 142 | kids := findKids(r.self, resourceMap) 143 | for _, k := range kids { 144 | childTree := buildTree(k, resourceMap) 145 | rt.children = append(rt.children, childTree) 146 | } 147 | 148 | return &rt 149 | } 150 | 151 | func (v TreeView) addBlankRow(table *uitable.Table) { 152 | row := []uitable.Value{ 153 | uitable.NewValueString(" "), 154 | uitable.NewValueString(" "), 155 | uitable.NewValueString(" "), 156 | uitable.NewValueString(" "), 157 | uitable.NewValueString(" "), 158 | uitable.NewValueString(" "), 159 | } 160 | table.Rows = append(table.Rows, row) 161 | } 162 | 163 | func (v TreeView) addRows(table *uitable.Table, rt resourceTree, depth int, connector string, hasSibling bool) { 164 | resource := rt.Resource() 165 | cond := resources.Conditions{Resource: resource} 166 | 167 | msg := "False" 168 | ready, msg := cond.IsSelectedTrue([]string{"Ready"}) 169 | if ready { 170 | msg = "True" 171 | } 172 | 173 | reason := cond.Reason("Ready") 174 | 175 | if hasSibling { 176 | connector += " |" 177 | } else { 178 | connector += " " 179 | } 180 | 181 | var delim string 182 | if depth > 0 { 183 | delim = fmt.Sprintf("%sL", connector) 184 | if !hasSibling { 185 | delim += "_" 186 | } 187 | delim += " " 188 | } 189 | 190 | row := []uitable.Value{ 191 | uitable.NewValueString(""), 192 | uitable.NewValueString(resource.Namespace()), 193 | uitable.NewValueString(resource.Name()), 194 | uitable.NewValueString(resource.APIVersion()), 195 | ValueEncoded{ 196 | S: delim + resource.Kind(), 197 | Func: func(str string, opts ...interface{}) string { 198 | result := fmt.Sprintf(str, opts...) 199 | return strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(result, "|L", "├─"), "|", "│"), "L_", "└─") 200 | }, 201 | }, 202 | ValueEncoded{ 203 | S: msg, 204 | Func: func(str string, opts ...interface{}) string { 205 | result := fmt.Sprintf(str, opts...) 206 | if ready { 207 | return color.New(color.FgGreen).Sprintf("%s", result) 208 | } 209 | if msg != "" { 210 | return color.New(color.FgRed).Sprintf("%s", result) 211 | } 212 | return result 213 | }, 214 | }, 215 | ValueEncoded{ 216 | S: reason, 217 | Func: func(str string, opts ...interface{}) string { 218 | result := fmt.Sprintf(str, opts...) 219 | if !ready && msg != "" { 220 | return color.New(color.FgRed).Sprintf("%s", result) 221 | } 222 | return "" 223 | }, 224 | }, 225 | } 226 | 227 | table.Rows = append(table.Rows, row) 228 | 229 | sortedChildren := byUID(rt.Children()) 230 | sort.Sort(sortedChildren) 231 | for i, c := range sortedChildren { 232 | sibling := false 233 | if i+1 < len(rt.Children()) { 234 | sibling = true 235 | } 236 | v.addRows(table, c, depth+1, connector, sibling) 237 | } 238 | } 239 | 240 | type ValueEncoded struct { 241 | S string 242 | Func func(string, ...interface{}) string 243 | } 244 | 245 | func (t ValueEncoded) String() string { return t.S } 246 | func (t ValueEncoded) Value() uitable.Value { return t } 247 | func (t ValueEncoded) Compare(other uitable.Value) int { panic("Never called") } 248 | 249 | func (t ValueEncoded) Fprintf(w io.Writer, pattern string, rest ...interface{}) (int, error) { 250 | return fmt.Fprintf(w, "%s", t.Func(pattern, rest...)) 251 | } 252 | -------------------------------------------------------------------------------- /pkg/cmd/version.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/cppforlife/go-cli-ui/ui" 7 | "github.com/spf13/cobra" 8 | ) 9 | 10 | const ( 11 | Version = "0.2.0" 12 | ) 13 | 14 | type VersionOptions struct { 15 | ui ui.UI 16 | } 17 | 18 | func NewVersionOptions(ui ui.UI) *VersionOptions { 19 | return &VersionOptions{ui} 20 | } 21 | 22 | func NewVersionCmd(o *VersionOptions) *cobra.Command { 23 | cmd := &cobra.Command{ 24 | Use: "version", 25 | Short: "Print version", 26 | RunE: func(_ *cobra.Command, _ []string) error { return o.Run() }, 27 | } 28 | return cmd 29 | } 30 | 31 | func (o *VersionOptions) Run() error { 32 | o.ui.PrintBlock([]byte(fmt.Sprintf("Client Version: %s\n", Version))) 33 | 34 | return nil 35 | } 36 | -------------------------------------------------------------------------------- /pkg/inspect/config/configs.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "reflect" 7 | "time" 8 | 9 | core "github.com/nimakaviani/knative-inspect/pkg/cmd/core" 10 | corev1 "k8s.io/api/core/v1" 11 | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 12 | // TODO: look for reason - prevent config reflection from panicking 13 | _ "knative.dev/pkg/system/testing" 14 | 15 | diff "github.com/walmartlabs/object-diff/pkg/obj_diff" 16 | 17 | // "knative.dev/pkg/configmap" 18 | apisconfig "knative.dev/serving/pkg/apis/config" 19 | autoscalerconfig "knative.dev/serving/pkg/autoscaler" 20 | deployment "knative.dev/serving/pkg/deployment" 21 | gcconfig "knative.dev/serving/pkg/gc" 22 | networkconfig "knative.dev/serving/pkg/network" 23 | certconfig "knative.dev/serving/pkg/reconciler/certificate/config" 24 | istioconfig "knative.dev/serving/pkg/reconciler/ingress/config" 25 | domainconfig "knative.dev/serving/pkg/reconciler/route/config" 26 | tracingconfig "knative.dev/serving/pkg/tracing/config" 27 | ) 28 | 29 | type ConfigMapChangeOpts struct { 30 | Namespace string 31 | ConfigMapNames []string 32 | 33 | Deps core.Deps 34 | Config core.Config 35 | } 36 | 37 | type ConfigInspector struct { 38 | opts ConfigMapChangeOpts 39 | skippedNames map[string]interface{} 40 | knativeConfigs map[string]interface{} 41 | } 42 | 43 | func NewConfigInspector(opts ConfigMapChangeOpts) *ConfigInspector { 44 | logger := &logger{} 45 | d, _ := time.ParseDuration("1m") 46 | 47 | knativeConfigs := map[string]interface{}{ 48 | tracingconfig.ConfigName: tracingconfig.NewTracingConfigFromConfigMap, 49 | apisconfig.DefaultsConfigName: apisconfig.NewDefaultsConfigFromConfigMap, 50 | gcconfig.ConfigName: gcconfig.NewConfigFromConfigMapFunc(logger, d), 51 | domainconfig.DomainConfigName: domainconfig.NewDomainFromConfigMap, 52 | networkconfig.ConfigName: networkconfig.NewConfigFromConfigMap, 53 | certconfig.CertManagerConfigName: certconfig.NewCertManagerConfigFromConfigMap, 54 | istioconfig.IstioConfigName: istioconfig.NewIstioFromConfigMap, 55 | autoscalerconfig.ConfigName: autoscalerconfig.NewConfigFromConfigMap, 56 | deployment.ConfigName: deployment.NewConfigFromConfigMap, 57 | } 58 | 59 | skippedNames := make(map[string]interface{}) 60 | if len(opts.ConfigMapNames) > 0 { 61 | for k, _ := range knativeConfigs { 62 | found := false 63 | for _, n := range opts.ConfigMapNames { 64 | if k == n { 65 | found = true 66 | break 67 | } 68 | } 69 | if !found { 70 | skippedNames[k] = struct{}{} 71 | } 72 | } 73 | } 74 | 75 | return &ConfigInspector{ 76 | opts: opts, 77 | skippedNames: skippedNames, 78 | knativeConfigs: knativeConfigs, 79 | } 80 | } 81 | 82 | func (o *ConfigInspector) Run() (map[string]*diff.ChangeSet, error) { 83 | coreClient, err := o.opts.Deps.CoreClient() 84 | if err != nil { 85 | return nil, err 86 | } 87 | 88 | configs, err := coreClient.CoreV1().ConfigMaps(o.opts.Namespace).List(metav1.ListOptions{}) 89 | if err != nil { 90 | return nil, err 91 | } 92 | 93 | changes := make(map[string]*diff.ChangeSet) 94 | 95 | for _, config := range configs.Items { 96 | if fn, ok := o.knativeConfigs[config.Name]; ok { 97 | 98 | if _, ok := o.skippedNames[config.Name]; ok { 99 | continue 100 | } 101 | 102 | defaultConfig, err := call(fn, &corev1.ConfigMap{}) 103 | if err != nil { 104 | log.Printf("default config for %s => %s", config.Name, err.Error()) 105 | continue 106 | } 107 | 108 | appliedConfig, err := call(fn, &config) 109 | if err != nil { 110 | log.Printf("applied config for %s => %s", config.Name, err.Error()) 111 | continue 112 | } 113 | 114 | diffs, err := diff.Diff(defaultConfig, appliedConfig) 115 | if err != nil { 116 | log.Printf("diff failed for %s", config.Name) 117 | continue 118 | } 119 | 120 | changes[config.Name] = diffs 121 | } 122 | } 123 | 124 | return changes, nil 125 | } 126 | 127 | func call(fn interface{}, configMap *corev1.ConfigMap) (interface{}, error) { 128 | constructor := reflect.ValueOf(fn) 129 | inputs := []reflect.Value{reflect.ValueOf(configMap)} 130 | outputs := constructor.Call(inputs) 131 | 132 | result := outputs[0].Interface() 133 | errVal := outputs[1] 134 | 135 | if !errVal.IsNil() { 136 | return nil, fmt.Errorf("%q", errVal.Interface()) 137 | } 138 | 139 | return result, nil 140 | } 141 | -------------------------------------------------------------------------------- /pkg/inspect/config/logger.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | import ( 4 | "log" 5 | ) 6 | 7 | type logger struct{} 8 | 9 | func (o *logger) Infof(s string, params ...interface{}) { 10 | log.Printf(s, params...) 11 | } 12 | 13 | func (o *logger) Errorf(s string, params ...interface{}) { 14 | log.Printf(s, params...) 15 | } 16 | 17 | func (o *logger) Fatalf(s string, params ...interface{}) { 18 | log.Fatalf(s, params) 19 | } 20 | -------------------------------------------------------------------------------- /pkg/inspect/ksvc/inspector.go: -------------------------------------------------------------------------------- 1 | package inspect 2 | 3 | import ( 4 | krsc "github.com/nimakaviani/kapp/pkg/kapp/resources" 5 | core "github.com/nimakaviani/knative-inspect/pkg/cmd/core" 6 | ) 7 | 8 | type ResourceMap [][]krsc.Resource 9 | 10 | type Inspector interface { 11 | Run() (ResourceMap, error) 12 | } 13 | 14 | type InspectorOptions struct { 15 | Namespace string 16 | Services []string 17 | 18 | Config core.Config 19 | Deps core.Deps 20 | } 21 | 22 | func (k *InspectorOptions) WithNamespace(namespace string) *InspectorOptions { 23 | k.Namespace = namespace 24 | return k 25 | } 26 | 27 | type inspectorImpl struct { 28 | opts InspectorOptions 29 | } 30 | 31 | func NewInspector(opts InspectorOptions) Inspector { 32 | return &inspectorImpl{opts} 33 | } 34 | 35 | func (o *inspectorImpl) Run() (ResourceMap, error) { 36 | ksvcOpts := KsvcOpts{ 37 | Services: o.opts.Services, 38 | Namespace: o.opts.Namespace, 39 | Deps: o.opts.Deps, 40 | } 41 | 42 | resourceMap, err := NewKsvc(ksvcOpts).Inspect() 43 | if err != nil { 44 | return nil, err 45 | } 46 | 47 | return resourceMap, nil 48 | } 49 | -------------------------------------------------------------------------------- /pkg/inspect/ksvc/ksvc.go: -------------------------------------------------------------------------------- 1 | package inspect 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "reflect" 7 | 8 | krsc "github.com/nimakaviani/kapp/pkg/kapp/resources" 9 | core "github.com/nimakaviani/knative-inspect/pkg/cmd/core" 10 | resources "github.com/nimakaviani/knative-inspect/pkg/resources" 11 | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 12 | "k8s.io/apimachinery/pkg/labels" 13 | "k8s.io/apimachinery/pkg/runtime/schema" 14 | "knative.dev/serving/pkg/apis/serving" 15 | ) 16 | 17 | type KsvcOpts struct { 18 | Deps core.Deps 19 | 20 | Services []string 21 | Namespace string 22 | } 23 | 24 | type KSVC struct { 25 | opts KsvcOpts 26 | } 27 | 28 | func NewKsvc(opts KsvcOpts) *KSVC { 29 | return &KSVC{opts: opts} 30 | } 31 | 32 | type ResourceOpts struct { 33 | kind string 34 | group string 35 | version string 36 | } 37 | 38 | type SearchOpts struct { 39 | ResourceOpts 40 | service string 41 | name string 42 | namespace string 43 | 44 | selectorField string 45 | selectorValue string 46 | } 47 | 48 | func (k *KSVC) Inspect() ([][]krsc.Resource, error) { 49 | dynamicClient, err := k.opts.Deps.DynamicClient() 50 | if err != nil { 51 | return nil, err 52 | } 53 | 54 | resourceSearch := resources.NewResourceSearch(dynamicClient) 55 | resourceMap := [][]krsc.Resource{} 56 | var serviceResource krsc.Resource 57 | for _, svc := range k.opts.Services { 58 | ropts := SearchOpts{ 59 | service: svc, 60 | name: svc, 61 | namespace: k.opts.Namespace, 62 | 63 | ResourceOpts: ResourceOpts{ 64 | kind: "services", 65 | group: "serving.knative.dev", 66 | version: "v1beta1", 67 | }, 68 | 69 | selectorField: "FieldSelector", 70 | selectorValue: fmt.Sprintf("metadata.name=%s", svc), 71 | } 72 | 73 | serviceResource, err = getService(resourceSearch, ropts) 74 | if err != nil { 75 | continue 76 | } 77 | 78 | labeledResources, err := findLabeledResoures(svc, k.opts.Namespace, k.opts.Deps) 79 | if err != nil { 80 | return nil, err 81 | } 82 | 83 | resourceMap = append(resourceMap, append(labeledResources, serviceResource)) 84 | } 85 | 86 | return resourceMap, nil 87 | } 88 | 89 | func getService(resourceSearch *resources.ResourceSearchImpl, ropts SearchOpts) (krsc.Resource, error) { 90 | listOpts := setListOption(&metav1.ListOptions{}, ropts.selectorField, ropts.selectorValue) 91 | 92 | searchOpts := resources.ResourceSearchOpts{ 93 | GroupVersion: schema.GroupVersionResource{ 94 | Group: ropts.group, 95 | Version: ropts.version, 96 | Resource: ropts.kind, 97 | }, 98 | ListOpts: *listOpts, 99 | Namespace: ropts.namespace, 100 | } 101 | 102 | rs, err := resourceSearch.Find(searchOpts) 103 | if err != nil { 104 | return nil, err 105 | } 106 | 107 | if len(rs) > 1 { 108 | panic(fmt.Errorf("found more than one resource for %s:%s/%s:%s", ropts.group, ropts.version, ropts.kind, ropts.name)) 109 | } 110 | 111 | if len(rs) == 0 { 112 | log.Fatalf("service %s not found", ropts.service) 113 | } 114 | 115 | return rs[0], nil 116 | } 117 | 118 | func setListOption(opts *metav1.ListOptions, fieldName string, fieldValue string) *metav1.ListOptions { 119 | ps := reflect.ValueOf(opts) 120 | s := ps.Elem() 121 | if s.Kind() == reflect.Struct { 122 | f := s.FieldByName(fieldName) 123 | if f.IsValid() { 124 | if f.CanSet() { 125 | if f.Kind() == reflect.String { 126 | f.SetString(fieldValue) 127 | } 128 | } 129 | } 130 | } 131 | 132 | return opts 133 | } 134 | 135 | func findLabeledResoures(service, namespace string, deps core.Deps) ([]krsc.Resource, error) { 136 | dynamicClient, err := deps.DynamicClient() 137 | if err != nil { 138 | return nil, err 139 | } 140 | 141 | coreClient, err := deps.CoreClient() 142 | if err != nil { 143 | return nil, err 144 | } 145 | 146 | idr := krsc.NewIdentifiedResources(coreClient, dynamicClient, []string{}) 147 | 148 | filterLabels := []map[string]string{ 149 | {serving.ServiceLabelKey: service}, 150 | {serving.RouteLabelKey: service}, 151 | } 152 | labeledResources := []krsc.Resource{} 153 | for _, l := range filterLabels { 154 | list, err := idr.List(labels.Set(l).AsSelector()) 155 | if err != nil { 156 | return nil, err 157 | } 158 | labeledResources = append(labeledResources, list...) 159 | } 160 | 161 | return labeledResources, nil 162 | } 163 | -------------------------------------------------------------------------------- /pkg/inspect/logs/dump.go: -------------------------------------------------------------------------------- 1 | package logs 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "os" 7 | "strings" 8 | 9 | . "github.com/cppforlife/go-cli-ui/ui/table" 10 | ) 11 | 12 | type DumpUI struct { 13 | filter string 14 | } 15 | 16 | func NewDumpUI(filter string) *DumpUI { 17 | log.SetOutput(os.Stdout) 18 | log.SetFlags(log.Flags() &^ (log.Ldate | log.Ltime)) 19 | return &DumpUI{filter: filter} 20 | } 21 | 22 | func (o *DumpUI) Close() { 23 | log.SetFlags(log.Flags() & (log.Ldate | log.Ltime)) 24 | log.SetOutput(os.Stderr) 25 | } 26 | 27 | func (o *DumpUI) ErrorLinef(pattern string, args ...interface{}) { 28 | log.Printf(pattern, args...) 29 | } 30 | 31 | func (o *DumpUI) PrintLinef(pattern string, args ...interface{}) { 32 | log.Printf(pattern, args...) 33 | } 34 | 35 | func (o *DumpUI) BeginLinef(pattern string, args ...interface{}) { 36 | log.Printf(pattern, args...) 37 | } 38 | 39 | func (o *DumpUI) EndLinef(pattern string, args ...interface{}) { 40 | log.Printf(pattern, args...) 41 | } 42 | 43 | func (o *DumpUI) PrintBlock(data []byte) { // takes []byte to avoid string copy 44 | logLine := string(data) 45 | if o.filter == "" { 46 | log.Print(logLine) 47 | return 48 | } 49 | 50 | if strings.Contains(logLine, fmt.Sprintf(`"level":"%s"`, o.filter)) { 51 | log.Print(logLine) 52 | } 53 | } 54 | 55 | func (o *DumpUI) PrintErrorBlock(string) { 56 | } 57 | 58 | func (o *DumpUI) PrintTable(Table) { 59 | } 60 | 61 | func (o *DumpUI) AskForText(label string) (string, error) { 62 | return "", nil 63 | } 64 | 65 | func (o *DumpUI) AskForChoice(label string, options []string) (int, error) { 66 | return -1, nil 67 | } 68 | 69 | func (o *DumpUI) AskForPassword(label string) (string, error) { 70 | return "", nil 71 | } 72 | 73 | // AskForConfirmation returns error if user doesnt want to continue 74 | func (o *DumpUI) AskForConfirmation() error { return nil } 75 | func (o *DumpUI) IsInteractive() bool { return false } 76 | func (o *DumpUI) Flush() {} 77 | -------------------------------------------------------------------------------- /pkg/inspect/logs/logs.go: -------------------------------------------------------------------------------- 1 | package logs 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | "sync" 7 | 8 | klogs "github.com/nimakaviani/kapp/pkg/kapp/logs" 9 | core "github.com/nimakaviani/knative-inspect/pkg/cmd/core" 10 | corev1 "k8s.io/api/core/v1" 11 | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 12 | ) 13 | 14 | type LogOptions struct { 15 | Namespace string 16 | Follow bool 17 | Lines int64 18 | Filter string 19 | Pods []string 20 | 21 | Deps core.Deps 22 | Config core.Config 23 | } 24 | 25 | type Logs struct { 26 | opts *LogOptions 27 | } 28 | 29 | func NewLogs(opts *LogOptions) *Logs { 30 | return &Logs{opts: opts} 31 | } 32 | 33 | func (o *Logs) Run() error { 34 | err := o.checks() 35 | if err != nil { 36 | return err 37 | } 38 | 39 | coreClient, err := o.opts.Deps.CoreClient() 40 | if err != nil { 41 | return err 42 | } 43 | 44 | pods, err := coreClient.CoreV1().Pods(o.opts.Namespace).List(metav1.ListOptions{}) 45 | if err != nil { 46 | return err 47 | } 48 | 49 | wg := sync.WaitGroup{} 50 | 51 | lineOpts := (*int64)(nil) 52 | if o.opts.Lines > 0 { 53 | lineOpts = &o.opts.Lines 54 | } 55 | 56 | for _, pod := range pods.Items { 57 | logOpts := klogs.PodLogOpts{ 58 | Follow: o.opts.Follow, 59 | Lines: lineOpts, 60 | ContainerTag: true, 61 | } 62 | 63 | if len(o.opts.Pods) > 0 && !contains(o.opts.Pods, pod.Name) { 64 | continue 65 | } 66 | 67 | wg.Add(1) 68 | pod := pod 69 | go func() { 70 | tagFunc := func(cont corev1.Container) string { 71 | return fmt.Sprintf("%s > %s", pod.Name, cont.Name) 72 | } 73 | 74 | podClient := coreClient.CoreV1().Pods(o.opts.Namespace) 75 | 76 | dumpUI := NewDumpUI(o.opts.Filter) 77 | defer dumpUI.Close() 78 | 79 | klogs.NewPodLog(pod, podClient, tagFunc, logOpts).TailAll(dumpUI, make(chan struct{})) 80 | wg.Done() 81 | }() 82 | } 83 | 84 | wg.Wait() 85 | return nil 86 | } 87 | 88 | func contains(slice []string, name string) bool { 89 | for _, f := range slice { 90 | if strings.Contains(name, f) { 91 | return true 92 | } 93 | } 94 | 95 | return false 96 | } 97 | 98 | func (o Logs) checks() error { 99 | if o.opts.Filter != "" && !contains([]string{"warn", "info", "error"}, o.opts.Filter) { 100 | return fmt.Errorf(`--filter "%s" is invalid. It should be one of "error", "info", "warn"`, o.opts.Filter) 101 | } 102 | 103 | if o.opts.Follow && o.opts.Lines <= 0 { 104 | return fmt.Errorf("expected --lines to be greater than zero since --follow is not specified") 105 | } 106 | 107 | return nil 108 | } 109 | -------------------------------------------------------------------------------- /pkg/inspect/version/kube_version.go: -------------------------------------------------------------------------------- 1 | package inspect 2 | 3 | import ( 4 | "fmt" 5 | 6 | core "github.com/nimakaviani/knative-inspect/pkg/cmd/core" 7 | ) 8 | 9 | func KubeVersion(deps core.Deps) (string, error) { 10 | cli, err := deps.DiscoveryClient() 11 | if err != nil { 12 | return "", err 13 | } 14 | 15 | ver, err := cli.ServerVersion() 16 | if err != nil { 17 | return "", err 18 | } 19 | 20 | return fmt.Sprintf("%s.%s", ver.Major, ver.Minor), nil 21 | } 22 | -------------------------------------------------------------------------------- /pkg/resources/conditions.go: -------------------------------------------------------------------------------- 1 | package resources 2 | 3 | import ( 4 | "fmt" 5 | 6 | krsc "github.com/nimakaviani/kapp/pkg/kapp/resources" 7 | ) 8 | 9 | type Conditions struct { 10 | Resource krsc.Resource 11 | } 12 | 13 | func (c Conditions) Reason(checkedType string) string { 14 | messages := c.reasons() 15 | 16 | if reason, found := messages[checkedType]; found { 17 | return reason 18 | } 19 | 20 | return "-" 21 | } 22 | 23 | func (c Conditions) IsSelectedTrue(checkedTypes []string) (bool, string) { 24 | statuses := c.statuses() 25 | 26 | for _, t := range checkedTypes { 27 | status, found := statuses[t] 28 | if !found { 29 | return false, "" 30 | } 31 | if status != "True" { 32 | return false, status 33 | } 34 | } 35 | 36 | return true, "" 37 | } 38 | 39 | func (c Conditions) IsAllTrue() (bool, string) { 40 | statuses := c.statuses() 41 | if len(statuses) == 0 { 42 | return false, "No conditions found" 43 | } 44 | 45 | for t, status := range c.statuses() { 46 | if status != "True" { 47 | return false, fmt.Sprintf("Condition %s is not True (%s)", t, status) 48 | } 49 | } 50 | 51 | return true, "" 52 | } 53 | 54 | func (c Conditions) statuses() map[string]string { 55 | statuses := map[string]string{} 56 | if conditions, ok := c.Resource.Status()["conditions"].([]interface{}); ok { 57 | for _, cond := range conditions { 58 | if typedCond, ok := cond.(map[string]interface{}); ok { 59 | if typedType, ok := typedCond["type"].(string); ok { 60 | if typedStatus, ok := typedCond["status"].(string); ok { 61 | statuses[typedType] = typedStatus 62 | } 63 | } 64 | } 65 | } 66 | } 67 | return statuses 68 | } 69 | 70 | func (c Conditions) reasons() map[string]string { 71 | statuses := map[string]string{} 72 | if conditions, ok := c.Resource.Status()["conditions"].([]interface{}); ok { 73 | for _, cond := range conditions { 74 | if typedCond, ok := cond.(map[string]interface{}); ok { 75 | if typedType, ok := typedCond["type"].(string); ok { 76 | if typedStatus, ok := typedCond["reason"].(string); ok { 77 | statuses[typedType] = typedStatus 78 | } 79 | } 80 | } 81 | } 82 | } 83 | return statuses 84 | } 85 | -------------------------------------------------------------------------------- /pkg/resources/resource_search.go: -------------------------------------------------------------------------------- 1 | package resources 2 | 3 | import ( 4 | krsc "github.com/nimakaviani/kapp/pkg/kapp/resources" 5 | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 6 | "k8s.io/apimachinery/pkg/runtime/schema" 7 | "k8s.io/client-go/dynamic" 8 | ) 9 | 10 | type ResourceSearchOpts struct { 11 | GroupVersion schema.GroupVersionResource 12 | ListOpts metav1.ListOptions 13 | 14 | Namespace string 15 | } 16 | 17 | type ResourceSearchImpl struct { 18 | dynamicClient dynamic.Interface 19 | } 20 | 21 | func NewResourceSearch(dynamicClient dynamic.Interface) *ResourceSearchImpl { 22 | return &ResourceSearchImpl{ 23 | dynamicClient: dynamicClient, 24 | } 25 | } 26 | 27 | func (o *ResourceSearchImpl) Find(opts ResourceSearchOpts) ([]krsc.Resource, error) { 28 | list, err := o.dynamicClient.Resource(opts.GroupVersion).Namespace(opts.Namespace).List(opts.ListOpts) 29 | if err != nil { 30 | return nil, err 31 | } 32 | 33 | var resources []krsc.Resource 34 | for _, item := range list.Items { 35 | resource := krsc.NewResourceUnstructured(item, opts.GroupVersion) 36 | resources = append(resources, resource) 37 | } 38 | return resources, nil 39 | } 40 | -------------------------------------------------------------------------------- /tests/buffer_reader.go: -------------------------------------------------------------------------------- 1 | package tests 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | "log" 7 | "regexp" 8 | "sync" 9 | ) 10 | 11 | type buffer struct { 12 | contents []byte 13 | readCursor uint64 14 | lock *sync.Mutex 15 | closed bool 16 | } 17 | 18 | func BufferReader(reader io.Reader) *buffer { 19 | b := &buffer{ 20 | lock: &sync.Mutex{}, 21 | } 22 | 23 | io.Copy(b, reader) 24 | b.Close() 25 | 26 | return b 27 | } 28 | 29 | func (b *buffer) Write(p []byte) (n int, err error) { 30 | b.lock.Lock() 31 | defer b.lock.Unlock() 32 | 33 | if b.closed { 34 | return 0, fmt.Errorf("attempt to write to closed buffer") 35 | } 36 | 37 | println("here!!") 38 | 39 | b.contents = append(b.contents, p...) 40 | return len(p), nil 41 | } 42 | 43 | func (b *buffer) Read(d []byte) (int, error) { 44 | b.lock.Lock() 45 | defer b.lock.Unlock() 46 | 47 | if b.closed { 48 | return 0, fmt.Errorf("attempt to read from closed buffer") 49 | } 50 | 51 | if uint64(len(b.contents)) <= b.readCursor { 52 | return 0, io.EOF 53 | } 54 | 55 | n := copy(d, b.contents[b.readCursor:]) 56 | b.readCursor += uint64(n) 57 | 58 | return n, nil 59 | } 60 | 61 | func (b *buffer) Close() error { 62 | b.lock.Lock() 63 | defer b.lock.Unlock() 64 | 65 | b.closed = true 66 | 67 | return nil 68 | } 69 | 70 | func (b *buffer) Closed() bool { 71 | b.lock.Lock() 72 | defer b.lock.Unlock() 73 | 74 | return b.closed 75 | } 76 | 77 | func (b *buffer) Contents() []byte { 78 | b.lock.Lock() 79 | defer b.lock.Unlock() 80 | 81 | contents := make([]byte, len(b.contents)) 82 | copy(contents, b.contents) 83 | return contents 84 | } 85 | 86 | func (b *buffer) ShouldSay(expr string) (bool, []byte) { 87 | b.lock.Lock() 88 | defer b.lock.Unlock() 89 | 90 | re := regexp.MustCompile(expr) 91 | 92 | unreadBytes := b.contents[b.readCursor:] 93 | copyOfUnreadBytes := make([]byte, len(unreadBytes)) 94 | copy(copyOfUnreadBytes, unreadBytes) 95 | 96 | loc := re.FindIndex(unreadBytes) 97 | 98 | if loc != nil { 99 | b.readCursor += uint64(loc[1]) 100 | return true, copyOfUnreadBytes 101 | } 102 | log.Fatalf("didnot find %s", expr) 103 | return false, copyOfUnreadBytes 104 | } 105 | -------------------------------------------------------------------------------- /tests/e2e.go: -------------------------------------------------------------------------------- 1 | package tests 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | type Logger struct{} 8 | 9 | func (l Logger) Section(msg string, f func()) { 10 | fmt.Printf("==> %s\n", msg) 11 | f() 12 | } 13 | 14 | func (l Logger) Debugf(msg string, args ...interface{}) { 15 | fmt.Printf(msg, args...) 16 | } 17 | -------------------------------------------------------------------------------- /tests/env.go: -------------------------------------------------------------------------------- 1 | package tests 2 | 3 | import ( 4 | "os" 5 | "strings" 6 | "testing" 7 | ) 8 | 9 | type Env struct { 10 | Namespace string 11 | } 12 | 13 | func BuildEnv(t *testing.T) Env { 14 | env := Env{ 15 | Namespace: os.Getenv("KNI_E2E_NAMESPACE"), 16 | } 17 | env.Validate(t) 18 | return env 19 | } 20 | 21 | func (e Env) Validate(t *testing.T) { 22 | errStrs := []string{} 23 | 24 | if len(e.Namespace) == 0 { 25 | errStrs = append(errStrs, "Expected Namespace to be non-empty") 26 | } 27 | 28 | if len(errStrs) > 0 { 29 | t.Fatalf("%s", strings.Join(errStrs, "\n")) 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /tests/inspect_test.go: -------------------------------------------------------------------------------- 1 | package tests 2 | 3 | import ( 4 | // "reflect" 5 | "strings" 6 | "testing" 7 | "time" 8 | ) 9 | 10 | func TestInspect(t *testing.T) { 11 | env := BuildEnv(t) 12 | logger := Logger{} 13 | kni := Kni{t, env.Namespace, logger} 14 | kubectl := Kubectl{t, env.Namespace, logger} 15 | 16 | yaml := ` 17 | apiVersion: serving.knative.dev/v1alpha1 18 | kind: Service 19 | metadata: 20 | name: testapp 21 | spec: 22 | template: 23 | spec: 24 | containers: 25 | - image: nimak/knative-sample-app:v3 26 | env: 27 | - name: NAME 28 | value: "John" 29 | ` 30 | 31 | cleanUp := func() { 32 | kubectl.RunWithOpts([]string{"delete", "-f", "-"}, RunOpts{AllowError: true, StdinReader: strings.NewReader(yaml)}) 33 | } 34 | 35 | cleanUp() 36 | defer cleanUp() 37 | 38 | logger.Section("deploy initial", func() { 39 | kubectl.RunWithOpts([]string{"apply", "-f", "-"}, RunOpts{StdinReader: strings.NewReader(yaml)}) 40 | }) 41 | 42 | logger.Section("check resources", func() { 43 | 44 | time.Sleep(1 * time.Second) 45 | 46 | out, _ := kni.RunWithOpts([]string{"inspect", "-s", "testapp"}, RunOpts{}) 47 | bufferReader := BufferReader(strings.NewReader(out)) 48 | 49 | resources := []string{ 50 | "Service", 51 | "Configuration", 52 | "Revision", 53 | "Deployment", 54 | "ReplicaSet", 55 | "Image", 56 | "PodAutoscaler", 57 | "Service", 58 | "ServerlessService", 59 | } 60 | 61 | for _, r := range resources { 62 | bufferReader.ShouldSay("testapp") 63 | bufferReader.ShouldSay(r) 64 | } 65 | }) 66 | } 67 | -------------------------------------------------------------------------------- /tests/kni.go: -------------------------------------------------------------------------------- 1 | package tests 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "io" 7 | "os" 8 | "os/exec" 9 | "strings" 10 | "testing" 11 | ) 12 | 13 | type Kni struct { 14 | t *testing.T 15 | namespace string 16 | l Logger 17 | } 18 | 19 | type RunOpts struct { 20 | NoNamespace bool 21 | AllowError bool 22 | StderrWriter io.Writer 23 | StdoutWriter io.Writer 24 | StdinReader io.Reader 25 | CancelCh chan struct{} 26 | } 27 | 28 | func (k Kni) Run(args []string) string { 29 | out, _ := k.RunWithOpts(args, RunOpts{}) 30 | return out 31 | } 32 | 33 | func (k Kni) RunWithOpts(args []string, opts RunOpts) (string, error) { 34 | if !opts.NoNamespace { 35 | args = append(args, []string{"-n", k.namespace}...) 36 | } 37 | 38 | k.l.Debugf("Running '%s'...\n", k.cmdDesc(args, opts)) 39 | 40 | cmdName := "kni" 41 | cmd := exec.Command(cmdName, args...) 42 | cmd.Stdin = opts.StdinReader 43 | 44 | var stderr, stdout bytes.Buffer 45 | 46 | if opts.StderrWriter != nil { 47 | cmd.Stderr = opts.StderrWriter 48 | } else { 49 | cmd.Stderr = &stderr 50 | } 51 | 52 | if opts.StdoutWriter != nil { 53 | cmd.Stdout = opts.StdoutWriter 54 | } else { 55 | cmd.Stdout = &stdout 56 | } 57 | 58 | if opts.CancelCh != nil { 59 | go func() { 60 | select { 61 | case <-opts.CancelCh: 62 | cmd.Process.Signal(os.Interrupt) 63 | } 64 | }() 65 | } 66 | 67 | err := cmd.Run() 68 | stdoutStr := stdout.String() 69 | 70 | if err != nil { 71 | err = fmt.Errorf("Execution error: stdout: '%s' stderr: '%s' error: '%s'", stdoutStr, stderr.String(), err) 72 | 73 | if !opts.AllowError { 74 | k.t.Fatalf("Failed to successfully execute '%s': %v", k.cmdDesc(args, opts), err) 75 | } 76 | } 77 | 78 | return stdoutStr, err 79 | } 80 | 81 | func (k Kni) cmdDesc(args []string, opts RunOpts) string { 82 | prefix := "kni" 83 | return fmt.Sprintf("%s %s", prefix, strings.Join(args, " ")) 84 | } 85 | -------------------------------------------------------------------------------- /tests/kube_version_test.go: -------------------------------------------------------------------------------- 1 | package tests 2 | 3 | import ( 4 | "strings" 5 | "testing" 6 | ) 7 | 8 | func TestKubeVersion(t *testing.T) { 9 | env := BuildEnv(t) 10 | kni := Kni{t, env.Namespace, Logger{}} 11 | 12 | out, _ := kni.RunWithOpts([]string{"kube-version"}, RunOpts{NoNamespace: true}) 13 | 14 | if !strings.Contains(out, "Kubernetes Version: 1.") { 15 | t.Fatalf("Expected to find kubernetes version") 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /tests/kubectl.go: -------------------------------------------------------------------------------- 1 | package tests 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "os" 7 | "os/exec" 8 | "strings" 9 | "testing" 10 | ) 11 | 12 | type Kubectl struct { 13 | t *testing.T 14 | namespace string 15 | l Logger 16 | } 17 | 18 | func (k Kubectl) Run(args []string) string { 19 | out, _ := k.RunWithOpts(args, RunOpts{}) 20 | return out 21 | } 22 | 23 | func (k Kubectl) RunWithOpts(args []string, opts RunOpts) (string, error) { 24 | if !opts.NoNamespace { 25 | args = append(args, []string{"-n", k.namespace}...) 26 | } 27 | 28 | k.l.Debugf("Running '%s'...\n", k.cmdDesc(args)) 29 | 30 | var stderr bytes.Buffer 31 | var stdout bytes.Buffer 32 | 33 | cmd := exec.Command("kubectl", args...) 34 | cmd.Stderr = &stderr 35 | 36 | if opts.CancelCh != nil { 37 | go func() { 38 | select { 39 | case <-opts.CancelCh: 40 | cmd.Process.Signal(os.Interrupt) 41 | } 42 | }() 43 | } 44 | 45 | if opts.StdoutWriter != nil { 46 | cmd.Stdout = opts.StdoutWriter 47 | } else { 48 | cmd.Stdout = &stdout 49 | } 50 | 51 | cmd.Stdin = opts.StdinReader 52 | 53 | err := cmd.Run() 54 | if err != nil { 55 | err = fmt.Errorf("Execution error: stderr: '%s' error: '%s'", stderr.String(), err) 56 | 57 | if !opts.AllowError { 58 | k.t.Fatalf("Failed to successfully execute '%s': %v", k.cmdDesc(args), err) 59 | } 60 | } 61 | 62 | return stdout.String(), err 63 | } 64 | 65 | func (k Kubectl) cmdDesc(args []string) string { 66 | return fmt.Sprintf("kubectl %s", strings.Join(args, " ")) 67 | } 68 | -------------------------------------------------------------------------------- /tests/version_test.go: -------------------------------------------------------------------------------- 1 | package tests 2 | 3 | import ( 4 | "strings" 5 | "testing" 6 | ) 7 | 8 | func TestVersion(t *testing.T) { 9 | env := BuildEnv(t) 10 | kni := Kni{t, env.Namespace, Logger{}} 11 | 12 | out, _ := kni.RunWithOpts([]string{"version"}, RunOpts{NoNamespace: true}) 13 | 14 | if !strings.Contains(out, "Client Version") { 15 | t.Fatalf("Expected to find client version") 16 | } 17 | } 18 | --------------------------------------------------------------------------------