Skip to content

Commit 8119718

Browse files
authored
cmd/catalog: Migrate to using cobra for CLI flag management (#2362)
* cmd/catalog: Migrate to using cobra for CLI flag management Update the cmd/catalog/main.go and use cobra's CLI library for managing CLI executables and parsing flags. Introduce cmd/catalog/start.go which is responsible for returning a populated command.Command structure that the main function can call and execute. Signed-off-by: timflannagan <[email protected]> * deploy/chart: Use double-hyphen for CLI catalog operator flags Signed-off-by: timflannagan <[email protected]>
1 parent 103ed08 commit 8119718

File tree

4 files changed

+138
-82
lines changed

4 files changed

+138
-82
lines changed

cmd/catalog/main.go

+48-76
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,13 @@ package main
22

33
import (
44
"context"
5-
"flag"
65
"fmt"
76
"net/http"
87
"os"
98
"time"
109

1110
configv1client "github.com/openshift/client-go/config/clientset/versioned/typed/config/v1"
12-
log "github.com/sirupsen/logrus"
11+
"github.com/sirupsen/logrus"
1312
utilclock "k8s.io/apimachinery/pkg/util/clock"
1413
k8sscheme "k8s.io/client-go/kubernetes/scheme"
1514
"k8s.io/client-go/tools/clientcmd"
@@ -20,9 +19,7 @@ import (
2019
"github.com/operator-framework/operator-lifecycle-manager/pkg/lib/operatorclient"
2120
"github.com/operator-framework/operator-lifecycle-manager/pkg/lib/operatorstatus"
2221
"github.com/operator-framework/operator-lifecycle-manager/pkg/lib/server"
23-
"github.com/operator-framework/operator-lifecycle-manager/pkg/lib/signals"
2422
"github.com/operator-framework/operator-lifecycle-manager/pkg/metrics"
25-
olmversion "github.com/operator-framework/operator-lifecycle-manager/pkg/version"
2623
)
2724

2825
const (
@@ -36,80 +33,33 @@ const (
3633
)
3734

3835
// config flags defined globally so that they appear on the test binary as well
39-
var (
40-
kubeConfigPath = flag.String(
41-
"kubeconfig", os.Getenv("KUBECONFIG"), "absolute path to the kubeconfig file")
42-
43-
wakeupInterval = flag.Duration(
44-
"interval", defaultWakeupInterval, "wakeup interval")
45-
46-
catalogNamespace = flag.String(
47-
"namespace", defaultCatalogNamespace, "namespace where catalog will run and install catalog resources")
48-
49-
configmapServerImage = flag.String(
50-
"configmapServerImage", defaultConfigMapServerImage, "the image to use for serving the operator registry api for a configmap")
51-
52-
opmImage = flag.String(
53-
"opmImage", defaultOPMImage, "the image to use for unpacking bundle content with opm")
54-
55-
utilImage = flag.String(
56-
"util-image", defaultUtilImage, "an image containing custom olm utilities")
57-
58-
writeStatusName = flag.String(
59-
"writeStatusName", defaultOperatorName, "ClusterOperator name in which to write status, set to \"\" to disable.")
60-
61-
debug = flag.Bool(
62-
"debug", false, "use debug log level")
63-
64-
version = flag.Bool("version", false, "displays olm version")
65-
66-
tlsKeyPath = flag.String(
67-
"tls-key", "", "Path to use for private key (requires tls-cert)")
68-
69-
tlsCertPath = flag.String(
70-
"tls-cert", "", "Path to use for certificate key (requires tls-key)")
71-
72-
_ = flag.Bool("profiling", false, "deprecated")
73-
74-
clientCAPath = flag.String("client-ca", "", "path to watch for client ca bundle")
75-
76-
installPlanTimeout = flag.Duration("install-plan-retry-timeout", 1*time.Minute, "time since first attempt at which plan execution errors are considered fatal")
77-
bundleUnpackTimeout = flag.Duration("bundle-unpack-timeout", 10*time.Minute, "The time limit for bundle unpacking, after which InstallPlan execution is considered to have failed. 0 is considered as having no timeout.")
78-
)
7936

8037
func init() {
8138
metrics.RegisterCatalog()
8239
}
8340

8441
func main() {
85-
// Get exit signal context
86-
ctx, cancel := context.WithCancel(signals.Context())
87-
defer cancel()
88-
89-
// Parse the command-line flags.
90-
flag.Parse()
91-
92-
// Check if version flag was set
93-
if *version {
94-
fmt.Print(olmversion.String())
95-
os.Exit(0)
96-
}
97-
98-
logger := log.New()
99-
if *debug {
100-
logger.SetLevel(log.DebugLevel)
42+
cmd := newRootCmd()
43+
if err := cmd.Execute(); err != nil {
44+
fmt.Fprintln(os.Stderr, err)
45+
os.Exit(1)
10146
}
102-
logger.Infof("log level %s", logger.Level)
47+
}
10348

49+
func (o *options) run(ctx context.Context, logger *logrus.Logger) error {
10450
// If the catalogNamespaceEnvVarName environment variable is set, then update the value of catalogNamespace.
10551
if catalogNamespaceEnvVarValue := os.Getenv(catalogNamespaceEnvVarName); catalogNamespaceEnvVarValue != "" {
10652
logger.Infof("%s environment variable is set. Updating Global Catalog Namespace to %s", catalogNamespaceEnvVarName, catalogNamespaceEnvVarValue)
107-
*catalogNamespace = catalogNamespaceEnvVarValue
53+
o.catalogNamespace = catalogNamespaceEnvVarValue
10854
}
10955

110-
listenAndServe, err := server.GetListenAndServeFunc(server.WithLogger(logger), server.WithTLS(tlsCertPath, tlsKeyPath, clientCAPath), server.WithDebug(*debug))
56+
listenAndServe, err := server.GetListenAndServeFunc(
57+
server.WithLogger(logger),
58+
server.WithTLS(&o.tlsCertPath, &o.tlsKeyPath, &o.clientCAPath),
59+
server.WithDebug(o.debug),
60+
)
11161
if err != nil {
112-
logger.Fatalf("Error setting up health/metric/pprof service: %v", err)
62+
return fmt.Errorf("error setting up health/metric/pprof service: %v", err)
11363
}
11464

11565
go func() {
@@ -119,29 +69,49 @@ func main() {
11969
}()
12070

12171
// create a config client for operator status
122-
config, err := clientcmd.BuildConfigFromFlags("", *kubeConfigPath)
72+
config, err := clientcmd.BuildConfigFromFlags("", o.kubeconfig)
12373
if err != nil {
124-
log.Fatalf("error configuring client: %s", err.Error())
74+
return fmt.Errorf("error configuring client: %s", err.Error())
12575
}
12676
configClient, err := configv1client.NewForConfig(config)
12777
if err != nil {
128-
log.Fatalf("error configuring client: %s", err.Error())
78+
return fmt.Errorf("error configuring client: %s", err.Error())
12979
}
130-
opClient := operatorclient.NewClientFromConfig(*kubeConfigPath, logger)
131-
crClient, err := client.NewClient(*kubeConfigPath)
80+
opClient := operatorclient.NewClientFromConfig(o.kubeconfig, logger)
81+
crClient, err := client.NewClient(o.kubeconfig)
13282
if err != nil {
133-
log.Fatalf("error configuring client: %s", err.Error())
83+
return fmt.Errorf("error configuring client: %s", err.Error())
13484
}
13585

86+
// TODO(tflannag): Use options pattern for catalog operator
13687
// Create a new instance of the operator.
137-
op, err := catalog.NewOperator(ctx, *kubeConfigPath, utilclock.RealClock{}, logger, *wakeupInterval, *configmapServerImage, *opmImage, *utilImage, *catalogNamespace, k8sscheme.Scheme, *installPlanTimeout, *bundleUnpackTimeout)
88+
op, err := catalog.NewOperator(
89+
ctx,
90+
o.kubeconfig,
91+
utilclock.RealClock{},
92+
logger,
93+
o.wakeupInterval,
94+
o.configMapServerImage,
95+
o.opmImage,
96+
o.utilImage,
97+
o.catalogNamespace,
98+
k8sscheme.Scheme,
99+
o.installPlanTimeout,
100+
o.bundleUnpackTimeout,
101+
)
138102
if err != nil {
139-
log.Fatalf("error configuring catalog operator: %s", err.Error())
103+
return fmt.Errorf("error configuring catalog operator: %s", err.Error())
140104
}
141105

142-
opCatalogTemplate, err := catalogtemplate.NewOperator(ctx, *kubeConfigPath, logger, *wakeupInterval, *catalogNamespace)
106+
opCatalogTemplate, err := catalogtemplate.NewOperator(
107+
ctx,
108+
o.kubeconfig,
109+
logger,
110+
o.wakeupInterval,
111+
o.catalogNamespace,
112+
)
143113
if err != nil {
144-
log.Fatalf("error configuring catalog template operator: %s", err.Error())
114+
return fmt.Errorf("error configuring catalog template operator: %s", err.Error())
145115
}
146116

147117
op.Run(ctx)
@@ -150,9 +120,11 @@ func main() {
150120
opCatalogTemplate.Run(ctx)
151121
<-opCatalogTemplate.Ready()
152122

153-
if *writeStatusName != "" {
154-
operatorstatus.MonitorClusterStatus(*writeStatusName, op.AtLevel(), op.Done(), opClient, configClient, crClient)
123+
if o.writeStatusName != "" {
124+
operatorstatus.MonitorClusterStatus(o.writeStatusName, op.AtLevel(), op.Done(), opClient, configClient, crClient)
155125
}
156126

157127
<-op.Done()
128+
129+
return nil
158130
}

cmd/catalog/start.go

+84
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
package main
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"os"
7+
"time"
8+
9+
"github.com/operator-framework/operator-lifecycle-manager/pkg/lib/signals"
10+
olmversion "github.com/operator-framework/operator-lifecycle-manager/pkg/version"
11+
"github.com/sirupsen/logrus"
12+
"github.com/spf13/cobra"
13+
)
14+
15+
type options struct {
16+
kubeconfig string
17+
catalogNamespace string
18+
configMapServerImage string
19+
opmImage string
20+
utilImage string
21+
writeStatusName string
22+
debug bool
23+
version bool
24+
profiling bool
25+
tlsKeyPath string
26+
tlsCertPath string
27+
clientCAPath string
28+
29+
installPlanTimeout time.Duration
30+
bundleUnpackTimeout time.Duration
31+
wakeupInterval time.Duration
32+
}
33+
34+
func newRootCmd() *cobra.Command {
35+
o := options{}
36+
37+
cmd := &cobra.Command{
38+
Use: "Start",
39+
Short: "Starts the Catalog Operator",
40+
SilenceUsage: true,
41+
RunE: func(cmd *cobra.Command, args []string) error {
42+
if o.version {
43+
fmt.Print(olmversion.String())
44+
return nil
45+
}
46+
47+
logger := logrus.New()
48+
if o.debug {
49+
logger.SetLevel(logrus.DebugLevel)
50+
}
51+
logger.Infof("log level %s", logger.Level)
52+
53+
ctx, cancel := context.WithCancel(signals.Context())
54+
defer cancel()
55+
56+
if err := o.run(ctx, logger); err != nil {
57+
return err
58+
}
59+
return nil
60+
},
61+
}
62+
63+
cmd.Flags().StringVar(&o.kubeconfig, "kubeconfig", os.Getenv("KUBECONFIG"), "absolute path to the kubeconfig file")
64+
cmd.Flags().StringVar(&o.catalogNamespace, "namespace", defaultCatalogNamespace, "namespace where catalog will run and install catalog resources")
65+
cmd.Flags().StringVar(&o.configMapServerImage, "configmapServerImage", defaultConfigMapServerImage, "the image to use for serving the operator registry api for a configmap")
66+
cmd.Flags().StringVar(&o.opmImage, "opmImage", defaultOPMImage, "the image to use for unpacking bundle content with opm")
67+
cmd.Flags().StringVar(&o.utilImage, "util-image", defaultUtilImage, "an image containing custom olm utilities")
68+
cmd.Flags().StringVar(&o.writeStatusName, "writeStatusName", defaultOperatorName, "ClusterOperator name in which to write status, set to \"\" to disable.")
69+
70+
cmd.Flags().BoolVar(&o.debug, "debug", false, "use debug log level")
71+
cmd.Flags().BoolVar(&o.version, "version", false, "displays the olm version")
72+
cmd.Flags().BoolVar(&o.profiling, "profiling", false, "deprecated")
73+
cmd.Flags().MarkDeprecated("profiling", "profiling is now enabled by default")
74+
75+
cmd.Flags().StringVar(&o.tlsKeyPath, "tls-key", "", "path to use for private key (requires tls-cert)")
76+
cmd.Flags().StringVar(&o.tlsCertPath, "tls-cert", "", "path to use for certificate key (requires tls-key)")
77+
cmd.Flags().StringVar(&o.clientCAPath, "client-ca", "", "path to watch for client ca bundle")
78+
79+
cmd.Flags().DurationVar(&o.wakeupInterval, "interval", defaultWakeupInterval, "wakeup interval")
80+
cmd.Flags().DurationVar(&o.bundleUnpackTimeout, "bundle-unpack-timeout", 10*time.Minute, "The time limit for bundle unpacking, after which InstallPlan execution is considered to have failed. 0 is considered as having no timeout.")
81+
cmd.Flags().DurationVar(&o.installPlanTimeout, "install-plan-retry-timeout", 1*time.Minute, "time since first attempt at which plan execution errors are considered fatal")
82+
83+
return cmd
84+
}

deploy/chart/templates/0000_50_olm_08-catalog-operator.deployment.yaml

+5-5
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ spec:
1919
spec:
2020
serviceAccountName: olm-operator-serviceaccount
2121
{{- if or .Values.catalog.tlsSecret .Values.catalog.clientCASecret }}
22-
volumes:
22+
volumes:
2323
{{- end }}
2424
{{- if .Values.catalog.tlsSecret }}
2525
- name: srv-cert
@@ -49,21 +49,21 @@ spec:
4949
command:
5050
- /bin/catalog
5151
args:
52-
- '-namespace'
52+
- '--namespace'
5353
- {{ .Values.catalog_namespace }}
5454
{{- if .Values.debug }}
55-
- '-debug'
55+
- '--debug'
5656
{{- end }}
5757
{{- if .Values.catalog.commandArgs }}
5858
- {{ .Values.catalog.commandArgs }}
5959
{{- end }}
6060
{{- if .Values.catalog.opmImageArgs }}
6161
- {{ .Values.catalog.opmImageArgs }}
6262
{{- end }}
63-
- -util-image
63+
- --util-image
6464
- {{ .Values.catalog.image.ref }}
6565
{{- if .Values.writeStatusNameCatalog }}
66-
- -writeStatusName
66+
- --writeStatusName
6767
- {{ .Values.writeStatusNameCatalog }}
6868
{{- end }}
6969
{{- if .Values.catalog.tlsSecret }}

deploy/chart/values.yaml

+1-1
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ olm:
2626

2727
catalog:
2828
replicaCount: 1
29-
commandArgs: -configmapServerImage=quay.io/operator-framework/configmap-operator-registry:latest
29+
commandArgs: --configmapServerImage=quay.io/operator-framework/configmap-operator-registry:latest
3030
image:
3131
ref: quay.io/operator-framework/olm:master
3232
pullPolicy: Always

0 commit comments

Comments
 (0)