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

package configure

import (
8
9
10
11
12
	"dcu-container-toolkit/internal/logger"
	"dcu-container-toolkit/pkg/config/engine"
	"dcu-container-toolkit/pkg/config/engine/containerd"
	"dcu-container-toolkit/pkg/config/engine/crio"
	"dcu-container-toolkit/pkg/config/engine/docker"
songlinfeng's avatar
songlinfeng committed
13
        "dcu-container-toolkit/pkg/config/engine/podman"
songlinfeng's avatar
songlinfeng committed
14
15
16
	"encoding/json"
	"fmt"
	"path/filepath"
songlinfeng's avatar
songlinfeng committed
17
      
songlinfeng's avatar
songlinfeng committed
18
19
20
21
22
23
24
	"github.com/urfave/cli/v2"
)

const (
	defaultRuntime = "docker"

	// defaultDTKRuntimeName is the default name to use in configs for the DTK Container Runtime
songlinfeng's avatar
songlinfeng committed
25
	defaultDTKRuntimeName = "dcu"
songlinfeng's avatar
songlinfeng committed
26
27

	// defaultDTKRuntimeExecutable is the default DTK Container Runtime executable file name
28
29
	defaultDTKRuntimeExecutable      = "dcu-container-runtime"
	defaultDTKRuntimeExpecutablePath = "/usr/bin/dcu-container-runtime"
songlinfeng's avatar
songlinfeng committed
30

songlinfeng's avatar
songlinfeng committed
31
        defaultPodmanConfigFilePath     = "/usr/share/containers/containers.conf"
songlinfeng's avatar
songlinfeng committed
32
33
34
35
36
37
38
39
40
	defaultContainerdConfigFilePath = "/etc/containerd/config.toml"
	defaultCrioConfigFilePath       = "/etc/crio/crio.conf"
	defaultDockerConfigFilePath     = "/etc/docker/daemon.json"
)

type command struct {
	logger logger.Interface
}

songlinfeng's avatar
songlinfeng committed
41

songlinfeng's avatar
songlinfeng committed
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
// NewCommand constructs an configure command with the specified logger
func NewCommand(logger logger.Interface) *cli.Command {
	c := command{
		logger: logger,
	}
	return c.build()
}

// config defines the options that can be set for the CLI through config files,
// environment variables, or command line config
type config struct {
	dryRun         bool
	runtime        string
	configFilePath string
	mode           string

	runtimeConfigOverrideJSON string

	dtkRuntime struct {
		name         string
		path         string
		setAsDefault bool
	}

	// cdi-specific options
	cdi struct {
		enabled bool
	}
}

