forked from kubernetes/kubernetes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
annotate.go
325 lines (282 loc) · 10.9 KB
/
annotate.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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
/*
Copyright 2014 The Kubernetes Authors All rights reserved.
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 cmd
import (
"bytes"
"encoding/json"
"fmt"
"io"
"strings"
"github.com/spf13/cobra"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/kubectl"
cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
"k8s.io/kubernetes/pkg/kubectl/resource"
"k8s.io/kubernetes/pkg/runtime"
"k8s.io/kubernetes/pkg/util/strategicpatch"
)
// AnnotateOptions have the data required to perform the annotate operation
type AnnotateOptions struct {
resources []string
newAnnotations map[string]string
removeAnnotations []string
builder *resource.Builder
filenames []string
overwrite bool
all bool
resourceVersion string
f *cmdutil.Factory
out io.Writer
cmd *cobra.Command
}
const (
annotate_long = `Update the annotations on one or more resources.
An annotation is a key/value pair that can hold larger (compared to a label), and possibly not human-readable, data.
It is intended to store non-identifying auxiliary data, especially data manipulated by tools and system extensions.
If --overwrite is true, then existing annotations can be overwritten, otherwise attempting to overwrite an annotation will result in an error.
If --resource-version is specified, then updates will use this resource version, otherwise the existing resource-version will be used.
Possible resources include (case insensitive): pods (po), services (svc),
replicationcontrollers (rc), nodes (no), events (ev), componentstatuses (cs),
limitranges (limits), persistentvolumes (pv), persistentvolumeclaims (pvc),
horizontalpodautoscalers (hpa), resourcequotas (quota) or secrets.`
annotate_example = `# Update pod 'foo' with the annotation 'description' and the value 'my frontend'.
# If the same annotation is set multiple times, only the last value will be applied
$ kubectl annotate pods foo description='my frontend'
# Update a pod identified by type and name in "pod.json"
$ kubectl annotate -f pod.json description='my frontend'
# Update pod 'foo' with the annotation 'description' and the value 'my frontend running nginx', overwriting any existing value.
$ kubectl annotate --overwrite pods foo description='my frontend running nginx'
# Update all pods in the namespace
$ kubectl annotate pods --all description='my frontend running nginx'
# Update pod 'foo' only if the resource is unchanged from version 1.
$ kubectl annotate pods foo description='my frontend running nginx' --resource-version=1
# Update pod 'foo' by removing an annotation named 'description' if it exists.
# Does not require the --overwrite flag.
$ kubectl annotate pods foo description-`
)
func NewCmdAnnotate(f *cmdutil.Factory, out io.Writer) *cobra.Command {
options := &AnnotateOptions{}
cmd := &cobra.Command{
Use: "annotate [--overwrite] (-f FILENAME | TYPE NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--resource-version=version]",
Short: "Update the annotations on a resource",
Long: annotate_long,
Example: annotate_example,
Run: func(cmd *cobra.Command, args []string) {
if err := options.Complete(f, out, cmd, args); err != nil {
cmdutil.CheckErr(err)
}
if err := options.Validate(args); err != nil {
cmdutil.CheckErr(cmdutil.UsageError(cmd, err.Error()))
}
if err := options.RunAnnotate(); err != nil {
cmdutil.CheckErr(err)
}
},
}
cmdutil.AddPrinterFlags(cmd)
cmd.Flags().BoolVar(&options.overwrite, "overwrite", false, "If true, allow annotations to be overwritten, otherwise reject annotation updates that overwrite existing annotations.")
cmd.Flags().BoolVar(&options.all, "all", false, "select all resources in the namespace of the specified resource types")
cmd.Flags().StringVar(&options.resourceVersion, "resource-version", "", "If non-empty, the annotation update will only succeed if this is the current resource-version for the object. Only valid when specifying a single resource.")
usage := "Filename, directory, or URL to a file identifying the resource to update the annotation"
kubectl.AddJsonFilenameFlag(cmd, &options.filenames, usage)
return cmd
}
// Complete adapts from the command line args and factory to the data required.
func (o *AnnotateOptions) Complete(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) (err error) {
namespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
// retrieves resource and annotation args from args
// also checks args to verify that all resources are specified before annotations
annotationArgs := []string{}
metAnnotaionArg := false
for _, s := range args {
isAnnotation := strings.Contains(s, "=") || strings.HasSuffix(s, "-")
switch {
case !metAnnotaionArg && isAnnotation:
metAnnotaionArg = true
fallthrough
case metAnnotaionArg && isAnnotation:
annotationArgs = append(annotationArgs, s)
case !metAnnotaionArg && !isAnnotation:
o.resources = append(o.resources, s)
case metAnnotaionArg && !isAnnotation:
return fmt.Errorf("all resources must be specified before annotation changes: %s", s)
}
}
if len(o.resources) < 1 && len(o.filenames) == 0 {
return fmt.Errorf("one or more resources must be specified as <resource> <name> or <resource>/<name>")
}
if len(annotationArgs) < 1 {
return fmt.Errorf("at least one annotation update is required")
}
if o.newAnnotations, o.removeAnnotations, err = parseAnnotations(annotationArgs); err != nil {
return err
}
mapper, typer := f.Object()
o.builder = resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()).
ContinueOnError().
NamespaceParam(namespace).DefaultNamespace().
FilenameParam(enforceNamespace, o.filenames...).
ResourceTypeOrNameArgs(o.all, o.resources...).
Flatten().
Latest()
o.f = f
o.out = out
o.cmd = cmd
return nil
}
// Validate checks to the AnnotateOptions to see if there is sufficient information run the command.
func (o AnnotateOptions) Validate(args []string) error {
if err := validateAnnotations(o.removeAnnotations, o.newAnnotations); err != nil {
return err
}
// only apply resource version locking on a single resource
if len(o.resources) > 1 && len(o.resourceVersion) > 0 {
return fmt.Errorf("--resource-version may only be used with a single resource")
}
return nil
}
// RunAnnotate does the work
func (o AnnotateOptions) RunAnnotate() error {
r := o.builder.Do()
if err := r.Err(); err != nil {
return err
}
return r.Visit(func(info *resource.Info, err error) error {
if err != nil {
return err
}
name, namespace, obj := info.Name, info.Namespace, info.Object
oldData, err := json.Marshal(obj)
if err != nil {
return err
}
if err := o.updateAnnotations(obj); err != nil {
return err
}
newData, err := json.Marshal(obj)
if err != nil {
return err
}
patchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, obj)
if err != nil {
return err
}
mapping := info.ResourceMapping()
client, err := o.f.RESTClient(mapping)
if err != nil {
return err
}
helper := resource.NewHelper(client, mapping)
outputObj, err := helper.Patch(namespace, name, api.StrategicMergePatchType, patchBytes)
if err != nil {
return err
}
outputFormat := cmdutil.GetFlagString(o.cmd, "output")
if outputFormat != "" {
return o.f.PrintObject(o.cmd, outputObj, o.out)
}
mapper, _ := o.f.Object()
cmdutil.PrintSuccess(mapper, false, o.out, info.Mapping.Resource, info.Name, "annotated")
return nil
})
}
// parseAnnotations retrieves new and remove annotations from annotation args
func parseAnnotations(annotationArgs []string) (map[string]string, []string, error) {
var invalidBuf bytes.Buffer
newAnnotations := map[string]string{}
removeAnnotations := []string{}
for _, annotationArg := range annotationArgs {
if strings.Index(annotationArg, "=") != -1 {
parts := strings.SplitN(annotationArg, "=", 2)
if len(parts) != 2 || len(parts[1]) == 0 {
if invalidBuf.Len() > 0 {
invalidBuf.WriteString(", ")
}
invalidBuf.WriteString(fmt.Sprintf(annotationArg))
} else {
newAnnotations[parts[0]] = parts[1]
}
} else if strings.HasSuffix(annotationArg, "-") {
removeAnnotations = append(removeAnnotations, annotationArg[:len(annotationArg)-1])
} else {
if invalidBuf.Len() > 0 {
invalidBuf.WriteString(", ")
}
invalidBuf.WriteString(fmt.Sprintf(annotationArg))
}
}
if invalidBuf.Len() > 0 {
return newAnnotations, removeAnnotations, fmt.Errorf("invalid annotation format: %s", invalidBuf.String())
}
return newAnnotations, removeAnnotations, nil
}
// validateAnnotations checks the format of annotation args and checks removed annotations aren't in the new annotations map
func validateAnnotations(removeAnnotations []string, newAnnotations map[string]string) error {
var modifyRemoveBuf bytes.Buffer
for _, removeAnnotation := range removeAnnotations {
if _, found := newAnnotations[removeAnnotation]; found {
if modifyRemoveBuf.Len() > 0 {
modifyRemoveBuf.WriteString(", ")
}
modifyRemoveBuf.WriteString(fmt.Sprintf(removeAnnotation))
}
}
if modifyRemoveBuf.Len() > 0 {
return fmt.Errorf("can not both modify and remove the following annotation(s) in the same command: %s", modifyRemoveBuf.String())
}
return nil
}
// validateNoAnnotationOverwrites validates that when overwrite is false, to-be-updated annotations don't exist in the object annotation map (yet)
func validateNoAnnotationOverwrites(meta *api.ObjectMeta, annotations map[string]string) error {
var buf bytes.Buffer
for key := range annotations {
if value, found := meta.Annotations[key]; found {
if buf.Len() > 0 {
buf.WriteString("; ")
}
buf.WriteString(fmt.Sprintf("'%s' already has a value (%s)", key, value))
}
}
if buf.Len() > 0 {
return fmt.Errorf("--overwrite is false but found the following declared annotation(s): %s", buf.String())
}
return nil
}
// updateAnnotations updates annotations of obj
func (o AnnotateOptions) updateAnnotations(obj runtime.Object) error {
meta, err := api.ObjectMetaFor(obj)
if err != nil {
return err
}
if !o.overwrite {
if err := validateNoAnnotationOverwrites(meta, o.newAnnotations); err != nil {
return err
}
}
if meta.Annotations == nil {
meta.Annotations = make(map[string]string)
}
for key, value := range o.newAnnotations {
meta.Annotations[key] = value
}
for _, annotation := range o.removeAnnotations {
delete(meta.Annotations, annotation)
}
if len(o.resourceVersion) != 0 {
meta.ResourceVersion = o.resourceVersion
}
return nil
}