Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add output format flag to the k0s sysinfo command #5264

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
132 changes: 121 additions & 11 deletions cmd/sysinfo/sysinfo.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ limitations under the License.
package sysinfo

import (
"encoding/json"
"errors"
"fmt"
"io"
"strings"

Expand All @@ -28,11 +30,13 @@ import (
"github.com/logrusorgru/aurora/v3"
"github.com/spf13/cobra"
"k8s.io/kubectl/pkg/util/term"
"sigs.k8s.io/yaml"
)

func NewSysinfoCmd() *cobra.Command {

var sysinfoSpec sysinfo.K0sSysinfoSpec
var outputFormat string

cmd := &cobra.Command{
Use: "sysinfo",
Expand All @@ -42,20 +46,32 @@ func NewSysinfoCmd() *cobra.Command {
sysinfoSpec.AddDebugProbes = true
probes := sysinfoSpec.NewSysinfoProbes()
out := cmd.OutOrStdout()
cli := &cliReporter{
w: out,
colors: aurora.NewAurora(term.IsTerminal(out)),
}

if err := probes.Probe(cli); err != nil {
return err
}
switch outputFormat {
case "text":
cli := &cliReporter{
w: out,
colors: aurora.NewAurora(term.IsTerminal(out)),
}
if err := probes.Probe(cli); err != nil {
return err
}
if cli.failed {
return errors.New("sysinfo failed")
}
return nil

if cli.failed {
return errors.New("sysinfo failed")
}
case "json":
return collectAndPrint(probes, out, func(v interface{}) ([]byte, error) {
return json.MarshalIndent(v, "", " ")
})

return nil
case "yaml":
return collectAndPrint(probes, out, yaml.Marshal)

default:
return fmt.Errorf("unknown output format: %q", outputFormat)
}
},
}

Expand All @@ -64,6 +80,7 @@ func NewSysinfoCmd() *cobra.Command {
flags.BoolVar(&sysinfoSpec.ControllerRoleEnabled, "controller", true, "Include controller-specific sysinfo")
flags.BoolVar(&sysinfoSpec.WorkerRoleEnabled, "worker", true, "Include worker-specific sysinfo")
flags.StringVar(&sysinfoSpec.DataDir, "data-dir", constant.DataDirDefault, "Data Directory for k0s")
flags.StringVarP(&outputFormat, "output", "o", "text", "Output format (valid values: text, json, yaml)")

return cmd
}
Expand Down Expand Up @@ -121,11 +138,104 @@ func (r *cliReporter) Error(p probes.ProbeDesc, err error) error {
)
}

func collectAndPrint(probe probes.Probe, out io.Writer, marshal func(any) ([]byte, error)) error {
var c resultsCollector
if err := probe.Probe(&c); err != nil {
return err
}
bytes, err := marshal(c.results)
if err != nil {
return err
}
_, err = out.Write(bytes)
if err != nil {
return err
}
if c.failed {
return errors.New("sysinfo failed")
}
return nil
}

func (r *cliReporter) printf(format interface{}, args ...interface{}) error {
_, err := io.WriteString(r.w, aurora.Sprintf(format, args...))
return err
}

type Probe struct {
Path []string `json:"path"`
DisplayName string `json:"displayName"`
Prop string `json:"prop"`
Message string `json:"message"`
Category ProbeCategory `json:"category"`
Error error `json:"error"`
}

type ProbeCategory string

const (
ProbeCategoryPass ProbeCategory = "pass"
ProbeCategoryWarning ProbeCategory = "warning"
ProbeCategoryRejected ProbeCategory = "rejected"
ProbeCategoryError ProbeCategory = "error"
)

type resultsCollector struct {
results []Probe
failed bool
}

func (r *resultsCollector) Pass(p probes.ProbeDesc, v probes.ProbedProp) error {
r.results = append(r.results, Probe{
Path: probePath(p),
DisplayName: p.DisplayName(),
Prop: propString(v),
Category: ProbeCategoryPass,
})
return nil
}

func (r *resultsCollector) Warn(p probes.ProbeDesc, v probes.ProbedProp, msg string) error {
r.results = append(r.results, Probe{
Path: probePath(p),
DisplayName: p.DisplayName(),
Prop: propString(v),
Message: msg,
Category: ProbeCategoryWarning,
})
return nil
}

func (r *resultsCollector) Reject(p probes.ProbeDesc, v probes.ProbedProp, msg string) error {
r.failed = true
r.results = append(r.results, Probe{
Path: probePath(p),
DisplayName: p.DisplayName(),
Prop: propString(v),
Message: msg,
Category: ProbeCategoryRejected,
})
return nil
}

func (r *resultsCollector) Error(p probes.ProbeDesc, err error) error {
r.failed = true
r.results = append(r.results, Probe{
Path: probePath(p),
DisplayName: p.DisplayName(),
Category: ProbeCategoryError,
Error: err,
})
return nil
}

func probePath(p probes.ProbeDesc) []string {
if len(p.Path()) == 0 {
return nil
}
return p.Path()
}

func propString(p probes.ProbedProp) string {
if p == nil {
return ""
Expand Down
74 changes: 74 additions & 0 deletions cmd/sysinfo/sysinfo_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -237,3 +237,77 @@ func (d *testDesc) DisplayName() string { return d.name }
type testProp string

func (p testProp) String() string { return string(p) }

func Test_resultsCollector(t *testing.T) {
for _, data := range []struct {
name string
probe func(t *testing.T, cli *resultsCollector)
xpectResults []Probe
xpectFailed bool
}{
{
"success",
func(t *testing.T, cli *resultsCollector) {
err := cli.Pass(&testDesc{"foo", probes.ProbePath{"bar"}}, testProp("baz"))
assert.NoError(t, err)
err = cli.Pass(&testDesc{"foo", probes.ProbePath{"bar", "baz"}}, testProp("qux"))
assert.NoError(t, err)
err = cli.Warn(&testDesc{"foo", nil}, testProp("bar"), "baz")
assert.NoError(t, err)
},
[]Probe{
{Path: []string{"bar"}, DisplayName: "foo", Prop: "baz", Message: "", Category: "pass", Error: nil},
{Path: []string{"bar", "baz"}, DisplayName: "foo", Prop: "qux", Message: "", Category: "pass", Error: nil},
{Path: []string(nil), DisplayName: "foo", Prop: "bar", Message: "baz", Category: "warning", Error: nil},
},
false,
},
{
"has_reject",
func(t *testing.T, cli *resultsCollector) {
err := cli.Pass(&testDesc{"foo", probes.ProbePath{"bar"}}, testProp("baz"))
assert.NoError(t, err)
err = cli.Pass(&testDesc{"foo", probes.ProbePath{"bar", "baz"}}, testProp("qux"))
assert.NoError(t, err)
err = cli.Warn(&testDesc{"foo", nil}, testProp("bar"), "baz")
assert.NoError(t, err)
err = cli.Reject(&testDesc{"foo", nil}, testProp("bar"), "baz")
assert.NoError(t, err)
},
[]Probe{
{Path: []string{"bar"}, DisplayName: "foo", Prop: "baz", Message: "", Category: "pass", Error: nil},
{Path: []string{"bar", "baz"}, DisplayName: "foo", Prop: "qux", Message: "", Category: "pass", Error: nil},
{Path: []string(nil), DisplayName: "foo", Prop: "bar", Message: "baz", Category: "warning", Error: nil},
{Path: []string(nil), DisplayName: "foo", Prop: "bar", Message: "baz", Category: "rejected", Error: nil},
},
true,
},
{
"has_error",
func(t *testing.T, cli *resultsCollector) {
err := cli.Pass(&testDesc{"foo", probes.ProbePath{"bar"}}, testProp("baz"))
assert.NoError(t, err)
err = cli.Pass(&testDesc{"foo", probes.ProbePath{"bar", "baz"}}, testProp("qux"))
assert.NoError(t, err)
err = cli.Warn(&testDesc{"foo", nil}, testProp("bar"), "baz")
assert.NoError(t, err)
err = cli.Error(&testDesc{"foo", probes.ProbePath{}}, errors.New("bar"))
assert.NoError(t, err)
},
[]Probe{
{Path: []string{"bar"}, DisplayName: "foo", Prop: "baz", Message: "", Category: "pass", Error: nil},
{Path: []string{"bar", "baz"}, DisplayName: "foo", Prop: "qux", Message: "", Category: "pass", Error: nil},
{Path: []string(nil), DisplayName: "foo", Prop: "bar", Message: "baz", Category: "warning", Error: nil},
{Path: []string(nil), DisplayName: "foo", Prop: "", Message: "", Category: "error", Error: errors.New("bar")},
},
true,
},
} {
t.Run(data.name, func(t *testing.T) {
c := &resultsCollector{}
data.probe(t, c)
assert.Equal(t, data.xpectResults, c.results)
assert.Equal(t, data.xpectFailed, c.failed)
})
}
}
Loading