Debian Codegraph @

plugin/builtin/sortordertransformer/SortOrderTransformer.go

raw
1 // Copyright 2019 The Kubernetes Authors.
2 // SPDX-License-Identifier: Apache-2.0
3
4 //go:generate pluginator
5 package main
6
7 import (
8 "sort"
9 "strings"
10
11 "sigs.k8s.io/kustomize/api/resmap"
12 "sigs.k8s.io/kustomize/api/resource"
13 "sigs.k8s.io/kustomize/api/types"
14 "sigs.k8s.io/kustomize/kyaml/errors"
15 "sigs.k8s.io/kustomize/kyaml/resid"
16 "sigs.k8s.io/yaml"
17 )
18
19 // Sort the resources using a customizable ordering based of Kind.
20 // Defaults to the ordering of the GVK struct, which puts cluster-wide basic
21 // resources with no dependencies (like Namespace, StorageClass, etc.) first,
22 // and resources with a high number of dependencies
23 // (like ValidatingWebhookConfiguration) last.
24 type plugin struct {
25 SortOptions *types.SortOptions `json:"sortOptions,omitempty" yaml:"sortOptions,omitempty"`
26 }
27
28 var KustomizePlugin plugin //nolint:gochecknoglobals
29
30 func (p *plugin) Config(
31 _ *resmap.PluginHelpers, c []byte) error {
32 return errors.WrapPrefixf(yaml.Unmarshal(c, p), "Failed to unmarshal SortOrderTransformer config")
33 }
34
35 func (p *plugin) applyDefaults() {
36 // Default to FIFO sort, aka no-op.
37 if p.SortOptions == nil {
38 p.SortOptions = &types.SortOptions{
39 Order: types.FIFOSortOrder,
40 }
41 }
42
43 // If legacy sort is selected and no options are given, default to
44 // hardcoded order.
45 if p.SortOptions.Order == types.LegacySortOrder && p.SortOptions.LegacySortOptions == nil {
46 p.SortOptions.LegacySortOptions = &types.LegacySortOptions{
47 OrderFirst: defaultOrderFirst,
48 OrderLast: defaultOrderLast,
49 }
50 }
51 }
52
53 func (p *plugin) validate() error {
54 // Check valid values for SortOrder
55 if p.SortOptions.Order != types.FIFOSortOrder && p.SortOptions.Order != types.LegacySortOrder {
56 return errors.Errorf("the field 'sortOptions.order' must be one of [%s, %s]",
57 types.FIFOSortOrder, types.LegacySortOrder)
58 }
59
60 // Validate that the only options set are the ones corresponding to the
61 // selected sort order.
62 if p.SortOptions.Order == types.FIFOSortOrder &&
63 p.SortOptions.LegacySortOptions != nil {
64 return errors.Errorf("the field 'sortOptions.legacySortOptions' is"+
65 " set but the selected sort order is '%v', not 'legacy'",
66 p.SortOptions.Order)
67 }
68 return nil
69 }
70
71 func (p *plugin) Transform(m resmap.ResMap) (err error) {
72 p.applyDefaults()
73 err = p.validate()
74 if err != nil {
75 return err
76 }
77
78 // Sort
79 if p.SortOptions.Order == types.LegacySortOrder {
80 s := newLegacyIDSorter(m.Resources(), p.SortOptions.LegacySortOptions)
81 sort.Sort(s)
82
83 // Clear the map and re-add the resources in the sorted order.
84 m.Clear()
85 for _, r := range s.resources {
86 err := m.Append(r)
87 if err != nil {
88 return errors.WrapPrefixf(err, "SortOrderTransformer: Failed to append to resources")
89 }
90 }
91 }
92 return nil
93 }
94
95 // Code for legacy sorting.
96 // Legacy sorting is a "fixed" order sorting maintained for backwards
97 // compatibility.
98
99 // legacyIDSorter sorts resources based on two priority lists:
100 // - orderFirst: Resources that should be placed in the start, in the given order.
101 // - orderLast: Resources that should be placed in the end, in the given order.
102 type legacyIDSorter struct {
103 // resids only stores the metadata of the object. This is an optimization as
104 // it's expensive to compute these again and again during ordering.
105 resids []resid.ResId
106 // Initially, we sorted the metadata (ResId) of each object and then called GetByCurrentId on each to construct the final list.
107 // The problem is that GetByCurrentId is inefficient and does a linear scan in a list every time we do that.
108 // So instead, we sort resources alongside the ResIds.
109 resources []*resource.Resource
110
111 typeOrders map[string]int
112 }
113
114 func newLegacyIDSorter(
115 resources []*resource.Resource,
116 options *types.LegacySortOptions) *legacyIDSorter {
117 // Precalculate a resource ranking based on the priority lists.
118 var typeOrders = func() map[string]int {
119 m := map[string]int{}
120 for i, n := range options.OrderFirst {
121 m[n] = -len(options.OrderFirst) + i
122 }
123 for i, n := range options.OrderLast {
124 m[n] = 1 + i
125 }
126 return m
127 }()
128
129 ret := &legacyIDSorter{typeOrders: typeOrders}
130 for _, res := range resources {
131 ret.resids = append(ret.resids, res.CurId())
132 ret.resources = append(ret.resources, res)
133 }
134 return ret
135 }
136
137 var _ sort.Interface = legacyIDSorter{}
138
139 func (a legacyIDSorter) Len() int { return len(a.resids) }
140 func (a legacyIDSorter) Swap(i, j int) {
141 a.resids[i], a.resids[j] = a.resids[j], a.resids[i]
142 a.resources[i], a.resources[j] = a.resources[j], a.resources[i]
143 }
144 func (a legacyIDSorter) Less(i, j int) bool {
145 if !a.resids[i].Gvk.Equals(a.resids[j].Gvk) {
146 return gvkLessThan(a.resids[i].Gvk, a.resids[j].Gvk, a.typeOrders)
147 }
148 return legacyResIDSortString(a.resids[i]) < legacyResIDSortString(a.resids[j])
149 }
150
151 func gvkLessThan(gvk1, gvk2 resid.Gvk, typeOrders map[string]int) bool {
152 index1 := typeOrders[gvk1.Kind]
153 index2 := typeOrders[gvk2.Kind]
154 if index1 != index2 {
155 return index1 < index2
156 }
157 if (gvk1.Kind == types.NamespaceKind && gvk2.Kind == types.NamespaceKind) && (gvk1.Group == "" || gvk2.Group == "") {
158 return legacyGVKSortString(gvk1) > legacyGVKSortString(gvk2)
159 }
160 return legacyGVKSortString(gvk1) < legacyGVKSortString(gvk2)
161 }
162
163 // legacyGVKSortString returns a string representation of given GVK used for
164 // stable sorting.
165 func legacyGVKSortString(x resid.Gvk) string {
166 legacyNoGroup := "~G"
167 legacyNoVersion := "~V"
168 legacyNoKind := "~K"
169 legacyFieldSeparator := "_"
170
171 g := x.Group
172 if g == "" {
173 g = legacyNoGroup
174 }
175 v := x.Version
176 if v == "" {
177 v = legacyNoVersion
178 }
179 k := x.Kind
180 if k == "" {
181 k = legacyNoKind
182 }
183 return strings.Join([]string{g, v, k}, legacyFieldSeparator)
184 }
185
186 // legacyResIDSortString returns a string representation of given ResID used for
187 // stable sorting.
188 func legacyResIDSortString(id resid.ResId) string {
189 legacyNoNamespace := "~X"
190 legacyNoName := "~N"
191 legacySeparator := "|"
192
193 ns := id.Namespace
194 if ns == "" {
195 ns = legacyNoNamespace
196 }
197 nm := id.Name
198 if nm == "" {
199 nm = legacyNoName
200 }
201 return strings.Join(
202 []string{id.Gvk.String(), ns, nm}, legacySeparator)
203 }
204
205 // DO NOT CHANGE!
206 // Final legacy ordering provided as a default by kustomize.
207 // Originally an attempt to apply resources in the correct order, an effort
208 // which later proved impossible as not all types are known beforehand.
209 // See: https://github.com/kubernetes-sigs/kustomize/issues/3913
210 var defaultOrderFirst = []string{ //nolint:gochecknoglobals
211 "Namespace",
212 "ResourceQuota",
213 "StorageClass",
214 "CustomResourceDefinition",
215 "ServiceAccount",
216 "PodSecurityPolicy",
217 "Role",
218 "ClusterRole",
219 "RoleBinding",
220 "ClusterRoleBinding",
221 "ConfigMap",
222 "Secret",
223 "Endpoints",
224 "Service",
225 "LimitRange",
226 "PriorityClass",
227 "PersistentVolume",
228 "PersistentVolumeClaim",
229 "Deployment",
230 "StatefulSet",
231 "CronJob",
232 "PodDisruptionBudget",
233 }
234 var defaultOrderLast = []string{ //nolint:gochecknoglobals
235 "MutatingWebhookConfiguration",
236 "ValidatingWebhookConfiguration",
237 }