本文整理汇总了Golang中k8s/io/kubernetes/pkg/kubectl/cmd/util.GetDryRunFlag函数的典型用法代码示例。如果您正苦于以下问题:Golang GetDryRunFlag函数的具体用法?Golang GetDryRunFlag怎么用?Golang GetDryRunFlag使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了GetDryRunFlag函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Run
func (o *ResourcesOptions) Run() error {
allErrs := []error{}
patches := CalculatePatches(o.f, o.Infos, o.Encoder, cmdutil.GetDryRunFlag(o.Cmd), func(info *resource.Info) (bool, error) {
transformed := false
_, err := o.UpdatePodSpecForObject(info.Object, func(spec *api.PodSpec) error {
containers, _ := selectContainers(spec.Containers, o.ContainerSelector)
if len(containers) != 0 {
for i := range containers {
containers[i].Resources = o.ResourceRequirements
transformed = true
}
} else {
allErrs = append(allErrs, fmt.Errorf("error: unable to find container named %s", o.ContainerSelector))
}
return nil
})
return transformed, err
})
for _, patch := range patches {
info := patch.Info
if patch.Err != nil {
allErrs = append(allErrs, fmt.Errorf("error: %s/%s %v\n", info.Mapping.Resource, info.Name, patch.Err))
continue
}
//no changes
if string(patch.Patch) == "{}" || len(patch.Patch) == 0 {
allErrs = append(allErrs, fmt.Errorf("info: %s %q was not changed\n", info.Mapping.Resource, info.Name))
continue
}
if cmdutil.GetDryRunFlag(o.Cmd) {
fmt.Fprintln(o.Err, "info: running in local mode...")
return o.PrintObject(o.Cmd, o.Mapper, info.Object, o.Out)
}
obj, err := resource.NewHelper(info.Client, info.Mapping).Patch(info.Namespace, info.Name, api.StrategicMergePatchType, patch.Patch)
if err != nil {
allErrs = append(allErrs, fmt.Errorf("failed to patch limit update to pod template %v\n", err))
continue
}
info.Refresh(obj, true)
//record this change (for rollout history)
if o.Record || cmdutil.ContainsChangeCause(info) {
if err := cmdutil.RecordChangeCause(obj, o.ChangeCause); err == nil {
if obj, err = resource.NewHelper(info.Client, info.Mapping).Replace(info.Namespace, info.Name, false, obj); err != nil {
allErrs = append(allErrs, fmt.Errorf("changes to %s/%s can't be recorded: %v\n", info.Mapping.Resource, info.Name, err))
}
}
}
info.Refresh(obj, true)
cmdutil.PrintSuccess(o.Mapper, o.ShortOutput, o.Out, info.Mapping.Resource, info.Name, false, "resource requirements updated")
}
return utilerrors.NewAggregate(allErrs)
}
示例2: CreateSecretDockerRegistry
// CreateSecretDockerRegistry is the implementation of the create secret docker-registry command
func CreateSecretDockerRegistry(f cmdutil.Factory, cmdOut io.Writer, cmd *cobra.Command, args []string) error {
name, err := NameFromCommandArgs(cmd, args)
if err != nil {
return err
}
requiredFlags := []string{"docker-username", "docker-password", "docker-email", "docker-server"}
for _, requiredFlag := range requiredFlags {
if value := cmdutil.GetFlagString(cmd, requiredFlag); len(value) == 0 {
return cmdutil.UsageError(cmd, "flag %s is required", requiredFlag)
}
}
var generator kubectl.StructuredGenerator
switch generatorName := cmdutil.GetFlagString(cmd, "generator"); generatorName {
case cmdutil.SecretForDockerRegistryV1GeneratorName:
generator = &kubectl.SecretForDockerRegistryGeneratorV1{
Name: name,
Username: cmdutil.GetFlagString(cmd, "docker-username"),
Email: cmdutil.GetFlagString(cmd, "docker-email"),
Password: cmdutil.GetFlagString(cmd, "docker-password"),
Server: cmdutil.GetFlagString(cmd, "docker-server"),
}
default:
return cmdutil.UsageError(cmd, fmt.Sprintf("Generator: %s not supported.", generatorName))
}
return RunCreateSubcommand(f, cmd, cmdOut, &CreateSubcommandOptions{
Name: name,
StructuredGenerator: generator,
DryRun: cmdutil.GetDryRunFlag(cmd),
OutputFormat: cmdutil.GetFlagString(cmd, "output"),
})
}
示例3: Complete
// Complete assigns the SelectorOptions from args.
func (o *SelectorOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string, out io.Writer) error {
o.local = cmdutil.GetFlagBool(cmd, "local")
o.all = cmdutil.GetFlagBool(cmd, "all")
o.record = cmdutil.GetRecordFlag(cmd)
o.dryrun = cmdutil.GetDryRunFlag(cmd)
cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
o.changeCause = f.Command()
mapper, _ := f.Object()
o.mapper = mapper
o.encoder = f.JSONEncoder()
o.builder = f.NewBuilder().
ContinueOnError().
NamespaceParam(cmdNamespace).DefaultNamespace().
FilenameParam(enforceNamespace, &o.fileOptions).
Flatten()
o.PrintObject = func(obj runtime.Object) error {
return f.PrintObject(cmd, mapper, obj, o.out)
}
o.ClientForMapping = func(mapping *meta.RESTMapping) (resource.RESTClient, error) {
return f.ClientForMapping(mapping)
}
o.resources, o.selector, err = getResourcesAndSelector(args)
return err
}
示例4: Complete
func (o *ResourcesOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {
o.Mapper, o.Typer = f.Object()
o.UpdatePodSpecForObject = f.UpdatePodSpecForObject
o.Encoder = f.JSONEncoder()
o.ShortOutput = cmdutil.GetFlagString(cmd, "output") == "name"
o.Record = cmdutil.GetRecordFlag(cmd)
o.ChangeCause = f.Command()
o.PrintObject = f.PrintObject
o.Cmd = cmd
cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
builder := resource.NewBuilder(o.Mapper, o.Typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)).
ContinueOnError().
NamespaceParam(cmdNamespace).DefaultNamespace().
//FilenameParam(enforceNamespace, o.Filenames...).
FilenameParam(enforceNamespace, &o.FilenameOptions).
Flatten()
if !cmdutil.GetDryRunFlag(cmd) {
builder = builder.
SelectorParam(o.Selector).
ResourceTypeOrNameArgs(o.All, args...).
Latest()
}
o.Infos, err = builder.Do().Infos()
if err != nil {
return err
}
return nil
}
示例5: CreateRoleBinding
func CreateRoleBinding(f cmdutil.Factory, cmdOut io.Writer, cmd *cobra.Command, args []string) error {
name, err := NameFromCommandArgs(cmd, args)
if err != nil {
return err
}
var generator kubectl.StructuredGenerator
switch generatorName := cmdutil.GetFlagString(cmd, "generator"); generatorName {
case cmdutil.RoleBindingV1GeneratorName:
generator = &kubectl.RoleBindingGeneratorV1{
Name: name,
ClusterRole: cmdutil.GetFlagString(cmd, "clusterrole"),
Role: cmdutil.GetFlagString(cmd, "role"),
Users: cmdutil.GetFlagStringSlice(cmd, "user"),
Groups: cmdutil.GetFlagStringSlice(cmd, "group"),
ServiceAccounts: cmdutil.GetFlagStringSlice(cmd, "serviceaccount"),
}
default:
return cmdutil.UsageError(cmd, fmt.Sprintf("Generator: %s not supported.", generatorName))
}
return RunCreateSubcommand(f, cmd, cmdOut, &CreateSubcommandOptions{
Name: name,
StructuredGenerator: generator,
DryRun: cmdutil.GetDryRunFlag(cmd),
OutputFormat: cmdutil.GetFlagString(cmd, "output"),
})
}
示例6: CreateServiceNodePort
// CreateServiceNodePort is the implementation of the create secret docker-registry command
func CreateServiceNodePort(f *cmdutil.Factory, cmdOut io.Writer, cmd *cobra.Command, args []string) error {
name, err := NameFromCommandArgs(cmd, args)
if err != nil {
return err
}
var generator kubectl.StructuredGenerator
switch generatorName := cmdutil.GetFlagString(cmd, "generator"); generatorName {
case cmdutil.ServiceNodePortGeneratorV1Name:
generator = &kubectl.ServiceCommonGeneratorV1{
Name: name,
TCP: cmdutil.GetFlagStringSlice(cmd, "tcp"),
Type: api.ServiceTypeNodePort,
ClusterIP: "",
NodePort: cmdutil.GetFlagInt(cmd, "node-port"),
}
default:
return cmdutil.UsageError(cmd, fmt.Sprintf("Generator: %s not supported.", generatorName))
}
return RunCreateSubcommand(f, cmd, cmdOut, &CreateSubcommandOptions{
Name: name,
StructuredGenerator: generator,
DryRun: cmdutil.GetDryRunFlag(cmd),
OutputFormat: cmdutil.GetFlagString(cmd, "output"),
})
}
示例7: generateService
func generateService(f cmdutil.Factory, cmd *cobra.Command, args []string, serviceGenerator string, paramsIn map[string]interface{}, namespace string, out io.Writer) error {
generators := f.Generators("expose")
generator, found := generators[serviceGenerator]
if !found {
return fmt.Errorf("missing service generator: %s", serviceGenerator)
}
names := generator.ParamNames()
port := cmdutil.GetFlagString(cmd, "port")
if len(port) == 0 {
return fmt.Errorf("--port must be set when exposing a service")
}
params := map[string]interface{}{}
for key, value := range paramsIn {
_, isString := value.(string)
if isString {
params[key] = value
}
}
name, found := params["name"]
if !found || len(name.(string)) == 0 {
return fmt.Errorf("name is a required parameter")
}
selector, found := params["labels"]
if !found || len(selector.(string)) == 0 {
selector = fmt.Sprintf("run=%s", name.(string))
}
params["selector"] = selector
if defaultName, found := params["default-name"]; !found || len(defaultName.(string)) == 0 {
params["default-name"] = name
}
obj, _, mapper, mapping, err := createGeneratedObject(f, cmd, generator, names, params, cmdutil.GetFlagString(cmd, "service-overrides"), namespace)
if err != nil {
return err
}
if cmdutil.GetFlagString(cmd, "output") != "" || cmdutil.GetDryRunFlag(cmd) {
return f.PrintObject(cmd, mapper, obj, out)
}
cmdutil.PrintSuccess(mapper, false, out, mapping.Resource, args[0], cmdutil.GetDryRunFlag(cmd), "created")
return nil
}
示例8: joinFederation
// joinFederation is the implementation of the `join federation` command.
func joinFederation(f cmdutil.Factory, cmdOut io.Writer, config util.AdminConfig, cmd *cobra.Command, args []string) error {
joinFlags, err := util.GetSubcommandFlags(cmd, args)
if err != nil {
return err
}
dryRun := cmdutil.GetDryRunFlag(cmd)
glog.V(2).Infof("Args and flags: name %s, host: %s, host-system-namespace: %s, kubeconfig: %s, dry-run: %s", joinFlags.Name, joinFlags.Host, joinFlags.FederationSystemNamespace, joinFlags.Kubeconfig, dryRun)
po := config.PathOptions()
po.LoadingRules.ExplicitPath = joinFlags.Kubeconfig
clientConfig, err := po.GetStartingConfig()
if err != nil {
return err
}
generator, err := clusterGenerator(clientConfig, joinFlags.Name)
if err != nil {
glog.V(2).Infof("Failed creating cluster generator: %v", err)
return err
}
glog.V(2).Infof("Created cluster generator: %#v", generator)
hostFactory := config.HostFactory(joinFlags.Host, joinFlags.Kubeconfig)
// We are not using the `kubectl create secret` machinery through
// `RunCreateSubcommand` as we do to the cluster resource below
// because we have a bunch of requirements that the machinery does
// not satisfy.
// 1. We want to create the secret in a specific namespace, which
// is neither the "default" namespace nor the one specified
// via the `--namespace` flag.
// 2. `SecretGeneratorV1` requires LiteralSources in a string-ified
// form that it parses to generate the secret data key-value
// pairs. We, however, have the key-value pairs ready without a
// need for parsing.
// 3. The result printing mechanism needs to be mostly quiet. We
// don't have to print the created secret in the default case.
// Having said that, secret generation machinery could be altered to
// suit our needs, but it is far less invasive and readable this way.
_, err = createSecret(hostFactory, clientConfig, joinFlags.FederationSystemNamespace, joinFlags.Name, dryRun)
if err != nil {
glog.V(2).Infof("Failed creating the cluster credentials secret: %v", err)
return err
}
glog.V(2).Infof("Cluster credentials secret created")
return kubectlcmd.RunCreateSubcommand(f, cmd, cmdOut, &kubectlcmd.CreateSubcommandOptions{
Name: joinFlags.Name,
StructuredGenerator: generator,
DryRun: dryRun,
OutputFormat: cmdutil.GetFlagString(cmd, "output"),
})
}
示例9: Complete
// Complete adapts from the command line args and factory to the data required.
func (o *LabelOptions) Complete(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) (err error) {
o.out = out
o.local = cmdutil.GetFlagBool(cmd, "local")
o.overwrite = cmdutil.GetFlagBool(cmd, "overwrite")
o.all = cmdutil.GetFlagBool(cmd, "all")
o.resourceVersion = cmdutil.GetFlagString(cmd, "resource-version")
o.selector = cmdutil.GetFlagString(cmd, "selector")
o.outputFormat = cmdutil.GetFlagString(cmd, "output")
o.dryrun = cmdutil.GetDryRunFlag(cmd)
resources, labelArgs, err := cmdutil.GetResourcesAndPairs(args, "label")
if err != nil {
return err
}
o.resources = resources
o.newLabels, o.removeLabels, err = parseLabels(labelArgs)
return err
}
示例10: CreateNamespace
// CreateNamespace implements the behavior to run the create namespace command
func CreateNamespace(f cmdutil.Factory, cmdOut io.Writer, cmd *cobra.Command, args []string) error {
name, err := NameFromCommandArgs(cmd, args)
if err != nil {
return err
}
var generator kubectl.StructuredGenerator
switch generatorName := cmdutil.GetFlagString(cmd, "generator"); generatorName {
case cmdutil.NamespaceV1GeneratorName:
generator = &kubectl.NamespaceGeneratorV1{Name: name}
default:
return cmdutil.UsageError(cmd, fmt.Sprintf("Generator: %s not supported.", generatorName))
}
return RunCreateSubcommand(f, cmd, cmdOut, &CreateSubcommandOptions{
Name: name,
StructuredGenerator: generator,
DryRun: cmdutil.GetDryRunFlag(cmd),
OutputFormat: cmdutil.GetFlagString(cmd, "output"),
})
}
示例11: Complete
// Complete adapts from the command line args and factory to the data required.
func (o *AnnotateOptions) Complete(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) (err error) {
o.out = out
o.local = cmdutil.GetFlagBool(cmd, "local")
o.overwrite = cmdutil.GetFlagBool(cmd, "overwrite")
o.all = cmdutil.GetFlagBool(cmd, "all")
o.resourceVersion = cmdutil.GetFlagString(cmd, "resource-version")
o.selector = cmdutil.GetFlagString(cmd, "selector")
o.outputFormat = cmdutil.GetFlagString(cmd, "output")
o.dryrun = cmdutil.GetDryRunFlag(cmd)
o.recordChangeCause = cmdutil.GetRecordFlag(cmd)
// retrieves resource and annotation args from args
// also checks args to verify that all resources are specified before annotations
resources, annotationArgs, err := cmdutil.GetResourcesAndPairs(args, "annotation")
if err != nil {
return err
}
o.resources = resources
o.newAnnotations, o.removeAnnotations, err = parseAnnotations(annotationArgs)
return err
}
示例12: CreateConfigMap
// CreateConfigMap is the implementation of the create configmap command.
func CreateConfigMap(f *cmdutil.Factory, cmdOut io.Writer, cmd *cobra.Command, args []string) error {
name, err := NameFromCommandArgs(cmd, args)
if err != nil {
return err
}
var generator kubectl.StructuredGenerator
switch generatorName := cmdutil.GetFlagString(cmd, "generator"); generatorName {
case cmdutil.ConfigMapV1GeneratorName:
generator = &kubectl.ConfigMapGeneratorV1{
Name: name,
FileSources: cmdutil.GetFlagStringSlice(cmd, "from-file"),
LiteralSources: cmdutil.GetFlagStringArray(cmd, "from-literal"),
}
default:
return cmdutil.UsageError(cmd, fmt.Sprintf("Generator: %s not supported.", generatorName))
}
return RunCreateSubcommand(f, cmd, cmdOut, &CreateSubcommandOptions{
Name: name,
StructuredGenerator: generator,
DryRun: cmdutil.GetDryRunFlag(cmd),
OutputFormat: cmdutil.GetFlagString(cmd, "output"),
})
}
示例13: Run
func Run(f cmdutil.Factory, cmdIn io.Reader, cmdOut, cmdErr io.Writer, cmd *cobra.Command, args []string, argsLenAtDash int) error {
if len(os.Args) > 1 && os.Args[1] == "run-container" {
printDeprecationWarning("run", "run-container")
}
// Let kubectl run follow rules for `--`, see #13004 issue
if len(args) == 0 || argsLenAtDash == 0 {
return cmdutil.UsageError(cmd, "NAME is required for run")
}
// validate image name
imageName := cmdutil.GetFlagString(cmd, "image")
validImageRef := reference.ReferenceRegexp.MatchString(imageName)
if !validImageRef {
return fmt.Errorf("Invalid image name %q: %v", imageName, reference.ErrReferenceInvalidFormat)
}
interactive := cmdutil.GetFlagBool(cmd, "stdin")
tty := cmdutil.GetFlagBool(cmd, "tty")
if tty && !interactive {
return cmdutil.UsageError(cmd, "-i/--stdin is required for containers with -t/--tty=true")
}
replicas := cmdutil.GetFlagInt(cmd, "replicas")
if interactive && replicas != 1 {
return cmdutil.UsageError(cmd, fmt.Sprintf("-i/--stdin requires that replicas is 1, found %d", replicas))
}
namespace, _, err := f.DefaultNamespace()
if err != nil {
return err
}
restartPolicy, err := getRestartPolicy(cmd, interactive)
if err != nil {
return err
}
if restartPolicy != api.RestartPolicyAlways && replicas != 1 {
return cmdutil.UsageError(cmd, fmt.Sprintf("--restart=%s requires that --replicas=1, found %d", restartPolicy, replicas))
}
attachFlag := cmd.Flags().Lookup("attach")
attach := cmdutil.GetFlagBool(cmd, "attach")
if !attachFlag.Changed && interactive {
attach = true
}
remove := cmdutil.GetFlagBool(cmd, "rm")
if !attach && remove {
return cmdutil.UsageError(cmd, "--rm should only be used for attached containers")
}
if attach && cmdutil.GetDryRunFlag(cmd) {
return cmdutil.UsageError(cmd, "--dry-run can't be used with attached containers options (--attach, --stdin, or --tty)")
}
if err := verifyImagePullPolicy(cmd); err != nil {
return err
}
generatorName := cmdutil.GetFlagString(cmd, "generator")
schedule := cmdutil.GetFlagString(cmd, "schedule")
if len(schedule) != 0 && len(generatorName) == 0 {
generatorName = "cronjob/v2alpha1"
}
if len(generatorName) == 0 {
clientset, err := f.ClientSet()
if err != nil {
return err
}
resourcesList, err := clientset.Discovery().ServerResources()
// ServerResources ignores errors for old servers do not expose discovery
if err != nil {
return fmt.Errorf("failed to discover supported resources: %v", err)
}
switch restartPolicy {
case api.RestartPolicyAlways:
if contains(resourcesList, v1beta1.SchemeGroupVersion.WithResource("deployments")) {
generatorName = "deployment/v1beta1"
} else {
generatorName = "run/v1"
}
case api.RestartPolicyOnFailure:
if contains(resourcesList, batchv1.SchemeGroupVersion.WithResource("jobs")) {
generatorName = "job/v1"
} else if contains(resourcesList, v1beta1.SchemeGroupVersion.WithResource("jobs")) {
generatorName = "job/v1beta1"
} else {
generatorName = "run-pod/v1"
}
case api.RestartPolicyNever:
generatorName = "run-pod/v1"
}
}
if generatorName == "job/v1beta1" {
fmt.Fprintf(cmdErr, "DEPRECATED: --generator=job/v1beta1 is deprecated, use job/v1 instead.\n")
}
generators := f.Generators("run")
generator, found := generators[generatorName]
if !found {
return cmdutil.UsageError(cmd, fmt.Sprintf("generator %q not found.", generatorName))
//.........这里部分代码省略.........
示例14: RunExpose
//.........这里部分代码省略.........
// For objects that need a port, derive it from the exposed object in case a user
// didn't explicitly specify one via --port
if port, found := params["port"]; found && kubectl.IsZero(port) {
ports, err := f.PortsForObject(info.Object)
if err != nil {
return cmdutil.UsageError(cmd, fmt.Sprintf("couldn't find port via --port flag or introspection: %s", err))
}
switch len(ports) {
case 0:
return cmdutil.UsageError(cmd, "couldn't find port via --port flag or introspection")
case 1:
params["port"] = ports[0]
default:
params["ports"] = strings.Join(ports, ",")
}
}
// Always try to derive protocols from the exposed object, may use
// different protocols for different ports.
if _, found := params["protocol"]; found {
protocolsMap, err := f.ProtocolsForObject(info.Object)
if err != nil {
return cmdutil.UsageError(cmd, fmt.Sprintf("couldn't find protocol via introspection: %s", err))
}
if protocols := kubectl.MakeProtocols(protocolsMap); !kubectl.IsZero(protocols) {
params["protocols"] = protocols
}
}
if kubectl.IsZero(params["labels"]) {
labels, err := f.LabelsForObject(info.Object)
if err != nil {
return err
}
params["labels"] = kubectl.MakeLabels(labels)
}
if err = kubectl.ValidateParams(names, params); err != nil {
return err
}
// Check for invalid flags used against the present generator.
if err := kubectl.EnsureFlagsValid(cmd, generators, generatorName); err != nil {
return err
}
// Generate new object
object, err := generator.Generate(params)
if err != nil {
return err
}
if inline := cmdutil.GetFlagString(cmd, "overrides"); len(inline) > 0 {
codec := runtime.NewCodec(f.JSONEncoder(), f.Decoder(true))
object, err = cmdutil.Merge(codec, object, inline, mapping.GroupVersionKind.Kind)
if err != nil {
return err
}
}
resourceMapper := &resource.Mapper{
ObjectTyper: typer,
RESTMapper: mapper,
ClientMapper: resource.ClientMapperFunc(f.ClientForMapping),
Decoder: f.Decoder(true),
}
info, err = resourceMapper.InfoForObject(object, nil)
if err != nil {
return err
}
if cmdutil.ShouldRecord(cmd, info) {
if err := cmdutil.RecordChangeCause(object, f.Command()); err != nil {
return err
}
}
info.Refresh(object, true)
if cmdutil.GetDryRunFlag(cmd) {
return f.PrintObject(cmd, mapper, object, out)
}
if err := kubectl.CreateOrUpdateAnnotation(cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag), info, f.JSONEncoder()); err != nil {
return err
}
// Serialize the object with the annotation applied.
object, err = resource.NewHelper(info.Client, info.Mapping).Create(namespace, false, object)
if err != nil {
return err
}
if len(cmdutil.GetFlagString(cmd, "output")) > 0 {
return f.PrintObject(cmd, mapper, object, out)
}
cmdutil.PrintSuccess(mapper, false, out, info.Mapping.Resource, info.Name, "exposed")
return nil
})
if err != nil {
return err
}
return nil
}
示例15: RunLabel
func RunLabel(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, options *LabelOptions) error {
resources, labelArgs, err := cmdutil.GetResourcesAndPairs(args, "label")
if err != nil {
return err
}
if len(resources) < 1 && len(options.Filenames) == 0 {
return cmdutil.UsageError(cmd, "one or more resources must be specified as <resource> <name> or <resource>/<name>")
}
if len(labelArgs) < 1 {
return cmdutil.UsageError(cmd, "at least one label update is required")
}
selector := cmdutil.GetFlagString(cmd, "selector")
all := cmdutil.GetFlagBool(cmd, "all")
overwrite := cmdutil.GetFlagBool(cmd, "overwrite")
resourceVersion := cmdutil.GetFlagString(cmd, "resource-version")
cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
lbls, remove, err := parseLabels(labelArgs)
if err != nil {
return cmdutil.UsageError(cmd, err.Error())
}
mapper, typer := f.Object(cmdutil.GetIncludeThirdPartyAPIs(cmd))
b := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)).
ContinueOnError().
NamespaceParam(cmdNamespace).DefaultNamespace().
FilenameParam(enforceNamespace, options.Recursive, options.Filenames...).
SelectorParam(selector).
ResourceTypeOrNameArgs(all, resources...).
Flatten().
Latest()
one := false
r := b.Do().IntoSingular(&one)
if err := r.Err(); err != nil {
return err
}
// only apply resource version locking on a single resource
if !one && len(resourceVersion) > 0 {
return cmdutil.UsageError(cmd, "--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
dataChangeMsg := "not labeled"
if cmdutil.GetDryRunFlag(cmd) {
err = labelFunc(info.Object, overwrite, resourceVersion, lbls, remove)
if err != nil {
return err
}
outputObj = info.Object
} else {
obj, err := cmdutil.MaybeConvertObject(info.Object, info.Mapping.GroupVersionKind.GroupVersion(), info.Mapping)
if err != nil {
return err
}
name, namespace := info.Name, info.Namespace
oldData, err := json.Marshal(obj)
if err != nil {
return err
}
accessor, err := meta.Accessor(obj)
if err != nil {
return err
}
for _, label := range remove {
if _, ok := accessor.GetLabels()[label]; !ok {
fmt.Fprintf(out, "label %q not found.\n", label)
}
}
if err := labelFunc(obj, overwrite, resourceVersion, lbls, remove); err != nil {
return err
}
if cmdutil.ShouldRecord(cmd, info) {
if err := cmdutil.RecordChangeCause(obj, f.Command()); err != nil {
return err
}
}
newData, err := json.Marshal(obj)
if err != nil {
return err
}
if !reflect.DeepEqual(oldData, newData) {
dataChangeMsg = "labeled"
}
patchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, obj)
createdPatch := err == nil
if err != nil {
glog.V(2).Infof("couldn't compute patch: %v", err)
//.........这里部分代码省略.........