annotate.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  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. "regexp"
  20. "strings"
  21. "github.com/golang/glog"
  22. "github.com/renstrom/dedent"
  23. "github.com/spf13/cobra"
  24. "k8s.io/kubernetes/pkg/api"
  25. "k8s.io/kubernetes/pkg/api/meta"
  26. "k8s.io/kubernetes/pkg/kubectl"
  27. cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
  28. "k8s.io/kubernetes/pkg/kubectl/resource"
  29. "k8s.io/kubernetes/pkg/runtime"
  30. "k8s.io/kubernetes/pkg/util/strategicpatch"
  31. )
  32. // AnnotateOptions have the data required to perform the annotate operation
  33. type AnnotateOptions struct {
  34. resources []string
  35. newAnnotations map[string]string
  36. removeAnnotations []string
  37. builder *resource.Builder
  38. filenames []string
  39. selector string
  40. overwrite bool
  41. all bool
  42. resourceVersion string
  43. changeCause string
  44. recordChangeCause bool
  45. f *cmdutil.Factory
  46. out io.Writer
  47. cmd *cobra.Command
  48. recursive bool
  49. }
  50. var (
  51. annotate_resources = `
  52. pod (po), service (svc), replicationcontroller (rc),
  53. node (no), event (ev), componentstatuse (cs),
  54. limitrange (limits), persistentvolume (pv), persistentvolumeclaim (pvc),
  55. horizontalpodautoscaler (hpa), resourcequota (quota), secret`
  56. annotate_long = dedent.Dedent(`
  57. Update the annotations on one or more resources.
  58. An annotation is a key/value pair that can hold larger (compared to a label), and possibly not human-readable, data.
  59. It is intended to store non-identifying auxiliary data, especially data manipulated by tools and system extensions.
  60. If --overwrite is true, then existing annotations can be overwritten, otherwise attempting to overwrite an annotation will result in an error.
  61. If --resource-version is specified, then updates will use this resource version, otherwise the existing resource-version will be used.
  62. Possible resources include (case insensitive):`) + annotate_resources
  63. annotate_example = dedent.Dedent(`
  64. # Update pod 'foo' with the annotation 'description' and the value 'my frontend'.
  65. # If the same annotation is set multiple times, only the last value will be applied
  66. kubectl annotate pods foo description='my frontend'
  67. # Update a pod identified by type and name in "pod.json"
  68. kubectl annotate -f pod.json description='my frontend'
  69. # Update pod 'foo' with the annotation 'description' and the value 'my frontend running nginx', overwriting any existing value.
  70. kubectl annotate --overwrite pods foo description='my frontend running nginx'
  71. # Update all pods in the namespace
  72. kubectl annotate pods --all description='my frontend running nginx'
  73. # Update pod 'foo' only if the resource is unchanged from version 1.
  74. kubectl annotate pods foo description='my frontend running nginx' --resource-version=1
  75. # Update pod 'foo' by removing an annotation named 'description' if it exists.
  76. # Does not require the --overwrite flag.
  77. kubectl annotate pods foo description-`)
  78. )
  79. func NewCmdAnnotate(f *cmdutil.Factory, out io.Writer) *cobra.Command {
  80. options := &AnnotateOptions{}
  81. validArgs, argAliases := []string{}, []string{}
  82. resources := regexp.MustCompile(`\s*,`).Split(annotate_resources, -1)
  83. for _, r := range resources {
  84. validArgs = append(validArgs, strings.Fields(r)[0])
  85. argAliases = kubectl.ResourceAliases(validArgs)
  86. }
  87. cmd := &cobra.Command{
  88. Use: "annotate [--overwrite] (-f FILENAME | TYPE NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--resource-version=version]",
  89. Short: "Update the annotations on a resource",
  90. Long: annotate_long,
  91. Example: annotate_example,
  92. Run: func(cmd *cobra.Command, args []string) {
  93. if err := options.Complete(f, out, cmd, args); err != nil {
  94. cmdutil.CheckErr(err)
  95. }
  96. if err := options.Validate(args); err != nil {
  97. cmdutil.CheckErr(cmdutil.UsageError(cmd, err.Error()))
  98. }
  99. if err := options.RunAnnotate(); err != nil {
  100. cmdutil.CheckErr(err)
  101. }
  102. },
  103. ValidArgs: validArgs,
  104. ArgAliases: argAliases,
  105. }
  106. cmdutil.AddPrinterFlags(cmd)
  107. cmdutil.AddInclude3rdPartyFlags(cmd)
  108. cmd.Flags().StringVarP(&options.selector, "selector", "l", "", "Selector (label query) to filter on")
  109. cmd.Flags().BoolVar(&options.overwrite, "overwrite", false, "If true, allow annotations to be overwritten, otherwise reject annotation updates that overwrite existing annotations.")
  110. cmd.Flags().BoolVar(&options.all, "all", false, "select all resources in the namespace of the specified resource types")
  111. 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.")
  112. usage := "Filename, directory, or URL to a file identifying the resource to update the annotation"
  113. kubectl.AddJsonFilenameFlag(cmd, &options.filenames, usage)
  114. cmdutil.AddRecursiveFlag(cmd, &options.recursive)
  115. cmdutil.AddRecordFlag(cmd)
  116. return cmd
  117. }
  118. // Complete adapts from the command line args and factory to the data required.
  119. func (o *AnnotateOptions) Complete(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) (err error) {
  120. namespace, enforceNamespace, err := f.DefaultNamespace()
  121. if err != nil {
  122. return err
  123. }
  124. // retrieves resource and annotation args from args
  125. // also checks args to verify that all resources are specified before annotations
  126. resources, annotationArgs, err := cmdutil.GetResourcesAndPairs(args, "annotation")
  127. if err != nil {
  128. return err
  129. }
  130. o.resources = resources
  131. if len(o.resources) < 1 && len(o.filenames) == 0 {
  132. return fmt.Errorf("one or more resources must be specified as <resource> <name> or <resource>/<name>")
  133. }
  134. if len(annotationArgs) < 1 {
  135. return fmt.Errorf("at least one annotation update is required")
  136. }
  137. if o.newAnnotations, o.removeAnnotations, err = parseAnnotations(annotationArgs); err != nil {
  138. return err
  139. }
  140. o.recordChangeCause = cmdutil.GetRecordFlag(cmd)
  141. o.changeCause = f.Command()
  142. mapper, typer := f.Object(cmdutil.GetIncludeThirdPartyAPIs(cmd))
  143. o.builder = resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)).
  144. ContinueOnError().
  145. NamespaceParam(namespace).DefaultNamespace().
  146. FilenameParam(enforceNamespace, o.recursive, o.filenames...).
  147. SelectorParam(o.selector).
  148. ResourceTypeOrNameArgs(o.all, o.resources...).
  149. Flatten().
  150. Latest()
  151. o.f = f
  152. o.out = out
  153. o.cmd = cmd
  154. return nil
  155. }
  156. // Validate checks to the AnnotateOptions to see if there is sufficient information run the command.
  157. func (o AnnotateOptions) Validate(args []string) error {
  158. return validateAnnotations(o.removeAnnotations, o.newAnnotations)
  159. }
  160. // RunAnnotate does the work
  161. func (o AnnotateOptions) RunAnnotate() error {
  162. r := o.builder.Do()
  163. if err := r.Err(); err != nil {
  164. return err
  165. }
  166. var singularResource bool
  167. r.IntoSingular(&singularResource)
  168. // only apply resource version locking on a single resource.
  169. // we must perform this check after o.builder.Do() as
  170. // []o.resources can not not accurately return the proper number
  171. // of resources when they are not passed in "resource/name" format.
  172. if !singularResource && len(o.resourceVersion) > 0 {
  173. return fmt.Errorf("--resource-version may only be used with a single resource")
  174. }
  175. return r.Visit(func(info *resource.Info, err error) error {
  176. if err != nil {
  177. return err
  178. }
  179. obj, err := cmdutil.MaybeConvertObject(info.Object, info.Mapping.GroupVersionKind.GroupVersion(), info.Mapping)
  180. if err != nil {
  181. return err
  182. }
  183. name, namespace := info.Name, info.Namespace
  184. oldData, err := json.Marshal(obj)
  185. if err != nil {
  186. return err
  187. }
  188. // If we should record change-cause, add it to new annotations
  189. if cmdutil.ContainsChangeCause(info) || o.recordChangeCause {
  190. o.newAnnotations[kubectl.ChangeCauseAnnotation] = o.changeCause
  191. }
  192. if err := o.updateAnnotations(obj); err != nil {
  193. return err
  194. }
  195. newData, err := json.Marshal(obj)
  196. if err != nil {
  197. return err
  198. }
  199. patchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, obj)
  200. createdPatch := err == nil
  201. if err != nil {
  202. glog.V(2).Infof("couldn't compute patch: %v", err)
  203. }
  204. mapping := info.ResourceMapping()
  205. client, err := o.f.ClientForMapping(mapping)
  206. if err != nil {
  207. return err
  208. }
  209. helper := resource.NewHelper(client, mapping)
  210. var outputObj runtime.Object
  211. if createdPatch {
  212. outputObj, err = helper.Patch(namespace, name, api.StrategicMergePatchType, patchBytes)
  213. } else {
  214. outputObj, err = helper.Replace(namespace, name, false, obj)
  215. }
  216. if err != nil {
  217. return err
  218. }
  219. mapper, _ := o.f.Object(cmdutil.GetIncludeThirdPartyAPIs(o.cmd))
  220. outputFormat := cmdutil.GetFlagString(o.cmd, "output")
  221. if outputFormat != "" {
  222. return o.f.PrintObject(o.cmd, mapper, outputObj, o.out)
  223. }
  224. cmdutil.PrintSuccess(mapper, false, o.out, info.Mapping.Resource, info.Name, "annotated")
  225. return nil
  226. })
  227. }
  228. // parseAnnotations retrieves new and remove annotations from annotation args
  229. func parseAnnotations(annotationArgs []string) (map[string]string, []string, error) {
  230. return cmdutil.ParsePairs(annotationArgs, "annotation", true)
  231. }
  232. // validateAnnotations checks the format of annotation args and checks removed annotations aren't in the new annotations map
  233. func validateAnnotations(removeAnnotations []string, newAnnotations map[string]string) error {
  234. var modifyRemoveBuf bytes.Buffer
  235. for _, removeAnnotation := range removeAnnotations {
  236. if _, found := newAnnotations[removeAnnotation]; found {
  237. if modifyRemoveBuf.Len() > 0 {
  238. modifyRemoveBuf.WriteString(", ")
  239. }
  240. modifyRemoveBuf.WriteString(fmt.Sprintf(removeAnnotation))
  241. }
  242. }
  243. if modifyRemoveBuf.Len() > 0 {
  244. return fmt.Errorf("can not both modify and remove the following annotation(s) in the same command: %s", modifyRemoveBuf.String())
  245. }
  246. return nil
  247. }
  248. // validateNoAnnotationOverwrites validates that when overwrite is false, to-be-updated annotations don't exist in the object annotation map (yet)
  249. func validateNoAnnotationOverwrites(accessor meta.Object, annotations map[string]string) error {
  250. var buf bytes.Buffer
  251. for key := range annotations {
  252. // change-cause annotation can always be overwritten
  253. if key == kubectl.ChangeCauseAnnotation {
  254. continue
  255. }
  256. if value, found := accessor.GetAnnotations()[key]; found {
  257. if buf.Len() > 0 {
  258. buf.WriteString("; ")
  259. }
  260. buf.WriteString(fmt.Sprintf("'%s' already has a value (%s)", key, value))
  261. }
  262. }
  263. if buf.Len() > 0 {
  264. return fmt.Errorf("--overwrite is false but found the following declared annotation(s): %s", buf.String())
  265. }
  266. return nil
  267. }
  268. // updateAnnotations updates annotations of obj
  269. func (o AnnotateOptions) updateAnnotations(obj runtime.Object) error {
  270. accessor, err := meta.Accessor(obj)
  271. if err != nil {
  272. return err
  273. }
  274. if !o.overwrite {
  275. if err := validateNoAnnotationOverwrites(accessor, o.newAnnotations); err != nil {
  276. return err
  277. }
  278. }
  279. annotations := accessor.GetAnnotations()
  280. if annotations == nil {
  281. annotations = make(map[string]string)
  282. }
  283. for key, value := range o.newAnnotations {
  284. annotations[key] = value
  285. }
  286. for _, annotation := range o.removeAnnotations {
  287. delete(annotations, annotation)
  288. }
  289. accessor.SetAnnotations(annotations)
  290. if len(o.resourceVersion) != 0 {
  291. accessor.SetResourceVersion(o.resourceVersion)
  292. }
  293. return nil
  294. }