mirror of
https://github.com/ceph/ceph-csi.git
synced 2025-06-14 10:53:34 +00:00
Fresh dep ensure
This commit is contained in:
61
vendor/k8s.io/kubernetes/pkg/kubectl/cmd/label/BUILD
generated
vendored
Normal file
61
vendor/k8s.io/kubernetes/pkg/kubectl/cmd/label/BUILD
generated
vendored
Normal file
@ -0,0 +1,61 @@
|
||||
load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
|
||||
|
||||
go_library(
|
||||
name = "go_default_library",
|
||||
srcs = ["label.go"],
|
||||
importpath = "k8s.io/kubernetes/pkg/kubectl/cmd/label",
|
||||
visibility = ["//visibility:public"],
|
||||
deps = [
|
||||
"//pkg/kubectl/cmd/util:go_default_library",
|
||||
"//pkg/kubectl/scheme:go_default_library",
|
||||
"//pkg/kubectl/util/i18n:go_default_library",
|
||||
"//pkg/kubectl/util/templates:go_default_library",
|
||||
"//staging/src/k8s.io/apimachinery/pkg/api/meta:go_default_library",
|
||||
"//staging/src/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library",
|
||||
"//staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructuredscheme:go_default_library",
|
||||
"//staging/src/k8s.io/apimachinery/pkg/runtime:go_default_library",
|
||||
"//staging/src/k8s.io/apimachinery/pkg/types:go_default_library",
|
||||
"//staging/src/k8s.io/apimachinery/pkg/util/errors:go_default_library",
|
||||
"//staging/src/k8s.io/apimachinery/pkg/util/json:go_default_library",
|
||||
"//staging/src/k8s.io/apimachinery/pkg/util/validation:go_default_library",
|
||||
"//staging/src/k8s.io/cli-runtime/pkg/genericclioptions:go_default_library",
|
||||
"//staging/src/k8s.io/cli-runtime/pkg/genericclioptions/printers:go_default_library",
|
||||
"//staging/src/k8s.io/cli-runtime/pkg/genericclioptions/resource:go_default_library",
|
||||
"//vendor/github.com/evanphx/json-patch:go_default_library",
|
||||
"//vendor/github.com/spf13/cobra:go_default_library",
|
||||
"//vendor/k8s.io/klog:go_default_library",
|
||||
],
|
||||
)
|
||||
|
||||
go_test(
|
||||
name = "go_default_test",
|
||||
srcs = ["label_test.go"],
|
||||
data = [
|
||||
"//test/e2e/testing-manifests:all-srcs",
|
||||
],
|
||||
embed = [":go_default_library"],
|
||||
deps = [
|
||||
"//pkg/kubectl/cmd/testing:go_default_library",
|
||||
"//pkg/kubectl/scheme:go_default_library",
|
||||
"//staging/src/k8s.io/api/core/v1:go_default_library",
|
||||
"//staging/src/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library",
|
||||
"//staging/src/k8s.io/apimachinery/pkg/runtime:go_default_library",
|
||||
"//staging/src/k8s.io/cli-runtime/pkg/genericclioptions:go_default_library",
|
||||
"//staging/src/k8s.io/cli-runtime/pkg/genericclioptions/resource:go_default_library",
|
||||
"//staging/src/k8s.io/client-go/rest/fake:go_default_library",
|
||||
],
|
||||
)
|
||||
|
||||
filegroup(
|
||||
name = "package-srcs",
|
||||
srcs = glob(["**"]),
|
||||
tags = ["automanaged"],
|
||||
visibility = ["//visibility:private"],
|
||||
)
|
||||
|
||||
filegroup(
|
||||
name = "all-srcs",
|
||||
srcs = [":package-srcs"],
|
||||
tags = ["automanaged"],
|
||||
visibility = ["//visibility:public"],
|
||||
)
|
425
vendor/k8s.io/kubernetes/pkg/kubectl/cmd/label/label.go
generated
vendored
Normal file
425
vendor/k8s.io/kubernetes/pkg/kubectl/cmd/label/label.go
generated
vendored
Normal file
@ -0,0 +1,425 @@
|
||||
/*
|
||||
Copyright 2014 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 label
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
jsonpatch "github.com/evanphx/json-patch"
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/klog"
|
||||
|
||||
"k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructuredscheme"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
utilerrors "k8s.io/apimachinery/pkg/util/errors"
|
||||
"k8s.io/apimachinery/pkg/util/json"
|
||||
"k8s.io/apimachinery/pkg/util/validation"
|
||||
|
||||
"k8s.io/cli-runtime/pkg/genericclioptions"
|
||||
"k8s.io/cli-runtime/pkg/genericclioptions/printers"
|
||||
"k8s.io/cli-runtime/pkg/genericclioptions/resource"
|
||||
cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
|
||||
"k8s.io/kubernetes/pkg/kubectl/scheme"
|
||||
"k8s.io/kubernetes/pkg/kubectl/util/i18n"
|
||||
"k8s.io/kubernetes/pkg/kubectl/util/templates"
|
||||
)
|
||||
|
||||
// LabelOptions have the data required to perform the label operation
|
||||
type LabelOptions struct {
|
||||
// Filename options
|
||||
resource.FilenameOptions
|
||||
RecordFlags *genericclioptions.RecordFlags
|
||||
|
||||
PrintFlags *genericclioptions.PrintFlags
|
||||
ToPrinter func(string) (printers.ResourcePrinter, error)
|
||||
|
||||
// Common user flags
|
||||
overwrite bool
|
||||
list bool
|
||||
local bool
|
||||
dryrun bool
|
||||
all bool
|
||||
resourceVersion string
|
||||
selector string
|
||||
fieldSelector string
|
||||
outputFormat string
|
||||
|
||||
// results of arg parsing
|
||||
resources []string
|
||||
newLabels map[string]string
|
||||
removeLabels []string
|
||||
|
||||
Recorder genericclioptions.Recorder
|
||||
|
||||
namespace string
|
||||
enforceNamespace bool
|
||||
includeUninitialized bool
|
||||
builder *resource.Builder
|
||||
unstructuredClientForMapping func(mapping *meta.RESTMapping) (resource.RESTClient, error)
|
||||
|
||||
// Common shared fields
|
||||
genericclioptions.IOStreams
|
||||
}
|
||||
|
||||
var (
|
||||
labelLong = templates.LongDesc(i18n.T(`
|
||||
Update the labels on a resource.
|
||||
|
||||
* A label key and value must begin with a letter or number, and may contain letters, numbers, hyphens, dots, and underscores, up to %[1]d characters each.
|
||||
* Optionally, the key can begin with a DNS subdomain prefix and a single '/', like example.com/my-app
|
||||
* If --overwrite is true, then existing labels can be overwritten, otherwise attempting to overwrite a label will result in an error.
|
||||
* If --resource-version is specified, then updates will use this resource version, otherwise the existing resource-version will be used.`))
|
||||
|
||||
labelExample = templates.Examples(i18n.T(`
|
||||
# Update pod 'foo' with the label 'unhealthy' and the value 'true'.
|
||||
kubectl label pods foo unhealthy=true
|
||||
|
||||
# Update pod 'foo' with the label 'status' and the value 'unhealthy', overwriting any existing value.
|
||||
kubectl label --overwrite pods foo status=unhealthy
|
||||
|
||||
# Update all pods in the namespace
|
||||
kubectl label pods --all status=unhealthy
|
||||
|
||||
# Update a pod identified by the type and name in "pod.json"
|
||||
kubectl label -f pod.json status=unhealthy
|
||||
|
||||
# Update pod 'foo' only if the resource is unchanged from version 1.
|
||||
kubectl label pods foo status=unhealthy --resource-version=1
|
||||
|
||||
# Update pod 'foo' by removing a label named 'bar' if it exists.
|
||||
# Does not require the --overwrite flag.
|
||||
kubectl label pods foo bar-`))
|
||||
)
|
||||
|
||||
func NewLabelOptions(ioStreams genericclioptions.IOStreams) *LabelOptions {
|
||||
return &LabelOptions{
|
||||
RecordFlags: genericclioptions.NewRecordFlags(),
|
||||
Recorder: genericclioptions.NoopRecorder{},
|
||||
|
||||
PrintFlags: genericclioptions.NewPrintFlags("labeled").WithTypeSetter(scheme.Scheme),
|
||||
|
||||
IOStreams: ioStreams,
|
||||
}
|
||||
}
|
||||
|
||||
func NewCmdLabel(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
|
||||
o := NewLabelOptions(ioStreams)
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "label [--overwrite] (-f FILENAME | TYPE NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--resource-version=version]",
|
||||
DisableFlagsInUseLine: true,
|
||||
Short: i18n.T("Update the labels on a resource"),
|
||||
Long: fmt.Sprintf(labelLong, validation.LabelValueMaxLength),
|
||||
Example: labelExample,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
cmdutil.CheckErr(o.Complete(f, cmd, args))
|
||||
cmdutil.CheckErr(o.Validate())
|
||||
cmdutil.CheckErr(o.RunLabel())
|
||||
},
|
||||
}
|
||||
|
||||
o.RecordFlags.AddFlags(cmd)
|
||||
o.PrintFlags.AddFlags(cmd)
|
||||
|
||||
cmd.Flags().BoolVar(&o.overwrite, "overwrite", o.overwrite, "If true, allow labels to be overwritten, otherwise reject label updates that overwrite existing labels.")
|
||||
cmd.Flags().BoolVar(&o.list, "list", o.list, "If true, display the labels for a given resource.")
|
||||
cmd.Flags().BoolVar(&o.local, "local", o.local, "If true, label will NOT contact api-server but run locally.")
|
||||
cmd.Flags().StringVarP(&o.selector, "selector", "l", o.selector, "Selector (label query) to filter on, not including uninitialized ones, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2).")
|
||||
cmd.Flags().StringVar(&o.fieldSelector, "field-selector", o.fieldSelector, "Selector (field query) to filter on, supports '=', '==', and '!='.(e.g. --field-selector key1=value1,key2=value2). The server only supports a limited number of field queries per type.")
|
||||
cmd.Flags().BoolVar(&o.all, "all", o.all, "Select all resources, including uninitialized ones, in the namespace of the specified resource types")
|
||||
cmd.Flags().StringVar(&o.resourceVersion, "resource-version", o.resourceVersion, i18n.T("If non-empty, the labels update will only succeed if this is the current resource-version for the object. Only valid when specifying a single resource."))
|
||||
usage := "identifying the resource to update the labels"
|
||||
cmdutil.AddFilenameOptionFlags(cmd, &o.FilenameOptions, usage)
|
||||
cmdutil.AddDryRunFlag(cmd)
|
||||
cmdutil.AddIncludeUninitializedFlag(cmd)
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
// Complete adapts from the command line args and factory to the data required.
|
||||
func (o *LabelOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {
|
||||
var err error
|
||||
|
||||
o.RecordFlags.Complete(cmd)
|
||||
o.Recorder, err = o.RecordFlags.ToRecorder()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
o.outputFormat = cmdutil.GetFlagString(cmd, "output")
|
||||
o.dryrun = cmdutil.GetDryRunFlag(cmd)
|
||||
|
||||
o.ToPrinter = func(operation string) (printers.ResourcePrinter, error) {
|
||||
o.PrintFlags.NamePrintFlags.Operation = operation
|
||||
if o.dryrun {
|
||||
o.PrintFlags.Complete("%s (dry run)")
|
||||
}
|
||||
|
||||
return o.PrintFlags.ToPrinter()
|
||||
}
|
||||
|
||||
resources, labelArgs, err := cmdutil.GetResourcesAndPairs(args, "label")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
o.resources = resources
|
||||
o.newLabels, o.removeLabels, err = parseLabels(labelArgs)
|
||||
|
||||
if o.list && len(o.outputFormat) > 0 {
|
||||
return fmt.Errorf("--list and --output may not be specified together")
|
||||
}
|
||||
|
||||
o.namespace, o.enforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
o.includeUninitialized = cmdutil.ShouldIncludeUninitialized(cmd, false)
|
||||
o.builder = f.NewBuilder()
|
||||
o.unstructuredClientForMapping = f.UnstructuredClientForMapping
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Validate checks to the LabelOptions to see if there is sufficient information run the command.
|
||||
func (o *LabelOptions) Validate() error {
|
||||
if o.all && len(o.selector) > 0 {
|
||||
return fmt.Errorf("cannot set --all and --selector at the same time")
|
||||
}
|
||||
if o.all && len(o.fieldSelector) > 0 {
|
||||
return fmt.Errorf("cannot set --all and --field-selector at the same time")
|
||||
}
|
||||
if len(o.resources) < 1 && cmdutil.IsFilenameSliceEmpty(o.FilenameOptions.Filenames) {
|
||||
return fmt.Errorf("one or more resources must be specified as <resource> <name> or <resource>/<name>")
|
||||
}
|
||||
if len(o.newLabels) < 1 && len(o.removeLabels) < 1 && !o.list {
|
||||
return fmt.Errorf("at least one label update is required")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RunLabel does the work
|
||||
func (o *LabelOptions) RunLabel() error {
|
||||
b := o.builder.
|
||||
Unstructured().
|
||||
LocalParam(o.local).
|
||||
ContinueOnError().
|
||||
NamespaceParam(o.namespace).DefaultNamespace().
|
||||
FilenameParam(o.enforceNamespace, &o.FilenameOptions).
|
||||
IncludeUninitialized(o.includeUninitialized).
|
||||
Flatten()
|
||||
|
||||
if !o.local {
|
||||
b = b.LabelSelectorParam(o.selector).
|
||||
FieldSelectorParam(o.fieldSelector).
|
||||
ResourceTypeOrNameArgs(o.all, o.resources...).
|
||||
Latest()
|
||||
}
|
||||
|
||||
one := false
|
||||
r := b.Do().IntoSingleItemImplied(&one)
|
||||
if err := r.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// only apply resource version locking on a single resource
|
||||
if !one && len(o.resourceVersion) > 0 {
|
||||
return fmt.Errorf("--resource-version may only be used with a single resource")
|
||||
}
|
||||
|
||||
// TODO: support bulk generic output a la Get
|
||||
return r.Visit(func(info *resource.Info, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var outputObj runtime.Object
|
||||
var dataChangeMsg string
|
||||
obj := info.Object
|
||||
oldData, err := json.Marshal(obj)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if o.dryrun || o.local || o.list {
|
||||
err = labelFunc(obj, o.overwrite, o.resourceVersion, o.newLabels, o.removeLabels)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
newObj, err := json.Marshal(obj)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dataChangeMsg = updateDataChangeMsg(oldData, newObj)
|
||||
outputObj = info.Object
|
||||
} else {
|
||||
name, namespace := info.Name, info.Namespace
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
accessor, err := meta.Accessor(obj)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, label := range o.removeLabels {
|
||||
if _, ok := accessor.GetLabels()[label]; !ok {
|
||||
fmt.Fprintf(o.Out, "label %q not found.\n", label)
|
||||
}
|
||||
}
|
||||
|
||||
if err := labelFunc(obj, o.overwrite, o.resourceVersion, o.newLabels, o.removeLabels); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := o.Recorder.Record(obj); err != nil {
|
||||
klog.V(4).Infof("error recording current command: %v", err)
|
||||
}
|
||||
newObj, err := json.Marshal(obj)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dataChangeMsg = updateDataChangeMsg(oldData, newObj)
|
||||
patchBytes, err := jsonpatch.CreateMergePatch(oldData, newObj)
|
||||
createdPatch := err == nil
|
||||
if err != nil {
|
||||
klog.V(2).Infof("couldn't compute patch: %v", err)
|
||||
}
|
||||
|
||||
mapping := info.ResourceMapping()
|
||||
client, err := o.unstructuredClientForMapping(mapping)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
helper := resource.NewHelper(client, mapping)
|
||||
|
||||
if createdPatch {
|
||||
outputObj, err = helper.Patch(namespace, name, types.MergePatchType, patchBytes, nil)
|
||||
} else {
|
||||
outputObj, err = helper.Replace(namespace, name, false, obj)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if o.list {
|
||||
accessor, err := meta.Accessor(outputObj)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
indent := ""
|
||||
if !one {
|
||||
indent = " "
|
||||
gvks, _, err := unstructuredscheme.NewUnstructuredObjectTyper().ObjectKinds(info.Object)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Fprintf(o.ErrOut, "Listing labels for %s.%s/%s:\n", gvks[0].Kind, gvks[0].Group, info.Name)
|
||||
}
|
||||
for k, v := range accessor.GetLabels() {
|
||||
fmt.Fprintf(o.Out, "%s%s=%s\n", indent, k, v)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
printer, err := o.ToPrinter(dataChangeMsg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
printer.PrintObj(info.Object, o.Out)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func updateDataChangeMsg(oldObj []byte, newObj []byte) string {
|
||||
msg := "not labeled"
|
||||
if !reflect.DeepEqual(oldObj, newObj) {
|
||||
msg = "labeled"
|
||||
}
|
||||
return msg
|
||||
}
|
||||
|
||||
func validateNoOverwrites(accessor metav1.Object, labels map[string]string) error {
|
||||
allErrs := []error{}
|
||||
for key := range labels {
|
||||
if value, found := accessor.GetLabels()[key]; found {
|
||||
allErrs = append(allErrs, fmt.Errorf("'%s' already has a value (%s), and --overwrite is false", key, value))
|
||||
}
|
||||
}
|
||||
return utilerrors.NewAggregate(allErrs)
|
||||
}
|
||||
|
||||
func parseLabels(spec []string) (map[string]string, []string, error) {
|
||||
labels := map[string]string{}
|
||||
var remove []string
|
||||
for _, labelSpec := range spec {
|
||||
if strings.Contains(labelSpec, "=") {
|
||||
parts := strings.Split(labelSpec, "=")
|
||||
if len(parts) != 2 {
|
||||
return nil, nil, fmt.Errorf("invalid label spec: %v", labelSpec)
|
||||
}
|
||||
if errs := validation.IsValidLabelValue(parts[1]); len(errs) != 0 {
|
||||
return nil, nil, fmt.Errorf("invalid label value: %q: %s", labelSpec, strings.Join(errs, ";"))
|
||||
}
|
||||
labels[parts[0]] = parts[1]
|
||||
} else if strings.HasSuffix(labelSpec, "-") {
|
||||
remove = append(remove, labelSpec[:len(labelSpec)-1])
|
||||
} else {
|
||||
return nil, nil, fmt.Errorf("unknown label spec: %v", labelSpec)
|
||||
}
|
||||
}
|
||||
for _, removeLabel := range remove {
|
||||
if _, found := labels[removeLabel]; found {
|
||||
return nil, nil, fmt.Errorf("can not both modify and remove a label in the same command")
|
||||
}
|
||||
}
|
||||
return labels, remove, nil
|
||||
}
|
||||
|
||||
func labelFunc(obj runtime.Object, overwrite bool, resourceVersion string, labels map[string]string, remove []string) error {
|
||||
accessor, err := meta.Accessor(obj)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !overwrite {
|
||||
if err := validateNoOverwrites(accessor, labels); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
objLabels := accessor.GetLabels()
|
||||
if objLabels == nil {
|
||||
objLabels = make(map[string]string)
|
||||
}
|
||||
|
||||
for key, value := range labels {
|
||||
objLabels[key] = value
|
||||
}
|
||||
for _, label := range remove {
|
||||
delete(objLabels, label)
|
||||
}
|
||||
accessor.SetLabels(objLabels)
|
||||
|
||||
if len(resourceVersion) != 0 {
|
||||
accessor.SetResourceVersion(resourceVersion)
|
||||
}
|
||||
return nil
|
||||
}
|
498
vendor/k8s.io/kubernetes/pkg/kubectl/cmd/label/label_test.go
generated
vendored
Normal file
498
vendor/k8s.io/kubernetes/pkg/kubectl/cmd/label/label_test.go
generated
vendored
Normal file
@ -0,0 +1,498 @@
|
||||
/*
|
||||
Copyright 2014 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 label
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"k8s.io/api/core/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
"k8s.io/cli-runtime/pkg/genericclioptions"
|
||||
"k8s.io/cli-runtime/pkg/genericclioptions/resource"
|
||||
"k8s.io/client-go/rest/fake"
|
||||
cmdtesting "k8s.io/kubernetes/pkg/kubectl/cmd/testing"
|
||||
"k8s.io/kubernetes/pkg/kubectl/scheme"
|
||||
)
|
||||
|
||||
func TestValidateLabels(t *testing.T) {
|
||||
tests := []struct {
|
||||
meta *metav1.ObjectMeta
|
||||
labels map[string]string
|
||||
expectErr bool
|
||||
test string
|
||||
}{
|
||||
{
|
||||
meta: &metav1.ObjectMeta{
|
||||
Labels: map[string]string{
|
||||
"a": "b",
|
||||
"c": "d",
|
||||
},
|
||||
},
|
||||
labels: map[string]string{
|
||||
"a": "c",
|
||||
"d": "b",
|
||||
},
|
||||
test: "one shared",
|
||||
expectErr: true,
|
||||
},
|
||||
{
|
||||
meta: &metav1.ObjectMeta{
|
||||
Labels: map[string]string{
|
||||
"a": "b",
|
||||
"c": "d",
|
||||
},
|
||||
},
|
||||
labels: map[string]string{
|
||||
"b": "d",
|
||||
"c": "a",
|
||||
},
|
||||
test: "second shared",
|
||||
expectErr: true,
|
||||
},
|
||||
{
|
||||
meta: &metav1.ObjectMeta{
|
||||
Labels: map[string]string{
|
||||
"a": "b",
|
||||
"c": "d",
|
||||
},
|
||||
},
|
||||
labels: map[string]string{
|
||||
"b": "a",
|
||||
"d": "c",
|
||||
},
|
||||
test: "no overlap",
|
||||
},
|
||||
{
|
||||
meta: &metav1.ObjectMeta{},
|
||||
labels: map[string]string{
|
||||
"b": "a",
|
||||
"d": "c",
|
||||
},
|
||||
test: "no labels",
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
err := validateNoOverwrites(test.meta, test.labels)
|
||||
if test.expectErr && err == nil {
|
||||
t.Errorf("%s: unexpected non-error", test.test)
|
||||
}
|
||||
if !test.expectErr && err != nil {
|
||||
t.Errorf("%s: unexpected error: %v", test.test, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseLabels(t *testing.T) {
|
||||
tests := []struct {
|
||||
labels []string
|
||||
expected map[string]string
|
||||
expectedRemove []string
|
||||
expectErr bool
|
||||
}{
|
||||
{
|
||||
labels: []string{"a=b", "c=d"},
|
||||
expected: map[string]string{"a": "b", "c": "d"},
|
||||
},
|
||||
{
|
||||
labels: []string{},
|
||||
expected: map[string]string{},
|
||||
},
|
||||
{
|
||||
labels: []string{"a=b", "c=d", "e-"},
|
||||
expected: map[string]string{"a": "b", "c": "d"},
|
||||
expectedRemove: []string{"e"},
|
||||
},
|
||||
{
|
||||
labels: []string{"ab", "c=d"},
|
||||
expectErr: true,
|
||||
},
|
||||
{
|
||||
labels: []string{"a=b", "c=d", "a-"},
|
||||
expectErr: true,
|
||||
},
|
||||
{
|
||||
labels: []string{"a="},
|
||||
expected: map[string]string{"a": ""},
|
||||
},
|
||||
{
|
||||
labels: []string{"a=%^$"},
|
||||
expectErr: true,
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
labels, remove, err := parseLabels(test.labels)
|
||||
if test.expectErr && err == nil {
|
||||
t.Errorf("unexpected non-error: %v", test)
|
||||
}
|
||||
if !test.expectErr && err != nil {
|
||||
t.Errorf("unexpected error: %v %v", err, test)
|
||||
}
|
||||
if !reflect.DeepEqual(labels, test.expected) {
|
||||
t.Errorf("expected: %v, got %v", test.expected, labels)
|
||||
}
|
||||
if !reflect.DeepEqual(remove, test.expectedRemove) {
|
||||
t.Errorf("expected: %v, got %v", test.expectedRemove, remove)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLabelFunc(t *testing.T) {
|
||||
tests := []struct {
|
||||
obj runtime.Object
|
||||
overwrite bool
|
||||
version string
|
||||
labels map[string]string
|
||||
remove []string
|
||||
expected runtime.Object
|
||||
expectErr bool
|
||||
}{
|
||||
{
|
||||
obj: &v1.Pod{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Labels: map[string]string{"a": "b"},
|
||||
},
|
||||
},
|
||||
labels: map[string]string{"a": "b"},
|
||||
expectErr: true,
|
||||
},
|
||||
{
|
||||
obj: &v1.Pod{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Labels: map[string]string{"a": "b"},
|
||||
},
|
||||
},
|
||||
labels: map[string]string{"a": "c"},
|
||||
overwrite: true,
|
||||
expected: &v1.Pod{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Labels: map[string]string{"a": "c"},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
obj: &v1.Pod{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Labels: map[string]string{"a": "b"},
|
||||
},
|
||||
},
|
||||
labels: map[string]string{"c": "d"},
|
||||
expected: &v1.Pod{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Labels: map[string]string{"a": "b", "c": "d"},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
obj: &v1.Pod{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Labels: map[string]string{"a": "b"},
|
||||
},
|
||||
},
|
||||
labels: map[string]string{"c": "d"},
|
||||
version: "2",
|
||||
expected: &v1.Pod{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Labels: map[string]string{"a": "b", "c": "d"},
|
||||
ResourceVersion: "2",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
obj: &v1.Pod{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Labels: map[string]string{"a": "b"},
|
||||
},
|
||||
},
|
||||
labels: map[string]string{},
|
||||
remove: []string{"a"},
|
||||
expected: &v1.Pod{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Labels: map[string]string{},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
obj: &v1.Pod{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Labels: map[string]string{"a": "b", "c": "d"},
|
||||
},
|
||||
},
|
||||
labels: map[string]string{"e": "f"},
|
||||
remove: []string{"a"},
|
||||
expected: &v1.Pod{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Labels: map[string]string{
|
||||
"c": "d",
|
||||
"e": "f",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
obj: &v1.Pod{
|
||||
ObjectMeta: metav1.ObjectMeta{},
|
||||
},
|
||||
labels: map[string]string{"a": "b"},
|
||||
expected: &v1.Pod{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Labels: map[string]string{"a": "b"},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
err := labelFunc(test.obj, test.overwrite, test.version, test.labels, test.remove)
|
||||
if test.expectErr {
|
||||
if err == nil {
|
||||
t.Errorf("unexpected non-error: %v", test)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !test.expectErr && err != nil {
|
||||
t.Errorf("unexpected error: %v %v", err, test)
|
||||
}
|
||||
if !reflect.DeepEqual(test.obj, test.expected) {
|
||||
t.Errorf("expected: %v, got %v", test.expected, test.obj)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLabelErrors(t *testing.T) {
|
||||
testCases := map[string]struct {
|
||||
args []string
|
||||
flags map[string]string
|
||||
errFn func(error) bool
|
||||
}{
|
||||
"no args": {
|
||||
args: []string{},
|
||||
errFn: func(err error) bool { return strings.Contains(err.Error(), "one or more resources must be specified") },
|
||||
},
|
||||
"not enough labels": {
|
||||
args: []string{"pods"},
|
||||
errFn: func(err error) bool { return strings.Contains(err.Error(), "at least one label update is required") },
|
||||
},
|
||||
"wrong labels": {
|
||||
args: []string{"pods", "-"},
|
||||
errFn: func(err error) bool { return strings.Contains(err.Error(), "at least one label update is required") },
|
||||
},
|
||||
"wrong labels 2": {
|
||||
args: []string{"pods", "=bar"},
|
||||
errFn: func(err error) bool { return strings.Contains(err.Error(), "at least one label update is required") },
|
||||
},
|
||||
"no resources": {
|
||||
args: []string{"pods-"},
|
||||
errFn: func(err error) bool { return strings.Contains(err.Error(), "one or more resources must be specified") },
|
||||
},
|
||||
"no resources 2": {
|
||||
args: []string{"pods=bar"},
|
||||
errFn: func(err error) bool { return strings.Contains(err.Error(), "one or more resources must be specified") },
|
||||
},
|
||||
"resources but no selectors": {
|
||||
args: []string{"pods", "app=bar"},
|
||||
errFn: func(err error) bool {
|
||||
return strings.Contains(err.Error(), "resource(s) were provided, but no name, label selector, or --all flag specified")
|
||||
},
|
||||
},
|
||||
"multiple resources but no selectors": {
|
||||
args: []string{"pods,deployments", "app=bar"},
|
||||
errFn: func(err error) bool {
|
||||
return strings.Contains(err.Error(), "resource(s) were provided, but no name, label selector, or --all flag specified")
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for k, testCase := range testCases {
|
||||
t.Run(k, func(t *testing.T) {
|
||||
tf := cmdtesting.NewTestFactory().WithNamespace("test")
|
||||
defer tf.Cleanup()
|
||||
|
||||
tf.ClientConfigVal = cmdtesting.DefaultClientConfig()
|
||||
|
||||
ioStreams, _, _, _ := genericclioptions.NewTestIOStreams()
|
||||
buf := bytes.NewBuffer([]byte{})
|
||||
cmd := NewCmdLabel(tf, ioStreams)
|
||||
cmd.SetOutput(buf)
|
||||
|
||||
for k, v := range testCase.flags {
|
||||
cmd.Flags().Set(k, v)
|
||||
}
|
||||
opts := NewLabelOptions(ioStreams)
|
||||
err := opts.Complete(tf, cmd, testCase.args)
|
||||
if err == nil {
|
||||
err = opts.Validate()
|
||||
}
|
||||
if err == nil {
|
||||
err = opts.RunLabel()
|
||||
}
|
||||
if !testCase.errFn(err) {
|
||||
t.Errorf("%s: unexpected error: %v", k, err)
|
||||
return
|
||||
}
|
||||
if buf.Len() > 0 {
|
||||
t.Errorf("buffer should be empty: %s", string(buf.Bytes()))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLabelForResourceFromFile(t *testing.T) {
|
||||
pods, _, _ := cmdtesting.TestData()
|
||||
tf := cmdtesting.NewTestFactory().WithNamespace("test")
|
||||
defer tf.Cleanup()
|
||||
|
||||
codec := scheme.Codecs.LegacyCodec(scheme.Scheme.PrioritizedVersionsAllGroups()...)
|
||||
|
||||
tf.UnstructuredClient = &fake.RESTClient{
|
||||
NegotiatedSerializer: resource.UnstructuredPlusDefaultContentConfig().NegotiatedSerializer,
|
||||
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
|
||||
switch req.Method {
|
||||
case "GET":
|
||||
switch req.URL.Path {
|
||||
case "/namespaces/test/replicationcontrollers/cassandra":
|
||||
return &http.Response{StatusCode: 200, Header: cmdtesting.DefaultHeader(), Body: cmdtesting.ObjBody(codec, &pods.Items[0])}, nil
|
||||
default:
|
||||
t.Fatalf("unexpected request: %#v\n%#v", req.URL, req)
|
||||
return nil, nil
|
||||
}
|
||||
case "PATCH":
|
||||
switch req.URL.Path {
|
||||
case "/namespaces/test/replicationcontrollers/cassandra":
|
||||
return &http.Response{StatusCode: 200, Header: cmdtesting.DefaultHeader(), Body: cmdtesting.ObjBody(codec, &pods.Items[0])}, nil
|
||||
default:
|
||||
t.Fatalf("unexpected request: %#v\n%#v", req.URL, req)
|
||||
return nil, nil
|
||||
}
|
||||
default:
|
||||
t.Fatalf("unexpected request: %s %#v\n%#v", req.Method, req.URL, req)
|
||||
return nil, nil
|
||||
}
|
||||
}),
|
||||
}
|
||||
tf.ClientConfigVal = cmdtesting.DefaultClientConfig()
|
||||
|
||||
ioStreams, _, buf, _ := genericclioptions.NewTestIOStreams()
|
||||
cmd := NewCmdLabel(tf, ioStreams)
|
||||
opts := NewLabelOptions(ioStreams)
|
||||
opts.Filenames = []string{"../../../../test/e2e/testing-manifests/statefulset/cassandra/controller.yaml"}
|
||||
err := opts.Complete(tf, cmd, []string{"a=b"})
|
||||
if err == nil {
|
||||
err = opts.Validate()
|
||||
}
|
||||
if err == nil {
|
||||
err = opts.RunLabel()
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !strings.Contains(buf.String(), "labeled") {
|
||||
t.Errorf("did not set labels: %s", buf.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestLabelLocal(t *testing.T) {
|
||||
tf := cmdtesting.NewTestFactory().WithNamespace("test")
|
||||
defer tf.Cleanup()
|
||||
|
||||
tf.UnstructuredClient = &fake.RESTClient{
|
||||
NegotiatedSerializer: resource.UnstructuredPlusDefaultContentConfig().NegotiatedSerializer,
|
||||
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
|
||||
t.Fatalf("unexpected request: %s %#v\n%#v", req.Method, req.URL, req)
|
||||
return nil, nil
|
||||
}),
|
||||
}
|
||||
tf.ClientConfigVal = cmdtesting.DefaultClientConfig()
|
||||
|
||||
ioStreams, _, buf, _ := genericclioptions.NewTestIOStreams()
|
||||
cmd := NewCmdLabel(tf, ioStreams)
|
||||
opts := NewLabelOptions(ioStreams)
|
||||
opts.Filenames = []string{"../../../../test/e2e/testing-manifests/statefulset/cassandra/controller.yaml"}
|
||||
opts.local = true
|
||||
err := opts.Complete(tf, cmd, []string{"a=b"})
|
||||
if err == nil {
|
||||
err = opts.Validate()
|
||||
}
|
||||
if err == nil {
|
||||
err = opts.RunLabel()
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !strings.Contains(buf.String(), "labeled") {
|
||||
t.Errorf("did not set labels: %s", buf.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestLabelMultipleObjects(t *testing.T) {
|
||||
pods, _, _ := cmdtesting.TestData()
|
||||
tf := cmdtesting.NewTestFactory().WithNamespace("test")
|
||||
defer tf.Cleanup()
|
||||
|
||||
codec := scheme.Codecs.LegacyCodec(scheme.Scheme.PrioritizedVersionsAllGroups()...)
|
||||
|
||||
tf.UnstructuredClient = &fake.RESTClient{
|
||||
NegotiatedSerializer: resource.UnstructuredPlusDefaultContentConfig().NegotiatedSerializer,
|
||||
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
|
||||
switch req.Method {
|
||||
case "GET":
|
||||
switch req.URL.Path {
|
||||
case "/namespaces/test/pods":
|
||||
return &http.Response{StatusCode: 200, Header: cmdtesting.DefaultHeader(), Body: cmdtesting.ObjBody(codec, pods)}, nil
|
||||
default:
|
||||
t.Fatalf("unexpected request: %#v\n%#v", req.URL, req)
|
||||
return nil, nil
|
||||
}
|
||||
case "PATCH":
|
||||
switch req.URL.Path {
|
||||
case "/namespaces/test/pods/foo":
|
||||
return &http.Response{StatusCode: 200, Header: cmdtesting.DefaultHeader(), Body: cmdtesting.ObjBody(codec, &pods.Items[0])}, nil
|
||||
case "/namespaces/test/pods/bar":
|
||||
return &http.Response{StatusCode: 200, Header: cmdtesting.DefaultHeader(), Body: cmdtesting.ObjBody(codec, &pods.Items[1])}, nil
|
||||
default:
|
||||
t.Fatalf("unexpected request: %#v\n%#v", req.URL, req)
|
||||
return nil, nil
|
||||
}
|
||||
default:
|
||||
t.Fatalf("unexpected request: %s %#v\n%#v", req.Method, req.URL, req)
|
||||
return nil, nil
|
||||
}
|
||||
}),
|
||||
}
|
||||
tf.ClientConfigVal = cmdtesting.DefaultClientConfig()
|
||||
|
||||
ioStreams, _, buf, _ := genericclioptions.NewTestIOStreams()
|
||||
opts := NewLabelOptions(ioStreams)
|
||||
opts.all = true
|
||||
cmd := NewCmdLabel(tf, ioStreams)
|
||||
err := opts.Complete(tf, cmd, []string{"pods", "a=b"})
|
||||
if err == nil {
|
||||
err = opts.Validate()
|
||||
}
|
||||
if err == nil {
|
||||
err = opts.RunLabel()
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if strings.Count(buf.String(), "labeled") != len(pods.Items) {
|
||||
t.Errorf("not all labels are set: %s", buf.String())
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user