本文整理汇总了Golang中k8s/io/kubernetes/pkg/kubectl/cmd/util.Factory.DefaultTenant方法的典型用法代码示例。如果您正苦于以下问题:Golang Factory.DefaultTenant方法的具体用法?Golang Factory.DefaultTenant怎么用?Golang Factory.DefaultTenant使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类k8s/io/kubernetes/pkg/kubectl/cmd/util.Factory
的用法示例。
在下文中一共展示了Factory.DefaultTenant方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: RunStop
func RunStop(f *cmdutil.Factory, cmd *cobra.Command, args []string, out io.Writer, options *StopOptions) error {
cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
cmdTenant, enforceTenant, err := f.DefaultTenant()
if err != nil {
return err
}
mapper, typer := f.Object()
r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()).
ContinueOnError().
NamespaceParam(cmdNamespace).DefaultNamespace().
TenantParam(cmdTenant).DefaultTenant().
ResourceTypeOrNameArgs(false, args...).
FilenameParam(enforceTenant, enforceNamespace, options.Filenames...).
SelectorParam(cmdutil.GetFlagString(cmd, "selector")).
SelectAllParam(cmdutil.GetFlagBool(cmd, "all")).
Flatten().
Do()
if r.Err() != nil {
return r.Err()
}
shortOutput := cmdutil.GetFlagString(cmd, "output") == "name"
return ReapResult(r, f, out, false, cmdutil.GetFlagBool(cmd, "ignore-not-found"), cmdutil.GetFlagDuration(cmd, "timeout"), cmdutil.GetFlagInt(cmd, "grace-period"), shortOutput, mapper)
}
示例2: RunPatch
func RunPatch(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, shortOutput bool, options *PatchOptions) error {
cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
cmdTenant, enforceTenant, err := f.DefaultTenant()
if err != nil {
return err
}
patch := cmdutil.GetFlagString(cmd, "patch")
if len(patch) == 0 {
return cmdutil.UsageError(cmd, "Must specify -p to patch")
}
patchBytes, err := yaml.ToJSON([]byte(patch))
if err != nil {
return fmt.Errorf("unable to parse %q: %v", patch, err)
}
mapper, typer := f.Object()
r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()).
ContinueOnError().
NamespaceParam(cmdNamespace).DefaultNamespace().
TenantParam(cmdTenant).DefaultTenant().
FilenameParam(enforceTenant, enforceNamespace, options.Filenames...).
ResourceTypeOrNameArgs(false, args...).
Flatten().
Do()
err = r.Err()
if err != nil {
return err
}
infos, err := r.Infos()
if err != nil {
return err
}
if len(infos) > 1 {
return fmt.Errorf("multiple resources provided")
}
info := infos[0]
name, namespace := info.Name, info.Namespace
mapping := info.ResourceMapping()
client, err := f.RESTClient(mapping)
if err != nil {
return err
}
helper := resource.NewHelper(client, mapping)
_, err = helper.Patch(namespace, name, api.StrategicMergePatchType, patchBytes)
if err != nil {
return err
}
cmdutil.PrintSuccess(mapper, shortOutput, out, "", name, "patched")
return nil
}
示例3: Complete
// Complete adapts from the command line args and factory to the data required.
func (o *AnnotateOptions) Complete(f *cmdutil.Factory, args []string) (err error) {
namespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
tenant, enforceTenant, err := f.DefaultTenant()
if err != nil {
return err
}
// retrieves resource and annotation args from args
// also checks args to verify that all resources are specified before annotations
annotationArgs := []string{}
metAnnotaionArg := false
for _, s := range args {
isAnnotation := strings.Contains(s, "=") || strings.HasSuffix(s, "-")
switch {
case !metAnnotaionArg && isAnnotation:
metAnnotaionArg = true
fallthrough
case metAnnotaionArg && isAnnotation:
annotationArgs = append(annotationArgs, s)
case !metAnnotaionArg && !isAnnotation:
o.resources = append(o.resources, s)
case metAnnotaionArg && !isAnnotation:
return fmt.Errorf("all resources must be specified before annotation changes: %s", s)
}
}
if len(o.resources) < 1 && len(o.filenames) == 0 {
return fmt.Errorf("one or more resources must be specified as <resource> <name> or <resource>/<name>")
}
if len(annotationArgs) < 1 {
return fmt.Errorf("at least one annotation update is required")
}
if o.newAnnotations, o.removeAnnotations, err = parseAnnotations(annotationArgs); err != nil {
return err
}
mapper, typer := f.Object()
o.builder = resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()).
ContinueOnError().
NamespaceParam(namespace).DefaultNamespace().
TenantParam(tenant).DefaultTenant().
FilenameParam(enforceTenant, enforceNamespace, o.filenames...).
ResourceTypeOrNameArgs(o.all, o.resources...).
Flatten().
Latest()
return nil
}
示例4: RunDelete
func RunDelete(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, options *DeleteOptions) error {
cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
cmdTenant, enforceTenant, err := f.DefaultTenant()
if err != nil {
return err
}
deleteAll := cmdutil.GetFlagBool(cmd, "all")
mapper, typer := f.Object()
r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()).
ContinueOnError().
NamespaceParam(cmdNamespace).DefaultNamespace().
TenantParam(cmdTenant).DefaultTenant().
FilenameParam(enforceTenant, enforceNamespace, options.Filenames...).
SelectorParam(cmdutil.GetFlagString(cmd, "selector")).
SelectAllParam(deleteAll).
ResourceTypeOrNameArgs(false, args...).RequireObject(false).
Flatten().
Do()
err = r.Err()
if err != nil {
return err
}
ignoreNotFound := cmdutil.GetFlagBool(cmd, "ignore-not-found")
if deleteAll {
f := cmd.Flags().Lookup("ignore-not-found")
// The flag should never be missing
if f == nil {
return fmt.Errorf("missing --ignore-not-found flag")
}
// If the user didn't explicitly set the option, default to ignoring NotFound errors when used with --all
if !f.Changed {
ignoreNotFound = true
}
}
shortOutput := cmdutil.GetFlagString(cmd, "output") == "name"
// By default use a reaper to delete all related resources.
if cmdutil.GetFlagBool(cmd, "cascade") {
return ReapResult(r, f, out, cmdutil.GetFlagBool(cmd, "cascade"), ignoreNotFound, cmdutil.GetFlagDuration(cmd, "timeout"), cmdutil.GetFlagInt(cmd, "grace-period"), shortOutput, mapper)
}
return DeleteResult(r, out, ignoreNotFound, shortOutput, mapper)
}
示例5: RunExpose
func RunExpose(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, options *ExposeOptions) error {
namespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
tenant, enforceTenant, err := f.DefaultTenant()
if err != nil {
return err
}
mapper, typer := f.Object()
r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()).
ContinueOnError().
NamespaceParam(namespace).DefaultNamespace().
TenantParam(tenant).DefaultTenant().
FilenameParam(enforceTenant, enforceNamespace, options.Filenames...).
ResourceTypeOrNameArgs(false, args...).
Flatten().
Do()
infos, err := r.Infos()
if err != nil {
return err
}
if len(infos) > 1 {
return fmt.Errorf("multiple resources provided: %v", args)
}
info := infos[0]
mapping := info.ResourceMapping()
if err := f.CanBeExposed(mapping.Kind); err != nil {
return err
}
// Get the input object
inputObject, err := r.Object()
if err != nil {
return err
}
// Get the generator, setup and validate all required parameters
generatorName := cmdutil.GetFlagString(cmd, "generator")
generator, found := f.Generator(generatorName)
if !found {
return cmdutil.UsageError(cmd, fmt.Sprintf("generator %q not found.", generatorName))
}
names := generator.ParamNames()
params := kubectl.MakeParams(cmd, names)
name := info.Name
if len(name) > validation.DNS952LabelMaxLength {
name = name[:validation.DNS952LabelMaxLength]
}
params["default-name"] = name
// For objects that need a pod selector, derive it from the exposed object in case a user
// didn't explicitly specify one via --selector
if s, found := params["selector"]; found && kubectl.IsZero(s) {
s, err := f.PodSelectorForObject(inputObject)
if err != nil {
return cmdutil.UsageError(cmd, fmt.Sprintf("couldn't find selectors via --selector flag or introspection: %s", err))
}
params["selector"] = s
}
// 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(inputObject)
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, ",")
}
}
if kubectl.IsZero(params["labels"]) {
labels, err := f.LabelsForObject(inputObject)
if err != nil {
return err
}
params["labels"] = kubectl.MakeLabels(labels)
}
if err = kubectl.ValidateParams(names, params); 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 {
object, err = cmdutil.Merge(object, inline, mapping.Kind)
if err != nil {
return err
}
}
//.........这里部分代码省略.........
示例6: RunCreate
func RunCreate(f *cmdutil.Factory, cmd *cobra.Command, out io.Writer, options *CreateOptions) error {
schema, err := f.Validator(cmdutil.GetFlagBool(cmd, "validate"), cmdutil.GetFlagString(cmd, "schema-cache-dir"))
if err != nil {
return err
}
cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
cmdTenant, enforceTenant, err := f.DefaultTenant()
if err != nil {
return err
}
client, err := f.ClientConfig()
if err != nil {
return err
}
if strings.Index(client.Host, "http://") == 0 {
if cmdTenant == "" {
cmdTenant = api.TenantDefault
}
}
mapper, typer := f.Object()
r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()).
Schema(schema).
ContinueOnError().
NamespaceParam(cmdNamespace).DefaultNamespace().
TenantParam(cmdTenant).DefaultTenant().
FilenameParam(enforceTenant, enforceNamespace, options.Filenames...).
Flatten().
Do()
err = r.Err()
if err != nil {
return err
}
count := 0
err = r.Visit(func(info *resource.Info, err error) error {
if err != nil {
return err
}
if err := kubectl.CreateOrUpdateAnnotation(cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag), info); err != nil {
return cmdutil.AddSourceToErr("creating", info.Source, err)
}
if err := createAndRefresh(info); err != nil {
return cmdutil.AddSourceToErr("creating", info.Source, err)
}
count++
shortOutput := cmdutil.GetFlagString(cmd, "output") == "name"
if !shortOutput {
printObjectSpecificMessage(info.Object, out)
}
cmdutil.PrintSuccess(mapper, shortOutput, out, info.Mapping.Resource, info.Name, "created")
return nil
})
if err != nil {
return err
}
if count == 0 {
return fmt.Errorf("no objects passed to create")
}
return nil
}
示例7: RunScale
// RunScale executes the scaling
func RunScale(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, shortOutput bool, options *ScaleOptions) error {
if len(os.Args) > 1 && os.Args[1] == "resize" {
printDeprecationWarning("scale", "resize")
}
count := cmdutil.GetFlagInt(cmd, "replicas")
if count < 0 {
return cmdutil.UsageError(cmd, "--replicas=COUNT is required, and COUNT must be greater than or equal to 0")
}
cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
cmdTenant, enforceTenant, err := f.DefaultTenant()
if err != nil {
return err
}
mapper, typer := f.Object()
r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()).
ContinueOnError().
NamespaceParam(cmdNamespace).DefaultNamespace().
TenantParam(cmdTenant).DefaultTenant().
FilenameParam(enforceTenant, enforceNamespace, options.Filenames...).
ResourceTypeOrNameArgs(false, args...).
Flatten().
Do()
err = r.Err()
if err != nil {
return err
}
infos, err := r.Infos()
if err != nil {
return err
}
info := infos[0]
mapping := info.ResourceMapping()
scaler, err := f.Scaler(mapping)
if err != nil {
return err
}
resourceVersion := cmdutil.GetFlagString(cmd, "resource-version")
if len(resourceVersion) != 0 && len(infos) > 1 {
return fmt.Errorf("cannot use --resource-version with multiple controllers")
}
currentSize := cmdutil.GetFlagInt(cmd, "current-replicas")
if currentSize != -1 && len(infos) > 1 {
return fmt.Errorf("cannot use --current-replicas with multiple controllers")
}
precondition := &kubectl.ScalePrecondition{Size: currentSize, ResourceVersion: resourceVersion}
retry := kubectl.NewRetryParams(kubectl.Interval, kubectl.Timeout)
var waitForReplicas *kubectl.RetryParams
if timeout := cmdutil.GetFlagDuration(cmd, "timeout"); timeout != 0 {
waitForReplicas = kubectl.NewRetryParams(kubectl.Interval, timeout)
}
errs := []error{}
for _, info := range infos {
if err := scaler.Scale(info.Namespace, info.Name, uint(count), precondition, retry, waitForReplicas); err != nil {
errs = append(errs, err)
continue
}
cmdutil.PrintSuccess(mapper, shortOutput, out, info.Mapping.Resource, info.Name, "scaled")
}
return utilerrors.NewAggregate(errs)
}
示例8: RunRollingUpdate
func RunRollingUpdate(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, options *RollingUpdateOptions) error {
if len(os.Args) > 1 && os.Args[1] == "rollingupdate" {
printDeprecationWarning("rolling-update", "rollingupdate")
}
err := validateArguments(cmd, options.Filenames, args)
if err != nil {
return err
}
deploymentKey := cmdutil.GetFlagString(cmd, "deployment-label-key")
filename := ""
image := cmdutil.GetFlagString(cmd, "image")
oldName := args[0]
rollback := cmdutil.GetFlagBool(cmd, "rollback")
period := cmdutil.GetFlagDuration(cmd, "update-period")
interval := cmdutil.GetFlagDuration(cmd, "poll-interval")
timeout := cmdutil.GetFlagDuration(cmd, "timeout")
dryrun := cmdutil.GetFlagBool(cmd, "dry-run")
outputFormat := cmdutil.GetFlagString(cmd, "output")
if len(options.Filenames) > 0 {
filename = options.Filenames[0]
}
cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
cmdTenant, enforceTenant, err := f.DefaultTenant()
if err != nil {
return err
}
client, err := f.Client()
if err != nil {
return err
}
var newRc *api.ReplicationController
// fetch rc
oldRc, err := client.ReplicationControllers(cmdNamespace).Get(oldName)
if err != nil {
if !errors.IsNotFound(err) || len(image) == 0 || len(args) > 1 {
return err
}
// We're in the middle of a rename, look for an RC with a source annotation of oldName
newRc, err := kubectl.FindSourceController(client, cmdNamespace, oldName)
if err != nil {
return err
}
return kubectl.Rename(client, newRc, oldName)
}
var keepOldName bool
var replicasDefaulted bool
mapper, typer := f.Object()
if len(filename) != 0 {
schema, err := f.Validator(cmdutil.GetFlagBool(cmd, "validate"), cmdutil.GetFlagString(cmd, "schema-cache-dir"))
if err != nil {
return err
}
request := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()).
Schema(schema).
NamespaceParam(cmdNamespace).DefaultNamespace().
TenantParam(cmdTenant).DefaultTenant().
FilenameParam(enforceTenant, enforceNamespace, filename).
Do()
obj, err := request.Object()
if err != nil {
return err
}
var ok bool
// Handle filename input from stdin. The resource builder always returns an api.List
// when creating resource(s) from a stream.
if list, ok := obj.(*api.List); ok {
if len(list.Items) > 1 {
return cmdutil.UsageError(cmd, "%s specifies multiple items", filename)
}
obj = list.Items[0]
}
newRc, ok = obj.(*api.ReplicationController)
if !ok {
if _, kind, err := typer.ObjectVersionAndKind(obj); err == nil {
return cmdutil.UsageError(cmd, "%s contains a %s not a ReplicationController", filename, kind)
}
glog.V(4).Infof("Object %#v is not a ReplicationController", obj)
return cmdutil.UsageError(cmd, "%s does not specify a valid ReplicationController", filename)
}
infos, err := request.Infos()
if err != nil || len(infos) != 1 {
glog.V(2).Infof("was not able to recover adequate information to discover if .spec.replicas was defaulted")
} else {
replicasDefaulted = isReplicasDefaulted(infos[0])
}
}
// If the --image option is specified, we need to create a new rc with at least one different selector
// than the old rc. This selector is the hash of the rc, which will differ because the new rc has a
//.........这里部分代码省略.........
示例9: RunGet
// RunGet implements the generic Get command
// TODO: convert all direct flag accessors to a struct and pass that instead of cmd
func RunGet(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, options *GetOptions) error {
selector := cmdutil.GetFlagString(cmd, "selector")
allNamespaces := cmdutil.GetFlagBool(cmd, "all-namespaces")
mapper, typer := f.Object()
var all bool = allNamespaces
cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
cmdTenant, enforceTenant, err := f.DefaultTenant()
if err != nil {
return err
}
if len(args) == 0 && len(options.Filenames) == 0 {
fmt.Fprint(out, "You must specify the type of resource to get. ", valid_resources, ` * componentstatuses (aka 'cs')
* endpoints (aka 'ep')
`)
return cmdutil.UsageError(cmd, "Required resource not specified.")
}
client, err := f.ClientConfig()
if err != nil {
return err
}
userNamespace := cmdutil.GetFlagString(cmd, "namespace")
if userNamespace == "" && strings.Index(client.Host, "https://") == 0 {
all = true
}
// handle watch separately since we cannot watch multiple resource types
isWatch, isWatchOnly := cmdutil.GetFlagBool(cmd, "watch"), cmdutil.GetFlagBool(cmd, "watch-only")
if isWatch || isWatchOnly {
r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()).
NamespaceParam(cmdNamespace).DefaultNamespace().AllNamespaces(all).
TenantParam(cmdTenant).DefaultTenant().
FilenameParam(enforceTenant, enforceNamespace, options.Filenames...).
SelectorParam(selector).
ResourceTypeOrNameArgs(true, args...).
SingleResourceType().
Latest().
Do()
err := r.Err()
if err != nil {
return err
}
infos, err := r.Infos()
if err != nil {
return err
}
if len(infos) != 1 {
return fmt.Errorf("watch is only supported on individual resources and resource collections - %d resources were found", len(infos))
}
info := infos[0]
mapping := info.ResourceMapping()
printer, err := f.PrinterForMapping(cmd, mapping, allNamespaces)
if err != nil {
return err
}
obj, err := r.Object()
if err != nil {
return err
}
rv, err := mapping.MetadataAccessor.ResourceVersion(obj)
if err != nil {
return err
}
// print the current object
if !isWatchOnly {
if err := printer.PrintObj(obj, out); err != nil {
return fmt.Errorf("unable to output the provided object: %v", err)
}
}
// print watched changes
w, err := r.Watch(rv)
if err != nil {
return err
}
kubectl.WatchLoop(w, func(e watch.Event) error {
return printer.PrintObj(e.Object, out)
})
return nil
}
b := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()).
NamespaceParam(cmdNamespace).DefaultNamespace().AllNamespaces(all).
TenantParam(cmdTenant).DefaultTenant().
FilenameParam(enforceTenant, enforceNamespace, options.Filenames...).
SelectorParam(selector).
ResourceTypeOrNameArgs(true, args...).
ContinueOnError().
Latest()
printer, generic, err := cmdutil.PrinterForCommand(cmd)
if err != nil {
//.........这里部分代码省略.........
示例10: RunEdit
func RunEdit(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, filenames []string) error {
var printer kubectl.ResourcePrinter
var ext string
switch format := cmdutil.GetFlagString(cmd, "output"); format {
case "json":
printer = &kubectl.JSONPrinter{}
ext = ".json"
case "yaml":
printer = &kubectl.YAMLPrinter{}
ext = ".yaml"
default:
return cmdutil.UsageError(cmd, "The flag 'output' must be one of yaml|json")
}
cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
cmdTenant, enforceTenant, err := f.DefaultTenant()
if err != nil {
return err
}
mapper, typer := f.Object()
rmap := &resource.Mapper{
ObjectTyper: typer,
RESTMapper: mapper,
ClientMapper: f.ClientMapperForCommand(),
}
r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()).
NamespaceParam(cmdNamespace).DefaultNamespace().
TenantParam(cmdTenant).DefaultTenant().
FilenameParam(enforceTenant, enforceNamespace, filenames...).
ResourceTypeOrNameArgs(true, args...).
Latest().
Flatten().
Do()
err = r.Err()
if err != nil {
return err
}
infos, err := r.Infos()
if err != nil {
return err
}
clientConfig, err := f.ClientConfig()
if err != nil {
return err
}
windowsLineEndings := cmdutil.GetFlagBool(cmd, "windows-line-endings")
edit := editor.NewDefaultEditor()
defaultVersion := cmdutil.OutputVersion(cmd, clientConfig.Version)
results := editResults{}
for {
objs, err := resource.AsVersionedObjects(infos, defaultVersion)
if err != nil {
return preservedFile(err, results.file, out)
}
// if input object is a list, traverse and edit each item one at a time
for _, obj := range objs {
// TODO: add an annotating YAML printer that can print inline comments on each field,
// including descriptions or validation errors
// generate the file to edit
buf := &bytes.Buffer{}
var w io.Writer = buf
if windowsLineEndings {
w = util.NewCRLFWriter(w)
}
if err := results.header.writeTo(w); err != nil {
return preservedFile(err, results.file, out)
}
if err := printer.PrintObj(obj, w); err != nil {
return preservedFile(err, results.file, out)
}
original := buf.Bytes()
// launch the editor
edited, file, err := edit.LaunchTempFile("kubectl-edit-", ext, buf)
if err != nil {
return preservedFile(err, results.file, out)
}
// cleanup any file from the previous pass
if len(results.file) > 0 {
os.Remove(results.file)
}
glog.V(4).Infof("User edited:\n%s", string(edited))
lines, err := hasLines(bytes.NewBuffer(edited))
if err != nil {
return preservedFile(err, file, out)
}
// Compare content without comments
if bytes.Equal(stripComments(original), stripComments(edited)) {
if len(results.edit) > 0 {
//.........这里部分代码省略.........
示例11: RunReplace
func RunReplace(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, options *ReplaceOptions) error {
if len(os.Args) > 1 && os.Args[1] == "update" {
printDeprecationWarning("replace", "update")
}
schema, err := f.Validator(cmdutil.GetFlagBool(cmd, "validate"), cmdutil.GetFlagString(cmd, "schema-cache-dir"))
if err != nil {
return err
}
cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
cmdTenant, enforceTenant, err := f.DefaultTenant()
if err != nil {
return err
}
force := cmdutil.GetFlagBool(cmd, "force")
if len(options.Filenames) == 0 {
return cmdutil.UsageError(cmd, "Must specify --filename to replace")
}
shortOutput := cmdutil.GetFlagString(cmd, "output") == "name"
if force {
return forceReplace(f, out, cmd, args, shortOutput, options)
}
mapper, typer := f.Object()
r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()).
Schema(schema).
ContinueOnError().
NamespaceParam(cmdNamespace).DefaultNamespace().
TenantParam(cmdTenant).DefaultTenant().
FilenameParam(enforceTenant, enforceNamespace, options.Filenames...).
Flatten().
Do()
err = r.Err()
if err != nil {
return err
}
return r.Visit(func(info *resource.Info, err error) error {
if err != nil {
return err
}
if err := kubectl.CreateOrUpdateAnnotation(cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag), info); err != nil {
return cmdutil.AddSourceToErr("replacing", info.Source, err)
}
// Serialize the object with the annotation applied.
obj, err := resource.NewHelper(info.Client, info.Mapping).Replace(info.Namespace, info.Name, true, info.Object)
if err != nil {
return cmdutil.AddSourceToErr("replacing", info.Source, err)
}
info.Refresh(obj, true)
printObjectSpecificMessage(obj, out)
cmdutil.PrintSuccess(mapper, shortOutput, out, info.Mapping.Resource, info.Name, "replaced")
return nil
})
}
示例12: forceReplace
func forceReplace(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, shortOutput bool, options *ReplaceOptions) error {
schema, err := f.Validator(cmdutil.GetFlagBool(cmd, "validate"), cmdutil.GetFlagString(cmd, "schema-cache-dir"))
if err != nil {
return err
}
cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
cmdTenant, enforceTenant, err := f.DefaultTenant()
if err != nil {
return err
}
for i, filename := range options.Filenames {
if filename == "-" {
tempDir, err := ioutil.TempDir("", "kubectl_replace_")
if err != nil {
return err
}
defer os.RemoveAll(tempDir)
tempFilename := filepath.Join(tempDir, "resource.stdin")
err = cmdutil.DumpReaderToFile(os.Stdin, tempFilename)
if err != nil {
return err
}
options.Filenames[i] = tempFilename
}
}
mapper, typer := f.Object()
r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()).
ContinueOnError().
NamespaceParam(cmdNamespace).DefaultNamespace().
TenantParam(cmdTenant).DefaultTenant().
FilenameParam(enforceTenant, enforceNamespace, options.Filenames...).
ResourceTypeOrNameArgs(false, args...).RequireObject(false).
Flatten().
Do()
err = r.Err()
if err != nil {
return err
}
//Replace will create a resource if it doesn't exist already, so ignore not found error
ignoreNotFound := true
// By default use a reaper to delete all related resources.
if cmdutil.GetFlagBool(cmd, "cascade") {
err = ReapResult(r, f, out, cmdutil.GetFlagBool(cmd, "cascade"), ignoreNotFound, cmdutil.GetFlagDuration(cmd, "timeout"), cmdutil.GetFlagInt(cmd, "grace-period"), shortOutput, mapper)
} else {
err = DeleteResult(r, out, ignoreNotFound, shortOutput, mapper)
}
if err != nil {
return err
}
time.Sleep(200 * time.Millisecond)
r = resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()).
Schema(schema).
ContinueOnError().
NamespaceParam(cmdNamespace).DefaultNamespace().
TenantParam(cmdTenant).DefaultTenant().
FilenameParam(enforceTenant, enforceNamespace, options.Filenames...).
Flatten().
Do()
err = r.Err()
if err != nil {
return err
}
count := 0
err = r.Visit(func(info *resource.Info, err error) error {
if err != nil {
return err
}
if err := kubectl.CreateOrUpdateAnnotation(cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag), info); err != nil {
return err
}
obj, err := resource.NewHelper(info.Client, info.Mapping).Create(info.Namespace, true, info.Object)
if err != nil {
return err
}
count++
info.Refresh(obj, true)
printObjectSpecificMessage(obj, out)
cmdutil.PrintSuccess(mapper, shortOutput, out, info.Mapping.Resource, info.Name, "replaced")
return nil
})
if err != nil {
return err
}
if count == 0 {
return fmt.Errorf("no objects passed to replace")
}
return nil
}