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

package runtime

import (
8
9
10
	"dcu-container-toolkit/internal/config"
	"dcu-container-toolkit/internal/info"
	"dcu-container-toolkit/internal/lookup/root"
songlinfeng's avatar
songlinfeng committed
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
	"encoding/json"
	"errors"
	"fmt"
	"strings"

	"github.com/opencontainers/runtime-spec/specs-go"
)

// Run is an entry point that allows for idiomatic handling of errors
// when calling from the main function.
func (r rt) Run(argv []string) (rerr error) {
	defer func() {
		if rerr != nil {
			r.logger.Errorf("%v", rerr)
		}
	}()

	printVersion := hasVersionFlag(argv)
	if printVersion {
		fmt.Printf("%v version %v\n", "DTK Container Runtime", info.GetVersionString(fmt.Sprintf("spec: %v", specs.Version)))
	}

	cfg, err := config.GetConfig()
	if err != nil {
		return fmt.Errorf("error loading config: %v", err)
	}
	r.logger.Update(
		cfg.DTKContainerRuntimeConfig.DebugFilePath,
		cfg.DTKContainerRuntimeConfig.LogLevel,
		argv,
	)
	defer func() {
		if rerr != nil {
			r.logger.Errorf("%v", rerr)
		}
		if err := r.logger.Reset(); err != nil {
			rerr = errors.Join(rerr, fmt.Errorf("failed to reset logger: %v", err))
		}
	}()

51
	//nolint:staticcheck  // TODO(elezar): We should switch the dcu-container-runtime from using dcu-ctk to using dcu-cdi-hook.
songlinfeng's avatar
songlinfeng committed
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
	cfg.DTKCTKConfig.Path = config.ResolveDTKCDIHookPath(r.logger, cfg.DTKCTKConfig.Path)

	// Print the config to the output.
	configJSON, err := json.MarshalIndent(cfg, "", "  ")
	if err == nil {
		r.logger.Debugf("Running with config:\n%v", string(configJSON))
	} else {
		r.logger.Debugf("Running with config:\n%+v", cfg)
	}

	driver := root.New(
		root.WithLogger(r.logger),
		root.WithDriverRoot(""),
	)

	r.logger.Infof("Command line arguments: %v", argv)
	runtime, err := newDTKContainerRuntime(r.logger, cfg, argv, driver)
	if err != nil {
		return fmt.Errorf("failed to create DTK Container Runtime: %v", err)
	}

	if printVersion {
		fmt.Print("\n")
	}
	return runtime.Exec(argv)
}

func (r rt) Errorf(format string, args ...interface{}) {
	r.logger.Errorf(format, args...)
}

// TODO: This should be refactored / combined with parseArgs in logger.
func hasVersionFlag(args []string) bool {
	for i := 0; i < len(args); i++ {
		param := args[i]

		parts := strings.SplitN(param, "=", 2)
		trimmed := strings.TrimLeft(parts[0], "-")
		// If this is not a flag we continue
		if parts[0] == trimmed {
			continue
		}

		// Check the version flag
		if trimmed == "version" {
			return true
		}
	}

	return false
}