Skip to content

Commit 9c986a7

Browse files
authored
make runPreflight and preflight cli flags public (#769)
1 parent e020749 commit 9c986a7

File tree

6 files changed

+129
-44
lines changed

6 files changed

+129
-44
lines changed

cmd/preflight/cli/root.go

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66

77
"github.com/go-logr/logr"
88
"github.com/replicatedhq/troubleshoot/pkg/k8sutil"
9+
"github.com/replicatedhq/troubleshoot/pkg/preflight"
910
"github.com/spf13/cobra"
1011
"github.com/spf13/viper"
1112
"k8s.io/klog/v2"
@@ -29,24 +30,14 @@ that a cluster meets the requirements to run an application.`,
2930
},
3031
RunE: func(cmd *cobra.Command, args []string) error {
3132
v := viper.GetViper()
32-
return runPreflights(v, args[0])
33+
return preflight.RunPreflights(v.GetBool("interactive"), v.GetString("output"), v.GetString("format"), args[0])
3334
},
3435
}
3536

3637
cobra.OnInitialize(initConfig)
3738

3839
cmd.AddCommand(VersionCmd())
39-
40-
cmd.Flags().Bool("interactive", true, "interactive preflights")
41-
cmd.Flags().String("format", "human", "output format, one of human, json, yaml. only used when interactive is set to false")
42-
cmd.Flags().String("collector-image", "", "the full name of the collector image to use")
43-
cmd.Flags().String("collector-pullpolicy", "", "the pull policy of the collector image")
44-
cmd.Flags().Bool("collect-without-permissions", true, "always run preflight checks even if some require permissions that preflight does not have")
45-
cmd.Flags().String("selector", "", "selector (label query) to filter remote collection nodes on.")
46-
cmd.Flags().String("since-time", "", "force pod logs collectors to return logs after a specific date (RFC3339)")
47-
cmd.Flags().String("since", "", "force pod logs collectors to return logs newer than a relative duration like 5s, 2m, or 3h.")
48-
cmd.Flags().StringP("output", "o", "", "specify the output file path for the preflight checks")
49-
cmd.Flags().Bool("debug", false, "enable debug logging")
40+
preflight.AddFlags(cmd.PersistentFlags())
5041

5142
viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
5243

pkg/preflight/flags.go

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
package preflight
2+
3+
import (
4+
flag "github.com/spf13/pflag"
5+
utilpointer "k8s.io/utils/pointer"
6+
)
7+
8+
const (
9+
flagInteractive = "interactive"
10+
flagFormat = "format"
11+
flagCollectorImage = "collector-image"
12+
flagCollectorPullPolicy = "collector-pullpolicy"
13+
flagCollectWithoutPermissions = "collect-without-permissions"
14+
flagSelector = "selector"
15+
flagSinceTime = "since-time"
16+
flagSince = "since"
17+
flagOutput = "output"
18+
flagDebug = "debug"
19+
)
20+
21+
type PreflightFlags struct {
22+
Interactive *bool
23+
Format *string
24+
CollectorImage *string
25+
CollectorPullPolicy *string
26+
CollectWithoutPermissions *bool
27+
Selector *string
28+
SinceTime *string
29+
Since *string
30+
Output *string
31+
Debug *bool
32+
}
33+
34+
var preflightFlags *PreflightFlags
35+
36+
func NewPreflightFlags() *PreflightFlags {
37+
return &PreflightFlags{
38+
Interactive: utilpointer.Bool(true),
39+
Format: utilpointer.String("human"),
40+
CollectorImage: utilpointer.String(""),
41+
CollectorPullPolicy: utilpointer.String(""),
42+
CollectWithoutPermissions: utilpointer.Bool(true),
43+
Selector: utilpointer.String(""),
44+
SinceTime: utilpointer.String(""),
45+
Since: utilpointer.String(""),
46+
Output: utilpointer.String("o"),
47+
Debug: utilpointer.Bool(false),
48+
}
49+
}
50+
51+
func AddFlags(flags *flag.FlagSet) {
52+
if preflightFlags == nil {
53+
preflightFlags = NewPreflightFlags()
54+
}
55+
56+
preflightFlags.addFlags(flags)
57+
}
58+
59+
// AddFlags binds client configuration flags to a given flagset
60+
func (f *PreflightFlags) addFlags(flags *flag.FlagSet) {
61+
if preflightFlags == nil {
62+
preflightFlags = NewPreflightFlags()
63+
}
64+
65+
if f.Interactive != nil {
66+
flags.BoolVar(f.Interactive, flagInteractive, *f.Interactive, "interactive preflights")
67+
}
68+
if f.Format != nil {
69+
flags.StringVar(f.Format, flagFormat, *f.Format, "output format, one of human, json, yaml. only used when interactive is set to false")
70+
}
71+
72+
if f.CollectorImage != nil {
73+
flags.StringVar(f.CollectorImage, flagCollectorImage, *f.CollectorImage, "the full name of the collector image to use")
74+
}
75+
if f.CollectorPullPolicy != nil {
76+
flags.StringVar(f.CollectorPullPolicy, flagCollectorPullPolicy, *f.CollectorPullPolicy, "the pull policy of the collector image")
77+
}
78+
if f.CollectWithoutPermissions != nil {
79+
flags.BoolVar(f.CollectWithoutPermissions, flagCollectWithoutPermissions, *f.CollectWithoutPermissions, "always run preflight checks even if some require permissions that preflight does not have")
80+
}
81+
if f.Selector != nil {
82+
flags.StringVar(f.Selector, flagSelector, *f.Selector, "selector (label query) to filter remote collection nodes on.")
83+
}
84+
if f.SinceTime != nil {
85+
flags.StringVar(f.SinceTime, flagSinceTime, *f.SinceTime, "force pod logs collectors to return logs after a specific date (RFC3339)")
86+
}
87+
if f.Since != nil {
88+
flags.StringVar(f.Since, flagSince, *f.Since, "force pod logs collectors to return logs newer than a relative duration like 5s, 2m, or 3h.")
89+
}
90+
if f.Output != nil {
91+
flags.StringVar(f.Output, flagOutput, *f.Output, "specify the output file path for the preflight checks")
92+
}
93+
if f.Debug != nil {
94+
flags.BoolVar(f.Debug, flagDebug, *f.Debug, "enable debug logging")
95+
}
96+
}

cmd/preflight/cli/interactive_results.go renamed to pkg/preflight/interactive_results.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package cli
1+
package preflight
22

33
import (
44
"fmt"

cmd/preflight/cli/run.go renamed to pkg/preflight/run.go

Lines changed: 20 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package cli
1+
package preflight
22

33
import (
44
"context"
@@ -21,7 +21,6 @@ import (
2121
"github.com/replicatedhq/troubleshoot/pkg/docrewrite"
2222
"github.com/replicatedhq/troubleshoot/pkg/k8sutil"
2323
"github.com/replicatedhq/troubleshoot/pkg/oci"
24-
"github.com/replicatedhq/troubleshoot/pkg/preflight"
2524
"github.com/replicatedhq/troubleshoot/pkg/specs"
2625
"github.com/spf13/viper"
2726
spin "github.com/tj/go-spin"
@@ -31,8 +30,8 @@ import (
3130
"k8s.io/client-go/kubernetes/scheme"
3231
)
3332

34-
func runPreflights(v *viper.Viper, arg string) error {
35-
if v.GetBool("interactive") {
33+
func RunPreflights(interactive bool, output, format, arg string) error {
34+
if interactive {
3635
fmt.Print(cursor.Hide())
3736
defer fmt.Print(cursor.Show())
3837
}
@@ -120,7 +119,7 @@ func runPreflights(v *viper.Viper, arg string) error {
120119
return errors.Wrapf(err, "failed to parse %s", arg)
121120
}
122121

123-
var collectResults []preflight.CollectResult
122+
var collectResults []CollectResult
124123
preflightSpecName := ""
125124

126125
progressCh := make(chan interface{})
@@ -131,7 +130,7 @@ func runPreflights(v *viper.Viper, arg string) error {
131130
defer stopProgressCollection()
132131
progressCollection, ctx := errgroup.WithContext(ctx)
133132

134-
if v.GetBool("interactive") {
133+
if interactive {
135134
progressCollection.Go(collectInteractiveProgress(ctx, progressCh))
136135
} else {
137136
progressCollection.Go(collectNonInteractiveProgess(ctx, progressCh))
@@ -183,14 +182,14 @@ func runPreflights(v *viper.Viper, arg string) error {
183182
stopProgressCollection()
184183
progressCollection.Wait()
185184

186-
if v.GetBool("interactive") {
185+
if interactive {
187186
if len(analyzeResults) == 0 {
188187
return errors.New("no data has been collected")
189188
}
190-
return showInteractiveResults(preflightSpecName, v.GetString("output"), analyzeResults)
189+
return showInteractiveResults(preflightSpecName, output, analyzeResults)
191190
}
192191

193-
return showStdoutResults(v.GetString("format"), preflightSpecName, analyzeResults)
192+
return showStdoutResults(format, preflightSpecName, analyzeResults)
194193
}
195194

196195
func collectInteractiveProgress(ctx context.Context, progressCh <-chan interface{}) func() error {
@@ -235,7 +234,7 @@ func collectNonInteractiveProgess(ctx context.Context, progressCh <-chan interfa
235234
fmt.Fprintf(os.Stderr, "error - %v\n", msg)
236235
case string:
237236
fmt.Fprintf(os.Stderr, "%s\n", msg)
238-
case preflight.CollectProgress:
237+
case CollectProgress:
239238
fmt.Fprintf(os.Stderr, "%s\n", msg.String())
240239

241240
}
@@ -246,15 +245,15 @@ func collectNonInteractiveProgess(ctx context.Context, progressCh <-chan interfa
246245
}
247246
}
248247

249-
func collectInCluster(preflightSpec *troubleshootv1beta2.Preflight, progressCh chan interface{}) (*preflight.CollectResult, error) {
248+
func collectInCluster(preflightSpec *troubleshootv1beta2.Preflight, progressCh chan interface{}) (*CollectResult, error) {
250249
v := viper.GetViper()
251250

252251
restConfig, err := k8sutil.GetRESTConfig()
253252
if err != nil {
254253
return nil, errors.Wrap(err, "failed to convert kube flags to rest config")
255254
}
256255

257-
collectOpts := preflight.CollectOpts{
256+
collectOpts := CollectOpts{
258257
Namespace: v.GetString("namespace"),
259258
IgnorePermissionErrors: v.GetBool("collect-without-permissions"),
260259
ProgressChan: progressCh,
@@ -268,11 +267,11 @@ func collectInCluster(preflightSpec *troubleshootv1beta2.Preflight, progressCh c
268267
}
269268
}
270269

271-
collectResults, err := preflight.Collect(collectOpts, preflightSpec)
270+
collectResults, err := Collect(collectOpts, preflightSpec)
272271
if err != nil {
273-
if !collectResults.IsRBACAllowed() {
272+
if collectResults != nil && !collectResults.IsRBACAllowed() {
274273
if preflightSpec.Spec.UploadResultsTo != "" {
275-
clusterCollectResults := collectResults.(preflight.ClusterCollectResult)
274+
clusterCollectResults := collectResults.(ClusterCollectResult)
276275
err := uploadErrors(preflightSpec.Spec.UploadResultsTo, clusterCollectResults.Collectors)
277276
if err != nil {
278277
progressCh <- err
@@ -285,7 +284,7 @@ func collectInCluster(preflightSpec *troubleshootv1beta2.Preflight, progressCh c
285284
return &collectResults, nil
286285
}
287286

288-
func collectRemote(preflightSpec *troubleshootv1beta2.HostPreflight, progressCh chan interface{}) (*preflight.CollectResult, error) {
287+
func collectRemote(preflightSpec *troubleshootv1beta2.HostPreflight, progressCh chan interface{}) (*CollectResult, error) {
289288
v := viper.GetViper()
290289

291290
restConfig, err := k8sutil.GetRESTConfig()
@@ -308,7 +307,7 @@ func collectRemote(preflightSpec *troubleshootv1beta2.HostPreflight, progressCh
308307
timeout = 30 * time.Second
309308
}
310309

311-
collectOpts := preflight.CollectOpts{
310+
collectOpts := CollectOpts{
312311
Namespace: namespace,
313312
IgnorePermissionErrors: v.GetBool("collect-without-permissions"),
314313
ProgressChan: progressCh,
@@ -319,20 +318,20 @@ func collectRemote(preflightSpec *troubleshootv1beta2.HostPreflight, progressCh
319318
Timeout: timeout,
320319
}
321320

322-
collectResults, err := preflight.CollectRemote(collectOpts, preflightSpec)
321+
collectResults, err := CollectRemote(collectOpts, preflightSpec)
323322
if err != nil {
324323
return nil, errors.Wrap(err, "failed to collect from remote")
325324
}
326325

327326
return &collectResults, nil
328327
}
329328

330-
func collectHost(hostPreflightSpec *troubleshootv1beta2.HostPreflight, progressCh chan interface{}) (*preflight.CollectResult, error) {
331-
collectOpts := preflight.CollectOpts{
329+
func collectHost(hostPreflightSpec *troubleshootv1beta2.HostPreflight, progressCh chan interface{}) (*CollectResult, error) {
330+
collectOpts := CollectOpts{
332331
ProgressChan: progressCh,
333332
}
334333

335-
collectResults, err := preflight.CollectHost(collectOpts, hostPreflightSpec)
334+
collectResults, err := CollectHost(collectOpts, hostPreflightSpec)
336335
if err != nil {
337336
return nil, errors.Wrap(err, "failed to collect from host")
338337
}

cmd/preflight/cli/stdout_results.go renamed to pkg/preflight/stdout_results.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package cli
1+
package preflight
22

33
import (
44
"encoding/json"

cmd/preflight/cli/upload_results.go renamed to pkg/preflight/upload_results.go

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package cli
1+
package preflight
22

33
import (
44
"bytes"
@@ -8,15 +8,14 @@ import (
88
"github.com/pkg/errors"
99
analyzerunner "github.com/replicatedhq/troubleshoot/pkg/analyze"
1010
"github.com/replicatedhq/troubleshoot/pkg/collect"
11-
"github.com/replicatedhq/troubleshoot/pkg/preflight"
1211
)
1312

1413
func uploadResults(uri string, analyzeResults []*analyzerunner.AnalyzeResult) error {
15-
uploadPreflightResults := &preflight.UploadPreflightResults{
16-
Results: []*preflight.UploadPreflightResult{},
14+
uploadPreflightResults := &UploadPreflightResults{
15+
Results: []*UploadPreflightResult{},
1716
}
1817
for _, analyzeResult := range analyzeResults {
19-
uploadPreflightResult := &preflight.UploadPreflightResult{
18+
uploadPreflightResult := &UploadPreflightResult{
2019
Strict: analyzeResult.Strict,
2120
IsFail: analyzeResult.IsFail,
2221
IsWarn: analyzeResult.IsWarn,
@@ -33,23 +32,23 @@ func uploadResults(uri string, analyzeResults []*analyzerunner.AnalyzeResult) er
3332
}
3433

3534
func uploadErrors(uri string, collectors []collect.Collector) error {
36-
errors := []*preflight.UploadPreflightError{}
35+
errors := []*UploadPreflightError{}
3736
for _, collector := range collectors {
3837
for _, e := range collector.GetRBACErrors() {
39-
errors = append(errors, &preflight.UploadPreflightError{
38+
errors = append(errors, &UploadPreflightError{
4039
Error: e.Error(),
4140
})
4241
}
4342
}
4443

45-
results := &preflight.UploadPreflightResults{
44+
results := &UploadPreflightResults{
4645
Errors: errors,
4746
}
4847

4948
return upload(uri, results)
5049
}
5150

52-
func upload(uri string, payload *preflight.UploadPreflightResults) error {
51+
func upload(uri string, payload *UploadPreflightResults) error {
5352
b, err := json.Marshal(payload)
5453
if err != nil {
5554
return errors.Wrap(err, "failed to marshal payload")

0 commit comments

Comments
 (0)