Documentation
¶
Overview ¶
Package output carries the machine readable output contract of kubectl-nv: the API version and kinds every command stamps its output with, the printers behind -o, the exit code mapping, a stderr logger, and a deterministic order for findings.
The kinds themselves live in the packages that own them. A command defines its own typed payload, for instance
type GPUNode struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitzero"`
Spec GPUNodeSpec `json:"spec,omitzero"`
Status GPUNodeStatus `json:"status,omitzero"`
}
stamps it with TypeMetaFor(KindGPUNode), implements TableRows on it, and hands it to a Printer from this package. Object and List here are the small generic forms used by this package's own tests and by output that carries nothing but names.
Machine readable output is rendered by the k8s.io/cli-runtime printers, which marshal through sigs.k8s.io/yaml. That package reads the JSON struct tags for both JSON and YAML output, so the JSON tags are what the wire format follows; the yaml tags are there for callers that reach for a plain YAML marshaller.
Index ¶
- Constants
- Variables
- func BindBoundedOutputFlags(c *cobra.Command, b *BoundedOptions)
- func ExitCode(status ReportStatus, failOn Severity) int
- func ExitCodeFor(err error) int
- func FieldPaths(obj runtime.Object) ([]string, error)
- func GenerateSchema(kind string, prototype any) ([]byte, error)
- func PrintBounded(streams genericiooptions.IOStreams, format string, b BoundedOptions, ...) error
- func RegisterCommandKind(command, kind string)
- func RegisterSchema(kind string, prototype any)
- func RegisteredKinds() []string
- func SanitizeCell(s string) string
- func SchemaFor(name string) ([]byte, error)
- func SortFindings(findings []Finding)
- func TypeMetaFor(kind string) metav1.TypeMeta
- func ValidateAgainstSchema(kind string, sample any) error
- type BoundedOptions
- type Column
- type Finding
- type Format
- type List
- type Logger
- type LoggerOptions
- type Object
- type OutputOptions
- type Printer
- type ReportStatus
- type SchemaRegistry
- func (r *SchemaRegistry) Commands() []string
- func (r *SchemaRegistry) Kinds() []string
- func (r *SchemaRegistry) Register(kind string, prototype any)
- func (r *SchemaRegistry) RegisterCommand(command, kind string)
- func (r *SchemaRegistry) Schema(name string) ([]byte, error)
- func (r *SchemaRegistry) ValidateAgainstSchema(kind string, sample any) error
- type Severity
- type TablePrinter
- type TableRows
- type Unreachable
- type UsageError
Constants ¶
const ( // GroupName is the API group every kubectl-nv envelope is stamped with. GroupName = "kubectl-nv.nvidia.com" // Version is the API version of the envelope. Version = "v1alpha1" // APIVersion is the group and version as they appear on the wire. APIVersion = GroupName + "/" + Version )
const ( // KindGPUNodeList is a list of GPU capable nodes. KindGPUNodeList = "GPUNodeList" // KindGPUNode is a single GPU capable node. KindGPUNode = "GPUNode" // KindHealthReport is the result of a health check run. KindHealthReport = "HealthReport" // KindTopologyReport is the device topology of one node or of the cluster. KindTopologyReport = "TopologyReport" // KindBundleManifest is the index of a must-gather bundle. KindBundleManifest = "BundleManifest" // KindDebugReport is one node's inventory next to the must-gather bundle // collected for it. KindDebugReport = "DebugReport" )
The kinds kubectl-nv emits. The payload of each one is defined by the package that produces it; the kinds are fixed here so that every consumer, and every track, can switch on them from day one.
const ( // ExitOK means the run completed and found nothing at or above --fail-on. ExitOK = 0 // ExitFindings means the run found something at or above --fail-on. ExitFindings = 1 // ExitUsage means the command line or the configuration was wrong. ExitUsage = 2 // ExitPartial means the run completed over less than it was asked for, for // instance because RBAC or a denied exec hid part of the cluster. What was // missed is listed in the output. ExitPartial = 3 // ExitError means the run could not happen: the API server was unreachable, // or kubectl-nv hit an internal error. Nothing was checked, so nothing can // be concluded from it. ExitError = 4 )
The exit codes kubectl-nv uses. They are part of the contract: scripts branch on them, so a new meaning needs a new code rather than a new reading of one.
Variables ¶
var GroupVersion = schema.GroupVersion{Group: GroupName, Version: Version}
GroupVersion is the group and version of every kind in this contract.
Functions ¶
func BindBoundedOutputFlags ¶ added in v0.2.0
func BindBoundedOutputFlags(c *cobra.Command, b *BoundedOptions)
BindBoundedOutputFlags registers the two flags against options the caller already holds. AddOutputFlags needs it: pflag binds to an address, so a BoundedOptions copied out of a constructor would be a different struct from the one the flags write into, and every call would read its zero value.
func ExitCode ¶
func ExitCode(status ReportStatus, failOn Severity) int
ExitCode maps a report onto the process exit code. failOn is the threshold from --fail-on, as returned by ParseSeverity; its empty value means SeverityError.
Findings win over partial results: a run that found something at or above the threshold exits ExitFindings even when part of the cluster stayed out of reach, because the caller needs to hear about what was found first. A run that found nothing but could not see everything exits ExitPartial, so that "clean" is never reported for a scan that did not happen.
func ExitCodeFor ¶
ExitCodeFor maps an error onto the process exit code. Any error that carries its own code, this package's UsageError included, decides for itself; anything else means the run could not happen, which is ExitError.
func FieldPaths ¶ added in v0.2.0
FieldPaths returns every dotted JSON path --fields accepts for obj, sorted. For a list it is the paths of one item: a caller projects items, never the list envelope around them.
func GenerateSchema ¶ added in v0.2.0
GenerateSchema renders the JSON Schema of one kind. It is exported so that a package registering a kind can check its own prototype in a test without going through a registry.
func PrintBounded ¶ added in v0.2.0
func PrintBounded(streams genericiooptions.IOStreams, format string, b BoundedOptions, obj runtime.Object) error
PrintBounded applies --limit and --fields to obj and prints it in the format behind -o. Truncation is reported on the error stream and recorded in metadata.remainingItemCount, so that neither a reader nor a program can mistake a bounded answer for a complete one.
func RegisterCommandKind ¶ added in v0.2.0
func RegisterCommandKind(command, kind string)
RegisterCommandKind records which kind a command prints, so that a caller can ask for a schema by the command they were going to run.
func RegisterSchema ¶ added in v0.2.0
RegisterSchema records the prototype the JSON Schema of a kind is generated from. It panics when the kind is already registered.
func RegisteredKinds ¶ added in v0.2.0
func RegisteredKinds() []string
RegisteredKinds returns the kinds of the default registry, sorted.
func SanitizeCell ¶ added in v0.2.0
SanitizeCell makes one string safe to print on a terminal: tabs and newlines become spaces, and every other C0 and C1 control character is dropped.
It exists because the strings kubectl-nv prints are not kubectl-nv's. They are node labels, taint values, condition reasons and container images, which come either from a cluster where anyone with patch on nodes can write them, or from a must-gather directory that arrived in a support ticket from a cluster the reader does not control. An escape sequence in one of those is somebody else's cursor control, window title and scroll back manipulation running in the reader's shell.
The rule is the printers' own: this is the cell sanitiser the table output has always applied, exported so that a view which does not go through the table printer applies exactly the same one. Two sanitisers that drift apart would mean two answers to "is this safe to print".
It is deliberately not a quoting function. The text around a control character is kept, because a hostile label that erased the field it sits in would hide the very node a reader is looking at.
func SchemaFor ¶ added in v0.2.0
SchemaFor returns the JSON Schema of a kind or of a command, from the default registry.
func SortFindings ¶
func SortFindings(findings []Finding)
SortFindings orders findings by node name and then by code, in place. The sort is stable, so findings that share a node and a code keep the order the command produced them in. Output has to be byte identical across runs for diffs and golden files to be worth anything.
func TypeMetaFor ¶
TypeMetaFor returns the TypeMeta a kind of this contract is stamped with. It is how a payload type in another package joins the contract.
func ValidateAgainstSchema ¶ added in v0.2.0
ValidateAgainstSchema is ValidateAgainstSchema on the default registry.
Types ¶
type BoundedOptions ¶ added in v0.2.0
type BoundedOptions struct {
// Fields are the dotted JSON paths to keep on each item, for instance
// "status.ready". Empty keeps every field.
Fields []string
// Limit is how many items of a list to print, after the command's own sort.
// Zero means every item.
Limit int
}
BoundedOptions is what --fields and --limit parsed into. Its zero value prints everything, which is what a command that never calls AddBoundedOutputFlags gets.
func AddBoundedOutputFlags ¶ added in v0.2.0
func AddBoundedOutputFlags(c *cobra.Command) *BoundedOptions
AddBoundedOutputFlags registers --fields and --limit on a command and returns the options they write into. Every list-like command calls it, so that the two flags mean the same thing everywhere rather than once per command.
func (BoundedOptions) Validate ¶ added in v0.2.0
func (b BoundedOptions) Validate(prototype runtime.Object) error
Validate reports whether these bounds can be applied to a kind, without printing anything.
A command calls it before it reads from the cluster. A misspelled --fields found afterwards has cost a scan nobody needed, and the caller waited for it only to be told it typed the wrong thing.
type Column ¶
type Column struct {
// Header is the column title.
Header string
// Field is the dotted JSON path this column renders, for instance
// "status.ready". It is what --fields matches a column against, so a column
// that leaves it empty cannot be asked for by name and is dropped as soon as
// --fields is given.
Field string
}
Column is one column of the table output.
type Finding ¶
type Finding struct {
// Code is the stable identifier of the check that produced the finding,
// in the form NV-<AREA>-<NNN>. It is what a script greps for and what a
// suppression list names, so it never changes meaning.
Code string `json:"code,omitempty" yaml:"code,omitempty"`
// Severity decides whether this finding fails the run, through ExitCode
// and the --fail-on threshold.
Severity Severity `json:"severity,omitempty" yaml:"severity,omitempty"`
// Node is the node the finding is about. It is empty for a finding about
// the cluster as a whole.
Node string `json:"node,omitempty" yaml:"node,omitempty"`
// Component is the part the finding is about, for instance an operand
// name such as "nvidia-driver-daemonset" or "gpu-feature-discovery". It
// is empty when the finding is about the node itself.
Component string `json:"component,omitempty" yaml:"component,omitempty"`
// Message is the human readable detail, one sentence, no trailing period.
Message string `json:"message,omitempty" yaml:"message,omitempty"`
// Evidence is what the finding was concluded from: the label values, the
// counts, the exit codes. It is keyed by whatever names the value best,
// usually the label or the field it came from, verbatim, so that a reader
// can go and look at the same thing. It is never null on the wire.
//
// The values are strings because the keys are not a fixed set and the
// types behind them are not uniform, which rules out a typed struct and
// makes map[string]any a map whose values a consumer has to type switch
// on. So the encodings are fixed instead, and every rule in every track
// follows them:
//
// integers base 10, no separators, no units: "7", "0", "-1"
// booleans "true" or "false", never "True", "yes" or "1"
// lists sorted, comma joined, no spaces: "a,b,c"
// times RFC3339 in UTC: "2026-01-02T03:04:05Z"
// durations Go's form, as time.Duration.String writes it: "1h30m0s"
// quantities the resource.Quantity string: "16Gi", "250m"
// absent the key is left out, never set to "" or "<none>"
//
// Sorted and joined rather than indexed ("node.0", "node.1") because a
// finding is one line in a report and a reader compares two of them by
// eye. Deterministic for the same reason every other ordering here is: two
// runs over the same cluster have to produce the same bytes.
Evidence map[string]string `json:"evidence" yaml:"evidence"`
// Docs is where to read more: a URL, or a path to a document in this
// repository.
Docs string `json:"docs,omitempty" yaml:"docs,omitempty"`
// Next is the command to run next, ready to paste.
Next string `json:"next,omitempty" yaml:"next,omitempty"`
}
Finding is one thing a command noticed. It is what every check in every track emits and what every consumer parses, so the field names here are the contract and the order they appear in is fixed.
A finding answers four questions in order: what was found (Code, Severity), where (Node, Component), what it means (Message, Evidence), and what to do about it (Docs, Next). The last two are not decoration. A user who runs a health check and is told something is wrong, with no link and no next command, has been given a worse version of the problem they already had.
func (Finding) MarshalJSON ¶ added in v0.2.0
MarshalJSON renders a nil Evidence as an empty object, for the same reason List and ReportStatus render nil slices as empty arrays: a consumer that has to check for null before it can index is a consumer that will forget to.
type Format ¶
type Format string
Format is the value of the -o flag.
const ( // FormatTable is the human readable default. FormatTable Format = "table" // FormatWide is the table with the extra columns. FormatWide Format = "wide" // FormatJSON is the envelope as JSON. FormatJSON Format = "json" // FormatYAML is the envelope as YAML. FormatYAML Format = "yaml" // FormatName prints one "kind/name" line per item. FormatName Format = "name" )
func ParseFormat ¶
ParseFormat turns an -o value into a Format. An empty value is the table default; anything unrecognised is a usage error, which exits 2.
type List ¶
type List struct {
metav1.TypeMeta `json:",inline" yaml:",inline"`
metav1.ListMeta `json:"metadata,omitzero" yaml:"metadata,omitempty"`
// Items keeps the order the command produced. Nothing downstream reorders
// it, so a command that wants a stable order sorts before handing it over.
Items []Object `json:"items" yaml:"items"`
}
List is the generic envelope holding several Objects of one kind.
func (*List) DeepCopyInto ¶
DeepCopyInto copies the receiver into out.
func (*List) DeepCopyObject ¶
DeepCopyObject implements runtime.Object.
func (List) MarshalJSON ¶
MarshalJSON renders a nil Items as an empty array. A consumer that has to special case null before it can range over items is a consumer that will get it wrong, and the guarantee belongs on the type rather than on NewList.
func (*List) TableColumns ¶
TableColumns implements TableRows.
type Logger ¶
type Logger struct {
// contains filtered or unexported fields
}
Logger writes progress and warnings to the error stream. Nothing it prints ever reaches stdout, which belongs to the machine readable output alone, and it never asks the user anything: every command has to stay usable in a pipe.
It is safe to use from several goroutines, because a scan reports progress from whichever goroutine noticed something.
func NewLogger ¶
func NewLogger(streams genericiooptions.IOStreams, opts LoggerOptions) *Logger
NewLogger returns a logger writing to the error stream of streams. Color is used only when the caller did not pass --no-color, NO_COLOR is not set in the environment, and the error stream is a terminal.
type LoggerOptions ¶
type LoggerOptions struct {
// NoColor turns color off whatever the stream is, for --no-color.
NoColor bool
// IsTerminal reports whether the error stream is a terminal. A nil value
// means the real check; a test passes its own so that the color decision
// can be exercised without a pty.
IsTerminal func(w io.Writer) bool
}
LoggerOptions configures a Logger.
type Object ¶
type Object struct {
metav1.TypeMeta `json:",inline" yaml:",inline"`
// ObjectMeta carries the name the output is keyed by. It is the apimachinery
// type so that the printers can read the name through meta.Accessor.
metav1.ObjectMeta `json:"metadata,omitzero" yaml:"metadata,omitempty"`
}
Object is the generic envelope entry: a kind and a name, with no payload. A command with a payload defines its own type instead.
func (*Object) DeepCopyInto ¶
DeepCopyInto copies the receiver into out.
func (*Object) DeepCopyObject ¶
DeepCopyObject implements runtime.Object.
func (*Object) TableColumns ¶
TableColumns implements TableRows.
type OutputOptions ¶ added in v0.2.0
type OutputOptions struct {
// Format is the raw -o value, as ParseFormat reads it.
Format string
// Bounded is --fields and --limit.
Bounded BoundedOptions
}
OutputOptions is the whole output interface of a list-like command: the format behind -o and the two flags that bound what it prints.
func AddOutputFlags ¶ added in v0.2.0
func AddOutputFlags(c *cobra.Command) *OutputOptions
AddOutputFlags registers -o, --fields and --limit on a command and returns the options they write into.
The three are registered together because the MCP server and every command have to agree on what the format flag is called: the server forces -o json, and a command that spelled it differently would be served in whatever format it defaults to and its output would not parse.
func (*OutputOptions) Print ¶ added in v0.2.0
func (o *OutputOptions) Print(streams genericiooptions.IOStreams, obj runtime.Object) error
Print applies the bounds and prints obj in the chosen format.
type Printer ¶
Printer renders a kind of this contract onto a writer.
func NewPrinter ¶
NewPrinter returns the printer for an -o value, or a usage error when the value is not one this package knows.
type ReportStatus ¶
type ReportStatus struct {
// Findings is what the run found, in the order it should be printed.
Findings []Finding `json:"findings" yaml:"findings"`
// Partial is set when the run could not see everything it was asked about.
Partial bool `json:"partial,omitempty" yaml:"partial,omitempty"`
// Unreachable lists what Partial is about, so that a reader never has to
// guess which part of the cluster is missing from the findings.
Unreachable []Unreachable `json:"unreachable,omitempty" yaml:"unreachable,omitempty"`
}
ReportStatus is the outcome of a run: what it found, and what it could not see. Every command that reports findings embeds it, and the exit code is read from it.
func (ReportStatus) MarshalJSON ¶
func (s ReportStatus) MarshalJSON() ([]byte, error)
MarshalJSON renders a nil Findings as an empty array, for the same reason List does: ranging over the result must not need a null check first.
type SchemaRegistry ¶ added in v0.2.0
type SchemaRegistry struct {
// contains filtered or unexported fields
}
SchemaRegistry holds the prototype each kind's JSON Schema is generated from, and the command names that stand in for a kind on the command line.
A kind is registered by the package that defines it, which is the only place that can keep the prototype and the type a command actually prints in step. Registering the same kind twice is a programming error rather than a configuration one: the second prototype would silently win, and the published schema would describe a type nothing emits.
func DefaultSchemaRegistry ¶ added in v0.2.0
func DefaultSchemaRegistry() *SchemaRegistry
DefaultSchemaRegistry returns the registry RegisterSchema writes to and the schema command reads from.
func NewSchemaRegistry ¶ added in v0.2.0
func NewSchemaRegistry() *SchemaRegistry
NewSchemaRegistry returns an empty registry. Tests use their own rather than the package level one, so that what one test registers cannot be what another test sees.
func (*SchemaRegistry) Commands ¶ added in v0.2.0
func (r *SchemaRegistry) Commands() []string
Commands returns the registered command names, sorted.
func (*SchemaRegistry) Kinds ¶ added in v0.2.0
func (r *SchemaRegistry) Kinds() []string
Kinds returns the registered kinds, sorted. The order is the order the generated files are written in, so it has to be stable.
func (*SchemaRegistry) Register ¶ added in v0.2.0
func (r *SchemaRegistry) Register(kind string, prototype any)
Register records a prototype for a kind.
func (*SchemaRegistry) RegisterCommand ¶ added in v0.2.0
func (r *SchemaRegistry) RegisterCommand(command, kind string)
RegisterCommand maps a command name onto a kind. The kind has to be registered first: a command pointing at a kind nobody defined would answer "unknown kind" at the one moment the caller needs an answer.
func (*SchemaRegistry) Schema ¶ added in v0.2.0
func (r *SchemaRegistry) Schema(name string) ([]byte, error)
Schema returns the JSON Schema of a kind, or of a command name standing in for one. An unknown name is a usage error listing what there is, because the caller typed it.
func (*SchemaRegistry) ValidateAgainstSchema ¶ added in v0.2.0
func (r *SchemaRegistry) ValidateAgainstSchema(kind string, sample any) error
ValidateAgainstSchema checks that a sample of a kind validates against the schema this registry generates for it.
It is what a package that owns a kind calls in its own test. A schema is only worth publishing if what the command actually prints satisfies it, and the two drift apart silently: a field renamed in Go regenerates the schema, but a field that marshals as null where the schema says array does not.
type Severity ¶
type Severity string
Severity is how bad one finding is.
func ParseSeverity ¶
ParseSeverity turns a --fail-on value into a Severity. An empty value means SeverityError, the conservative default. Anything else that is not a severity is a usage error: a typo in --fail-on is the difference between a gate and no gate, so it has to stop the run rather than be read as something else.
type TablePrinter ¶
type TablePrinter struct {
// Wide turns on the columns the kind marks as wide.
Wide bool
// Fields, when it is not empty, restricts the table to the columns whose
// Field it names, plus the ones no projection drops. It is how --fields
// reaches a format that has no nested structure to project.
Fields []string
}
TablePrinter renders a kind that implements TableRows as an aligned table. Rows keep the order the kind produced them in.
type TableRows ¶
type TableRows interface {
// TableColumns returns the headers, with the wide ones when wide is set.
TableColumns(wide bool) []Column
// TableRows returns one row per item, each with one cell per column.
TableRows(wide bool) [][]string
}
TableRows is implemented by a kind that can render itself as a table. It is how a payload type in another package gets a default and a wide table without this package knowing any of its fields.
type Unreachable ¶
type Unreachable struct {
// Resource is what could not be read, for instance "nodes/node-a/proxy".
Resource string `json:"resource,omitempty" yaml:"resource,omitempty"`
// Node is the node it belongs to, empty for a cluster scoped resource.
Node string `json:"node,omitempty" yaml:"node,omitempty"`
// Reason is why it could not be read, for instance "forbidden".
Reason string `json:"reason,omitempty" yaml:"reason,omitempty"`
}
Unreachable is one thing a run was not allowed, or not able, to look at.
type UsageError ¶
type UsageError struct {
// Err is the cause, when there is one to unwrap to.
Err error
// contains filtered or unexported fields
}
UsageError is a command line or configuration error: something the user can fix by typing something else.
func NewUsageError ¶
func NewUsageError(format string, a ...any) *UsageError
NewUsageError returns a UsageError with the formatted message and no cause.
func WrapUsageError ¶
func WrapUsageError(err error, format string, a ...any) *UsageError
WrapUsageError returns a UsageError carrying err as its cause.
func (*UsageError) ExitCode ¶
func (e *UsageError) ExitCode() int
ExitCode is the code a command exits with after a usage error.
func (*UsageError) Unwrap ¶
func (e *UsageError) Unwrap() error
Unwrap returns the cause, so that errors.Is and errors.As reach it.