generate.go 7.85 KB
Newer Older
songlinfeng's avatar
songlinfeng committed
1
2
3
4
5
6
7
8
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
/**
# Copyright (c) 2024, HCUOpt CORPORATION.  All rights reserved.
**/

package generate

import (
	"dtk-container-toolkit/internal/config"
	"dtk-container-toolkit/internal/logger"
	"dtk-container-toolkit/pkg/c3000cdi"
	"dtk-container-toolkit/pkg/c3000cdi/spec"
	"dtk-container-toolkit/pkg/c3000cdi/transform"
	"fmt"
	"os"
	"path/filepath"
	"strings"

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

const (
	allDeviceName = "all"
)

type command struct {
	logger logger.Interface
}

type options struct {
	output               string
	format               string
	deviceNameStrategies cli.StringSlice
	driverRoot           string
	devRoot              string
	dtkCDIHookPath       string
	ldconfigPath         string
	mode                 string
	vendor               string
	class                string

	configSearchPaths  cli.StringSlice
	librarySearchPaths cli.StringSlice

	csv struct {
		files          cli.StringSlice
		ignorePatterns cli.StringSlice
	}
}

// NewCommand constructs a generate-cdi 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 {
	opts := options{}

	// Create the 'generate-cdi' command
	c := cli.Command{
		Name:  "generate",
		Usage: "Generate CDI specifications for use with CDI-enabled runtimes",
		Before: func(c *cli.Context) error {
			return m.validateFlags(c, &opts)
		},
		Action: func(c *cli.Context) error {
			return m.run(c, &opts)
		},
	}

	c.Flags = []cli.Flag{
		&cli.StringSliceFlag{
			Name:        "config-search-path",
			Usage:       "Specify the path to search for config files when discovering the entities that should be included in the CDI specification.",
			Destination: &opts.configSearchPaths,
		},
		&cli.StringFlag{
			Name:        "output",
			Usage:       "Specify the file to output the generated CDI specification to. If this is '' the specification is output to STDOUT",
			Destination: &opts.output,
		},
		&cli.StringFlag{
			Name:        "format",
			Usage:       "The output format for the generated spec [json | yaml]. This overrides the format defined by the output file extension (if specified).",
			Value:       spec.FormatYAML,
			Destination: &opts.format,
		},
		&cli.StringFlag{
			Name:    "mode",
			Aliases: []string{"discovery-mode"},
			Usage: "The mode to use when discovering the available entities. " +
				"One of [" + strings.Join(c3000cdi.AllModes[string](), " | ") + "]. " +
				"If mode is set to 'auto' the mode will be determined based on the system configuration.",
			Value:       string(c3000cdi.ModeAuto),
			Destination: &opts.mode,
		},
		&cli.StringSliceFlag{
			Name:        "device-name-strategy",
			Usage:       "Specify the strategy for generating device names. If this is specified multiple times, the devices will be duplicated for each strategy. One of [index | uuid | type-index]",
			Value:       cli.NewStringSlice(c3000cdi.DeviceNameStrategyIndex, c3000cdi.DeviceNameStrategyUUID),
			Destination: &opts.deviceNameStrategies,
		},
		&cli.StringSliceFlag{
			Name:        "library-search-path",
			Usage:       "Specify the path to search for libraries when discovering the entities that should be included in the CDI specification.\n\tNote: This option only applies to CSV mode.",
			Destination: &opts.librarySearchPaths,
		},
		&cli.StringFlag{
			Name:    "dtk-cdi-hook-path",
			Aliases: []string{"dtk-ctk-path"},
			Usage: "Specify the path to use for the dtk-cdi-hook in the generated CDI specification. " +
				"If not specified, the PATH will be searched for `dtk-cdi-hook`. " +
				"NOTE: That if this is specified as `dtk-ctk`, the PATH will be searched for `dtk-ctk` instead.",
			Destination: &opts.dtkCDIHookPath,
		},
		&cli.StringFlag{
			Name:        "ldconfig-path",
			Usage:       "Specify the path to use for ldconfig in the generated CDI specification",
			Destination: &opts.ldconfigPath,
		},
		&cli.StringFlag{
			Name:        "vendor",
			Aliases:     []string{"cdi-vendor"},
			Usage:       "the vendor string to use for the generated CDI specification.",
			Value:       "c-3000.com",
			Destination: &opts.vendor,
		},
		&cli.StringFlag{
			Name:        "class",
			Aliases:     []string{"cdi-class"},
			Usage:       "the class string to use for the generated CDI specification.",
			Value:       "hcu",
			Destination: &opts.class,
		},
	}

	return &c
}

