Debian Codegraph @

pkg/apis/meta/v1/helpers.go

raw
1 /*
2 Copyright 2016 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package v1
18
19 import (
20 "bytes"
21 "encoding/json"
22 "errors"
23 "fmt"
24
25 "k8s.io/apimachinery/pkg/fields"
26 "k8s.io/apimachinery/pkg/labels"
27 cbor "k8s.io/apimachinery/pkg/runtime/serializer/cbor/direct"
28 "k8s.io/apimachinery/pkg/selection"
29 "k8s.io/apimachinery/pkg/types"
30 utiljson "k8s.io/apimachinery/pkg/util/json"
31 )
32
33 // LabelSelectorAsSelector converts the LabelSelector api type into a struct that implements
34 // labels.Selector
35 // Note: This function should be kept in sync with the selector methods in pkg/labels/selector.go
36 func LabelSelectorAsSelector(ps *LabelSelector) (labels.Selector, error) {
37 if ps == nil {
38 return labels.Nothing(), nil
39 }
40 if len(ps.MatchLabels)+len(ps.MatchExpressions) == 0 {
41 return labels.Everything(), nil
42 }
43 requirements := make([]labels.Requirement, 0, len(ps.MatchLabels)+len(ps.MatchExpressions))
44 for k, v := range ps.MatchLabels {
45 r, err := labels.NewRequirement(k, selection.Equals, []string{v})
46 if err != nil {
47 return nil, err
48 }
49 requirements = append(requirements, *r)
50 }
51 for _, expr := range ps.MatchExpressions {
52 var op selection.Operator
53 switch expr.Operator {
54 case LabelSelectorOpIn:
55 op = selection.In
56 case LabelSelectorOpNotIn:
57 op = selection.NotIn
58 case LabelSelectorOpExists:
59 op = selection.Exists
60 case LabelSelectorOpDoesNotExist:
61 op = selection.DoesNotExist
62 default:
63 return nil, fmt.Errorf("%q is not a valid label selector operator", expr.Operator)
64 }
65 r, err := labels.NewRequirement(expr.Key, op, append([]string(nil), expr.Values...))
66 if err != nil {
67 return nil, err
68 }
69 requirements = append(requirements, *r)
70 }
71 selector := labels.NewSelector()
72 selector = selector.Add(requirements...)
73 return selector, nil
74 }
75
76 // LabelSelectorAsMap converts the LabelSelector api type into a map of strings, ie. the
77 // original structure of a label selector. Operators that cannot be converted into plain
78 // labels (Exists, DoesNotExist, NotIn, and In with more than one value) will result in
79 // an error.
80 func LabelSelectorAsMap(ps *LabelSelector) (map[string]string, error) {
81 if ps == nil {
82 return nil, nil
83 }
84 selector := map[string]string{}
85 for k, v := range ps.MatchLabels {
86 selector[k] = v
87 }
88 for _, expr := range ps.MatchExpressions {
89 switch expr.Operator {
90 case LabelSelectorOpIn:
91 if len(expr.Values) != 1 {
92 return selector, fmt.Errorf("operator %q without a single value cannot be converted into the old label selector format", expr.Operator)
93 }
94 // Should we do anything in case this will override a previous key-value pair?
95 selector[expr.Key] = expr.Values[0]
96 case LabelSelectorOpNotIn, LabelSelectorOpExists, LabelSelectorOpDoesNotExist:
97 return selector, fmt.Errorf("operator %q cannot be converted into the old label selector format", expr.Operator)
98 default:
99 return selector, fmt.Errorf("%q is not a valid selector operator", expr.Operator)
100 }
101 }
102 return selector, nil
103 }
104
105 // ParseToLabelSelector parses a string representing a selector into a LabelSelector object.
106 // Note: This function should be kept in sync with the parser in pkg/labels/selector.go
107 func ParseToLabelSelector(selector string) (*LabelSelector, error) {
108 reqs, err := labels.ParseToRequirements(selector)
109 if err != nil {
110 return nil, fmt.Errorf("couldn't parse the selector string \"%s\": %v", selector, err)
111 }
112
113 labelSelector := &LabelSelector{
114 MatchLabels: map[string]string{},
115 MatchExpressions: []LabelSelectorRequirement{},
116 }
117 for _, req := range reqs {
118 var op LabelSelectorOperator
119 switch req.Operator() {
120 case selection.Equals, selection.DoubleEquals:
121 vals := req.Values()
122 if vals.Len() != 1 {
123 return nil, fmt.Errorf("equals operator must have exactly one value")
124 }
125 val, ok := vals.PopAny()
126 if !ok {
127 return nil, fmt.Errorf("equals operator has exactly one value but it cannot be retrieved")
128 }
129 labelSelector.MatchLabels[req.Key()] = val
130 continue
131 case selection.In:
132 op = LabelSelectorOpIn
133 case selection.NotIn:
134 op = LabelSelectorOpNotIn
135 case selection.Exists:
136 op = LabelSelectorOpExists
137 case selection.DoesNotExist:
138 op = LabelSelectorOpDoesNotExist
139 case selection.GreaterThan, selection.LessThan:
140 // Adding a separate case for these operators to indicate that this is deliberate
141 return nil, fmt.Errorf("%q isn't supported in label selectors", req.Operator())
142 default:
143 return nil, fmt.Errorf("%q is not a valid label selector operator", req.Operator())
144 }
145 labelSelector.MatchExpressions = append(labelSelector.MatchExpressions, LabelSelectorRequirement{
146 Key: req.Key(),
147 Operator: op,
148 Values: req.Values().List(),
149 })
150 }
151 return labelSelector, nil
152 }
153
154 // SetAsLabelSelector converts the labels.Set object into a LabelSelector api object.
155 func SetAsLabelSelector(ls labels.Set) *LabelSelector {
156 if ls == nil {
157 return nil
158 }
159
160 selector := &LabelSelector{
161 MatchLabels: make(map[string]string, len(ls)),
162 }
163 for label, value := range ls {
164 selector.MatchLabels[label] = value
165 }
166
167 return selector
168 }
169
170 // FormatLabelSelector convert labelSelector into plain string
171 func FormatLabelSelector(labelSelector *LabelSelector) string {
172 selector, err := LabelSelectorAsSelector(labelSelector)
173 if err != nil {
174 return "<error>"
175 }
176
177 l := selector.String()
178 if len(l) == 0 {
179 l = "<none>"
180 }
181 return l
182 }
183
184 func ExtractGroupVersions(l *APIGroupList) []string {
185 var groupVersions []string
186 for _, g := range l.Groups {
187 for _, gv := range g.Versions {
188 groupVersions = append(groupVersions, gv.GroupVersion)
189 }
190 }
191 return groupVersions
192 }
193
194 // HasAnnotation returns a bool if passed in annotation exists
195 func HasAnnotation(obj ObjectMeta, ann string) bool {
196 _, found := obj.Annotations[ann]
197 return found
198 }
199
200 // SetMetaDataAnnotation sets the annotation and value
201 func SetMetaDataAnnotation(obj *ObjectMeta, ann string, value string) {
202 if obj.Annotations == nil {
203 obj.Annotations = make(map[string]string)
204 }
205 obj.Annotations[ann] = value
206 }
207
208 // HasLabel returns a bool if passed in label exists
209 func HasLabel(obj ObjectMeta, label string) bool {
210 _, found := obj.Labels[label]
211 return found
212 }
213
214 // SetMetaDataLabel sets the label and value
215 func SetMetaDataLabel(obj *ObjectMeta, label string, value string) {
216 if obj.Labels == nil {
217 obj.Labels = make(map[string]string)
218 }
219 obj.Labels[label] = value
220 }
221
222 // SingleObject returns a ListOptions for watching a single object.
223 func SingleObject(meta ObjectMeta) ListOptions {
224 return ListOptions{
225 FieldSelector: fields.OneTermEqualSelector("metadata.name", meta.Name).String(),
226 ResourceVersion: meta.ResourceVersion,
227 }
228 }
229
230 // NewDeleteOptions returns a DeleteOptions indicating the resource should
231 // be deleted within the specified grace period. Use zero to indicate
232 // immediate deletion. If you would prefer to use the default grace period,
233 // use &metav1.DeleteOptions{} directly.
234 func NewDeleteOptions(grace int64) *DeleteOptions {
235 return &DeleteOptions{GracePeriodSeconds: &grace}
236 }
237
238 // NewPreconditionDeleteOptions returns a DeleteOptions with a UID precondition set.
239 func NewPreconditionDeleteOptions(uid string) *DeleteOptions {
240 u := types.UID(uid)
241 p := Preconditions{UID: &u}
242 return &DeleteOptions{Preconditions: &p}
243 }
244
245 // NewUIDPreconditions returns a Preconditions with UID set.
246 func NewUIDPreconditions(uid string) *Preconditions {
247 u := types.UID(uid)
248 return &Preconditions{UID: &u}
249 }
250
251 // NewRVDeletionPrecondition returns a DeleteOptions with a ResourceVersion precondition set.
252 func NewRVDeletionPrecondition(rv string) *DeleteOptions {
253 p := Preconditions{ResourceVersion: &rv}
254 return &DeleteOptions{Preconditions: &p}
255 }
256
257 // HasObjectMetaSystemFieldValues returns true if fields that are managed by the system on ObjectMeta have values.
258 func HasObjectMetaSystemFieldValues(meta Object) bool {
259 return !meta.GetCreationTimestamp().Time.IsZero() ||
260 len(meta.GetUID()) != 0
261 }
262
263 // ResetObjectMetaForStatus forces the meta fields for a status update to match the meta fields
264 // for a pre-existing object. This is opt-in for new objects with Status subresource.
265 func ResetObjectMetaForStatus(meta, existingMeta Object) {
266 meta.SetDeletionTimestamp(existingMeta.GetDeletionTimestamp())
267 meta.SetGeneration(existingMeta.GetGeneration())
268 meta.SetSelfLink(existingMeta.GetSelfLink())
269 meta.SetLabels(existingMeta.GetLabels())
270 meta.SetAnnotations(existingMeta.GetAnnotations())
271 meta.SetFinalizers(existingMeta.GetFinalizers())
272 meta.SetOwnerReferences(existingMeta.GetOwnerReferences())
273 // managedFields must be preserved since it's been modified to
274 // track changed fields in the status update.
275 //meta.SetManagedFields(existingMeta.GetManagedFields())
276 }
277
278 // MarshalJSON implements json.Marshaler
279 // MarshalJSON may get called on pointers or values, so implement MarshalJSON on value.
280 // http://stackoverflow.com/questions/21390979/custom-marshaljson-never-gets-called-in-go
281 func (f FieldsV1) MarshalJSON() ([]byte, error) {
282 if f.Raw == nil {
283 return []byte("null"), nil
284 }
285 if f.getContentType() == fieldsV1InvalidOrValidCBORObject {
286 var u map[string]interface{}
287 if err := cbor.Unmarshal(f.Raw, &u); err != nil {
288 return nil, fmt.Errorf("metav1.FieldsV1 cbor invalid: %w", err)
289 }
290 return utiljson.Marshal(u)
291 }
292 return f.Raw, nil
293 }
294
295 // UnmarshalJSON implements json.Unmarshaler
296 func (f *FieldsV1) UnmarshalJSON(b []byte) error {
297 if f == nil {
298 return errors.New("metav1.FieldsV1: UnmarshalJSON on nil pointer")
299 }
300 if !bytes.Equal(b, []byte("null")) {
301 f.Raw = append(f.Raw[0:0], b...)
302 }
303 return nil
304 }
305
306 var _ json.Marshaler = FieldsV1{}
307 var _ json.Unmarshaler = &FieldsV1{}
308
309 func (f FieldsV1) MarshalCBOR() ([]byte, error) {
310 if f.Raw == nil {
311 return cbor.Marshal(nil)
312 }
313 if f.getContentType() == fieldsV1InvalidOrValidJSONObject {
314 var u map[string]interface{}
315 if err := utiljson.Unmarshal(f.Raw, &u); err != nil {
316 return nil, fmt.Errorf("metav1.FieldsV1 json invalid: %w", err)
317 }
318 return cbor.Marshal(u)
319 }
320 return f.Raw, nil
321 }
322
323 var cborNull = []byte{0xf6}
324
325 func (f *FieldsV1) UnmarshalCBOR(b []byte) error {
326 if f == nil {
327 return errors.New("metav1.FieldsV1: UnmarshalCBOR on nil pointer")
328 }
329 if !bytes.Equal(b, cborNull) {
330 f.Raw = append(f.Raw[0:0], b...)
331 }
332 return nil
333 }
334
335 const (
336 // fieldsV1InvalidOrEmpty indicates that a FieldsV1 either contains no raw bytes or its raw
337 // bytes don't represent an allowable value in any supported encoding.
338 fieldsV1InvalidOrEmpty = iota
339
340 // fieldsV1InvalidOrValidJSONObject indicates that a FieldV1 either contains raw bytes that
341 // are a valid JSON encoding of an allowable value or don't represent an allowable value in
342 // any supported encoding.
343 fieldsV1InvalidOrValidJSONObject
344
345 // fieldsV1InvalidOrValidCBORObject indicates that a FieldV1 either contains raw bytes that
346 // are a valid CBOR encoding of an allowable value or don't represent an allowable value in
347 // any supported encoding.
348 fieldsV1InvalidOrValidCBORObject
349 )
350
351 // getContentType returns one of fieldsV1InvalidOrEmpty, fieldsV1InvalidOrValidJSONObject,
352 // fieldsV1InvalidOrValidCBORObject based on the value of Raw.
353 //
354 // Raw can be encoded in JSON or CBOR and is only valid if it is empty, null, or an object (map)
355 // value. It is invalid if it contains a JSON string, number, boolean, or array. If Raw is nonempty
356 // and represents an allowable value, then the initial byte unambiguously distinguishes a
357 // JSON-encoded value from a CBOR-encoded value.
358 //
359 // A valid JSON-encoded value can begin with any of the four JSON whitespace characters, the first
360 // character 'n' of null, or '{' (0x09, 0x0a, 0x0d, 0x20, 0x6e, or 0x7b, respectively). A valid
361 // CBOR-encoded value can begin with the null simple value, an initial byte with major type "map",
362 // or, if a tag-enclosed map, an initial byte with major type "tag" (0xf6, 0xa0...0xbf, or
363 // 0xc6...0xdb). The two sets of valid initial bytes don't intersect.
364 func (f FieldsV1) getContentType() int {
365 if len(f.Raw) > 0 {
366 p := f.Raw[0]
367 switch p {
368 case 'n', '{', '\t', '\r', '\n', ' ':
369 return fieldsV1InvalidOrValidJSONObject
370 case 0xf6: // null
371 return fieldsV1InvalidOrValidCBORObject
372 default:
373 if p >= 0xa0 && p <= 0xbf /* map */ || p >= 0xc6 && p <= 0xdb /* tag */ {
374 return fieldsV1InvalidOrValidCBORObject
375 }
376 }
377 }
378 return fieldsV1InvalidOrEmpty
379 }