Debian Codegraph @

api/internal/plugins/utils/utils.go

raw
1 // Copyright 2020 The Kubernetes Authors.
2 // SPDX-License-Identifier: Apache-2.0
3
4 package utils
5
6 import (
7 "encoding/json"
8 "fmt"
9 "os"
10 "path/filepath"
11 "runtime"
12 "strconv"
13 "time"
14
15 "sigs.k8s.io/kustomize/api/konfig"
16 "sigs.k8s.io/kustomize/api/resmap"
17 "sigs.k8s.io/kustomize/api/resource"
18 "sigs.k8s.io/kustomize/api/types"
19 "sigs.k8s.io/kustomize/kyaml/filesys"
20 "sigs.k8s.io/yaml"
21 )
22
23 const (
24 idAnnotation = "kustomize.config.k8s.io/id"
25 HashAnnotation = "kustomize.config.k8s.io/needs-hash"
26 BehaviorAnnotation = "kustomize.config.k8s.io/behavior"
27 )
28
29 func GoBin() string {
30 return filepath.Join(runtime.GOROOT(), "bin", "go")
31 }
32
33 // DeterminePluginSrcRoot guesses where the user
34 // has her ${g}/${v}/$lower(${k})/${k}.go files.
35 func DeterminePluginSrcRoot(fSys filesys.FileSystem) (string, error) {
36 return konfig.FirstDirThatExistsElseError(
37 "plugin src root", fSys, []konfig.NotedFunc{
38 {
39 Note: "relative to unit test",
40 F: func() string {
41 return filepath.Clean(
42 filepath.Join(
43 os.Getenv("PWD"),
44 "..", "..",
45 konfig.RelPluginHome))
46 },
47 },
48 {
49 Note: "relative to unit test (internal pkg)",
50 F: func() string {
51 return filepath.Clean(
52 filepath.Join(
53 os.Getenv("PWD"),
54 "..", "..", "..", "..",
55 konfig.RelPluginHome))
56 },
57 },
58 {
59 Note: "relative to api package",
60 F: func() string {
61 return filepath.Clean(
62 filepath.Join(
63 os.Getenv("PWD"),
64 "..", "..", "..",
65 konfig.RelPluginHome))
66 },
67 },
68 {
69 Note: "old style $GOPATH",
70 F: func() string {
71 return filepath.Join(
72 os.Getenv("GOPATH"),
73 "src", konfig.DomainName,
74 konfig.ProgramName, konfig.RelPluginHome)
75 },
76 },
77 {
78 Note: "HOME with literal 'gopath'",
79 F: func() string {
80 return filepath.Join(
81 konfig.HomeDir(), "gopath",
82 "src", konfig.DomainName,
83 konfig.ProgramName, konfig.RelPluginHome)
84 },
85 },
86 {
87 Note: "home directory",
88 F: func() string {
89 return filepath.Join(
90 konfig.HomeDir(), konfig.DomainName,
91 konfig.ProgramName, konfig.RelPluginHome)
92 },
93 },
94 })
95 }
96
97 // FileYoungerThan returns true if the file both exists and has an
98 // age is <= the Duration argument.
99 func FileYoungerThan(path string, d time.Duration) bool {
100 fi, err := os.Stat(path)
101 if err != nil {
102 if os.IsNotExist(err) {
103 return false
104 }
105 }
106 return time.Since(fi.ModTime()) <= d
107 }
108
109 // FileModifiedAfter returns true if the file both exists and was
110 // modified after the given time..
111 func FileModifiedAfter(path string, t time.Time) bool {
112 fi, err := os.Stat(path)
113 if err != nil {
114 if os.IsNotExist(err) {
115 return false
116 }
117 }
118 return fi.ModTime().After(t)
119 }
120
121 func FileExists(path string) bool {
122 if _, err := os.Stat(path); err != nil {
123 if os.IsNotExist(err) {
124 return false
125 }
126 }
127 return true
128 }
129
130 // GetResMapWithIDAnnotation returns a new copy of the given ResMap with the ResIds annotated in each Resource
131 func GetResMapWithIDAnnotation(rm resmap.ResMap) (resmap.ResMap, error) {
132 inputRM := rm.DeepCopy()
133 for _, r := range inputRM.Resources() {
134 idString, err := yaml.Marshal(r.CurId())
135 if err != nil {
136 return nil, err
137 }
138 annotations := r.GetAnnotations()
139 annotations[idAnnotation] = string(idString)
140 if err = r.SetAnnotations(annotations); err != nil {
141 return nil, err
142 }
143 }
144 return inputRM, nil
145 }
146
147 // UpdateResMapValues updates the Resource value in the given ResMap
148 // with the emitted Resource values in output.
149 func UpdateResMapValues(pluginName string, h *resmap.PluginHelpers, output []byte, rm resmap.ResMap) error {
150 mapFactory := h.ResmapFactory()
151 resFactory := mapFactory.RF()
152 resources, err := resFactory.SliceFromBytes(output)
153 if err != nil {
154 return err
155 }
156 // Don't use resources here, or error message will be unfriendly to plugin builders
157 newMap, err := mapFactory.NewResMapFromBytes([]byte{})
158 if err != nil {
159 return err
160 }
161
162 for _, r := range resources {
163 // stale--not manipulated by plugin transformers
164 if err = removeIDAnnotation(r); err != nil {
165 return err
166 }
167
168 // Add to the new map, checking for duplicates
169 if err := newMap.Append(r); err != nil {
170 prettyID, err := json.Marshal(r.CurId())
171 if err != nil {
172 prettyID = []byte(r.CurId().String())
173 }
174 return fmt.Errorf("plugin %s generated duplicate resource: %s", pluginName, prettyID)
175 }
176
177 // Add to or update the old map
178 oldIdx, err := rm.GetIndexOfCurrentId(r.CurId())
179 if err != nil {
180 return err
181 }
182 if oldIdx != -1 {
183 rm.GetByIndex(oldIdx).ResetRNode(r)
184 } else {
185 if err := rm.Append(r); err != nil {
186 return err
187 }
188 }
189 }
190
191 // Remove items the transformer deleted from the old map
192 for _, id := range rm.AllIds() {
193 newIdx, _ := newMap.GetIndexOfCurrentId(id)
194 if newIdx == -1 {
195 if err = rm.Remove(id); err != nil {
196 return err
197 }
198 }
199 }
200
201 return nil
202 }
203
204 func removeIDAnnotation(r *resource.Resource) error {
205 // remove the annotation set by Kustomize to track the resource
206 annotations := r.GetAnnotations()
207 delete(annotations, idAnnotation)
208 return r.SetAnnotations(annotations)
209 }
210
211 // UpdateResourceOptions updates the generator options for each resource in the
212 // given ResMap based on plugin provided annotations.
213 func UpdateResourceOptions(rm resmap.ResMap) (resmap.ResMap, error) {
214 for _, r := range rm.Resources() {
215 // Disable name hashing by default and require plugin to explicitly
216 // request it for each resource.
217 annotations := r.GetAnnotations()
218 behavior := annotations[BehaviorAnnotation]
219 var needsHash bool
220 if val, ok := annotations[HashAnnotation]; ok {
221 b, err := strconv.ParseBool(val)
222 if err != nil {
223 return nil, fmt.Errorf(
224 "the annotation %q contains an invalid value (%q)",
225 HashAnnotation, val)
226 }
227 needsHash = b
228 }
229 delete(annotations, HashAnnotation)
230 delete(annotations, BehaviorAnnotation)
231 if err := r.SetAnnotations(annotations); err != nil {
232 return nil, err
233 }
234 if needsHash {
235 r.EnableHashSuffix()
236 }
237 r.SetBehavior(types.NewGenerationBehavior(behavior))
238 }
239 return rm, nil
240 }