func (m command) validateFlags(c *cli.Context, opts *options) error {
	opts.format = strings.ToLower(opts.format)

	switch opts.format {
	case spec.FormatJSON:
	case spec.FormatYAML:
	default:
		return fmt.Errorf("invalid output format: %v", opts.format)
	}

	opts.mode = strings.ToLower(opts.mode)
	if !c3000cdi.IsValidMode(opts.mode) {
		return fmt.Errorf("invalid discovery mode: %v", opts.mode)
	}

	for _, strategy := range opts.deviceNameStrategies.Value() {
		_, err := c3000cdi.NewDeviceNamer(strategy)
		if err != nil {
			return err
		}
	}

	opts.dtkCDIHookPath = config.ResolveDTKCDIHookPath(m.logger, opts.dtkCDIHookPath)

	if outputFileFormat := formatFromFilename(opts.output); outputFileFormat != "" {
		m.logger.Debugf("Inferred output format as %q from output file name", outputFileFormat)
		if !c.IsSet("format") {
			opts.format = outputFileFormat
		} else if outputFileFormat != opts.format {
			m.logger.Warningf("Requested output format %q does not match format implied by output file name: %q", opts.format, outputFileFormat)
		}
	}

	if err := parser.ValidateVendorName(opts.vendor); err != nil {
		return fmt.Errorf("invalid CDI vendor name: %v", err)
	}
	if err := parser.ValidateClassName(opts.class); err != nil {
		return fmt.Errorf("invalid CDI class name: %v", err)
	}
	return nil
}

func (m command) run(c *cli.Context, opts *options) error {
	spec, err := m.generateSpec(opts)
	if err != nil {
		return fmt.Errorf("failed to generate CDI spec: %v", err)
	}
	m.logger.Infof("Generated CDI spec with version %v", spec.Raw().Version)

	if opts.output == "" {
		_, err := spec.WriteTo(os.Stdout)
		if err != nil {
			return fmt.Errorf("failed to write CDI spec to STDOUT: %v", err)
		}
		return nil
	}

	return spec.Save(opts.output)
}

func formatFromFilename(filename string) string {
	ext := filepath.Ext(filename)
	switch strings.ToLower(ext) {
	case ".json":
		return spec.FormatJSON
	case ".yaml", ".yml":
		return spec.FormatYAML
	}

	return ""
}

func (m command) generateSpec(opts *options) (spec.Interface, error) {
	var deviceNamers []c3000cdi.DeviceNamer
	for _, strategy := range opts.deviceNameStrategies.Value() {
		deviceNamer, err := c3000cdi.NewDeviceNamer(strategy)
		if err != nil {
			return nil, fmt.Errorf("failed to create device namer: %v", err)
		}
		deviceNamers = append(deviceNamers, deviceNamer)
	}

	cdilib, err := c3000cdi.New(
		c3000cdi.WithLogger(m.logger),
		c3000cdi.WithDriverRoot(opts.driverRoot),
		c3000cdi.WithDevRoot(opts.devRoot),
		c3000cdi.WithDTKCDIHookPath(opts.dtkCDIHookPath),
		c3000cdi.WithLdconfigPath(opts.ldconfigPath),
		c3000cdi.WithDeviceNamers(deviceNamers...),
		c3000cdi.WithMode(opts.mode),
		c3000cdi.WithConfigSearchPaths(opts.configSearchPaths.Value()),
		c3000cdi.WithLibrarySearchPaths(opts.librarySearchPaths.Value()),
	)
	if err != nil {
		return nil, fmt.Errorf("failed to create CDI library: %v", err)
	}

	deviceSpecs, err := cdilib.GetAllDeviceSpecs()
	if err != nil {
		return nil, fmt.Errorf("failed to create device CDI specs: %v", err)
	}

	commonEdits, err := cdilib.GetCommonEdits()
	if err != nil {
		return nil, fmt.Errorf("failed to create edits common for entities: %v", err)
	}

	return spec.New(
		spec.WithVendor(opts.vendor),
		spec.WithClass(opts.class),
		spec.WithDeviceSpecs(deviceSpecs),
		spec.WithEdits(*commonEdits.ContainerEdits),
		spec.WithFormat(opts.format),
		spec.WithMergedDeviceOptions(
			transform.WithName(allDeviceName),
			transform.WithSkipIfExists(true),
		),
		spec.WithPermissions(0644),
	)
}