func (m command) build() *cli.Command {
	// Create a config struct to hold the parsed environment variables or command line flags
	config := config{}

	// Create the 'configure' command
	configure := cli.Command{
		Name:  "configure",
		Usage: "Add a runtime to the specified container engine",
		Before: func(c *cli.Context) error {
			return m.validateFlags(c, &config)
		},
		Action: func(c *cli.Context) error {
			return m.configureWrapper(c, &config)
		},
	}

	configure.Flags = []cli.Flag{
		&cli.BoolFlag{
			Name:        "dry-run",
			Usage:       "update the runtime configuration as required but don't write changes to disk",
			Destination: &config.dryRun,
		},
		&cli.StringFlag{
			Name:        "runtime",
			Usage:       "the target runtime engine; one of [containerd, crio, docker]",
			Value:       defaultRuntime,
			Destination: &config.runtime,
		},
		&cli.StringFlag{
			Name:        "config",
			Usage:       "path to the config file for the target runtime",
			Destination: &config.configFilePath,
		},
		&cli.StringFlag{
			Name:        "config-mode",
			Usage:       "the config mode for runtimes that support multiple configuration mechanisms",
			Destination: &config.mode,
		},
		&cli.StringFlag{
songlinfeng's avatar
songlinfeng committed
111
112
			Name:        "dcu-runtime-name",
			Usage:       "specify the name of the DCU runtime that will be added",
songlinfeng's avatar
songlinfeng committed
113
114
115
116
			Value:       defaultDTKRuntimeName,
			Destination: &config.dtkRuntime.name,
		},
		&cli.StringFlag{
songlinfeng's avatar
songlinfeng committed
117
			Name:        "dcu-runtime-path",
songlinfeng's avatar
songlinfeng committed
118
			Aliases:     []string{"runtime-path"},
songlinfeng's avatar
songlinfeng committed
119
			Usage:       "specify the path to the DCU runtime executable",
songlinfeng's avatar
songlinfeng committed
120
121
122
123
			Value:       defaultDTKRuntimeExecutable,
			Destination: &config.dtkRuntime.path,
		},
		&cli.BoolFlag{
songlinfeng's avatar
songlinfeng committed
124
			Name:        "dcu-set-as-default",
songlinfeng's avatar
songlinfeng committed
125
			Aliases:     []string{"set-as-default"},
songlinfeng's avatar
songlinfeng committed
126
			Usage:       "set the DCU runtime as the default runtime",
songlinfeng's avatar
songlinfeng committed
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
			Destination: &config.dtkRuntime.setAsDefault,
		},
		&cli.BoolFlag{
			Name:        "cdi.enabled",
			Aliases:     []string{"cdi.enable"},
			Usage:       "Enable CDI in the configured runtime",
			Destination: &config.cdi.enabled,
		},
		&cli.StringFlag{
			Name:        "runtime-config-override",
			Destination: &config.runtimeConfigOverrideJSON,
			Usage:       "specify additional runtime options as a JSON string. The paths are relative to the runtime config.",
			Value:       "{}",
			EnvVars:     []string{"RUNTIME_CONFIG_OVERRIDE"},
		},
	}
	return &configure
}

func (m command) validateFlags(c *cli.Context, config *config) error {
	if config.mode != "" && config.mode != "config-file" {
		m.logger.Warningf("Ignoring unsupported config mode for %v: %q", config.runtime, config.mode)
	}
	config.mode = "config-file"

	switch config.runtime {
songlinfeng's avatar
songlinfeng committed
153
	case "containerd", "crio", "docker", "podman":
songlinfeng's avatar
songlinfeng committed
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
		break
	default:
		return fmt.Errorf("unrecognized runtime '%v'", config.runtime)
	}

	switch config.runtime {
	case "containerd", "crio":
		if config.dtkRuntime.path == defaultDTKRuntimeExecutable {
			config.dtkRuntime.path = defaultDTKRuntimeExpecutablePath
		}
		if !filepath.IsAbs(config.dtkRuntime.path) {
			return fmt.Errorf("the DTK runtime path %q is not an absolute path", config.dtkRuntime.path)
		}
	}

	if config.runtime != "containerd" && config.runtime != "docker" {
		if config.cdi.enabled {
			m.logger.Warningf("Ignoring cdi.enabled flag for %v", config.runtime)
		}
		config.cdi.enabled = false
	}

	if config.runtimeConfigOverrideJSON != "" && config.runtime != "containerd" {
		m.logger.Warningf("Ignoring runtime-config-override flag for %v", config.runtime)
		config.runtimeConfigOverrideJSON = ""
	}

	return nil
}

// configureWrapper updates the specified container engine config to enable the DTK runtime
func (m command) configureWrapper(c *cli.Context, config *config) error {
	switch config.mode {
	case "config-file":
		return m.configureConfigFile(c, config)
	}
	return fmt.Errorf("unsupported config-mode: %v", config.mode)
}

