list.go 1.94 KB
Newer Older
songlinfeng's avatar
songlinfeng committed
1
2
3
4
5
6
7
/**
# Copyright (c) 2024, HCUOpt CORPORATION.  All rights reserved.
**/

package list

import (
8
	"dcu-container-toolkit/internal/logger"
songlinfeng's avatar
songlinfeng committed
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
	"errors"
	"fmt"

	"github.com/urfave/cli/v2"
	"tags.cncf.io/container-device-interface/pkg/cdi"
)

type command struct {
	logger logger.Interface
}

type config struct {
	cdiSpecDirs cli.StringSlice
}

// NewCommand constructs a cdi list command with the specified logger
func NewCommand(logger logger.Interface) *cli.Command {
	c := command{
		logger: logger,
	}
	return c.build()
}

// build creates the CLI command
func (m command) build() *cli.Command {
	cfg := config{}

	// Create the command
	c := cli.Command{
		Name:  "list",
		Usage: "List the available CDI devices",
		Before: func(c *cli.Context) error {
			return m.validateFlags(c, &cfg)
		},
		Action: func(c *cli.Context) error {
			return m.run(c, &cfg)
		},
	}

	c.Flags = []cli.Flag{
		&cli.StringSliceFlag{
			Name:        "spec-dir",
			Usage:       "specify the directories to scan for CDI specifications",
			Value:       cli.NewStringSlice(cdi.DefaultSpecDirs...),
			Destination: &cfg.cdiSpecDirs,
		},
	}

	return &c
}

func (m command) validateFlags(c *cli.Context, cfg *config) error {
	if len(cfg.cdiSpecDirs.Value()) == 0 {
		return errors.New("at least one CDI specification directory must be specified")
	}
	return nil
}

func (m command) run(c *cli.Context, cfg *config) error {
	registry, err := cdi.NewCache(
		cdi.WithAutoRefresh(false),
		cdi.WithSpecDirs(cfg.cdiSpecDirs.Value()...),
	)
	if err != nil {
		return fmt.Errorf("failed to create CDI cache: %v", err)
	}

	_ = registry.Refresh()
	if errors := registry.GetErrors(); len(errors) > 0 {
		m.logger.Warningf("The following registry errors were reported:")
		for k, err := range errors {
			m.logger.Warningf("%v: %v", k, err)
		}
	}

	devices := registry.ListDevices()
songlinfeng's avatar
songlinfeng committed
85
	m.logger.Infof("Found %d CDI devices", len(devices) / 2)
songlinfeng's avatar
songlinfeng committed
86
87
88
89
90
91
	for _, device := range devices {
		fmt.Printf("%s\n", device)
	}

	return nil
}