本文整理汇总了Golang中vulcan/kubernetes/pkg/kubectl/resource.NewBuilder函数的典型用法代码示例。如果您正苦于以下问题:Golang NewBuilder函数的具体用法?Golang NewBuilder怎么用?Golang NewBuilder使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewBuilder函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: 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
}
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().
FilenameParam(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
}
// Serialize the configuration into an annotation.
if err := kubectl.UpdateApplyAnnotation(info); err != nil {
return 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
})
}
示例2: Complete
// Complete collects information required to run Convert command from command line.
func (o *ConvertOptions) Complete(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) (err error) {
o.outputVersion = cmdutil.OutputVersion(cmd, latest.GroupOrDie("").Version)
if !registered.IsRegisteredAPIVersion(o.outputVersion) {
cmdutil.UsageError(cmd, "'%s' is not a registered version.", o.outputVersion)
}
// build the builder
mapper, typer := f.Object()
if o.local {
fmt.Fprintln(out, "running in local mode...")
o.builder = resource.NewBuilder(mapper, typer, f.NilClientMapperForCommand())
} else {
o.builder = resource.NewBuilder(mapper, typer, f.ClientMapperForCommand())
schema, err := f.Validator(cmdutil.GetFlagBool(cmd, "validate"), cmdutil.GetFlagString(cmd, "schema-cache-dir"))
if err != nil {
return err
}
o.builder = o.builder.Schema(schema)
}
cmdNamespace, _, err := f.DefaultNamespace()
if err != nil {
return err
}
o.builder = o.builder.NamespaceParam(cmdNamespace).
ContinueOnError().
FilenameParam(false, o.filenames...).
Flatten()
// build the printer
o.out = out
outputFormat := cmdutil.GetFlagString(cmd, "output")
templateFile := cmdutil.GetFlagString(cmd, "template")
if len(outputFormat) == 0 {
if len(templateFile) == 0 {
outputFormat = "yaml"
} else {
outputFormat = "template"
}
}
o.printer, _, err = kubectl.GetPrinter(outputFormat, templateFile)
if err != nil {
return err
}
return nil
}
示例3: 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
}
mapper, typer := f.Object()
r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()).
Schema(schema).
ContinueOnError().
NamespaceParam(cmdNamespace).DefaultNamespace().
FilenameParam(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
}
// Update the annotation used by kubectl apply
if err := kubectl.UpdateApplyAnnotation(info); err != nil {
return cmdutil.AddSourceToErr("creating", info.Source, err)
}
obj, err := resource.NewHelper(info.Client, info.Mapping).Create(info.Namespace, true, info.Object)
if err != nil {
return cmdutil.AddSourceToErr("creating", info.Source, err)
}
count++
info.Refresh(obj, true)
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
}
示例4: RunClusterInfo
func RunClusterInfo(factory *cmdutil.Factory, out io.Writer, cmd *cobra.Command) error {
if len(os.Args) > 1 && os.Args[1] == "clusterinfo" {
printDeprecationWarning("cluster-info", "clusterinfo")
}
client, err := factory.ClientConfig()
if err != nil {
return err
}
printService(out, "Kubernetes master", client.Host)
mapper, typer := factory.Object()
cmdNamespace := cmdutil.GetFlagString(cmd, "namespace")
if cmdNamespace == "" {
cmdNamespace = api.NamespaceSystem
}
// TODO use generalized labels once they are implemented (#341)
b := resource.NewBuilder(mapper, typer, factory.ClientMapperForCommand()).
NamespaceParam(cmdNamespace).DefaultNamespace().
SelectorParam("kubernetes.io/cluster-service=true").
ResourceTypeOrNameArgs(false, []string{"services"}...).
Latest()
b.Do().Visit(func(r *resource.Info, err error) error {
if err != nil {
return err
}
services := r.Object.(*api.ServiceList).Items
for _, service := range services {
var link string
if len(service.Status.LoadBalancer.Ingress) > 0 {
ingress := service.Status.LoadBalancer.Ingress[0]
ip := ingress.IP
if ip == "" {
ip = ingress.Hostname
}
for _, port := range service.Spec.Ports {
link += "http://" + ip + ":" + strconv.Itoa(port.Port) + " "
}
} else {
link = client.Host + "/api/" + client.Version + "/proxy/namespaces/" + service.ObjectMeta.Namespace + "/services/" + service.ObjectMeta.Name
}
name := service.ObjectMeta.Labels["kubernetes.io/name"]
if len(name) == 0 {
name = service.ObjectMeta.Name
}
printService(out, name, link)
}
return nil
})
return nil
// TODO consider printing more information about cluster
}
示例5: deleteHandler
func (d *Deployer) deleteHandler(request *restful.Request, response *restful.Response) {
var obj runtime.Object
var data interface{}
start := time.Now()
err := request.ReadEntity(&data)
if err != nil {
message := fmt.Sprintf("read post entity failed: %#v", err)
response.WriteAsJson(ApiResult{message, obj, false})
return
}
s, _ := json.Marshal(data)
ctime := time.Now().UTC().UnixNano()
tmp := fmt.Sprintf("/tmp/deploy_delete_%d.json", ctime)
file, err := os.OpenFile(tmp, os.O_CREATE|os.O_RDWR, 0644)
if os.IsExist(err) {
os.Remove(tmp)
}
file.WriteString(string(s))
// clean tmp created file
defer func() {
file.Close()
os.Remove(tmp)
WriteAccessLog(start, request, response)
}()
cmdNamespace, enforceNamespace, err := d.Factory.DefaultNamespace()
if err != nil {
message := fmt.Sprintf("get namespace error: %#v", err)
response.WriteAsJson(ApiResult{message, obj, false})
}
mapper, typer := d.Factory.Object()
r := resource.NewBuilder(mapper, typer, d.Factory.ClientMapperForCommand()).
ContinueOnError().
NamespaceParam(cmdNamespace).DefaultNamespace().
FilenameParam(enforceNamespace, tmp).
RequireObject(false).
Flatten().
Do()
err = r.Err()
if err != nil {
message := fmt.Sprintf("reousrce new builder failed: %#v", err)
response.WriteAsJson(ApiResult{message, obj, false})
return
}
ReapResult(r, d.Factory, response, true, true, 0, -1)
DeleteResult(r, response, true)
}
示例6: RunDescribe
func RunDescribe(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, options *DescribeOptions) error {
selector := cmdutil.GetFlagString(cmd, "selector")
cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
if len(args) == 0 && len(options.Filenames) == 0 {
fmt.Fprint(out, "You must specify the type of resource to describe. ", valid_resources)
return cmdutil.UsageError(cmd, "Required resource not specified.")
}
mapper, typer := f.Object()
r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()).
ContinueOnError().
NamespaceParam(cmdNamespace).DefaultNamespace().
FilenameParam(enforceNamespace, options.Filenames...).
SelectorParam(selector).
ResourceTypeOrNameArgs(true, args...).
Flatten().
Do()
err = r.Err()
if err != nil {
return err
}
allErrs := []error{}
infos, err := r.Infos()
if err != nil {
if apierrors.IsNotFound(err) && len(args) == 2 {
return DescribeMatchingResources(mapper, typer, f, cmdNamespace, args[0], args[1], out, err)
}
allErrs = append(allErrs, err)
}
for _, info := range infos {
mapping := info.ResourceMapping()
describer, err := f.Describer(mapping)
if err != nil {
allErrs = append(allErrs, err)
continue
}
s, err := describer.Describe(info.Namespace, info.Name)
if err != nil {
allErrs = append(allErrs, err)
continue
}
fmt.Fprintf(out, "%s\n\n", s)
}
return utilerrors.NewAggregate(allErrs)
}
示例7: 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
}
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().
FilenameParam(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
}
示例8: 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
}
// 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().
FilenameParam(enforceNamespace, o.filenames...).
ResourceTypeOrNameArgs(o.all, o.resources...).
Flatten().
Latest()
return nil
}
示例9: 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
}
deleteAll := cmdutil.GetFlagBool(cmd, "all")
mapper, typer := f.Object()
r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()).
ContinueOnError().
NamespaceParam(cmdNamespace).DefaultNamespace().
FilenameParam(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)
}
示例10: 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
}
mapper, typer := f.Object()
r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()).
ContinueOnError().
NamespaceParam(cmdNamespace).DefaultNamespace().
ResourceTypeOrNameArgs(false, args...).
FilenameParam(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)
}
示例11: DescribeMatchingResources
func DescribeMatchingResources(mapper meta.RESTMapper, typer runtime.ObjectTyper, f *cmdutil.Factory, namespace, rsrc, prefix string, out io.Writer, originalError error) error {
r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()).
NamespaceParam(namespace).DefaultNamespace().
ResourceTypeOrNameArgs(true, rsrc).
SingleResourceType().
Flatten().
Do()
mapping, err := r.ResourceMapping()
if err != nil {
return err
}
describer, err := f.Describer(mapping)
if err != nil {
return err
}
infos, err := r.Infos()
if err != nil {
return err
}
isFound := false
for ix := range infos {
info := infos[ix]
if strings.HasPrefix(info.Name, prefix) {
isFound = true
s, err := describer.Describe(info.Namespace, info.Name)
if err != nil {
return err
}
fmt.Fprintf(out, "%s\n", s)
}
}
if !isFound {
return originalError
}
return nil
}
示例12: RunAutoscale
func RunAutoscale(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, filenames []string) error {
namespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
// validate flags
if err := validateFlags(cmd); err != nil {
return err
}
mapper, typer := f.Object()
r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()).
ContinueOnError().
NamespaceParam(namespace).DefaultNamespace().
FilenameParam(enforceNamespace, 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.CanBeAutoscaled(mapping.Kind); 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
params["default-name"] = name
params["scaleRef-kind"] = mapping.Kind
params["scaleRef-name"] = name
params["scaleRef-apiVersion"] = mapping.APIVersion
if err = kubectl.ValidateParams(names, params); err != nil {
return err
}
// Generate new object
object, err := generator.Generate(params)
if err != nil {
return err
}
resourceMapper := &resource.Mapper{ObjectTyper: typer, RESTMapper: mapper, ClientMapper: f.ClientMapperForCommand()}
hpa, err := resourceMapper.InfoForObject(object)
if err != nil {
return err
}
// TODO: extract this flag to a central location, when such a location exists.
if cmdutil.GetFlagBool(cmd, "dry-run") {
return f.PrintObject(cmd, object, out)
}
// Serialize the configuration into an annotation.
if err := kubectl.UpdateApplyAnnotation(hpa); err != nil {
return err
}
object, err = resource.NewHelper(hpa.Client, hpa.Mapping).Create(namespace, false, object)
if err != nil {
return err
}
if len(cmdutil.GetFlagString(cmd, "output")) > 0 {
return f.PrintObject(cmd, object, out)
}
cmdutil.PrintSuccess(mapper, false, out, info.Mapping.Resource, info.Name, "autoscaled")
return nil
}
示例13: listHandler
func (d *Deployer) listHandler(request *restful.Request, response *restful.Response) {
var list runtime.Object
start := time.Now()
defer func() {
WriteAccessLog(start, request, response)
}()
mapper, typer := d.Factory.Object()
// request parameters
// namespace string # whether query between all-spaces
// outFormat string # format as json, yaml, etc.
// template string # whether use template to show result.
// kind string # resource kind for request.
// name string # resources name, multiple can separate by ,
// selector string # info selectors saved in etcd.
selector := request.QueryParameter("selector")
namespace := request.QueryParameter("namespace")
name := request.QueryParameter("name")
kind := request.PathParameter("kind")
template := request.QueryParameter("template")
if namespace == "" {
cmdNamespace, _, err := d.Factory.DefaultNamespace()
if err != nil {
message := fmt.Sprintf("get defaule namespace error %#v", err)
response.WriteAsJson(ApiResult{message, list, false})
return
}
namespace = cmdNamespace
}
var args = []string{kind}
if len(name) > 0 {
args = append(args, strings.Split(name, ",")...)
}
if len(kind) == 0 {
message := fmt.Sprintf("get resource kind unspecified")
response.WriteAsJson(ApiResult{message, list, false})
return
}
builder := resource.NewBuilder(mapper, typer, d.Factory.ClientMapperForCommand()).
NamespaceParam(namespace).DefaultNamespace().AllNamespaces(namespace == "all").
SelectorParam(selector).
ResourceTypeOrNameArgs(true, args...).
ContinueOnError().
Latest()
_, generic, err := PrinterForCommand("json", template)
if err != nil {
message := fmt.Sprintf("get resource kind unspecified: %#v", err)
response.WriteAsJson(ApiResult{message, list, false})
return
}
if generic {
clientConfig, err := d.Factory.ClientConfig()
if err != nil {
message := fmt.Sprintf("connect to API server failed: %#v", err)
response.WriteAsJson(ApiResult{message, list, false})
return
}
version := clientConfig.Version
singular := false
r := builder.Flatten().Do()
infos, err := r.IntoSingular(&singular).Infos()
if err != nil {
message := fmt.Sprintf("change into Singular failed: %#v", err)
response.WriteAsJson(ApiResult{message, list, false})
return
}
// the outermost object will be converted to the output-version, but inner
// objects can use their mappings
obj, err := resource.AsVersionedObject(infos, !singular, version)
if err != nil {
message := fmt.Sprintf("conversion object version failed: %#v", err)
response.WriteAsJson(ApiResult{message, list, false})
return
}
response.WriteAsJson(ApiResult{"", obj, true})
return
}
// use the default printer for each object
builder.Do().Visit(func(r *resource.Info) error {
_, err := d.PrinterForMapping("json", template, r.Mapping, namespace == "all")
if err != nil {
response.WriteAsJson(ApiResult{err.Error(), r.Object, false})
return err
}
response.WriteAsJson(ApiResult{"", r.Object, true})
return nil
})
}
示例14: RunLabel
func RunLabel(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, options *LabelOptions) error {
resources, labelArgs := []string{}, []string{}
first := true
for _, s := range args {
isLabel := strings.Contains(s, "=") || strings.HasSuffix(s, "-")
switch {
case first && isLabel:
first = false
fallthrough
case !first && isLabel:
labelArgs = append(labelArgs, s)
case first && !isLabel:
resources = append(resources, s)
case !first && !isLabel:
return cmdutil.UsageError(cmd, "all resources must be specified before label changes: %s", s)
}
}
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()
b := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()).
ContinueOnError().
NamespaceParam(cmdNamespace).DefaultNamespace().
FilenameParam(enforceNamespace, 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
if cmdutil.GetFlagBool(cmd, "dry-run") {
err = labelFunc(info.Object, overwrite, resourceVersion, lbls, remove)
if err != nil {
return err
}
outputObj = info.Object
} else {
name, namespace, obj := info.Name, info.Namespace, info.Object
oldData, err := json.Marshal(obj)
if err != nil {
return err
}
if err := labelFunc(obj, overwrite, resourceVersion, lbls, remove); err != nil {
return err
}
newData, err := json.Marshal(obj)
if err != nil {
return err
}
patchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, obj)
if err != nil {
return err
}
mapping := info.ResourceMapping()
client, err := f.RESTClient(mapping)
if err != nil {
return err
}
helper := resource.NewHelper(client, mapping)
outputObj, err = helper.Patch(namespace, name, api.StrategicMergePatchType, patchBytes)
if err != nil {
return err
//.........这里部分代码省略.........
示例15: 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
}
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().
FilenameParam(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
// different image.
if len(image) != 0 {
keepOldName = len(args) == 1
newName := findNewName(args, oldRc)
if newRc, err = kubectl.LoadExistingNextReplicationController(client, cmdNamespace, newName); err != nil {
//.........这里部分代码省略.........