-
Notifications
You must be signed in to change notification settings - Fork 65
/
generate.go
547 lines (473 loc) · 14.7 KB
/
generate.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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
/*
Copyright The containerd Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package generate
import (
"fmt"
"os"
"path/filepath"
"sort"
"strings"
rspec "github.com/opencontainers/runtime-spec/specs-go"
"github.com/opencontainers/runtime-tools/generate"
nri "github.com/containerd/nri/pkg/api"
)
// GeneratorOption is an option for Generator().
type GeneratorOption func(*Generator)
// Generator extends a stock runtime-tools Generator and extends it with
// a few functions for handling NRI container adjustment.
type Generator struct {
*generate.Generator
filterLabels func(map[string]string) (map[string]string, error)
filterAnnotations func(map[string]string) (map[string]string, error)
resolveBlockIO func(string) (*rspec.LinuxBlockIO, error)
resolveRdt func(string) (*rspec.LinuxIntelRdt, error)
injectCDIDevices func(*rspec.Spec, []string) error
checkResources func(*rspec.LinuxResources) error
}
// SpecGenerator returns a wrapped OCI Spec Generator.
func SpecGenerator(gg *generate.Generator, opts ...GeneratorOption) *Generator {
g := &Generator{
Generator: gg,
}
g.filterLabels = nopFilter
g.filterAnnotations = nopFilter
for _, o := range opts {
o(g)
}
return g
}
// WithLabelFilter provides an option for filtering or rejecting labels.
func WithLabelFilter(fn func(map[string]string) (map[string]string, error)) GeneratorOption {
return func(g *Generator) {
g.filterLabels = fn
}
}
// WithAnnotationFilter provides an option for filtering or rejecting annotations.
func WithAnnotationFilter(fn func(map[string]string) (map[string]string, error)) GeneratorOption {
return func(g *Generator) {
g.filterAnnotations = fn
}
}
// WithBlockIOResolver specifies a function for resolving Block I/O classes by name.
func WithBlockIOResolver(fn func(string) (*rspec.LinuxBlockIO, error)) GeneratorOption {
return func(g *Generator) {
g.resolveBlockIO = fn
}
}
// WithRdtResolver specifies a function for resolving RDT classes by name.
func WithRdtResolver(fn func(string) (*rspec.LinuxIntelRdt, error)) GeneratorOption {
return func(g *Generator) {
g.resolveRdt = fn
}
}
// WithResourceChecker specifies a function to perform final resource adjustment.
func WithResourceChecker(fn func(*rspec.LinuxResources) error) GeneratorOption {
return func(g *Generator) {
g.checkResources = fn
}
}
// WithCDIDeviceInjector specifies a runtime-specific function to use for CDI
// device resolution and injection into an OCI Spec.
func WithCDIDeviceInjector(fn func(*rspec.Spec, []string) error) GeneratorOption {
return func(g *Generator) {
g.injectCDIDevices = fn
}
}
// Adjust adjusts all aspects of the OCI Spec that NRI knows/cares about.
func (g *Generator) Adjust(adjust *nri.ContainerAdjustment) error {
if adjust == nil {
return nil
}
if err := g.AdjustAnnotations(adjust.GetAnnotations()); err != nil {
return fmt.Errorf("failed to adjust annotations in OCI Spec: %w", err)
}
g.AdjustEnv(adjust.GetEnv())
g.AdjustHooks(adjust.GetHooks())
if err := g.InjectCDIDevices(adjust.GetCDIDevices()); err != nil {
return err
}
g.AdjustDevices(adjust.GetLinux().GetDevices())
g.AdjustCgroupsPath(adjust.GetLinux().GetCgroupsPath())
g.AdjustOomScoreAdj(adjust.GetLinux().GetOomScoreAdj())
resources := adjust.GetLinux().GetResources()
if err := g.AdjustResources(resources); err != nil {
return err
}
if err := g.AdjustBlockIOClass(resources.GetBlockioClass().Get()); err != nil {
return err
}
if err := g.AdjustRdtClass(resources.GetRdtClass().Get()); err != nil {
return err
}
if err := g.AdjustMounts(adjust.GetMounts()); err != nil {
return err
}
if err := g.AdjustRlimits(adjust.GetRlimits()); err != nil {
return err
}
return nil
}
// AdjustEnv adjusts the environment of the OCI Spec.
func (g *Generator) AdjustEnv(env []*nri.KeyValue) {
mod := map[string]*nri.KeyValue{}
for _, e := range env {
key, _ := nri.IsMarkedForRemoval(e.Key)
mod[key] = e
}
// first modify existing environment
if len(mod) > 0 && g.Config != nil && g.Config.Process != nil {
old := g.Config.Process.Env
g.ClearProcessEnv()
for _, e := range old {
keyval := strings.SplitN(e, "=", 2)
if len(keyval) < 2 {
continue
}
if m, ok := mod[keyval[0]]; ok {
delete(mod, keyval[0])
if _, marked := m.IsMarkedForRemoval(); !marked {
g.AddProcessEnv(m.Key, m.Value)
}
continue
}
g.AddProcessEnv(keyval[0], keyval[1])
}
}
// then append remaining unprocessed adjustments (new variables)
for _, e := range env {
if _, marked := e.IsMarkedForRemoval(); marked {
continue
}
if _, ok := mod[e.Key]; ok {
g.AddProcessEnv(e.Key, e.Value)
}
}
}
// AdjustAnnotations adjusts the annotations in the OCI Spec.
func (g *Generator) AdjustAnnotations(annotations map[string]string) error {
var err error
if annotations, err = g.filterAnnotations(annotations); err != nil {
return err
}
for k, v := range annotations {
if key, marked := nri.IsMarkedForRemoval(k); marked {
g.RemoveAnnotation(key)
} else {
g.AddAnnotation(k, v)
}
}
return nil
}
// AdjustHooks adjusts the OCI hooks in the OCI Spec.
func (g *Generator) AdjustHooks(hooks *nri.Hooks) {
if hooks == nil {
return
}
for _, h := range hooks.Prestart {
g.AddPreStartHook(h.ToOCI())
}
for _, h := range hooks.Poststart {
g.AddPostStartHook(h.ToOCI())
}
for _, h := range hooks.Poststop {
g.AddPostStopHook(h.ToOCI())
}
for _, h := range hooks.CreateRuntime {
g.AddCreateRuntimeHook(h.ToOCI())
}
for _, h := range hooks.CreateContainer {
g.AddCreateContainerHook(h.ToOCI())
}
for _, h := range hooks.StartContainer {
g.AddStartContainerHook(h.ToOCI())
}
}
// AdjustResources adjusts the (Linux) resources in the OCI Spec.
func (g *Generator) AdjustResources(r *nri.LinuxResources) error {
if r == nil {
return nil
}
g.initConfigLinux()
if r.Cpu != nil {
if r.Cpu.Period != nil {
g.SetLinuxResourcesCPUPeriod(r.Cpu.GetPeriod().GetValue())
}
if r.Cpu.Quota != nil {
g.SetLinuxResourcesCPUQuota(r.Cpu.GetQuota().GetValue())
}
if r.Cpu.Shares != nil {
g.SetLinuxResourcesCPUShares(r.Cpu.GetShares().GetValue())
}
if r.Cpu.Cpus != "" {
g.SetLinuxResourcesCPUCpus(r.Cpu.GetCpus())
}
if r.Cpu.Mems != "" {
g.SetLinuxResourcesCPUMems(r.Cpu.GetMems())
}
if r.Cpu.RealtimeRuntime != nil {
g.SetLinuxResourcesCPURealtimeRuntime(r.Cpu.GetRealtimeRuntime().GetValue())
}
if r.Cpu.RealtimePeriod != nil {
g.SetLinuxResourcesCPURealtimePeriod(r.Cpu.GetRealtimePeriod().GetValue())
}
}
if r.Memory != nil {
if l := r.Memory.GetLimit().GetValue(); l != 0 {
g.SetLinuxResourcesMemoryLimit(l)
g.SetLinuxResourcesMemorySwap(l)
}
}
for _, l := range r.HugepageLimits {
g.AddLinuxResourcesHugepageLimit(l.PageSize, l.Limit)
}
for k, v := range r.Unified {
g.AddLinuxResourcesUnified(k, v)
}
if v := r.GetPids(); v != nil {
g.SetLinuxResourcesPidsLimit(v.GetLimit())
}
if g.checkResources != nil {
if err := g.checkResources(g.Config.Linux.Resources); err != nil {
return fmt.Errorf("failed to adjust resources in OCI Spec: %w", err)
}
}
return nil
}
// AdjustBlockIOClass adjusts the block I/O class in the OCI Spec.
func (g *Generator) AdjustBlockIOClass(blockIOClass *string) error {
if blockIOClass == nil || g.resolveBlockIO == nil {
return nil
}
if *blockIOClass == "" {
g.ClearLinuxResourcesBlockIO()
return nil
}
blockIO, err := g.resolveBlockIO(*blockIOClass)
if err != nil {
return fmt.Errorf("failed to adjust BlockIO class in OCI Spec: %w", err)
}
g.SetLinuxResourcesBlockIO(blockIO)
return nil
}
// AdjustRdtClass adjusts the RDT class in the OCI Spec.
func (g *Generator) AdjustRdtClass(rdtClass *string) error {
if rdtClass == nil || g.resolveRdt == nil {
return nil
}
if *rdtClass == "" {
g.ClearLinuxIntelRdt()
return nil
}
rdt, err := g.resolveRdt(*rdtClass)
if err != nil {
return fmt.Errorf("failed to adjust RDT class in OCI Spec: %w", err)
}
g.SetLinuxIntelRdt(rdt)
return nil
}
// AdjustCgroupsPath adjusts the cgroup pseudofs path in the OCI Spec.
func (g *Generator) AdjustCgroupsPath(path string) {
if path != "" {
g.SetLinuxCgroupsPath(path)
}
}
// AdjustOomScoreAdj adjusts the kernel's Out-Of-Memory (OOM) killer score for the container.
// This may override kubelet's settings for OOM score.
func (g *Generator) AdjustOomScoreAdj(score *nri.OptionalInt) {
if score != nil {
g.SetProcessOOMScoreAdj(int(score.Value))
}
}
// AdjustDevices adjusts the (Linux) devices in the OCI Spec.
func (g *Generator) AdjustDevices(devices []*nri.LinuxDevice) {
for _, d := range devices {
key, marked := d.IsMarkedForRemoval()
g.RemoveDevice(key)
if marked {
continue
}
g.AddDevice(d.ToOCI())
major, minor, access := &d.Major, &d.Minor, d.AccessString()
g.AddLinuxResourcesDevice(true, d.Type, major, minor, access)
}
}
// InjectCDIDevices injects the requested CDI devices into the OCI Spec.
// Devices are given by their fully qualified CDI device names. The
// actual device injection is done using a runtime-specific CDI
// injection function, set using the WithCDIDeviceInjector option.
func (g *Generator) InjectCDIDevices(devices []*nri.CDIDevice) error {
if len(devices) == 0 || g.injectCDIDevices == nil {
return nil
}
names := []string{}
for _, d := range devices {
names = append(names, d.Name)
}
return g.injectCDIDevices(g.Config, names)
}
func (g *Generator) AdjustRlimits(rlimits []*nri.POSIXRlimit) error {
for _, l := range rlimits {
if l == nil {
continue
}
g.Config.Process.Rlimits = append(g.Config.Process.Rlimits, rspec.POSIXRlimit{
Type: l.Type,
Hard: l.Hard,
Soft: l.Soft,
})
}
return nil
}
// AdjustMounts adjusts the mounts in the OCI Spec.
func (g *Generator) AdjustMounts(mounts []*nri.Mount) error {
if len(mounts) == 0 {
return nil
}
propagation := ""
for _, m := range mounts {
if destination, marked := m.IsMarkedForRemoval(); marked {
g.RemoveMount(destination)
continue
}
g.RemoveMount(m.Destination)
mnt := m.ToOCI(&propagation)
switch propagation {
case "rprivate":
case "rshared":
if err := ensurePropagation(mnt.Source, "rshared"); err != nil {
return fmt.Errorf("failed to adjust mounts in OCI Spec: %w", err)
}
if err := g.SetLinuxRootPropagation("rshared"); err != nil {
return fmt.Errorf("failed to adjust rootfs propagation in OCI Spec: %w", err)
}
case "rslave":
if err := ensurePropagation(mnt.Source, "rshared", "rslave"); err != nil {
return fmt.Errorf("failed to adjust mounts in OCI Spec: %w", err)
}
rootProp := g.Config.Linux.RootfsPropagation
if rootProp != "rshared" && rootProp != "rslave" {
if err := g.SetLinuxRootPropagation("rslave"); err != nil {
return fmt.Errorf("failed to adjust rootfs propagation in OCI Spec: %w", err)
}
}
}
g.AddMount(mnt)
}
g.sortMounts()
return nil
}
// sortMounts sorts the mounts in the generated OCI Spec.
func (g *Generator) sortMounts() {
mounts := g.Generator.Mounts()
g.Generator.ClearMounts()
sort.Sort(orderedMounts(mounts))
// TODO(klihub): This is now a bit ugly maybe we should introduce a
// SetMounts([]rspec.Mount) to runtime-tools/generate.Generator. That
// could also take care of properly sorting the mount slice.
g.Generator.Config.Mounts = mounts
}
// orderedMounts defines how to sort an OCI Spec Mount slice.
// This is the almost the same implementation sa used by CRI-O and Docker,
// with a minor tweak for stable sorting order (easier to test):
//
// https://github.com/moby/moby/blob/17.05.x/daemon/volumes.go#L26
type orderedMounts []rspec.Mount
// Len returns the number of mounts. Used in sorting.
func (m orderedMounts) Len() int {
return len(m)
}
// Less returns true if the number of parts (a/b/c would be 3 parts) in the
// mount indexed by parameter 1 is less than that of the mount indexed by
// parameter 2. Used in sorting.
func (m orderedMounts) Less(i, j int) bool {
ip, jp := m.parts(i), m.parts(j)
if ip < jp {
return true
}
if jp < ip {
return false
}
return m[i].Destination < m[j].Destination
}
// Swap swaps two items in an array of mounts. Used in sorting
func (m orderedMounts) Swap(i, j int) {
m[i], m[j] = m[j], m[i]
}
// parts returns the number of parts in the destination of a mount. Used in sorting.
func (m orderedMounts) parts(i int) int {
return strings.Count(filepath.Clean(m[i].Destination), string(os.PathSeparator))
}
func nopFilter(m map[string]string) (map[string]string, error) {
return m, nil
}
//
// TODO: these could be added to the stock Spec generator...
//
// AddCreateRuntimeHook adds a hooks new CreateRuntime hooks.
func (g *Generator) AddCreateRuntimeHook(hook rspec.Hook) {
g.initConfigHooks()
g.Config.Hooks.CreateRuntime = append(g.Config.Hooks.CreateRuntime, hook)
}
// AddCreateContainerHook adds a hooks new CreateContainer hooks.
func (g *Generator) AddCreateContainerHook(hook rspec.Hook) {
g.initConfigHooks()
g.Config.Hooks.CreateContainer = append(g.Config.Hooks.CreateContainer, hook)
}
// AddStartContainerHook adds a hooks new StartContainer hooks.
func (g *Generator) AddStartContainerHook(hook rspec.Hook) {
g.initConfigHooks()
g.Config.Hooks.StartContainer = append(g.Config.Hooks.StartContainer, hook)
}
// ClearLinuxIntelRdt clears RDT CLOS.
func (g *Generator) ClearLinuxIntelRdt() {
g.initConfigLinux()
g.Config.Linux.IntelRdt = nil
}
// SetLinuxIntelRdt sets RDT CLOS.
func (g *Generator) SetLinuxIntelRdt(rdt *rspec.LinuxIntelRdt) {
g.initConfigLinux()
g.Config.Linux.IntelRdt = rdt
}
// ClearLinuxResourcesBlockIO clears Block I/O settings.
func (g *Generator) ClearLinuxResourcesBlockIO() {
g.initConfigLinuxResources()
g.Config.Linux.Resources.BlockIO = nil
}
// SetLinuxResourcesBlockIO sets Block I/O settings.
func (g *Generator) SetLinuxResourcesBlockIO(blockIO *rspec.LinuxBlockIO) {
g.initConfigLinuxResources()
g.Config.Linux.Resources.BlockIO = blockIO
}
func (g *Generator) initConfig() {
if g.Config == nil {
g.Config = &rspec.Spec{}
}
}
func (g *Generator) initConfigHooks() {
g.initConfig()
if g.Config.Hooks == nil {
g.Config.Hooks = &rspec.Hooks{}
}
}
func (g *Generator) initConfigLinux() {
g.initConfig()
if g.Config.Linux == nil {
g.Config.Linux = &rspec.Linux{}
}
}
func (g *Generator) initConfigLinuxResources() {
g.initConfigLinux()
if g.Config.Linux.Resources == nil {
g.Config.Linux.Resources = &rspec.LinuxResources{}
}
}