PageRenderTime 27ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/compare/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/annotate.go

https://gitlab.com/jasonbishop/contrib
Go | 328 lines | 269 code | 33 blank | 26 comment | 76 complexity | 47373ddddccdec34d5261c29b71494ad MD5 | raw file
  1. /*
  2. Copyright 2014 The Kubernetes Authors All rights reserved.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package cmd
  14. import (
  15. "bytes"
  16. "encoding/json"
  17. "fmt"
  18. "io"
  19. "strings"
  20. "github.com/spf13/cobra"
  21. "k8s.io/kubernetes/pkg/api"
  22. "k8s.io/kubernetes/pkg/kubectl"
  23. cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
  24. "k8s.io/kubernetes/pkg/kubectl/resource"
  25. "k8s.io/kubernetes/pkg/runtime"
  26. "k8s.io/kubernetes/pkg/util/strategicpatch"
  27. )
  28. // AnnotateOptions have the data required to perform the annotate operation
  29. type AnnotateOptions struct {
  30. resources []string
  31. newAnnotations map[string]string
  32. removeAnnotations []string
  33. builder *resource.Builder
  34. filenames []string
  35. selector string
  36. overwrite bool
  37. all bool
  38. resourceVersion string
  39. f *cmdutil.Factory
  40. out io.Writer
  41. cmd *cobra.Command
  42. }
  43. const (
  44. annotate_long = `Update the annotations on one or more resources.
  45. An annotation is a key/value pair that can hold larger (compared to a label), and possibly not human-readable, data.
  46. It is intended to store non-identifying auxiliary data, especially data manipulated by tools and system extensions.
  47. If --overwrite is true, then existing annotations can be overwritten, otherwise attempting to overwrite an annotation will result in an error.
  48. If --resource-version is specified, then updates will use this resource version, otherwise the existing resource-version will be used.
  49. Possible resources include (case insensitive): pods (po), services (svc),
  50. replicationcontrollers (rc), nodes (no), events (ev), componentstatuses (cs),
  51. limitranges (limits), persistentvolumes (pv), persistentvolumeclaims (pvc),
  52. horizontalpodautoscalers (hpa), resourcequotas (quota) or secrets.`
  53. annotate_example = `# Update pod 'foo' with the annotation 'description' and the value 'my frontend'.
  54. # If the same annotation is set multiple times, only the last value will be applied
  55. $ kubectl annotate pods foo description='my frontend'
  56. # Update a pod identified by type and name in "pod.json"
  57. $ kubectl annotate -f pod.json description='my frontend'
  58. # Update pod 'foo' with the annotation 'description' and the value 'my frontend running nginx', overwriting any existing value.
  59. $ kubectl annotate --overwrite pods foo description='my frontend running nginx'
  60. # Update all pods in the namespace
  61. $ kubectl annotate pods --all description='my frontend running nginx'
  62. # Update pod 'foo' only if the resource is unchanged from version 1.
  63. $ kubectl annotate pods foo description='my frontend running nginx' --resource-version=1
  64. # Update pod 'foo' by removing an annotation named 'description' if it exists.
  65. # Does not require the --overwrite flag.
  66. $ kubectl annotate pods foo description-`
  67. )
  68. func NewCmdAnnotate(f *cmdutil.Factory, out io.Writer) *cobra.Command {
  69. options := &AnnotateOptions{}
  70. cmd := &cobra.Command{
  71. Use: "annotate [--overwrite] (-f FILENAME | TYPE NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--resource-version=version]",
  72. Short: "Update the annotations on a resource",
  73. Long: annotate_long,
  74. Example: annotate_example,
  75. Run: func(cmd *cobra.Command, args []string) {
  76. if err := options.Complete(f, out, cmd, args); err != nil {
  77. cmdutil.CheckErr(err)
  78. }
  79. if err := options.Validate(args); err != nil {
  80. cmdutil.CheckErr(cmdutil.UsageError(cmd, err.Error()))
  81. }
  82. if err := options.RunAnnotate(); err != nil {
  83. cmdutil.CheckErr(err)
  84. }
  85. },
  86. }
  87. cmdutil.AddPrinterFlags(cmd)
  88. cmd.Flags().StringVarP(&options.selector, "selector", "l", "", "Selector (label query) to filter on")
  89. cmd.Flags().BoolVar(&options.overwrite, "overwrite", false, "If true, allow annotations to be overwritten, otherwise reject annotation updates that overwrite existing annotations.")
  90. cmd.Flags().BoolVar(&options.all, "all", false, "select all resources in the namespace of the specified resource types")
  91. 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.")
  92. usage := "Filename, directory, or URL to a file identifying the resource to update the annotation"
  93. kubectl.AddJsonFilenameFlag(cmd, &options.filenames, usage)
  94. return cmd
  95. }
  96. // Complete adapts from the command line args and factory to the data required.
  97. func (o *AnnotateOptions) Complete(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) (err error) {
  98. namespace, enforceNamespace, err := f.DefaultNamespace()
  99. if err != nil {
  100. return err
  101. }
  102. // retrieves resource and annotation args from args
  103. // also checks args to verify that all resources are specified before annotations
  104. annotationArgs := []string{}
  105. metAnnotaionArg := false
  106. for _, s := range args {
  107. isAnnotation := strings.Contains(s, "=") || strings.HasSuffix(s, "-")
  108. switch {
  109. case !metAnnotaionArg && isAnnotation:
  110. metAnnotaionArg = true
  111. fallthrough
  112. case metAnnotaionArg && isAnnotation:
  113. annotationArgs = append(annotationArgs, s)
  114. case !metAnnotaionArg && !isAnnotation:
  115. o.resources = append(o.resources, s)
  116. case metAnnotaionArg && !isAnnotation:
  117. return fmt.Errorf("all resources must be specified before annotation changes: %s", s)
  118. }
  119. }
  120. if len(o.resources) < 1 && len(o.filenames) == 0 {
  121. return fmt.Errorf("one or more resources must be specified as <resource> <name> or <resource>/<name>")
  122. }
  123. if len(annotationArgs) < 1 {
  124. return fmt.Errorf("at least one annotation update is required")
  125. }
  126. if o.newAnnotations, o.removeAnnotations, err = parseAnnotations(annotationArgs); err != nil {
  127. return err
  128. }
  129. mapper, typer := f.Object()
  130. o.builder = resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()).
  131. ContinueOnError().
  132. NamespaceParam(namespace).DefaultNamespace().
  133. FilenameParam(enforceNamespace, o.filenames...).
  134. SelectorParam(o.selector).
  135. ResourceTypeOrNameArgs(o.all, o.resources...).
  136. Flatten().
  137. Latest()
  138. o.f = f
  139. o.out = out
  140. o.cmd = cmd
  141. return nil
  142. }
  143. // Validate checks to the AnnotateOptions to see if there is sufficient information run the command.
  144. func (o AnnotateOptions) Validate(args []string) error {
  145. if err := validateAnnotations(o.removeAnnotations, o.newAnnotations); err != nil {
  146. return err
  147. }
  148. // only apply resource version locking on a single resource
  149. if len(o.resources) > 1 && len(o.resourceVersion) > 0 {
  150. return fmt.Errorf("--resource-version may only be used with a single resource")
  151. }
  152. return nil
  153. }
  154. // RunAnnotate does the work
  155. func (o AnnotateOptions) RunAnnotate() error {
  156. r := o.builder.Do()
  157. if err := r.Err(); err != nil {
  158. return err
  159. }
  160. return r.Visit(func(info *resource.Info, err error) error {
  161. if err != nil {
  162. return err
  163. }
  164. name, namespace, obj := info.Name, info.Namespace, info.Object
  165. oldData, err := json.Marshal(obj)
  166. if err != nil {
  167. return err
  168. }
  169. if err := o.updateAnnotations(obj); err != nil {
  170. return err
  171. }
  172. newData, err := json.Marshal(obj)
  173. if err != nil {
  174. return err
  175. }
  176. patchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, obj)
  177. if err != nil {
  178. return err
  179. }
  180. mapping := info.ResourceMapping()
  181. client, err := o.f.RESTClient(mapping)
  182. if err != nil {
  183. return err
  184. }
  185. helper := resource.NewHelper(client, mapping)
  186. outputObj, err := helper.Patch(namespace, name, api.StrategicMergePatchType, patchBytes)
  187. if err != nil {
  188. return err
  189. }
  190. outputFormat := cmdutil.GetFlagString(o.cmd, "output")
  191. if outputFormat != "" {
  192. return o.f.PrintObject(o.cmd, outputObj, o.out)
  193. }
  194. mapper, _ := o.f.Object()
  195. cmdutil.PrintSuccess(mapper, false, o.out, info.Mapping.Resource, info.Name, "annotated")
  196. return nil
  197. })
  198. }
  199. // parseAnnotations retrieves new and remove annotations from annotation args
  200. func parseAnnotations(annotationArgs []string) (map[string]string, []string, error) {
  201. var invalidBuf bytes.Buffer
  202. newAnnotations := map[string]string{}
  203. removeAnnotations := []string{}
  204. for _, annotationArg := range annotationArgs {
  205. if strings.Index(annotationArg, "=") != -1 {
  206. parts := strings.SplitN(annotationArg, "=", 2)
  207. if len(parts) != 2 || len(parts[1]) == 0 {
  208. if invalidBuf.Len() > 0 {
  209. invalidBuf.WriteString(", ")
  210. }
  211. invalidBuf.WriteString(fmt.Sprintf(annotationArg))
  212. } else {
  213. newAnnotations[parts[0]] = parts[1]
  214. }
  215. } else if strings.HasSuffix(annotationArg, "-") {
  216. removeAnnotations = append(removeAnnotations, annotationArg[:len(annotationArg)-1])
  217. } else {
  218. if invalidBuf.Len() > 0 {
  219. invalidBuf.WriteString(", ")
  220. }
  221. invalidBuf.WriteString(fmt.Sprintf(annotationArg))
  222. }
  223. }
  224. if invalidBuf.Len() > 0 {
  225. return newAnnotations, removeAnnotations, fmt.Errorf("invalid annotation format: %s", invalidBuf.String())
  226. }
  227. return newAnnotations, removeAnnotations, nil
  228. }
  229. // validateAnnotations checks the format of annotation args and checks removed annotations aren't in the new annotations map
  230. func validateAnnotations(removeAnnotations []string, newAnnotations map[string]string) error {
  231. var modifyRemoveBuf bytes.Buffer
  232. for _, removeAnnotation := range removeAnnotations {
  233. if _, found := newAnnotations[removeAnnotation]; found {
  234. if modifyRemoveBuf.Len() > 0 {
  235. modifyRemoveBuf.WriteString(", ")
  236. }
  237. modifyRemoveBuf.WriteString(fmt.Sprintf(removeAnnotation))
  238. }
  239. }
  240. if modifyRemoveBuf.Len() > 0 {
  241. return fmt.Errorf("can not both modify and remove the following annotation(s) in the same command: %s", modifyRemoveBuf.String())
  242. }
  243. return nil
  244. }
  245. // validateNoAnnotationOverwrites validates that when overwrite is false, to-be-updated annotations don't exist in the object annotation map (yet)
  246. func validateNoAnnotationOverwrites(meta *api.ObjectMeta, annotations map[string]string) error {
  247. var buf bytes.Buffer
  248. for key := range annotations {
  249. if value, found := meta.Annotations[key]; found {
  250. if buf.Len() > 0 {
  251. buf.WriteString("; ")
  252. }
  253. buf.WriteString(fmt.Sprintf("'%s' already has a value (%s)", key, value))
  254. }
  255. }
  256. if buf.Len() > 0 {
  257. return fmt.Errorf("--overwrite is false but found the following declared annotation(s): %s", buf.String())
  258. }
  259. return nil
  260. }
  261. // updateAnnotations updates annotations of obj
  262. func (o AnnotateOptions) updateAnnotations(obj runtime.Object) error {
  263. meta, err := api.ObjectMetaFor(obj)
  264. if err != nil {
  265. return err
  266. }
  267. if !o.overwrite {
  268. if err := validateNoAnnotationOverwrites(meta, o.newAnnotations); err != nil {
  269. return err
  270. }
  271. }
  272. if meta.Annotations == nil {
  273. meta.Annotations = make(map[string]string)
  274. }
  275. for key, value := range o.newAnnotations {
  276. meta.Annotations[key] = value
  277. }
  278. for _, annotation := range o.removeAnnotations {
  279. delete(meta.Annotations, annotation)
  280. }
  281. if len(o.resourceVersion) != 0 {
  282. meta.ResourceVersion = o.resourceVersion
  283. }
  284. return nil
  285. }