-
Notifications
You must be signed in to change notification settings - Fork 64
/
utils.go
285 lines (239 loc) · 7.55 KB
/
utils.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
package run
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/containerd/nerdctl/pkg/strutil"
"github.com/dustin/go-humanize"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/uuid"
machineapi "kraftkit.sh/api/machine/v1alpha1"
networkapi "kraftkit.sh/api/network/v1alpha1"
volumeapi "kraftkit.sh/api/volume/v1alpha1"
"kraftkit.sh/initrd"
"kraftkit.sh/log"
machinename "kraftkit.sh/machine/name"
"kraftkit.sh/machine/volume"
"kraftkit.sh/unikraft"
"kraftkit.sh/unikraft/app"
)
// Are we publishing ports? E.g. -p/--ports=127.0.0.1:80:8080/tcp ...
func (opts *Run) parsePorts(_ context.Context, machine *machineapi.Machine) error {
if len(opts.Ports) == 0 {
return nil
}
opts.Ports = strutil.DedupeStrSlice(opts.Ports)
for _, port := range opts.Ports {
parsed, err := machineapi.ParsePort(port)
if err != nil {
return err
}
machine.Spec.Ports = append(machine.Spec.Ports, parsed...)
}
return nil
}
// Was a network specified? E.g. --network=bridge:kraft0
func (opts *Run) parseNetworks(ctx context.Context, machine *machineapi.Machine) error {
if opts.Network == "" {
return nil
}
// Try to discover the user-provided network.
found, err := opts.networkController.Get(ctx, &networkapi.Network{
ObjectMeta: metav1.ObjectMeta{
Name: opts.networkName,
},
})
if err != nil {
return err
}
// Generate the UID pre-emptively so that we can uniquely reference the
// network interface which will allow us to clean it up later. Additionally,
// it's OK if the IP or MAC address are empty, the network controller will
// populate values if they are unset and will populate with new values
// following the returning from the Update operation.
newIface := networkapi.NetworkInterfaceTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
UID: uuid.NewUUID(),
},
Spec: networkapi.NetworkInterfaceSpec{
IP: opts.IP,
MacAddress: opts.MacAddress,
},
}
// Update the list of interfaces
if found.Spec.Interfaces == nil {
found.Spec.Interfaces = []networkapi.NetworkInterfaceTemplateSpec{}
}
found.Spec.Interfaces = append(found.Spec.Interfaces, newIface)
// Update the network with the new interface.
found, err = opts.networkController.Update(ctx, found)
if err != nil {
return err
}
// Only use the single new interface.
for _, iface := range found.Spec.Interfaces {
if iface.UID == newIface.UID {
newIface = iface
break
}
}
// Set the interface on the machine.
found.Spec.Interfaces = []networkapi.NetworkInterfaceTemplateSpec{newIface}
machine.Spec.Networks = []networkapi.NetworkSpec{found.Spec}
return nil
}
// assignName determines the machine instance's name either from a provided
// argument or randomly generates one.
func (opts *Run) assignName(ctx context.Context, machine *machineapi.Machine) error {
if opts.Name == "" {
machine.ObjectMeta.Name = machinename.NewRandomMachineName(0)
return nil
}
// Check if this name has been previously used
machines, err := opts.machineController.List(ctx, &machineapi.MachineList{})
if err != nil {
return err
}
for _, found := range machines.Items {
if opts.Name == found.Name {
return fmt.Errorf("machine instance name already in use: %s", opts.Name)
}
}
machine.ObjectMeta.Name = opts.Name
return nil
}
// Was a volume specified? E.g. --volume=path:path
func (opts *Run) parseVolumes(ctx context.Context, machine *machineapi.Machine) error {
if len(opts.Volumes) == 0 {
return nil
}
var err error
controllers := map[string]volumeapi.VolumeService{}
machine.Spec.Volumes = []volumeapi.Volume{}
for _, volLine := range opts.Volumes {
var hostPath, mountPath string
split := strings.Split(volLine, ":")
if len(split) == 2 {
hostPath = split[0]
mountPath = split[1]
} else {
return fmt.Errorf("invalid syntax for --volume=%s expected --volume=<host>:<machine>", volLine)
}
var driver string
for sname, strategy := range volume.Strategies() {
if ok, _ := strategy.IsCompatible(hostPath, nil); !ok || err != nil {
continue
}
if _, ok := controllers[sname]; !ok {
controllers[sname], err = strategy.NewVolumeV1alpha1(ctx)
if err != nil {
return fmt.Errorf("could not prepare %s volume service: %w", sname, err)
}
}
driver = sname
}
if len(driver) == 0 {
return fmt.Errorf("could not find compatible volume driver for %s", hostPath)
}
vol, err := controllers[driver].Create(ctx, &volumeapi.Volume{
ObjectMeta: metav1.ObjectMeta{
Name: hostPath,
},
Spec: volumeapi.VolumeSpec{
Driver: driver,
Source: hostPath,
Destination: mountPath,
ReadOnly: false, // TODO(nderjung): Options are not yet supported.
},
})
if err != nil {
return fmt.Errorf("failed to create volume: %w", err)
}
machine.Spec.Volumes = append(machine.Spec.Volumes, *vol)
}
return nil
}
// Were any volumes supplied in the Kraftfile
func (opts *Run) parseKraftfileVolumes(ctx context.Context, project app.Application, machine *machineapi.Machine) error {
if project.Volumes() == nil {
return nil
}
var err error
controllers := map[string]volumeapi.VolumeService{}
machine.Spec.Volumes = []volumeapi.Volume{}
for _, volcfg := range project.Volumes() {
driver := volcfg.Driver()
if len(driver) == 0 {
for sname, strategy := range volume.Strategies() {
if ok, _ := strategy.IsCompatible(volcfg.Source(), nil); !ok || err != nil {
continue
}
if _, ok := controllers[sname]; !ok {
controllers[sname], err = strategy.NewVolumeV1alpha1(ctx)
if err != nil {
return fmt.Errorf("could not prepare %s volume service: %w", sname, err)
}
}
driver = sname
}
}
if len(driver) == 0 {
return fmt.Errorf("could not find compatible volume driver for %s", volcfg.Source())
}
vol, err := controllers[driver].Create(ctx, &volumeapi.Volume{
ObjectMeta: metav1.ObjectMeta{
Name: volcfg.Source(),
},
Spec: volumeapi.VolumeSpec{
Driver: driver,
Source: volcfg.Source(),
Destination: volcfg.Destination(),
ReadOnly: volcfg.ReadOnly(),
},
})
if err != nil {
return fmt.Errorf("failed to create volume: %w", err)
}
machine.Spec.Volumes = append(machine.Spec.Volumes, *vol)
}
return nil
}
// parse the provided `--rootfs` flag which ultimately is passed into the
// dynamic Initrd interface which either looks up or constructs the archive
// based on the value of the flag.
func (opts *Run) prepareRootfs(ctx context.Context, machine *machineapi.Machine) error {
// If the user has supplied an initram path, set this now, this overrides any
// preparation and is considered higher priority compared to what has been set
// prior to this point.
if opts.Rootfs == "" || machine.Status.InitrdPath != "" {
return nil
}
ramfs, err := initrd.New(ctx,
opts.Rootfs,
initrd.WithOutput(filepath.Join(opts.workdir, unikraft.BuildDir, initrd.DefaultInitramfsFileName)),
initrd.WithCacheDir(filepath.Join(opts.workdir, unikraft.BuildDir, "rootfs-cache")),
)
if err != nil {
return fmt.Errorf("could not prepare initramfs: %w", err)
}
machine.Status.InitrdPath, err = ramfs.Build(ctx)
if err != nil {
return err
}
// Warn if the initrd path is greater than allocated memory
fi, err := os.Stat(machine.Status.InitrdPath)
if err != nil {
return err
}
memRequest := machine.Spec.Resources.Requests[corev1.ResourceMemory]
if memRequest.Value() < fi.Size() {
log.G(ctx).Warnf("requested memory (%s) is less than initramfs (%s)",
humanize.Bytes(uint64(memRequest.Value())),
humanize.Bytes(uint64(fi.Size())),
)
}
return nil
}