Skip to content

Commit e27fb87

Browse files
authored
Merge pull request #1834 from rexagod/1791-1-incorporate-cobra
Incorporate Cobra
2 parents 8096b31 + b926fd9 commit e27fb87

File tree

8 files changed

+265
-103
lines changed

8 files changed

+265
-103
lines changed

docs/cli-arguments.md

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,18 @@ spec:
2424
[embedmd]:# (../help.txt)
2525
```txt
2626
$ kube-state-metrics -h
27-
Usage of ./kube-state-metrics:
27+
kube-state-metrics is a simple service that listens to the Kubernetes API server and generates metrics about the state of the objects.
28+
29+
Usage:
30+
kube-state-metrics [flags]
31+
kube-state-metrics [command]
32+
33+
Available Commands:
34+
completion Generate completion script for kube-state-metrics.
35+
help Help about any command
36+
version Print version information.
37+
38+
Flags:
2839
--add_dir_header If true, adds the file directory to the header of the log messages
2940
--alsologtostderr log to standard error as well as files (no effect when -logtostderr=true)
3041
--apiserver string The URL of the apiserver to use as a master
@@ -65,4 +76,6 @@ Usage of ./kube-state-metrics:
6576
-v, --v Level number for the log level verbosity
6677
--version kube-state-metrics build version information
6778
--vmodule moduleSpec comma-separated list of pattern=N settings for file-filtered logging
79+
80+
Use "kube-state-metrics [command] --help" for more information about a command.
6881
```

