docker.go 2.49 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
/**
# Copyright (c) 2024, HCUOpt CORPORATION.  All rights reserved.
**/

package docker

import (
	"dtk-container-toolkit/internal/logger"
	"dtk-container-toolkit/pkg/config/engine"
	"encoding/json"
	"fmt"
)

const (
	defaultDockerRuntime = "runc"
)

// Config defines a docker config file.
// TODO: This should not be public, but we need to access it from the tests in tools/container/docker
type Config map[string]interface{}

var _ engine.Interface = (*Config)(nil)

// New creates a docker config with the specified options
func New(opts ...Option) (engine.Interface, error) {
	b := &builder{}
	for _, opt := range opts {
		opt(b)
	}

	if b.logger == nil {
		b.logger = logger.New()
	}

	return b.build()
}

// AddRuntime adds a new runtime to the docker config
func (c *Config) AddRuntime(name string, path string, setAsDefault bool, _ ...map[string]interface{}) error {
	if c == nil {
		return fmt.Errorf("config is nil")
	}

	config := *c

	// Read the existing runtimes
	runtimes := make(map[string]interface{})
	if _, exists := config["runtimes"]; exists {
		runtimes = config["runtimes"].(map[string]interface{})
	}

	// Add / update the runtime definitions
	runtimes[name] = map[string]interface{}{
		"path": path,
		"args": []string{},
	}

	config["runtimes"] = runtimes

	if setAsDefault {
		config["default-runtime"] = name
	}

	*c = config
	return nil
}

// DefaultRuntime returns the default runtime for the docker config
func (c Config) DefaultRuntime() string {
	r, ok := c["default-runtime"].(string)
	if !ok {
		return ""
	}
	return r
}

// RemoveRuntime removes a runtime from the docker config
func (c *Config) RemoveRuntime(name string) error {
	if c == nil {
		return nil
	}
	config := *c

	if _, exists := config["default-runtime"]; exists {
		defaultRuntime := config["default-runtime"].(string)
		if defaultRuntime == name {
			config["default-runtime"] = defaultDockerRuntime
		}
	}

	if _, exists := config["runtimes"]; exists {
		runtimes := config["runtimes"].(map[string]interface{})

		delete(runtimes, name)

		if len(runtimes) == 0 {
			delete(config, "runtimes")
		}
	}

	*c = config

	return nil
}

// Set sets the specified docker option
func (c *Config) Set(key string, value interface{}) {
	(*c)[key] = value
}

// Save writes the config to the specified path
func (c Config) Save(path string) (int64, error) {
	output, err := json.MarshalIndent(c, "", "    ")
	if err != nil {
		return 0, fmt.Errorf("unable to convert to JSON: %v", err)
	}

	n, err := engine.Config(path).Write(output)
	return int64(n), err
}