Skip to content

Commit

Permalink
Introduce nfd client tool with subset of image compatibility commands
Browse files Browse the repository at this point in the history
Signed-off-by: Marcin Franczyk <marcin0franczyk@gmail.com>
  • Loading branch information
mfranczy committed Nov 2, 2024
1 parent 35050d0 commit 6227de7
Show file tree
Hide file tree
Showing 13 changed files with 736 additions and 0 deletions.
35 changes: 35 additions & 0 deletions api/image-compatibility/v1alpha1/spec.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
Copyright 2024 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package v1alpha1

import (
nfdv1alpha1 "sigs.k8s.io/node-feature-discovery/api/nfd/v1alpha1"
)

const ArtifactType = "application/vnd.k8s.nfd.image-compatibility.v1"

type Spec struct {
Version string `json:"version"`
Compatibilties []Compatibility `json:"compatibilities"`
}

type Compatibility struct {
Rules []nfdv1alpha1.Rule `json:"rules"`
Weight int `json:"weight,omitempty"`
Tag string `json:"tag,omitempty"`
Description string `json:"description,omitempty"`
}
9 changes: 9 additions & 0 deletions api/nfd/v1alpha1/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ limitations under the License.
package v1alpha1

import (
fmt "fmt"

corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
Expand Down Expand Up @@ -298,6 +300,13 @@ type MatchExpression struct {
Value MatchValue `json:"value,omitempty"`
}

func (m *MatchExpression) String() string {
if len(m.Value) > 0 {
return fmt.Sprintf("{op: %q, value: %q}", m.Op, m.Value)
}
return fmt.Sprintf("{op: %q}", m.Op)
}

// MatchOp is the match operator that is applied on values when evaluating a
// MatchExpression.
// +kubebuilder:validation:Enum="In";"NotIn";"InRegexp";"Exists";"DoesNotExist";"Gt";"Lt";"GtLt";"IsTrue";"IsFalse"
Expand Down
27 changes: 27 additions & 0 deletions cmd/client-nfd/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/*
Copyright 2024 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

import (
"sigs.k8s.io/node-feature-discovery/cmd/client-nfd/subcmd"
)

const ProgramName = "nfd"

func main() {
subcmd.Execute()
}
37 changes: 37 additions & 0 deletions cmd/client-nfd/subcmd/compat/compat.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
Copyright 2024 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package compat

import (
"fmt"
"os"

"github.com/spf13/cobra"
)

var CompatCmd = &cobra.Command{
Use: "compat",
Short: "image compatibility commands",
Long: "TBD",
}

func Execute() {
if err := CompatCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
65 changes: 65 additions & 0 deletions cmd/client-nfd/subcmd/compat/options/platform.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
Copyright 2024 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package options

import (
"fmt"
"runtime"
"strings"

ocispec "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/spf13/cobra"
)

type PlatformOption struct {
PlatformStr string
Platform *ocispec.Platform
}

func (opt *PlatformOption) Parse(*cobra.Command) error {
var pStr string

if opt.PlatformStr == "" {
return nil
}

p := &ocispec.Platform{}
pStr, p.OSVersion, _ = strings.Cut(opt.PlatformStr, ":")
parts := strings.Split(pStr, "/")

switch len(parts) {
case 3:
p.Variant = parts[2]
fallthrough
case 2:
p.Architecture = parts[1]
case 1:
p.Architecture = runtime.GOARCH
default:
return fmt.Errorf("failed to parse platform %q: expected format os[/arch[/variant]]", opt.PlatformStr)
}

p.OS = parts[0]
if p.OS == "" {
return fmt.Errorf("invalid platform: OS cannot be empty")
}
if p.Architecture == "" {
return fmt.Errorf("invalid platform: Architecture cannot be empty")
}
opt.Platform = p
return nil
}
141 changes: 141 additions & 0 deletions cmd/client-nfd/subcmd/compat/validate-node.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
/*
Copyright 2024 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package compat

import (
"context"
"fmt"
"os"
"strconv"
"time"

"github.com/jedib0t/go-pretty/v6/table"
"github.com/jedib0t/go-pretty/v6/text"
"github.com/spf13/cobra"
"oras.land/oras-go/v2/registry"

"sigs.k8s.io/node-feature-discovery/cmd/client-nfd/subcmd/compat/options"
nodevalidator "sigs.k8s.io/node-feature-discovery/pkg/client-nfd/compat/node-validator"
)

var (
image string
tags []string
platform options.PlatformOption
plainHTTP bool
)

var validateNodeCmd = &cobra.Command{
Use: "validate-node",
Short: "Validate node based on image compatibility metadata",
Long: "Validate node based on image compatibility metadata from the NFD artifact",
PreRunE: func(cmd *cobra.Command, args []string) error {
return platform.Parse(cmd)
},
RunE: func(cmd *cobra.Command, args []string) error {
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()

ref, err := registry.ParseReference(image)
if err != nil {
return err
}

a := &nodevalidator.Args{
RegReference: &ref,
Tags: tags,
Platform: platform.Platform,
PlainHTTP: plainHTTP,
}
nv := nodevalidator.New(nodevalidator.WithArgs(a))

out, err := nv.Execute(ctx)
if err != nil {
return err
}
printResult(out)

return nil
},
}

func printResult(css []*nodevalidator.CompatibilityStatus) {
for i, cs := range css {
fmt.Print(text.Colors{text.FgCyan, text.Bold}.Sprintf("Compatibility set #%d ", i+1))
fmt.Print(text.FgCyan.Sprintf("Weight: %d", cs.Weight))
if cs.Tag != "" {
fmt.Print(text.FgCyan.Sprintf("; Tag: %s", cs.Tag))
}
fmt.Println()
fmt.Println(text.FgWhite.Sprintf("Description: %s", cs.Description))

for _, r := range cs.Rules {
printTable(r)
}
fmt.Println()
}
}

func printTable(r nodevalidator.RuleStatus) {
t := table.NewWriter()
t.SetStyle(table.StyleLight)
t.SetOutputMirror(os.Stdout)

validTxt := text.BgRed.Sprint(" fail ")
if r.IsMatch {
validTxt = text.BgGreen.Sprint(" ok ")
}
t.SetTitle(fmt.Sprintf("rule: %s - %s", text.Bold.Sprintf("%s", r.Name), validTxt))
t.Style().Title.Format = text.FormatUpper
t.AppendHeader(table.Row{"#", "feature", "expression", "status"})

for i, f := range r.Features {
if i > 0 && r.Features[i-1].GetFeatureDomain() != f.GetFeatureDomain() {
t.AppendSeparator()
}
addTableRows(t, i, f)
}
t.Render()
}

func addTableRows(t table.Writer, idx int, fs *nodevalidator.FeatureStatus) {
status := text.FgRed.Sprint("FAIL")
if fs.IsMatch {
status = text.FgGreen.Sprint("OK")
}

t.AppendRow(
table.Row{
strconv.Itoa(idx + 1),
fs.GetFullDomain(),
fs.Expression,
status,
},
)
}

func init() {
CompatCmd.AddCommand(validateNodeCmd)
validateNodeCmd.Flags().StringVar(&image, "image", "", "URL of image with compatibility metadata")
validateNodeCmd.Flags().StringSliceVar(&tags, "tags", []string{}, "execute rules with specific tags")
validateNodeCmd.Flags().StringVar(&platform.PlatformStr, "platform", "", "artifact platform in the format os[/arch][/variant][:os_version]")
validateNodeCmd.Flags().BoolVar(&plainHTTP, "plain-http", false, "access image repository via HTTP")

if err := validateNodeCmd.MarkFlagRequired("image"); err != nil {
panic(err)
}
}
46 changes: 46 additions & 0 deletions cmd/client-nfd/subcmd/root.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
Copyright 2024 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package subcmd

import (
"fmt"
"os"

"github.com/spf13/cobra"

"sigs.k8s.io/node-feature-discovery/cmd/client-nfd/subcmd/compat"
)

// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
Use: "nfd",
Short: "NFD client",
Long: `NFD client TBD`,
}

func init() {
RootCmd.AddCommand(compat.CompatCmd)
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
if err := RootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
Loading

0 comments on commit 6227de7

Please sign in to comment.