/
env.go
302 lines (265 loc) · 7.87 KB
/
env.go
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
package dev
import (
"context"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path"
"strings"
"time"
"github.com/go-logr/logr"
"sigs.k8s.io/yaml"
kindv1alpha4 "sigs.k8s.io/kind/pkg/apis/config/v1alpha4"
"sigs.k8s.io/kind/pkg/cluster"
"sigs.k8s.io/kind/pkg/cluster/nodes"
"sigs.k8s.io/kind/pkg/cluster/nodeutils"
kindcmd "sigs.k8s.io/kind/pkg/cmd"
)
type EnvironmentConfig struct {
// Cluster initializers prepare a cluster for use.
ClusterInitializers []ClusterInitializer
// Container runtime to use
ContainerRuntime ContainerRuntime
NewCluster NewClusterFunc
ClusterOptions []ClusterOption
KindClusterConfig *kindv1alpha4.Cluster
}
// Apply default configuration.
func (c *EnvironmentConfig) Default() {
if len(c.ContainerRuntime) == 0 {
c.ContainerRuntime = ContainerRuntimeAuto
}
if c.NewCluster == nil {
c.NewCluster = NewCluster
}
if c.KindClusterConfig == nil {
defaultCluster := defaultKindClusterConfig()
c.KindClusterConfig = &defaultCluster
}
}
func sanitizeKindClusterConfig(conf *kindv1alpha4.Cluster) {
conf.TypeMeta = kindv1alpha4.TypeMeta{
Kind: "Cluster",
APIVersion: "kind.x-k8s.io/v1alpha4",
}
}
func defaultKindClusterConfig() kindv1alpha4.Cluster {
cluster := kindv1alpha4.Cluster{
TypeMeta: kindv1alpha4.TypeMeta{
Kind: "Cluster",
APIVersion: "kind.x-k8s.io/v1alpha4",
},
Nodes: []kindv1alpha4.Node{
{
Role: kindv1alpha4.ControlPlaneRole,
},
},
}
if _, err := os.Lstat("/dev/dm-0"); err == nil {
cluster.Nodes[0].ExtraMounts = []kindv1alpha4.Mount{
{
HostPath: "/dev/dm-0",
ContainerPath: "/dev/dm-0",
Propagation: kindv1alpha4.MountPropagationHostToContainer,
},
}
}
kindv1alpha4.SetDefaultsCluster(&cluster)
sanitizeKindClusterConfig(&cluster)
return cluster
}
type EnvironmentOption interface {
ApplyToEnvironmentConfig(c *EnvironmentConfig)
}
type NewClusterFunc func(kubeconfigPath string, opts ...ClusterOption) (*Cluster, error)
type ClusterInitializer interface {
Init(ctx context.Context, cluster *Cluster) error
}
// Environment represents a development environment.
type Environment struct {
Name string
// Working directory of the environment.
// Temporary files/kubeconfig etc. will be stored here.
WorkDir string
Cluster *Cluster
config EnvironmentConfig
}
// Creates a new development environment.
func NewEnvironment(name, workDir string, opts ...EnvironmentOption) *Environment {
env := &Environment{
Name: name,
WorkDir: workDir,
}
for _, opt := range opts {
opt.ApplyToEnvironmentConfig(&env.config)
}
env.config.Default()
return env
}
// Initializes the environment and prepares it for use.
func (env *Environment) Init(ctx context.Context) error {
if err := env.setContainerRuntime(); err != nil {
return err
}
if env.config.KindClusterConfig == nil {
return fmt.Errorf("no KinD cluster config found")
}
if err := os.MkdirAll(env.WorkDir, os.ModePerm); err != nil {
return fmt.Errorf("creating workdir: %w", err)
}
kindConfigYamlBytes, err := yaml.Marshal(env.config.KindClusterConfig)
if err != nil {
return fmt.Errorf("failed to process the KinD cluster config as a YAML: %w", err)
}
kubeconfigPath := path.Join(env.WorkDir, "kubeconfig.yaml")
kindconfigPath := path.Join(env.WorkDir, "/kind.yaml")
if err := os.WriteFile(
kindconfigPath, kindConfigYamlBytes, os.ModePerm); err != nil {
return fmt.Errorf("creating kind cluster config: %w", err)
}
provider, err := env.getKindProvider()
if err != nil {
return err
}
// check if cluster already exists with the same name
createCluster := true
existingKindClusters, err := provider.List()
if err != nil {
return fmt.Errorf("failed to fetch the existing KinD clusters: %w", err)
}
for _, cluster := range existingKindClusters {
if env.Name == cluster {
createCluster = false
break
}
}
if createCluster {
if err := provider.Create(env.Name,
cluster.CreateWithKubeconfigPath(kubeconfigPath),
cluster.CreateWithConfigFile(kindconfigPath),
cluster.CreateWithDisplayUsage(true),
cluster.CreateWithDisplaySalutation(true),
cluster.CreateWithWaitForReady(5*time.Minute),
cluster.CreateWithRetain(false),
); err != nil {
return fmt.Errorf("failed to create the cluster: %w", err)
}
}
// Create _all_ the clients
cluster, err := env.config.NewCluster(
env.WorkDir, append(env.config.ClusterOptions, WithKubeconfigPath(kubeconfigPath))...)
if err != nil {
return fmt.Errorf("creating k8s clients: %w", err)
}
env.Cluster = cluster
// Run ClusterInitializers
if createCluster {
for _, initializer := range env.config.ClusterInitializers {
if err := initializer.Init(ctx, cluster); err != nil {
return fmt.Errorf("running cluster initializer: %w", err)
}
}
}
return nil
}
// Destroy/Teardown the development environment.
func (env *Environment) Destroy(ctx context.Context) error {
provider, err := env.getKindProvider()
if err != nil {
return err
}
kubeConfigPath := path.Join(env.WorkDir, "kubeconfig.yaml")
if err := provider.Delete(env.Name, kubeConfigPath); err != nil {
return fmt.Errorf("failed to delete the cluster: %w", err)
}
return nil
}
// Load an image from a tar archive into the environment.
func (env *Environment) LoadImageFromTar(filePath string) error {
provider, err := env.getKindProvider()
if err != nil {
return err
}
nodesList, err := provider.ListInternalNodes(env.Name)
if err != nil {
return fmt.Errorf("failed to list the nodes of the KinD cluster: %w", err)
}
if _, err := os.Stat(filePath); err != nil {
return err
}
for _, node := range nodesList {
node := node
if err := loadImageTarIntoNode(filePath, node); err != nil {
return fmt.Errorf("failed to load the image: %w", err)
}
}
return nil
}
func loadImageTarIntoNode(imageTarPath string, node nodes.Node) error {
f, err := os.Open(imageTarPath)
if err != nil {
return fmt.Errorf("failed to open the image: %w", err)
}
defer f.Close()
return nodeutils.LoadImageArchive(node, f)
}
func (env *Environment) RunKindCommand(ctx context.Context, stdout, stderr io.Writer, args ...string) error {
log := logr.FromContextOrDiscard(ctx)
log.Info("exec: kind " + strings.Join(args, " "))
kindCmd := exec.CommandContext( //nolint:gosec
ctx, "kind", args...,
)
kindCmd.Env = os.Environ()
if env.config.ContainerRuntime == "podman" {
kindCmd.Env = append(kindCmd.Env, "KIND_EXPERIMENTAL_PROVIDER=podman")
}
kindCmd.Stdout = stdout
kindCmd.Stderr = stderr
return kindCmd.Run()
}
func (env *Environment) setContainerRuntime() error {
if env.config.ContainerRuntime == ContainerRuntimeAuto {
cr, err := DetectContainerRuntime()
if err != nil {
return err
}
env.config.ContainerRuntime = cr
}
return nil
}
func DetectContainerRuntime() (ContainerRuntime, error) {
if _, err := exec.LookPath("podman"); err == nil {
return ContainerRuntimePodman, nil
} else if !errors.Is(err, exec.ErrNotFound) {
return "", fmt.Errorf("looking up podman executable: %w", err)
}
if _, err := exec.LookPath("docker"); err == nil {
return ContainerRuntimeDocker, nil
} else if !errors.Is(err, exec.ErrNotFound) {
return "", fmt.Errorf("looking up docker executable: %w", err)
}
return "", fmt.Errorf("could not detect container runtime")
}
func (env *Environment) getKindProvider() (cluster.Provider, error) {
var providerOpt cluster.ProviderOption
switch env.config.ContainerRuntime {
case ContainerRuntimeDocker:
providerOpt = cluster.ProviderWithDocker()
case ContainerRuntimePodman:
providerOpt = cluster.ProviderWithPodman()
case ContainerRuntimeAuto:
if err := env.setContainerRuntime(); err != nil {
return cluster.Provider{}, fmt.Errorf("failed to auto-set the container runtime: %w", err)
}
return env.getKindProvider()
default:
return cluster.Provider{}, fmt.Errorf("unknown container runtime found")
}
logger := kindcmd.NewLogger()
return *cluster.NewProvider(
cluster.ProviderWithLogger(logger),
providerOpt,
), nil
}