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 1d6d96a
Show file tree
Hide file tree
Showing 12 changed files with 711 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"`
}
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)
}
}
31 changes: 31 additions & 0 deletions examples/compatibility-6-wind-router-rules.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
version: v1alpha1
compatibilities:
- description: "required kernel configuration"
rules:
- name: "kernel configuration"
matchFeatures:
- feature: kernel.config
matchExpressions:
CGROUP_BPF: {op: In, value: ["y"]}
XFRM_INTERFACE: {op: In, value: ["y"]}
NF_TABLES: {op: In, value: ["y"]}
NETFILTER_XT_TARGET_NOTRACK: {op: In, value: ["y"]}
NET_ACT_BPF: {op: In, value: ["y"]}
MPLS_ROUTING: {op: In, value: ["y"]}
MPLS_IPTUNNEL: {op: In, value: ["y"]}
PPPOE: {op: In, value: ["y"]}
- feature: kernel.loadedmodule
matchExpressions:
br_netfilter: {op: Exists}
ebtables: {op: Exists}
ifb: {op: Exists}
ip6_tables: {op: Exists}
ip_tables: {op: Exists}
mpls_iptunnel: {op: Exists}
mpls_router: {op: Exists}
nf_conntrack: {op: Exists}
overlay: {op: Exists}
ppp_generic: {op: Exists}
vfio-pci: {op: Exists}
vhost-net: {op: Exists}
vrf: {op: Exists}
Loading

0 comments on commit 1d6d96a

Please sign in to comment.