-
Notifications
You must be signed in to change notification settings - Fork 63
/
packager_kraftfile_runtime.go
348 lines (299 loc) · 9.8 KB
/
packager_kraftfile_runtime.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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2023, Unikraft GmbH and The KraftKit Authors.
// Licensed under the BSD-3-Clause License (the "License").
// You may not use this file except in compliance with the License.
package pkg
import (
"context"
"fmt"
"os"
"strings"
"github.com/mattn/go-shellwords"
"kraftkit.sh/config"
"kraftkit.sh/internal/cli/kraft/utils"
"kraftkit.sh/log"
"kraftkit.sh/pack"
"kraftkit.sh/packmanager"
"kraftkit.sh/tui/paraprogress"
"kraftkit.sh/tui/processtree"
"kraftkit.sh/tui/selection"
"kraftkit.sh/unikraft"
"kraftkit.sh/unikraft/target"
)
type packagerKraftfileRuntime struct{}
// String implements fmt.Stringer.
func (p *packagerKraftfileRuntime) String() string {
return "kraftfile-runtime"
}
// Packagable implements packager.
func (p *packagerKraftfileRuntime) Packagable(ctx context.Context, opts *PkgOptions, args ...string) (bool, error) {
if opts.Project == nil {
if err := opts.initProject(ctx); err != nil {
return false, err
}
}
if opts.Project.Runtime() == nil {
return false, fmt.Errorf("cannot package without unikraft core specification")
}
if opts.Project.Rootfs() != "" && opts.Rootfs == "" {
opts.Rootfs = opts.Project.Rootfs()
}
return true, nil
}
// Pack implements packager.
func (p *packagerKraftfileRuntime) Pack(ctx context.Context, opts *PkgOptions, args ...string) ([]pack.Package, error) {
var err error
var targ target.Target
targets := opts.Project.Targets()
qopts := []packmanager.QueryOption{
packmanager.WithName(opts.Project.Runtime().Name()),
packmanager.WithVersion(opts.Project.Runtime().Version()),
}
if len(targets) == 1 {
targ = targets[0]
} else if len(targets) > 1 {
// Filter project targets by any provided CLI options
targets = target.Filter(
targets,
opts.Architecture,
opts.Platform,
opts.Target,
)
switch {
case len(targets) == 0:
return nil, fmt.Errorf("could not detect any project targets based on plat=\"%s\" arch=\"%s\"", opts.Platform, opts.Architecture)
case len(targets) == 1:
targ = targets[0]
case config.G[config.KraftKit](ctx).NoPrompt && len(targets) > 1:
return nil, fmt.Errorf("could not determine what to run based on provided CLI arguments")
default:
targ, err = target.Select(targets)
if err != nil {
return nil, fmt.Errorf("could not select target: %v", err)
}
}
}
var selected *pack.Package
var packs []pack.Package
var kconfigs []string
if targ != nil {
for _, kc := range targ.KConfig() {
kconfigs = append(kconfigs, kc.String())
}
opts.Platform = targ.Platform().Name()
opts.Architecture = targ.Architecture().Name()
}
treemodel, err := processtree.NewProcessTree(
ctx,
[]processtree.ProcessTreeOption{
processtree.IsParallel(false),
processtree.WithRenderer(
log.LoggerTypeFromString(config.G[config.KraftKit](ctx).Log.Type) != log.FANCY,
),
processtree.WithFailFast(true),
processtree.WithHideOnSuccess(true),
},
processtree.NewProcessTreeItem(
fmt.Sprintf(
"searching for %s:%s",
opts.Project.Runtime().Name(),
opts.Project.Runtime().Version(),
),
"",
func(ctx context.Context) error {
qopts = append(qopts,
packmanager.WithArchitecture(opts.Architecture),
packmanager.WithPlatform(opts.Platform),
packmanager.WithKConfig(kconfigs),
)
packs, err = opts.pm.Catalog(ctx, append(qopts, packmanager.WithRemote(false))...)
if err != nil {
return fmt.Errorf("could not query catalog: %w", err)
} else if len(packs) == 0 {
// Try again with a remote update request. Save this to qopts in case we
// need to call `Catalog` again.
packs, err = opts.pm.Catalog(ctx, append(qopts, packmanager.WithRemote(true))...)
if err != nil {
return fmt.Errorf("could not query catalog: %w", err)
}
}
return nil
},
),
)
if err != nil {
return nil, err
}
if err := treemodel.Start(); err != nil {
return nil, err
}
if len(packs) == 0 {
return nil, fmt.Errorf(
"could not find runtime '%s:%s'",
opts.Project.Runtime().Name(),
opts.Project.Runtime().Version(),
)
} else if len(packs) == 1 {
selected = &packs[0]
} else if len(packs) > 1 {
// If a target has been previously selected, we can use this to filter the
// returned list of packages based on its platform and architecture.
if targ != nil {
found := []pack.Package{}
for _, p := range packs {
pt := p.(target.Target)
if pt.Architecture().String() == opts.Architecture && pt.Platform().String() == opts.Platform {
found = append(found, p)
}
}
// Could not find a package that matches the desired architecture and
// platform, prompt with available set of packages.
if len(found) == 0 {
if !config.G[config.KraftKit](ctx).NoPrompt {
log.G(ctx).Warnf("could not find package '%s:%s' based on %s/%s", opts.Project.Runtime().Name(), opts.Project.Runtime().Version(), opts.Platform, opts.Architecture)
p, err := selection.Select[pack.Package]("select alternative package with same name to continue", packs...)
if err != nil {
return nil, fmt.Errorf("could not select package: %w", err)
}
selected = p
} else {
return nil, fmt.Errorf("could not find package '%s:%s' based on %s/%s but %d others found but prompting has been disabled", opts.Project.Runtime().Name(), opts.Project.Runtime().Version(), opts.Platform, opts.Architecture, len(packs))
}
} else if len(found) == 1 {
selected = &found[0]
} else { // > 1
if !config.G[config.KraftKit](ctx).NoPrompt {
log.G(ctx).Infof("found %d packages named '%s:%s' based on %s/%s", len(found), opts.Project.Runtime().Name(), opts.Project.Runtime().Version(), opts.Platform, opts.Architecture)
p, err := selection.Select[pack.Package]("select package to continue", found...)
if err != nil {
return nil, fmt.Errorf("could not select package: %w", err)
}
selected = p
} else {
return nil, fmt.Errorf("found %d packages named '%s:%s' based on %s/%s but prompting has been disabled", len(found), opts.Project.Runtime().Name(), opts.Project.Runtime().Version(), opts.Platform, opts.Architecture)
}
}
} else {
selected, err = selection.Select[pack.Package]("multiple runtimes available", packs...)
if err != nil {
return nil, err
}
}
}
runtime := *selected
pulled, _, _ := runtime.PulledAt(ctx)
// Temporarily save the runtime package.
if err := runtime.Save(ctx); err != nil {
return nil, fmt.Errorf("could not save runtime package: %w", err)
}
// Remove the cached runtime package reference if it was not previously
// pulled.
if !pulled && opts.NoPull {
defer func() {
if err := runtime.Delete(ctx); err != nil {
log.G(ctx).Debugf("could not delete intermediate runtime package: %s", err.Error())
}
}()
}
if !pulled && !opts.NoPull {
paramodel, err := paraprogress.NewParaProgress(
ctx,
[]*paraprogress.Process{paraprogress.NewProcess(
fmt.Sprintf("pulling %s", runtime.String()),
func(ctx context.Context, w func(progress float64)) error {
popts := []pack.PullOption{}
if log.LoggerTypeFromString(config.G[config.KraftKit](ctx).Log.Type) == log.FANCY {
popts = append(popts, pack.WithPullProgressFunc(w))
}
return runtime.Pull(
ctx,
popts...,
)
},
)},
paraprogress.IsParallel(false),
paraprogress.WithRenderer(
log.LoggerTypeFromString(config.G[config.KraftKit](ctx).Log.Type) != log.FANCY,
),
paraprogress.WithFailFast(true),
)
if err != nil {
return nil, err
}
if err := paramodel.Start(); err != nil {
return nil, err
}
}
// Create a temporary directory we can use to store the artifacts from
// pulling and extracting the identified package.
tempDir, err := os.MkdirTemp("", "kraft-pkg-")
if err != nil {
return nil, fmt.Errorf("could not create temporary directory: %w", err)
}
defer func() {
os.RemoveAll(tempDir)
}()
// Crucially, the catalog should return an interface that also implements
// target.Target. This demonstrates that the implementing package can
// resolve application kernels.
targ, ok := runtime.(target.Target)
if !ok {
return nil, fmt.Errorf("package does not convert to target")
}
if opts.Rootfs, err = utils.BuildRootfs(ctx, opts.Workdir, opts.Rootfs, targ); err != nil {
return nil, fmt.Errorf("could not build rootfs: %w", err)
}
// If no arguments have been specified, use the ones which are default and
// that have been included in the package.
if len(opts.Args) == 0 {
if len(opts.Project.Command()) > 0 {
opts.Args = opts.Project.Command()
} else if len(targ.Command()) > 0 {
opts.Args = targ.Command()
}
}
cmdShellArgs, err := shellwords.Parse(strings.Join(opts.Args, " "))
if err != nil {
return nil, err
}
var result []pack.Package
norender := log.LoggerTypeFromString(config.G[config.KraftKit](ctx).Log.Type) != log.FANCY
model, err := processtree.NewProcessTree(
ctx,
[]processtree.ProcessTreeOption{
processtree.IsParallel(false),
processtree.WithRenderer(norender),
},
processtree.NewProcessTreeItem(
"packaging "+opts.Name,
targ.Platform().Name()+"/"+targ.Architecture().Name(),
func(ctx context.Context) error {
popts := append(opts.packopts,
packmanager.PackArgs(cmdShellArgs...),
packmanager.PackInitrd(opts.Rootfs),
packmanager.PackKConfig(!opts.NoKConfig),
packmanager.PackName(opts.Name),
packmanager.PackOutput(opts.Output),
)
if ukversion, ok := targ.KConfig().Get(unikraft.UK_FULLVERSION); ok {
popts = append(popts,
packmanager.PackWithKernelVersion(ukversion.Value),
)
}
more, err := opts.pm.Pack(ctx, targ, popts...)
if err != nil {
return err
}
result = append(result, more...)
return nil
},
),
)
if err != nil {
return nil, err
}
if err := model.Start(); err != nil {
return nil, err
}
return result, nil
}