2015-06-25 22:56:30 +00:00
/ *
2016-06-03 00:25:58 +00:00
Copyright 2014 The Kubernetes Authors .
2015-06-25 22:56:30 +00:00
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 (
2015-08-06 09:24:02 +00:00
"fmt"
2015-06-25 22:56:30 +00:00
"io"
2016-12-10 00:01:27 +00:00
"reflect"
2016-02-11 20:52:42 +00:00
"strings"
2015-06-25 22:56:30 +00:00
2016-12-10 00:01:27 +00:00
jsonpatch "github.com/evanphx/json-patch"
2017-01-23 02:15:10 +00:00
"github.com/golang/glog"
2015-06-25 22:56:30 +00:00
"github.com/spf13/cobra"
2015-09-30 15:58:42 +00:00
2017-01-22 16:38:05 +00:00
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
2017-01-11 14:09:48 +00:00
"k8s.io/apimachinery/pkg/runtime"
2017-01-26 02:21:47 +00:00
"k8s.io/apimachinery/pkg/runtime/schema"
2017-01-16 20:13:59 +00:00
"k8s.io/apimachinery/pkg/types"
2017-01-22 16:38:05 +00:00
"k8s.io/apimachinery/pkg/util/json"
2017-01-11 14:09:48 +00:00
"k8s.io/apimachinery/pkg/util/sets"
2017-01-24 14:35:22 +00:00
"k8s.io/apimachinery/pkg/util/strategicpatch"
2017-01-11 14:09:48 +00:00
"k8s.io/apimachinery/pkg/util/yaml"
2017-10-16 11:41:50 +00:00
"k8s.io/kubernetes/pkg/api/legacyscheme"
2015-08-06 09:24:02 +00:00
"k8s.io/kubernetes/pkg/kubectl"
2016-10-07 22:24:42 +00:00
"k8s.io/kubernetes/pkg/kubectl/cmd/templates"
2015-08-05 22:03:47 +00:00
cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
"k8s.io/kubernetes/pkg/kubectl/resource"
2017-07-07 04:04:11 +00:00
"k8s.io/kubernetes/pkg/kubectl/util/i18n"
2017-02-19 22:56:11 +00:00
"k8s.io/kubernetes/pkg/printers"
2015-06-25 22:56:30 +00:00
)
2017-01-16 20:13:59 +00:00
var patchTypes = map [ string ] types . PatchType { "json" : types . JSONPatchType , "merge" : types . MergePatchType , "strategic" : types . StrategicMergePatchType }
2016-02-11 20:52:42 +00:00
2015-08-14 18:46:43 +00:00
// PatchOptions is the start of the data required to perform the operation. As new fields are added, add them here instead of
// referencing the cmd.Flags()
type PatchOptions struct {
2016-08-17 18:28:07 +00:00
resource . FilenameOptions
Local bool
2016-06-02 17:50:52 +00:00
OutputFormat string
2015-08-14 18:46:43 +00:00
}
2016-05-20 17:49:56 +00:00
var (
2017-02-16 03:47:00 +00:00
patchLong = templates . LongDesc ( i18n . T ( `
2017-08-11 18:54:33 +00:00
Update field ( s ) of a resource using strategic merge patch , a JSON merge patch , or a JSON patch .
2015-06-25 22:56:30 +00:00
2016-05-20 17:49:56 +00:00
JSON and YAML formats are accepted .
2015-07-13 20:46:51 +00:00
2017-03-15 03:49:10 +00:00
Please refer to the models in https : //htmlpreview.github.io/?https://github.com/kubernetes/kubernetes/blob/HEAD/docs/api-reference/v1/definitions.html to find if a field is mutable.`))
2015-07-13 20:46:51 +00:00
2017-02-16 03:47:00 +00:00
patchExample = templates . Examples ( i18n . T ( `
2017-08-11 18:54:33 +00:00
# Partially update a node using a strategic merge patch . Specify the patch as JSON .
2016-05-20 17:49:56 +00:00
kubectl patch node k8s - node - 1 - p ' { "spec" : { "unschedulable" : true } } '
2015-08-06 09:24:02 +00:00
2017-08-11 18:54:33 +00:00
# Partially update a node using a strategic merge patch . Specify the patch as YAML .
kubectl patch node k8s - node - 1 - p $ ' spec : \ n unschedulable : true '
# Partially update a node identified by the type and name specified in "node.json" using strategic merge patch .
2016-05-20 17:49:56 +00:00
kubectl patch - f node . json - p ' { "spec" : { "unschedulable" : true } } '
2016-02-11 20:52:42 +00:00
2017-08-11 18:54:33 +00:00
# Update a container ' s image ; spec . containers [ * ] . name is required because it ' s a merge key .
2016-05-20 17:49:56 +00:00
kubectl patch pod valid - pod - p ' { "spec" : { "containers" : [ { "name" : "kubernetes-serve-hostname" , "image" : "new image" } ] } } '
2017-08-11 18:54:33 +00:00
# Update a container ' s image using a json patch with positional arrays .
2017-03-15 03:49:10 +00:00
kubectl patch pod valid - pod -- type = ' json ' - p = ' [ { "op" : "replace" , "path" : "/spec/containers/0/image" , "value" : "new image" } ] ' ` ) )
2015-06-25 22:56:30 +00:00
)
2016-10-13 00:18:39 +00:00
func NewCmdPatch ( f cmdutil . Factory , out io . Writer ) * cobra . Command {
2015-08-14 18:46:43 +00:00
options := & PatchOptions { }
2016-04-03 06:57:51 +00:00
// retrieve a list of handled resources from printer as valid args
validArgs , argAliases := [ ] string { } , [ ] string { }
2017-02-19 22:56:11 +00:00
p , err := f . Printer ( nil , printers . PrintOptions {
2016-06-23 14:49:31 +00:00
ColumnLabels : [ ] string { } ,
} )
2016-04-03 06:57:51 +00:00
cmdutil . CheckErr ( err )
if p != nil {
validArgs = p . HandledResources ( )
argAliases = kubectl . ResourceAliases ( validArgs )
}
2015-06-25 22:56:30 +00:00
cmd := & cobra . Command {
2015-08-06 09:24:02 +00:00
Use : "patch (-f FILENAME | TYPE NAME) -p PATCH" ,
2017-01-25 01:00:32 +00:00
Short : i18n . T ( "Update field(s) of a resource using strategic merge patch" ) ,
2017-02-16 03:47:00 +00:00
Long : patchLong ,
Example : patchExample ,
2015-06-25 22:56:30 +00:00
Run : func ( cmd * cobra . Command , args [ ] string ) {
2016-06-02 17:50:52 +00:00
options . OutputFormat = cmdutil . GetFlagString ( cmd , "output" )
err := RunPatch ( f , out , cmd , args , options )
2015-07-31 23:43:39 +00:00
cmdutil . CheckErr ( err )
2015-06-25 22:56:30 +00:00
} ,
2016-04-03 06:57:51 +00:00
ValidArgs : validArgs ,
ArgAliases : argAliases ,
2015-06-25 22:56:30 +00:00
}
2015-07-13 16:36:12 +00:00
cmd . Flags ( ) . StringP ( "patch" , "p" , "" , "The patch to be applied to the resource JSON file." )
2015-06-25 22:56:30 +00:00
cmd . MarkFlagRequired ( "patch" )
2016-02-11 20:52:42 +00:00
cmd . Flags ( ) . String ( "type" , "strategic" , fmt . Sprintf ( "The type of patch being provided; one of %v" , sets . StringKeySet ( patchTypes ) . List ( ) ) )
2016-06-02 17:50:52 +00:00
cmdutil . AddPrinterFlags ( cmd )
2016-01-22 18:33:23 +00:00
cmdutil . AddRecordFlag ( cmd )
2016-03-10 01:27:19 +00:00
cmdutil . AddInclude3rdPartyFlags ( cmd )
2015-08-06 09:24:02 +00:00
2016-08-17 18:28:07 +00:00
usage := "identifying the resource to update"
cmdutil . AddFilenameOptionFlags ( cmd , & options . FilenameOptions , usage )
2016-06-02 17:50:52 +00:00
cmd . Flags ( ) . BoolVar ( & options . Local , "local" , false , "If true, patch will operate on the content of the file, not the server-side resource." )
2015-06-25 22:56:30 +00:00
return cmd
}
2016-10-13 00:18:39 +00:00
func RunPatch ( f cmdutil . Factory , out io . Writer , cmd * cobra . Command , args [ ] string , options * PatchOptions ) error {
2016-06-02 17:50:52 +00:00
switch {
case options . Local && len ( args ) != 0 :
return fmt . Errorf ( "cannot specify --local and server resources" )
}
2015-08-06 09:24:02 +00:00
cmdNamespace , enforceNamespace , err := f . DefaultNamespace ( )
2015-06-25 22:56:30 +00:00
if err != nil {
return err
}
2017-01-16 20:13:59 +00:00
patchType := types . StrategicMergePatchType
2016-02-11 20:52:42 +00:00
patchTypeString := strings . ToLower ( cmdutil . GetFlagString ( cmd , "type" ) )
if len ( patchTypeString ) != 0 {
ok := false
patchType , ok = patchTypes [ patchTypeString ]
if ! ok {
2017-06-14 21:14:42 +00:00
return cmdutil . UsageErrorf ( cmd , "--type must be one of %v, not %q" ,
sets . StringKeySet ( patchTypes ) . List ( ) , patchTypeString )
2016-02-11 20:52:42 +00:00
}
}
2015-06-25 22:56:30 +00:00
patch := cmdutil . GetFlagString ( cmd , "patch" )
if len ( patch ) == 0 {
2017-06-14 21:14:42 +00:00
return cmdutil . UsageErrorf ( cmd , "Must specify -p to patch" )
2015-06-25 22:56:30 +00:00
}
2015-09-30 15:58:42 +00:00
patchBytes , err := yaml . ToJSON ( [ ] byte ( patch ) )
if err != nil {
return fmt . Errorf ( "unable to parse %q: %v" , patch , err )
}
2015-06-25 22:56:30 +00:00
2017-08-02 20:23:07 +00:00
mapper , typer , err := f . UnstructuredObject ( )
2017-01-22 16:38:05 +00:00
if err != nil {
return err
}
2017-05-16 21:52:51 +00:00
2017-08-02 20:23:07 +00:00
r := f . NewBuilder ( ) .
Unstructured ( f . UnstructuredClientForMapping , mapper , typer ) .
2015-06-25 22:56:30 +00:00
ContinueOnError ( ) .
NamespaceParam ( cmdNamespace ) . DefaultNamespace ( ) .
2016-08-17 18:28:07 +00:00
FilenameParam ( enforceNamespace , & options . FilenameOptions ) .
2015-06-25 22:56:30 +00:00
ResourceTypeOrNameArgs ( false , args ... ) .
Flatten ( ) .
Do ( )
err = r . Err ( )
if err != nil {
return err
}
2015-08-06 09:24:02 +00:00
2016-04-14 22:00:40 +00:00
count := 0
err = r . Visit ( func ( info * resource . Info , err error ) error {
if err != nil {
return err
}
name , namespace := info . Name , info . Namespace
mapping := info . ResourceMapping ( )
2017-01-22 16:38:05 +00:00
client , err := f . UnstructuredClientForMapping ( mapping )
2016-04-14 22:00:40 +00:00
if err != nil {
return err
}
2015-06-25 22:56:30 +00:00
2016-06-02 17:50:52 +00:00
if ! options . Local {
2016-12-10 00:01:27 +00:00
dataChangedMsg := "not patched"
2017-09-13 21:55:26 +00:00
didPatch := false
2016-06-02 17:50:52 +00:00
helper := resource . NewHelper ( client , mapping )
2016-12-10 00:01:27 +00:00
patchedObj , err := helper . Patch ( namespace , name , patchType , patchBytes )
2016-06-02 17:50:52 +00:00
if err != nil {
return err
}
2017-01-23 02:15:10 +00:00
// Record the change as a second patch to avoid trying to merge with a user's patch data
2016-06-02 17:50:52 +00:00
if cmdutil . ShouldRecord ( cmd , info ) {
2017-01-23 02:15:10 +00:00
// Copy the resource info and update with the result of applying the user's patch
infoCopy := * info
infoCopy . Object = patchedObj
infoCopy . VersionedObject = patchedObj
2017-02-25 15:40:50 +00:00
if patch , patchType , err := cmdutil . ChangeResourcePatch ( & infoCopy , f . Command ( cmd , true ) ) ; err == nil {
2017-02-21 02:12:13 +00:00
if recordedObj , err := helper . Patch ( info . Namespace , info . Name , patchType , patch ) ; err != nil {
2017-01-23 02:15:10 +00:00
glog . V ( 4 ) . Infof ( "error recording reason: %v" , err )
2017-02-21 02:12:13 +00:00
} else {
patchedObj = recordedObj
2017-01-23 02:15:10 +00:00
}
2016-06-02 17:50:52 +00:00
}
}
count ++
2016-12-10 00:01:27 +00:00
oldData , err := json . Marshal ( info . Object )
if err != nil {
return err
}
newData , err := json . Marshal ( patchedObj )
if err != nil {
return err
}
if ! reflect . DeepEqual ( oldData , newData ) {
2017-09-13 21:55:26 +00:00
didPatch = true
2016-12-10 00:01:27 +00:00
dataChangedMsg = "patched"
}
2017-03-02 06:00:48 +00:00
// After computing whether we changed data, refresh the resource info with the resulting object
if err := info . Refresh ( patchedObj , true ) ; err != nil {
return err
}
2017-02-21 02:12:13 +00:00
if len ( options . OutputFormat ) > 0 && options . OutputFormat != "name" {
return cmdutil . PrintResourceInfoForCommand ( cmd , info , f , out )
2016-06-02 17:50:52 +00:00
}
2017-05-16 21:52:51 +00:00
mapper , _ , err := f . UnstructuredObject ( )
if err != nil {
return err
}
2017-02-21 02:12:13 +00:00
cmdutil . PrintSuccess ( mapper , options . OutputFormat == "name" , out , info . Mapping . Resource , info . Name , false , dataChangedMsg )
2017-09-13 21:55:26 +00:00
// if object was not successfully patched, exit with error code 1
if ! didPatch {
return cmdutil . ErrExit
}
2016-06-02 17:50:52 +00:00
return nil
}
count ++
2017-01-26 02:21:47 +00:00
originalObjJS , err := runtime . Encode ( unstructured . UnstructuredJSONScheme , info . VersionedObject )
2016-04-14 22:00:40 +00:00
if err != nil {
return err
}
2017-05-16 21:52:51 +00:00
2017-10-16 11:41:50 +00:00
originalPatchedObjJS , err := getPatchedJSON ( patchType , originalObjJS , patchBytes , mapping . GroupVersionKind , legacyscheme . Scheme )
2016-06-02 17:50:52 +00:00
if err != nil {
return err
2016-04-14 22:00:40 +00:00
}
2017-05-16 21:52:51 +00:00
2017-01-26 02:21:47 +00:00
targetObj , err := runtime . Decode ( unstructured . UnstructuredJSONScheme , originalPatchedObjJS )
2016-06-02 17:50:52 +00:00
if err != nil {
return err
}
2017-05-16 21:52:51 +00:00
2016-06-02 17:50:52 +00:00
// TODO: if we ever want to go generic, this allows a clean -o yaml without trying to print columns or anything
// rawExtension := &runtime.Unknown{
2016-05-19 10:58:36 +00:00
// Raw: originalPatchedObjJS,
2016-06-02 17:50:52 +00:00
// }
2017-02-21 02:12:13 +00:00
if err := info . Refresh ( targetObj , true ) ; err != nil {
2016-06-02 17:50:52 +00:00
return err
}
2017-02-21 02:12:13 +00:00
return cmdutil . PrintResourceInfoForCommand ( cmd , info , f , out )
2016-04-14 22:00:40 +00:00
} )
2015-06-25 22:56:30 +00:00
if err != nil {
return err
}
2016-04-14 22:00:40 +00:00
if count == 0 {
return fmt . Errorf ( "no objects passed to patch" )
2016-01-22 18:33:23 +00:00
}
2015-06-25 22:56:30 +00:00
return nil
}
2016-06-02 17:50:52 +00:00
2017-01-26 02:21:47 +00:00
func getPatchedJSON ( patchType types . PatchType , originalJS , patchJS [ ] byte , gvk schema . GroupVersionKind , creater runtime . ObjectCreater ) ( [ ] byte , error ) {
2016-06-02 17:50:52 +00:00
switch patchType {
2017-01-16 20:13:59 +00:00
case types . JSONPatchType :
2016-06-02 17:50:52 +00:00
patchObj , err := jsonpatch . DecodePatch ( patchJS )
if err != nil {
return nil , err
}
return patchObj . Apply ( originalJS )
2017-01-16 20:13:59 +00:00
case types . MergePatchType :
2016-06-02 17:50:52 +00:00
return jsonpatch . MergePatch ( originalJS , patchJS )
2017-01-16 20:13:59 +00:00
case types . StrategicMergePatchType :
2017-01-26 02:21:47 +00:00
// get a typed object for this GVK if we need to apply a strategic merge patch
obj , err := creater . New ( gvk )
if err != nil {
return nil , fmt . Errorf ( "cannot apply strategic merge patch for %s locally, try --type merge" , gvk . String ( ) )
}
2016-12-30 10:19:22 +00:00
return strategicpatch . StrategicMergePatch ( originalJS , patchJS , obj )
2016-06-02 17:50:52 +00:00
default :
// only here as a safety net - go-restful filters content-type
return nil , fmt . Errorf ( "unknown Content-Type header for patch: %v" , patchType )
}
}