-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
manifest.go
270 lines (226 loc) · 6.9 KB
/
manifest.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
/*
Copyright 2017 The Kubernetes 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 kubemanifest
import (
"bytes"
"fmt"
"strings"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/klog/v2"
"k8s.io/kops/util/pkg/text"
"sigs.k8s.io/yaml"
)
// Object holds arbitrary untyped kubernetes objects; it is used when we don't have the type definitions for them
type Object struct {
data map[string]interface{}
}
// NewObject returns an Object wrapping the provided data
func NewObject(data map[string]interface{}) *Object {
return &Object{data: data}
}
// ToUnstructured converts the object to an unstructured.Unstructured
func (o *Object) ToUnstructured() *unstructured.Unstructured {
return &unstructured.Unstructured{Object: o.data}
}
// FromRuntimeObject converts from a runtime.Object.
func FromRuntimeObject(obj runtime.Object) (*Object, error) {
data, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj)
if err != nil {
return nil, fmt.Errorf("unable to convert %T to unstructured: %w", obj, err)
}
return NewObject(data), nil
}
// ObjectList describes a list of objects, allowing us to add bulk-methods
type ObjectList []*Object
// LoadObjectsFrom parses multiple objects from a yaml file
func LoadObjectsFrom(contents []byte) (ObjectList, error) {
var objects []*Object
sections := text.SplitContentToSections(contents)
for _, section := range sections {
// We need this so we don't error on a section that is empty / commented out
if !hasYAMLContent(section) {
continue
}
data := make(map[string]interface{})
err := yaml.Unmarshal(section, &data)
if err != nil {
klog.Infof("invalid YAML section: %s", string(section))
return nil, fmt.Errorf("error parsing yaml: %v", err)
}
obj := &Object{
// bytes: section,
data: data,
}
objects = append(objects, obj)
}
return objects, nil
}
// hasYAMLContent determines if the byte slice has any content,
// because yaml parsing gives an error if called with no content.
// TODO: How does apimachinery avoid this problem?
func hasYAMLContent(yamlData []byte) bool {
for _, line := range bytes.Split(yamlData, []byte("\n")) {
l := bytes.TrimSpace(line)
if len(l) != 0 && !bytes.HasPrefix(l, []byte("#")) {
return true
}
}
return false
}
// ToYAML serializes a list of objects back to bytes; it is the opposite of LoadObjectsFrom
func (l ObjectList) ToYAML() ([]byte, error) {
yamlSeparator := []byte("\n---\n\n")
var yamls [][]byte
for _, object := range l {
// Don't serialize empty objects - they confuse yaml parsers
if object.IsEmptyObject() {
continue
}
y, err := object.ToYAML()
if err != nil {
return nil, fmt.Errorf("error re-marshaling manifest: %v", err)
}
yamls = append(yamls, y)
}
return bytes.Join(yamls, yamlSeparator), nil
}
func (m *Object) ToYAML() ([]byte, error) {
b, err := yaml.Marshal(m.data)
if err != nil {
return nil, fmt.Errorf("error marshaling manifest to yaml: %v", err)
}
return b, nil
}
func (m *Object) accept(visitor Visitor) error {
err := visit(visitor, m.data, []string{}, func(v interface{}) {
klog.Fatal("cannot mutate top-level data")
})
return err
}
// IsEmptyObject checks if the object has no keys set (i.e. `== {}`)
func (m *Object) IsEmptyObject() bool {
return len(m.data) == 0
}
// Kind returns the kind field of the object, or "" if it cannot be found or is invalid
func (m *Object) Kind() string {
v, found := m.data["kind"]
if !found {
return ""
}
s, ok := v.(string)
if !ok {
return ""
}
return s
}
// GetNamespace returns the namespace field of the object, or "" if it cannot be found or is invalid
func (m *Object) GetNamespace() string {
metadata := m.metadata()
return getStringValue(metadata, "namespace")
}
// GetName returns the namespace field of the object, or "" if it cannot be found or is invalid
func (m *Object) GetName() string {
metadata := m.metadata()
return getStringValue(metadata, "name")
}
// getStringValue returns the specified field of the object, or "" if it cannot be found or is invalid
func getStringValue(m map[string]interface{}, key string) string {
v, found := m[key]
if !found {
return ""
}
s, ok := v.(string)
if !ok {
return ""
}
return s
}
// metadata returns the metadata map of the object, or nil if it cannot be found or is invalid
func (m *Object) metadata() map[string]interface{} {
v, found := m.data["metadata"]
if !found {
return nil
}
metadata, ok := v.(map[string]interface{})
if !ok {
return nil
}
return metadata
}
// APIVersion returns the apiVersion field of the object, or "" if it cannot be found or is invalid
func (m *Object) APIVersion() string {
v, found := m.data["apiVersion"]
if !found {
return ""
}
s, ok := v.(string)
if !ok {
return ""
}
return s
}
// Reparse parses a subfield from an object
func (m *Object) Reparse(obj interface{}, fields ...string) error {
humanFields := strings.Join(fields, ".")
current := m.data
for _, field := range fields {
v, found := current[field]
if !found {
return fmt.Errorf("field %q in %s not found", field, humanFields)
}
m, ok := v.(map[string]interface{})
if !ok {
return fmt.Errorf("field %q in %s was not an object, was %T", field, humanFields, v)
}
current = m
}
b, err := yaml.Marshal(current)
if err != nil {
return fmt.Errorf("error marshaling %s to yaml: %v", humanFields, err)
}
if err := yaml.Unmarshal(b, obj); err != nil {
return fmt.Errorf("error unmarshaling subobject %s: %v", humanFields, err)
}
return nil
}
// Set mutates a subfield to the newValue
func (m *Object) Set(newValue interface{}, fieldPath ...string) error {
humanFields := strings.Join(fieldPath, ".")
current := m.data
if len(fieldPath) >= 2 {
for _, field := range fieldPath[:len(fieldPath)-1] {
v, found := current[field]
if !found {
return fmt.Errorf("field %q in %s not found", field, humanFields)
}
m, ok := v.(map[string]interface{})
if !ok {
return fmt.Errorf("field %q in %s was not an object, was %T", field, humanFields, v)
}
current = m
}
}
// remarshal newValue so that it becomes a map. This allows us to do further amendments
b, err := yaml.Marshal(newValue)
if err != nil {
return fmt.Errorf("error marshaling %s to yaml: %v", humanFields, err)
}
newValue = make(map[string]interface{})
err = yaml.Unmarshal(b, &newValue)
if err != nil {
return fmt.Errorf("error parsing yaml: %v", err)
}
current[fieldPath[len(fieldPath)-1]] = newValue
return nil
}