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

package transform

import (
	"os"
	"path/filepath"
	"sort"
	"strings"

	"tags.cncf.io/container-device-interface/specs-go"
)

type sorter struct{}

var _ Transformer = (*sorter)(nil)

// NewSorter creates a transformer that sorts container edits.
func NewSorter() Transformer {
	return nil
}

// Transform sorts the entities in the specified CDI specification.
func (d sorter) Transform(spec *specs.Spec) error {
	if spec == nil {
		return nil
	}
	if err := d.transformEdits(&spec.ContainerEdits); err != nil {
		return err
	}
	var updatedDevices []specs.Device
	for _, device := range spec.Devices {
		device := device
		if err := d.transformEdits(&device.ContainerEdits); err != nil {
			return err
		}
		updatedDevices = append(updatedDevices, device)
	}
	spec.Devices = d.sortDevices(updatedDevices)
	return nil
}

func (d sorter) transformEdits(edits *specs.ContainerEdits) error {
	edits.DeviceNodes = d.sortDeviceNodes(edits.DeviceNodes)
	edits.Mounts = d.sortMounts(edits.Mounts)
	return nil
}

func (d sorter) sortDevices(devices []specs.Device) []specs.Device {
	sort.Slice(devices, func(i, j int) bool {
		return devices[i].Name < devices[j].Name
	})
	return devices
}

// sortDeviceNodes sorts the specified device nodes by container path.
// If two device nodes have the same container path, the host path is used to break ties.
func (d sorter) sortDeviceNodes(entities []*specs.DeviceNode) []*specs.DeviceNode {
	sort.Slice(entities, func(i, j int) bool {
		ip := strings.Count(filepath.Clean(entities[i].Path), string(os.PathSeparator))
		jp := strings.Count(filepath.Clean(entities[j].Path), string(os.PathSeparator))
		if ip == jp {
			return entities[i].Path < entities[j].Path
		}
		return ip < jp
	})
	return entities
}

// sortMounts sorts the specified mounts by container path.
// If two mounts have the same mount path, the host path is used to break ties.
func (d sorter) sortMounts(entities []*specs.Mount) []*specs.Mount {
	sort.Slice(entities, func(i, j int) bool {
		ip := strings.Count(filepath.Clean(entities[i].ContainerPath), string(os.PathSeparator))
		jp := strings.Count(filepath.Clean(entities[j].ContainerPath), string(os.PathSeparator))
		if ip == jp {
			return entities[i].ContainerPath < entities[j].ContainerPath
		}
		return ip < jp
	})
	return entities
}