2015-06-25 22:56:30 +00:00
/ *
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 (
2015-08-06 09:24:02 +00:00
"fmt"
2015-06-25 22:56:30 +00:00
"io"
2016-02-11 20:52:42 +00:00
"strings"
2015-06-25 22:56:30 +00:00
2016-06-02 17:50:52 +00:00
"github.com/evanphx/json-patch"
2016-05-20 17:49:56 +00:00
"github.com/renstrom/dedent"
2015-06-25 22:56:30 +00:00
"github.com/spf13/cobra"
2015-09-30 15:58:42 +00:00
2015-08-05 22:03:47 +00:00
"k8s.io/kubernetes/pkg/api"
2015-08-06 09:24:02 +00:00
"k8s.io/kubernetes/pkg/kubectl"
2015-08-05 22:03:47 +00:00
cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
"k8s.io/kubernetes/pkg/kubectl/resource"
2016-06-02 17:50:52 +00:00
"k8s.io/kubernetes/pkg/runtime"
2016-02-11 20:52:42 +00:00
"k8s.io/kubernetes/pkg/util/sets"
2016-06-02 17:50:52 +00:00
"k8s.io/kubernetes/pkg/util/strategicpatch"
2015-09-30 15:58:42 +00:00
"k8s.io/kubernetes/pkg/util/yaml"
2015-06-25 22:56:30 +00:00
)
2016-02-11 20:52:42 +00:00
var patchTypes = map [ string ] api . PatchType { "json" : api . JSONPatchType , "merge" : api . MergePatchType , "strategic" : api . StrategicMergePatchType }
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 {
Filenames [ ] string
2016-03-28 19:44:21 +00:00
Recursive bool
2016-06-02 17:50:52 +00:00
Local bool
OutputFormat string
2015-08-14 18:46:43 +00:00
}
2016-05-20 17:49:56 +00:00
var (
patch_long = dedent . Dedent ( `
Update field ( s ) of a resource using strategic merge 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
2016-05-20 17:49:56 +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.`)
patch_example = dedent . Dedent ( `
2015-07-13 20:46:51 +00:00
2016-05-20 17:49:56 +00:00
# Partially update a node using strategic merge patch
kubectl patch node k8s - node - 1 - p ' { "spec" : { "unschedulable" : true } } '
2015-08-06 09:24:02 +00:00
2016-05-20 17:49:56 +00:00
# Partially update a node identified by the type and name specified in "node.json" using strategic merge patch
kubectl patch - f node . json - p ' { "spec" : { "unschedulable" : true } } '
2016-02-11 20:52:42 +00:00
2016-05-20 17:49:56 +00:00
# Update a container ' s image ; spec . containers [ * ] . name is required because it ' s a merge key
kubectl patch pod valid - pod - p ' { "spec" : { "containers" : [ { "name" : "kubernetes-serve-hostname" , "image" : "new image" } ] } } '
# Update a container ' s image using a json patch with positional arrays
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
)
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 { }
p , err := f . Printer ( nil , false , false , false , false , false , false , [ ] string { } )
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" ,
2015-11-10 19:55:20 +00:00
Short : "Update field(s) of a resource using strategic merge patch." ,
2015-06-25 22:56:30 +00:00
Long : patch_long ,
Example : patch_example ,
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
usage := "Filename, directory, or URL to a file identifying the resource to update"
2015-08-14 18:46:43 +00:00
kubectl . AddJsonFilenameFlag ( cmd , & options . Filenames , usage )
2016-03-28 19:44:21 +00:00
cmdutil . AddRecursiveFlag ( cmd , & options . Recursive )
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-06-02 17:50:52 +00:00
func RunPatch ( f * cmdutil . Factory , out io . Writer , cmd * cobra . Command , args [ ] string , options * PatchOptions ) error {
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
}
2016-02-11 20:52:42 +00:00
patchType := api . StrategicMergePatchType
patchTypeString := strings . ToLower ( cmdutil . GetFlagString ( cmd , "type" ) )
if len ( patchTypeString ) != 0 {
ok := false
patchType , ok = patchTypes [ patchTypeString ]
if ! ok {
return cmdutil . UsageError ( cmd , fmt . Sprintf ( "--type must be one of %v, not %q" , sets . StringKeySet ( patchTypes ) . List ( ) , patchTypeString ) )
}
}
2015-06-25 22:56:30 +00:00
patch := cmdutil . GetFlagString ( cmd , "patch" )
if len ( patch ) == 0 {
return cmdutil . UsageError ( cmd , "Must specify -p to patch" )
}
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
2016-03-10 01:27:19 +00:00
mapper , typer := f . Object ( cmdutil . GetIncludeThirdPartyAPIs ( cmd ) )
2015-12-21 05:37:49 +00:00
r := resource . NewBuilder ( mapper , typer , resource . ClientMapperFunc ( f . ClientForMapping ) , f . Decoder ( true ) ) .
2015-06-25 22:56:30 +00:00
ContinueOnError ( ) .
NamespaceParam ( cmdNamespace ) . DefaultNamespace ( ) .
2016-03-28 19:44:21 +00:00
FilenameParam ( enforceNamespace , options . Recursive , options . Filenames ... ) .
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 ( )
client , err := f . ClientForMapping ( mapping )
if err != nil {
return err
}
2015-06-25 22:56:30 +00:00
2016-06-02 17:50:52 +00:00
if ! options . Local {
helper := resource . NewHelper ( client , mapping )
2016-05-19 10:58:36 +00:00
_ , err := helper . Patch ( namespace , name , patchType , patchBytes )
2016-06-02 17:50:52 +00:00
if err != nil {
return err
}
if cmdutil . ShouldRecord ( cmd , info ) {
2016-05-19 10:58:36 +00:00
// don't return an error on failure. The patch itself succeeded, its only the hint for that change that failed
// don't bother checking for failures of this replace, because a failure to indicate the hint doesn't fail the command
// also, don't force the replacement. If the replacement fails on a resourceVersion conflict, then it means this
// record hint is likely to be invalid anyway, so avoid the bad hint
patch , err := cmdutil . ChangeResourcePatch ( info , f . Command ( ) )
if err == nil {
helper . Patch ( info . Namespace , info . Name , api . StrategicMergePatchType , patch )
2016-06-02 17:50:52 +00:00
}
}
count ++
if options . OutputFormat == "name" || len ( options . OutputFormat ) == 0 {
cmdutil . PrintSuccess ( mapper , options . OutputFormat == "name" , out , "" , name , "patched" )
}
return nil
}
count ++
patchedObj , err := api . Scheme . DeepCopy ( info . VersionedObject )
2016-04-14 22:00:40 +00:00
if err != nil {
return err
}
2016-06-02 17:50:52 +00:00
originalObjJS , err := runtime . Encode ( api . Codecs . LegacyCodec ( ) , info . VersionedObject . ( runtime . Object ) )
if err != nil {
return err
2016-04-14 22:00:40 +00:00
}
2016-06-02 17:50:52 +00:00
originalPatchedObjJS , err := getPatchedJSON ( patchType , originalObjJS , patchBytes , patchedObj . ( runtime . Object ) )
if err != nil {
return err
}
targetObj , err := runtime . Decode ( api . Codecs . UniversalDecoder ( ) , originalPatchedObjJS )
if err != nil {
return err
}
// 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
// }
printer , err := f . PrinterForMapping ( cmd , mapping , false )
if err != nil {
return err
}
if err := printer . PrintObj ( targetObj , out ) ; err != nil {
return err
}
2016-04-14 22:00:40 +00:00
return nil
} )
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
func getPatchedJSON ( patchType api . PatchType , originalJS , patchJS [ ] byte , obj runtime . Object ) ( [ ] byte , error ) {
switch patchType {
case api . JSONPatchType :
patchObj , err := jsonpatch . DecodePatch ( patchJS )
if err != nil {
return nil , err
}
return patchObj . Apply ( originalJS )
case api . MergePatchType :
return jsonpatch . MergePatch ( originalJS , patchJS )
case api . StrategicMergePatchType :
return strategicpatch . StrategicMergePatchData ( originalJS , patchJS , obj )
default :
// only here as a safety net - go-restful filters content-type
return nil , fmt . Errorf ( "unknown Content-Type header for patch: %v" , patchType )
}
}