// configureConfigFile updates the specified container engine config file to enable the DTK runtime.
func (m command) configureConfigFile(c *cli.Context, config *config) error {
	configFilePath := config.resolveConfigFilePath()

	var cfg engine.Interface
	var err error
	switch config.runtime {
	case "containerd":
		cfg, err = containerd.New(
			containerd.WithLogger(m.logger),
			containerd.WithPath(configFilePath),
		)
	case "crio":
		cfg, err = crio.New(
			crio.WithLogger(m.logger),
			crio.WithPath(configFilePath),
		)
	case "docker":
		cfg, err = docker.New(
			docker.WithLogger(m.logger),
			docker.WithPath(configFilePath),
		)
songlinfeng's avatar
songlinfeng committed
215
216
217
218
219
        case "podman":
                cfg, err = podman.New(
                        podman.WithLogger(m.logger),
                        podman.WithPath(configFilePath),
                )
songlinfeng's avatar
songlinfeng committed
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
264
265
266
267
268
269
270
271
272
273
274
275
276
	default:
		err = fmt.Errorf("unrecognized runtime '%v'", config.runtime)
	}
	if err != nil || cfg == nil {
		return fmt.Errorf("unable to load config for runtime %v: %v", config.runtime, err)
	}

	runtimeConfigOverride, err := config.runtimeConfigOverride()
	if err != nil {
		return fmt.Errorf("unable to parse config overrides: %w", err)
	}

	err = cfg.AddRuntime(
		config.dtkRuntime.name,
		config.dtkRuntime.path,
		config.dtkRuntime.setAsDefault,
		runtimeConfigOverride,
	)
	if err != nil {
		return fmt.Errorf("unable to update config: %v", err)
	}

	err = enableCDI(config, cfg)
	if err != nil {
		return fmt.Errorf("failed to enable CDI in %s: %w", config.runtime, err)
	}

	outputPath := config.getOuputConfigPath()
	n, err := cfg.Save(outputPath)
	if err != nil {
		return fmt.Errorf("unable to flush config: %v", err)
	}

	if outputPath != "" {
		if n == 0 {
			m.logger.Infof("Removed empty config from %v", outputPath)
		} else {
			m.logger.Infof("Wrote updated config to %v", outputPath)
		}
		m.logger.Infof("It is recommended that %v daemon be restarted.", config.runtime)
	}

	return nil
}

// resolveConfigFilePath returns the default config file path for the configured container engine
func (c *config) resolveConfigFilePath() string {
	if c.configFilePath != "" {
		return c.configFilePath
	}
	switch c.runtime {
	case "containerd":
		return defaultContainerdConfigFilePath
	case "crio":
		return defaultCrioConfigFilePath
	case "docker":
		return defaultDockerConfigFilePath
songlinfeng's avatar
songlinfeng committed
277
278
        case "podman":
                return defaultPodmanConfigFilePath
songlinfeng's avatar
songlinfeng committed
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
	}
	return ""
}

// getOuputConfigPath returns the configured config path or "" if dry-run is enabled
func (c *config) getOuputConfigPath() string {
	if c.dryRun {
		return ""
	}
	return c.resolveConfigFilePath()
}

// runtimeConfigOverride converts the specified runtimeConfigOverride JSON string to a map.
func (o *config) runtimeConfigOverride() (map[string]interface{}, error) {
	if o.runtimeConfigOverrideJSON == "" {
		return nil, nil
	}

	runtimeOptions := make(map[string]interface{})
	if err := json.Unmarshal([]byte(o.runtimeConfigOverrideJSON), &runtimeOptions); err != nil {
		return nil, fmt.Errorf("failed to read %v as JSON: %w", o.runtimeConfigOverrideJSON, err)
	}

	return runtimeOptions, nil
}

// enableCDI enables the use of CDI in the corresponding container engine
func enableCDI(config *config, cfg engine.Interface) error {
	if !config.cdi.enabled {
		return nil
	}
	switch config.runtime {
	case "containerd":
		cfg.Set("enable_cdi", true)
	case "docker":
		cfg.Set("features", map[string]bool{"cdi": true})
	default:
		return fmt.Errorf("enabling CDI in %s is not supported", config.runtime)
	}
	return nil
}