2016-11-14 11:53:27 +00:00
/ *
Copyright 2016 The Kubernetes Authors .
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 set
import (
"fmt"
"io"
"github.com/spf13/cobra"
2017-11-13 06:27:59 +00:00
"k8s.io/api/core/v1"
2017-01-11 14:09:48 +00:00
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
2017-01-16 20:13:59 +00:00
"k8s.io/apimachinery/pkg/types"
2017-01-11 14:09:48 +00:00
"k8s.io/apimachinery/pkg/util/validation"
2016-11-14 11:53:27 +00:00
"k8s.io/kubernetes/pkg/kubectl/cmd/templates"
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"
2016-11-14 11:53:27 +00:00
)
// SelectorOptions 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 SelectorOptions struct {
fileOptions resource . FilenameOptions
local bool
dryrun bool
all bool
record bool
changeCause string
2017-05-23 07:49:07 +00:00
output string
2016-11-14 11:53:27 +00:00
resources [ ] string
selector * metav1 . LabelSelector
out io . Writer
PrintObject func ( obj runtime . Object ) error
ClientForMapping func ( mapping * meta . RESTMapping ) ( resource . RESTClient , error )
builder * resource . Builder
mapper meta . RESTMapper
}
var (
selectorLong = templates . LongDesc ( `
Set the selector on a resource . Note that the new selector will overwrite the old selector if the resource had one prior to the invocation
of ' set selector ' .
A selector must begin with a letter or number , and may contain letters , numbers , hyphens , dots , and underscores , up to % [ 1 ] d characters .
If -- resource - version is specified , then updates will use this resource version , otherwise the existing resource - version will be used .
Note : currently selectors can only be set on Service objects . ` )
selectorExample = templates . Examples ( `
# set the labels and selector before creating a deployment / service pair .
2017-01-16 07:55:30 +00:00
kubectl create service clusterip my - svc -- clusterip = "None" - o yaml -- dry - run | kubectl set selector -- local - f - ' environment = qa ' - o yaml | kubectl create - f -
2016-11-14 11:53:27 +00:00
kubectl create deployment my - dep - o yaml -- dry - run | kubectl label -- local - f - environment = qa - o yaml | kubectl create - f - ` )
)
// NewCmdSelector is the "set selector" command.
func NewCmdSelector ( f cmdutil . Factory , out io . Writer ) * cobra . Command {
options := & SelectorOptions {
out : out ,
}
cmd := & cobra . Command {
2017-10-11 06:26:02 +00:00
Use : "selector (-f FILENAME | TYPE NAME) EXPRESSIONS [--resource-version=version]" ,
DisableFlagsInUseLine : true ,
2017-01-26 06:21:28 +00:00
Short : i18n . T ( "Set the selector on a resource" ) ,
2016-12-29 04:47:24 +00:00
Long : fmt . Sprintf ( selectorLong , validation . LabelValueMaxLength ) ,
2016-11-14 11:53:27 +00:00
Example : selectorExample ,
Run : func ( cmd * cobra . Command , args [ ] string ) {
2017-03-17 13:55:46 +00:00
cmdutil . CheckErr ( options . Complete ( f , cmd , args ) )
2016-11-14 11:53:27 +00:00
cmdutil . CheckErr ( options . Validate ( ) )
cmdutil . CheckErr ( options . RunSelector ( ) )
} ,
}
cmdutil . AddPrinterFlags ( cmd )
2017-08-11 06:21:44 +00:00
cmd . Flags ( ) . Bool ( "all" , false , "Select all resources, including uninitialized ones, in the namespace of the specified resource types" )
2016-11-14 11:53:27 +00:00
cmd . Flags ( ) . Bool ( "local" , false , "If true, set selector will NOT contact api-server but run locally." )
cmd . Flags ( ) . String ( "resource-version" , "" , "If non-empty, the selectors update will only succeed if this is the current resource-version for the object. Only valid when specifying a single resource." )
usage := "the resource to update the selectors"
cmdutil . AddFilenameOptionFlags ( cmd , & options . fileOptions , usage )
cmdutil . AddDryRunFlag ( cmd )
cmdutil . AddRecordFlag ( cmd )
2017-08-11 06:21:44 +00:00
cmdutil . AddIncludeUninitializedFlag ( cmd )
2016-11-14 11:53:27 +00:00
return cmd
}
// Complete assigns the SelectorOptions from args.
2017-03-17 13:55:46 +00:00
func ( o * SelectorOptions ) Complete ( f cmdutil . Factory , cmd * cobra . Command , args [ ] string ) error {
2016-11-14 11:53:27 +00:00
o . local = cmdutil . GetFlagBool ( cmd , "local" )
o . all = cmdutil . GetFlagBool ( cmd , "all" )
o . record = cmdutil . GetRecordFlag ( cmd )
o . dryrun = cmdutil . GetDryRunFlag ( cmd )
2017-05-23 07:49:07 +00:00
o . output = cmdutil . GetFlagString ( cmd , "output" )
2016-11-14 11:53:27 +00:00
cmdNamespace , enforceNamespace , err := f . DefaultNamespace ( )
if err != nil {
return err
}
2017-02-25 15:40:50 +00:00
o . changeCause = f . Command ( cmd , false )
2016-11-14 11:53:27 +00:00
mapper , _ := f . Object ( )
o . mapper = mapper
2017-11-13 06:27:59 +00:00
2017-06-19 08:25:06 +00:00
o . resources , o . selector , err = getResourcesAndSelector ( args )
if err != nil {
return err
}
2016-11-14 11:53:27 +00:00
2017-08-11 06:21:44 +00:00
includeUninitialized := cmdutil . ShouldIncludeUninitialized ( cmd , false )
2017-08-02 20:23:07 +00:00
o . builder = f . NewBuilder ( ) .
2017-11-15 06:10:30 +00:00
Internal ( ) .
2017-11-15 04:03:06 +00:00
LocalParam ( o . local ) .
2016-11-14 11:53:27 +00:00
ContinueOnError ( ) .
NamespaceParam ( cmdNamespace ) . DefaultNamespace ( ) .
FilenameParam ( enforceNamespace , & o . fileOptions ) .
2017-08-11 06:21:44 +00:00
IncludeUninitialized ( includeUninitialized ) .
2016-11-14 11:53:27 +00:00
Flatten ( )
2017-11-14 03:43:58 +00:00
if ! o . local {
2017-11-15 04:03:06 +00:00
o . builder .
2017-11-14 03:43:58 +00:00
ResourceTypeOrNameArgs ( o . all , o . resources ... ) .
Latest ( )
} else {
2017-07-11 14:19:27 +00:00
// if a --local flag was provided, and a resource was specified in the form
// <resource>/<name>, fail immediately as --local cannot query the api server
// for the specified resource.
if len ( o . resources ) > 0 {
return resource . LocalResourceError
}
2017-05-16 21:52:51 +00:00
}
2016-11-14 11:53:27 +00:00
o . PrintObject = func ( obj runtime . Object ) error {
2018-02-21 01:14:21 +00:00
return cmdutil . PrintObject ( cmd , obj , o . out )
2016-11-14 11:53:27 +00:00
}
o . ClientForMapping = func ( mapping * meta . RESTMapping ) ( resource . RESTClient , error ) {
return f . ClientForMapping ( mapping )
}
return err
}
// Validate basic inputs
func ( o * SelectorOptions ) Validate ( ) error {
2017-06-14 21:14:42 +00:00
if len ( o . resources ) < 1 && cmdutil . IsFilenameSliceEmpty ( o . fileOptions . Filenames ) {
2016-11-14 11:53:27 +00:00
return fmt . Errorf ( "one or more resources must be specified as <resource> <name> or <resource>/<name>" )
}
2016-12-29 04:47:24 +00:00
if o . selector == nil {
return fmt . Errorf ( "one selector is required" )
}
2016-11-14 11:53:27 +00:00
return nil
}
// RunSelector executes the command.
func ( o * SelectorOptions ) RunSelector ( ) error {
r := o . builder . Do ( )
err := r . Err ( )
if err != nil {
return err
}
return r . Visit ( func ( info * resource . Info , err error ) error {
patch := & Patch { Info : info }
2018-02-21 17:10:38 +00:00
CalculatePatch ( patch , cmdutil . InternalVersionJSONEncoder ( ) , func ( info * resource . Info ) ( [ ] byte , error ) {
2017-11-14 04:01:51 +00:00
versioned := info . AsVersioned ( )
patch . Info . Object = versioned
selectErr := updateSelectorForObject ( info . Object , * o . selector )
2016-11-14 11:53:27 +00:00
if selectErr == nil {
2018-02-21 17:10:38 +00:00
return runtime . Encode ( cmdutil . InternalVersionJSONEncoder ( ) , info . Object )
2016-11-14 11:53:27 +00:00
}
return nil , selectErr
} )
if patch . Err != nil {
return patch . Err
}
if o . local || o . dryrun {
2017-11-14 04:01:51 +00:00
return o . PrintObject ( info . Object )
2016-11-14 11:53:27 +00:00
}
2017-01-16 20:13:59 +00:00
patched , err := resource . NewHelper ( info . Client , info . Mapping ) . Patch ( info . Namespace , info . Name , types . StrategicMergePatchType , patch . Patch )
2016-11-14 11:53:27 +00:00
if err != nil {
return err
}
if o . record || cmdutil . ContainsChangeCause ( info ) {
if err := cmdutil . RecordChangeCause ( patched , o . changeCause ) ; err == nil {
if patched , err = resource . NewHelper ( info . Client , info . Mapping ) . Replace ( info . Namespace , info . Name , false , patched ) ; err != nil {
return fmt . Errorf ( "changes to %s/%s can't be recorded: %v\n" , info . Mapping . Resource , info . Name , err )
}
}
}
info . Refresh ( patched , true )
2017-05-23 07:49:07 +00:00
shortOutput := o . output == "name"
if len ( o . output ) > 0 && ! shortOutput {
2017-11-13 06:27:59 +00:00
return o . PrintObject ( patched )
2017-05-23 07:49:07 +00:00
}
2018-02-21 01:14:21 +00:00
cmdutil . PrintSuccess ( shortOutput , o . out , info . Object , o . dryrun , "selector updated" )
2016-11-14 11:53:27 +00:00
return nil
} )
}
func updateSelectorForObject ( obj runtime . Object , selector metav1 . LabelSelector ) error {
copyOldSelector := func ( ) ( map [ string ] string , error ) {
if len ( selector . MatchExpressions ) > 0 {
return nil , fmt . Errorf ( "match expression %v not supported on this object" , selector . MatchExpressions )
}
dst := make ( map [ string ] string )
for label , value := range selector . MatchLabels {
dst [ label ] = value
}
return dst , nil
}
var err error
switch t := obj . ( type ) {
2017-11-13 06:27:59 +00:00
case * v1 . Service :
2016-11-14 11:53:27 +00:00
t . Spec . Selector , err = copyOldSelector ( )
default :
err = fmt . Errorf ( "setting a selector is only supported for Services" )
}
return err
}
// getResourcesAndSelector retrieves resources and the selector expression from the given args (assuming selectors the last arg)
func getResourcesAndSelector ( args [ ] string ) ( resources [ ] string , selector * metav1 . LabelSelector , err error ) {
2016-12-29 04:47:24 +00:00
if len ( args ) == 0 {
return [ ] string { } , nil , nil
2016-11-14 11:53:27 +00:00
}
2016-12-29 04:47:24 +00:00
resources = args [ : len ( args ) - 1 ]
2016-11-14 11:53:27 +00:00
selector , err = metav1 . ParseToLabelSelector ( args [ len ( args ) - 1 ] )
return resources , selector , err
}