go.mod

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ require (
1414
github.com/prometheus/common v0.37.0
1515
github.com/prometheus/exporter-toolkit v0.8.1
1616
github.com/robfig/cron/v3 v3.0.1
17-
github.com/spf13/pflag v1.0.5
17+
github.com/spf13/cobra v1.6.1
1818
github.com/stretchr/testify v1.8.1
1919
golang.org/x/perf v0.0.0-20220920022801-e8d778a60d07
2020
gopkg.in/yaml.v3 v3.0.1
@@ -62,6 +62,7 @@ require (
6262
github.com/google/gofuzz v1.1.0 // indirect
6363
github.com/google/safehtml v0.0.2 // indirect
6464
github.com/imdario/mergo v0.3.6 // indirect
65+
github.com/inconshreveable/mousetrap v1.0.1 // indirect
6566
github.com/josharian/intern v1.0.0 // indirect
6667
github.com/jpillora/backoff v1.0.0 // indirect
6768
github.com/json-iterator/go v1.1.12 // indirect
@@ -76,6 +77,7 @@ require (
7677
github.com/pkg/errors v0.9.1 // indirect
7778
github.com/pmezard/go-difflib v1.0.0 // indirect
7879
github.com/prometheus/procfs v0.8.0 // indirect
80+
github.com/spf13/pflag v1.0.5 // indirect
7981
golang.org/x/crypto v0.0.0-20221012134737-56aed061732a // indirect
8082
golang.org/x/net v0.0.0-20220909164309-bea034e7d591 // indirect
8183
golang.org/x/oauth2 v0.0.0-20220909003341-f21342109be1 // indirect

go.sum

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,7 @@ github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnht
110110
github.com/cncf/xds/go v0.0.0-20210312221358-fbca930ec8ed/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs=
111111
github.com/coreos/go-systemd/v22 v22.4.0 h1:y9YHcjnjynCd/DVbg5j9L/33jQM3MxJlbj/zWskzfGU=
112112
github.com/coreos/go-systemd/v22 v22.4.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
113+
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
113114
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
114115
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
115116
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
@@ -275,6 +276,8 @@ github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:
275276
github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
276277
github.com/imdario/mergo v0.3.6 h1:xTNEAn+kxVO7dTZGu0CegyqKZmoWFI0rF8UxjlB2d28=
277278
github.com/imdario/mergo v0.3.6/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA=
279+
github.com/inconshreveable/mousetrap v1.0.1 h1:U3uMjPSQEBMNp1lFxmllqCPM6P5u/Xq7Pgzkat/bFNc=
280+
github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
278281
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
279282
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
280283
github.com/jpillora/backoff v1.0.0 h1:uvFg412JmmHBHw7iwprIxkPMI+sGQ4kzOWsMeHnm2EA=
@@ -383,6 +386,7 @@ github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFR
383386
github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=
384387
github.com/rogpeppe/go-internal v1.8.1 h1:geMPLpDpQOgVyCg5z5GoRwLHepNdb71NXb67XFkP+Eg=
385388
github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o=
389+
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
386390
github.com/ruudk/golang-pdf417 v0.0.0-20181029194003-1af4ab5afa58/go.mod h1:6lfFZQK844Gfx8o5WFuvpxWRwnSoipWe/p622j1v06w=
387391
github.com/ruudk/golang-pdf417 v0.0.0-20201230142125-a7e3863a1245/go.mod h1:pQAZKsJ8yyVxGRWYNEm9oFB8ieLgKFnamEyDmSA0BRk=
388392
github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0=
@@ -391,6 +395,8 @@ github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPx
391395
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
392396
github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88=
393397
github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
398+
github.com/spf13/cobra v1.6.1 h1:o94oiPyS4KD1mPy2fmcYYHHfCxLqYjJOhGsCHFZtEzA=
399+
github.com/spf13/cobra v1.6.1/go.mod h1:IOw/AERYS7UzyrGinqmz6HLUo219MORXGxhbaJUqzrY=
394400
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
395401
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
396402
github.com/stoewer/go-strcase v1.2.0/go.mod h1:IBiWB2sKIp3wVVQ3Y035++gc+knqhUQag1KpM8ahLw8=

main.go

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -18,46 +18,41 @@ package main
1818

1919
import (
2020
"context"
21-
"fmt"
2221
"os"
2322
"path/filepath"
2423
"strings"
2524

26-
"github.com/prometheus/common/version"
25+
"github.com/spf13/cobra"
2726
"gopkg.in/yaml.v3"
2827
"k8s.io/klog/v2"
2928

29+
"k8s.io/kube-state-metrics/v2/pkg/app"
3030
"k8s.io/kube-state-metrics/v2/pkg/customresource"
3131
"k8s.io/kube-state-metrics/v2/pkg/customresourcestate"
3232

33-
"k8s.io/kube-state-metrics/v2/pkg/app"
3433
"k8s.io/kube-state-metrics/v2/pkg/options"
3534
)
3635

3736
func main() {
3837
opts := options.NewOptions()
39-
opts.AddFlags()
38+
cmd := options.InitCommand
39+
cmd.Run = func(cmd *cobra.Command, args []string) {
40+
RunKubeStateMetricsWrapper(opts)
41+
}
42+
opts.AddFlags(cmd)
4043

4144
if err := opts.Parse(); err != nil {
42-
klog.ErrorS(err, "Parsing flag definitions error")
4345
klog.FlushAndExit(klog.ExitFlushTimeout, 1)
4446
}
4547

46-
if opts.Version {
47-
fmt.Printf("%s\n", version.Print("kube-state-metrics"))
48-
os.Exit(0)
49-
}
50-
51-
if opts.Help {
52-
opts.Usage()
53-
os.Exit(0)
54-
}
55-
5648
if err := opts.Validate(); err != nil {
5749
klog.ErrorS(err, "Validating options error")
5850
klog.FlushAndExit(klog.ExitFlushTimeout, 1)
5951
}
52+
}
6053

54+
// RunKubeStateMetricsWrapper is a wrapper around KSM, delegated to the root command.
55+
func RunKubeStateMetricsWrapper(opts *options.Options) {
6156
var factories []customresource.RegistryFactory
6257
if config, set := resolveCustomResourceConfig(opts); set {
6358
crf, err := customresourcestate.FromConfig(config)

pkg/options/autoload.go

Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
/*
2+
Copyright 2022 The Kubernetes Authors All rights reserved.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package options
18+
19+
import (
20+
"os"
21+
22+
"github.com/spf13/cobra"
23+
"k8s.io/klog/v2"
24+
)
25+
26+
const autoloadZsh = `Generate the autocompletion script for the zsh shell.
27+
28+
If shell completion is not already enabled in your environment you will need
29+
to enable it. You can execute the following once:
30+
31+
echo "autoload -U compinit; compinit" >> ~/.zshrc
32+
33+
To load completions in your current shell session:
34+
35+
source <(kube-state-metrics completion zsh); compdef _kube-state-metrics kube-state-metrics
36+
37+
To load completions for every new session, execute once:
38+
39+
#### Linux:
40+
41+
kube-state-metrics completion zsh > "${fpath[1]}/_kube-state-metrics"
42+
43+
#### macOS:
44+
45+
kube-state-metrics completion zsh > $(brew --prefix)/share/zsh/site-functions/_kube-state-metrics
46+
47+
You will need to start a new shell for this setup to take effect.
48+
49+
Usage:
50+
kube-state-metrics completion zsh [flags]
51+
52+
Flags:
53+
--no-descriptions disable completion descriptions
54+
`
55+
const autoloadBash = `Generate the autocompletion script for the bash shell.
56+
57+
This script depends on the 'bash-completion' package.
58+
If it is not installed already, you can install it via your OS's package manager.
59+
60+
To load completions in your current shell session:
61+
62+
source <(kube-state-metrics completion bash)
63+
64+
To load completions for every new session, execute once:
65+
66+
#### Linux:
67+
68+
kube-state-metrics completion bash > /etc/bash_completion.d/kube-state-metrics
69+
70+
#### macOS:
71+
72+
kube-state-metrics completion bash > $(brew --prefix)/etc/bash_completion.d/kube-state-metrics
73+
74+
You will need to start a new shell for this setup to take effect.
75+
76+
Usage:
77+
kube-state-metrics completion bash
78+
79+
Flags:
80+
--no-descriptions disable completion descriptions
81+
`
82+
83+
const autoloadFish = `Generate the autocompletion script for the fish shell.
84+
85+
To load completions in your current shell session:
86+
87+
kube-state-metrics completion fish | source
88+
89+
To load completions for every new session, execute once:
90+
91+
kube-state-metrics completion fish > ~/.config/fish/completions/kube-state-metrics.fish
92+
93+
You will need to start a new shell for this setup to take effect.
94+
95+
Usage:
96+
kube-state-metrics completion fish [flags]
97+
98+
Flags:
99+
--no-descriptions disable completion descriptions
100+
`
101+
102+
// FetchLoadInstructions returns instructions for enabling autocompletion for a particular shell.
103+
func FetchLoadInstructions(shell string) string {
104+
switch shell {
105+
case "zsh":
106+
return autoloadZsh
107+
case "bash":
108+
return autoloadBash
109+
case "fish":
110+
return autoloadFish
111+
default:
112+
return ""
113+
}
114+
}
115+
116+
var completionCommand = &cobra.Command{
117+
Use: "completion [bash|zsh|fish]",
118+
Short: "Generate completion script for kube-state-metrics.",
119+
DisableFlagsInUseLine: true,
120+
Aliases: []string{"comp", "c"},
121+
ValidArgs: []string{"bash", "zsh", "fish"},
122+
Args: cobra.ExactArgs(1),
123+
Run: func(cmd *cobra.Command, args []string) {
124+
switch args[0] {
125+
case "bash":
126+
_ = cmd.Root().GenBashCompletion(os.Stdout)
127+
case "zsh":
128+
_ = cmd.Root().GenZshCompletion(os.Stdout)
129+
case "fish":
130+
_ = cmd.Root().GenFishCompletion(os.Stdout, true)
131+
}
132+
klog.FlushAndExit(klog.ExitFlushTimeout, 0)
133+
},
134+
Example: "kube-state-metrics completion bash > /tmp/kube-state-metrics.bash && source /tmp/kube-state-metrics.bash # for shells compatible with bash",
135+
}
136+
137+
// InitCommand defines the root command that others will latch onto.
138+
var InitCommand = &cobra.Command{
139+
Use: "kube-state-metrics",
140+
Short: "Add-on agent to generate and expose cluster-level metrics.",
141+
Long: "kube-state-metrics is a simple service that listens to the Kubernetes API server and generates metrics about the state of the objects.",
142+
Args: cobra.NoArgs,
143+
}

0 commit comments

Comments
 (0)