patch.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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 patch
  14. import (
  15. "fmt"
  16. "reflect"
  17. "strings"
  18. jsonpatch "github.com/evanphx/json-patch"
  19. "github.com/spf13/cobra"
  20. "k8s.io/klog"
  21. "k8s.io/apimachinery/pkg/api/meta"
  22. "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
  23. "k8s.io/apimachinery/pkg/runtime"
  24. "k8s.io/apimachinery/pkg/runtime/schema"
  25. "k8s.io/apimachinery/pkg/types"
  26. "k8s.io/apimachinery/pkg/util/sets"
  27. "k8s.io/apimachinery/pkg/util/strategicpatch"
  28. "k8s.io/apimachinery/pkg/util/yaml"
  29. "k8s.io/cli-runtime/pkg/genericclioptions"
  30. "k8s.io/cli-runtime/pkg/printers"
  31. "k8s.io/cli-runtime/pkg/resource"
  32. cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
  33. "k8s.io/kubernetes/pkg/kubectl/scheme"
  34. "k8s.io/kubernetes/pkg/kubectl/util/i18n"
  35. "k8s.io/kubernetes/pkg/kubectl/util/templates"
  36. )
  37. var patchTypes = map[string]types.PatchType{"json": types.JSONPatchType, "merge": types.MergePatchType, "strategic": types.StrategicMergePatchType}
  38. // PatchOptions is the start of the data required to perform the operation. As new fields are added, add them here instead of
  39. // referencing the cmd.Flags()
  40. type PatchOptions struct {
  41. resource.FilenameOptions
  42. RecordFlags *genericclioptions.RecordFlags
  43. PrintFlags *genericclioptions.PrintFlags
  44. ToPrinter func(string) (printers.ResourcePrinter, error)
  45. Recorder genericclioptions.Recorder
  46. Local bool
  47. PatchType string
  48. Patch string
  49. namespace string
  50. enforceNamespace bool
  51. dryRun bool
  52. outputFormat string
  53. args []string
  54. builder *resource.Builder
  55. unstructuredClientForMapping func(mapping *meta.RESTMapping) (resource.RESTClient, error)
  56. genericclioptions.IOStreams
  57. }
  58. var (
  59. patchLong = templates.LongDesc(i18n.T(`
  60. Update field(s) of a resource using strategic merge patch, a JSON merge patch, or a JSON patch.
  61. JSON and YAML formats are accepted.`))
  62. patchExample = templates.Examples(i18n.T(`
  63. # Partially update a node using a strategic merge patch. Specify the patch as JSON.
  64. kubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}'
  65. # Partially update a node using a strategic merge patch. Specify the patch as YAML.
  66. kubectl patch node k8s-node-1 -p $'spec:\n unschedulable: true'
  67. # Partially update a node identified by the type and name specified in "node.json" using strategic merge patch.
  68. kubectl patch -f node.json -p '{"spec":{"unschedulable":true}}'
  69. # Update a container's image; spec.containers[*].name is required because it's a merge key.
  70. kubectl patch pod valid-pod -p '{"spec":{"containers":[{"name":"kubernetes-serve-hostname","image":"new image"}]}}'
  71. # Update a container's image using a json patch with positional arrays.
  72. kubectl patch pod valid-pod --type='json' -p='[{"op": "replace", "path": "/spec/containers/0/image", "value":"new image"}]'`))
  73. )
  74. func NewPatchOptions(ioStreams genericclioptions.IOStreams) *PatchOptions {
  75. return &PatchOptions{
  76. RecordFlags: genericclioptions.NewRecordFlags(),
  77. Recorder: genericclioptions.NoopRecorder{},
  78. PrintFlags: genericclioptions.NewPrintFlags("patched").WithTypeSetter(scheme.Scheme),
  79. IOStreams: ioStreams,
  80. }
  81. }
  82. func NewCmdPatch(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
  83. o := NewPatchOptions(ioStreams)
  84. cmd := &cobra.Command{
  85. Use: "patch (-f FILENAME | TYPE NAME) -p PATCH",
  86. DisableFlagsInUseLine: true,
  87. Short: i18n.T("Update field(s) of a resource using strategic merge patch"),
  88. Long: patchLong,
  89. Example: patchExample,
  90. Run: func(cmd *cobra.Command, args []string) {
  91. cmdutil.CheckErr(o.Complete(f, cmd, args))
  92. cmdutil.CheckErr(o.Validate())
  93. cmdutil.CheckErr(o.RunPatch())
  94. },
  95. }
  96. o.RecordFlags.AddFlags(cmd)
  97. o.PrintFlags.AddFlags(cmd)
  98. cmd.Flags().StringVarP(&o.Patch, "patch", "p", "", "The patch to be applied to the resource JSON file.")
  99. cmd.MarkFlagRequired("patch")
  100. cmd.Flags().StringVar(&o.PatchType, "type", "strategic", fmt.Sprintf("The type of patch being provided; one of %v", sets.StringKeySet(patchTypes).List()))
  101. cmdutil.AddDryRunFlag(cmd)
  102. cmdutil.AddFilenameOptionFlags(cmd, &o.FilenameOptions, "identifying the resource to update")
  103. cmd.Flags().BoolVar(&o.Local, "local", o.Local, "If true, patch will operate on the content of the file, not the server-side resource.")
  104. return cmd
  105. }
  106. func (o *PatchOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {
  107. var err error
  108. o.RecordFlags.Complete(cmd)
  109. o.Recorder, err = o.RecordFlags.ToRecorder()
  110. if err != nil {
  111. return err
  112. }
  113. o.outputFormat = cmdutil.GetFlagString(cmd, "output")
  114. o.dryRun = cmdutil.GetFlagBool(cmd, "dry-run")
  115. o.ToPrinter = func(operation string) (printers.ResourcePrinter, error) {
  116. o.PrintFlags.NamePrintFlags.Operation = operation
  117. if o.dryRun {
  118. o.PrintFlags.Complete("%s (dry run)")
  119. }
  120. return o.PrintFlags.ToPrinter()
  121. }
  122. o.namespace, o.enforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()
  123. if err != nil {
  124. return err
  125. }
  126. o.args = args
  127. o.builder = f.NewBuilder()
  128. o.unstructuredClientForMapping = f.UnstructuredClientForMapping
  129. return nil
  130. }
  131. func (o *PatchOptions) Validate() error {
  132. if o.Local && len(o.args) != 0 {
  133. return fmt.Errorf("cannot specify --local and server resources")
  134. }
  135. if len(o.Patch) == 0 {
  136. return fmt.Errorf("must specify -p to patch")
  137. }
  138. if len(o.PatchType) != 0 {
  139. if _, ok := patchTypes[strings.ToLower(o.PatchType)]; !ok {
  140. return fmt.Errorf("--type must be one of %v, not %q", sets.StringKeySet(patchTypes).List(), o.PatchType)
  141. }
  142. }
  143. return nil
  144. }
  145. func (o *PatchOptions) RunPatch() error {
  146. patchType := types.StrategicMergePatchType
  147. if len(o.PatchType) != 0 {
  148. patchType = patchTypes[strings.ToLower(o.PatchType)]
  149. }
  150. patchBytes, err := yaml.ToJSON([]byte(o.Patch))
  151. if err != nil {
  152. return fmt.Errorf("unable to parse %q: %v", o.Patch, err)
  153. }
  154. r := o.builder.
  155. Unstructured().
  156. ContinueOnError().
  157. LocalParam(o.Local).
  158. NamespaceParam(o.namespace).DefaultNamespace().
  159. FilenameParam(o.enforceNamespace, &o.FilenameOptions).
  160. ResourceTypeOrNameArgs(false, o.args...).
  161. Flatten().
  162. Do()
  163. err = r.Err()
  164. if err != nil {
  165. return err
  166. }
  167. count := 0
  168. err = r.Visit(func(info *resource.Info, err error) error {
  169. if err != nil {
  170. return err
  171. }
  172. count++
  173. name, namespace := info.Name, info.Namespace
  174. if !o.Local && !o.dryRun {
  175. mapping := info.ResourceMapping()
  176. client, err := o.unstructuredClientForMapping(mapping)
  177. if err != nil {
  178. return err
  179. }
  180. helper := resource.NewHelper(client, mapping)
  181. patchedObj, err := helper.Patch(namespace, name, patchType, patchBytes, nil)
  182. if err != nil {
  183. return err
  184. }
  185. didPatch := !reflect.DeepEqual(info.Object, patchedObj)
  186. // if the recorder makes a change, compute and create another patch
  187. if mergePatch, err := o.Recorder.MakeRecordMergePatch(patchedObj); err != nil {
  188. klog.V(4).Infof("error recording current command: %v", err)
  189. } else if len(mergePatch) > 0 {
  190. if recordedObj, err := helper.Patch(info.Namespace, info.Name, types.MergePatchType, mergePatch, nil); err != nil {
  191. klog.V(4).Infof("error recording reason: %v", err)
  192. } else {
  193. patchedObj = recordedObj
  194. }
  195. }
  196. printer, err := o.ToPrinter(patchOperation(didPatch))
  197. if err != nil {
  198. return err
  199. }
  200. return printer.PrintObj(patchedObj, o.Out)
  201. }
  202. originalObjJS, err := runtime.Encode(unstructured.UnstructuredJSONScheme, info.Object)
  203. if err != nil {
  204. return err
  205. }
  206. originalPatchedObjJS, err := getPatchedJSON(patchType, originalObjJS, patchBytes, info.Object.GetObjectKind().GroupVersionKind(), scheme.Scheme)
  207. if err != nil {
  208. return err
  209. }
  210. targetObj, err := runtime.Decode(unstructured.UnstructuredJSONScheme, originalPatchedObjJS)
  211. if err != nil {
  212. return err
  213. }
  214. didPatch := !reflect.DeepEqual(info.Object, targetObj)
  215. printer, err := o.ToPrinter(patchOperation(didPatch))
  216. if err != nil {
  217. return err
  218. }
  219. return printer.PrintObj(targetObj, o.Out)
  220. })
  221. if err != nil {
  222. return err
  223. }
  224. if count == 0 {
  225. return fmt.Errorf("no objects passed to patch")
  226. }
  227. return nil
  228. }
  229. func getPatchedJSON(patchType types.PatchType, originalJS, patchJS []byte, gvk schema.GroupVersionKind, creater runtime.ObjectCreater) ([]byte, error) {
  230. switch patchType {
  231. case types.JSONPatchType:
  232. patchObj, err := jsonpatch.DecodePatch(patchJS)
  233. if err != nil {
  234. return nil, err
  235. }
  236. bytes, err := patchObj.Apply(originalJS)
  237. // TODO: This is pretty hacky, we need a better structured error from the json-patch
  238. if err != nil && strings.Contains(err.Error(), "doc is missing key") {
  239. msg := err.Error()
  240. ix := strings.Index(msg, "key:")
  241. key := msg[ix+5:]
  242. return bytes, fmt.Errorf("Object to be patched is missing field (%s)", key)
  243. }
  244. return bytes, err
  245. case types.MergePatchType:
  246. return jsonpatch.MergePatch(originalJS, patchJS)
  247. case types.StrategicMergePatchType:
  248. // get a typed object for this GVK if we need to apply a strategic merge patch
  249. obj, err := creater.New(gvk)
  250. if err != nil {
  251. return nil, fmt.Errorf("cannot apply strategic merge patch for %s locally, try --type merge", gvk.String())
  252. }
  253. return strategicpatch.StrategicMergePatch(originalJS, patchJS, obj)
  254. default:
  255. // only here as a safety net - go-restful filters content-type
  256. return nil, fmt.Errorf("unknown Content-Type header for patch: %v", patchType)
  257. }
  258. }
  259. func patchOperation(didPatch bool) string {
  260. if didPatch {
  261. return "patched"
  262. }
  263. return "patched (no change)"
  264. }