func RunStop(f cmdutil.Factory, cmd *cobra.Command, args []string, out io.Writer, options *resource.FilenameOptions) error { cmdNamespace, enforceNamespace, err := f.DefaultNamespace() if err != nil { return err } mapper, typer := f.Object() r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). ContinueOnError(). NamespaceParam(cmdNamespace).DefaultNamespace(). ResourceTypeOrNameArgs(false, args...). FilenameParam(enforceNamespace, options). 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" gracePeriod := cmdutil.GetFlagInt(cmd, "grace-period") waitForDeletion := false if gracePeriod == 0 { // To preserve backwards compatibility, but prevent accidental data loss, we convert --grace-period=0 // into --grace-period=1 and wait until the object is successfully deleted. gracePeriod = 1 waitForDeletion = true } return ReapResult(r, f, out, false, cmdutil.GetFlagBool(cmd, "ignore-not-found"), cmdutil.GetFlagDuration(cmd, "timeout"), gracePeriod, waitForDeletion, shortOutput, mapper, false) }
func (o *RolloutLatestOptions) Complete(f *clientcmd.Factory, cmd *cobra.Command, args []string, out io.Writer) error { if len(args) != 1 { return errors.New("one deployment config name is needed as argument.") } namespace, _, err := f.DefaultNamespace() if err != nil { return err } o.DryRun = kcmdutil.GetFlagBool(cmd, "dry-run") o.oc, o.kc, err = f.Clients() if err != nil { return err } o.mapper, o.typer = f.Object(false) o.infos, err = resource.NewBuilder(o.mapper, o.typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). ContinueOnError(). NamespaceParam(namespace). ResourceNames("deploymentconfigs", args[0]). SingleResourceType(). Do().Infos() if err != nil { return err } o.out = out o.output = kcmdutil.GetFlagString(cmd, "output") o.again = kcmdutil.GetFlagBool(cmd, "again") return nil }
// 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 }
func RunWhoAmI(f *clientcmd.Factory, out io.Writer, cmd *cobra.Command, args []string, o *WhoAmIOptions) error { if kcmdutil.GetFlagBool(cmd, "token") { cfg, err := f.OpenShiftClientConfig.ClientConfig() if err != nil { return err } if len(cfg.BearerToken) == 0 { return fmt.Errorf("no token is currently in use for this session") } fmt.Fprintf(out, "%s\n", cfg.BearerToken) return nil } if kcmdutil.GetFlagBool(cmd, "context") { cfg, err := f.OpenShiftClientConfig.RawConfig() if err != nil { return err } if len(cfg.CurrentContext) == 0 { return fmt.Errorf("no context has been set") } fmt.Fprintf(out, "%s\n", cfg.CurrentContext) return nil } client, _, err := f.Clients() if err != nil { return err } o.UserInterface = client.Users() o.Out = out _, err = o.WhoAmI() return err }
func RunVersion(f cmdutil.Factory, out io.Writer, cmd *cobra.Command) error { v := fmt.Sprintf("%#v", version.Get()) if cmdutil.GetFlagBool(cmd, "short") { v = version.Get().GitVersion } fmt.Fprintf(out, "Client Version: %s\n", v) if cmdutil.GetFlagBool(cmd, "client") { return nil } clientset, err := f.ClientSet() if err != nil { return err } serverVersion, err := clientset.Discovery().ServerVersion() if err != nil { return err } v = fmt.Sprintf("%#v", *serverVersion) if cmdutil.GetFlagBool(cmd, "short") { v = serverVersion.GitVersion } fmt.Fprintf(out, "Server Version: %s\n", v) return nil }
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) }
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, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). 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 } if err := kubectl.CreateOrUpdateAnnotation(cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag), info, f.JSONEncoder()); err != nil { return cmdutil.AddSourceToErr("creating", info.Source, err) } if cmdutil.ShouldRecord(cmd, info) { if err := cmdutil.RecordChangeCause(info.Object, f.Command()); 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 }
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 }) }
// RunLog retrieves a pod log func RunLog(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, p *logParams) error { if len(os.Args) > 1 && os.Args[1] == "log" { printDeprecationWarning("logs", "log") } if len(args) == 0 { return cmdutil.UsageError(cmd, "POD is required for log") } if len(args) > 2 { return cmdutil.UsageError(cmd, "log POD [CONTAINER]") } namespace, _, err := f.DefaultNamespace() if err != nil { return err } client, err := f.Client() if err != nil { return err } podID := args[0] pod, err := client.Pods(namespace).Get(podID) if err != nil { return err } // [-c CONTAINER] container := p.containerName if len(container) == 0 { // [CONTAINER] (container as arg not flag) is supported as legacy behavior. See PR #10519 for more details. if len(args) == 1 { if len(pod.Spec.Containers) != 1 { podContainersNames := []string{} for _, container := range pod.Spec.Containers { podContainersNames = append(podContainersNames, container.Name) } return fmt.Errorf("Pod %s has the following containers: %s; please specify the container to print logs for with -c", pod.ObjectMeta.Name, strings.Join(podContainersNames, ", ")) } container = pod.Spec.Containers[0].Name } else { container = args[1] } } follow := false if cmdutil.GetFlagBool(cmd, "follow") { follow = true } previous := false if cmdutil.GetFlagBool(cmd, "previous") { previous = true } return handleLog(client, namespace, podID, container, follow, previous, out) }
func createGeneratedObject(f *cmdutil.Factory, cmd *cobra.Command, generator kubectl.Generator, names []kubectl.GeneratorParam, params map[string]interface{}, overrides, namespace string) (runtime.Object, string, meta.RESTMapper, *meta.RESTMapping, error) { err := kubectl.ValidateParams(names, params) if err != nil { return nil, "", nil, nil, err } // TODO: Validate flag usage against selected generator. More tricky since --expose was added. obj, err := generator.Generate(params) if err != nil { return nil, "", nil, nil, err } mapper, typer := f.Object() groupVersionKind, err := typer.ObjectKind(obj) if err != nil { return nil, "", nil, nil, err } if len(overrides) > 0 { codec := runtime.NewCodec(f.JSONEncoder(), f.Decoder(true)) obj, err = cmdutil.Merge(codec, obj, overrides, groupVersionKind.Kind) if err != nil { return nil, "", nil, nil, err } } mapping, err := mapper.RESTMapping(groupVersionKind.GroupKind(), groupVersionKind.Version) if err != nil { return nil, "", nil, nil, err } client, err := f.ClientForMapping(mapping) if err != nil { return nil, "", nil, nil, err } // TODO: extract this flag to a central location, when such a location exists. if !cmdutil.GetFlagBool(cmd, "dry-run") { resourceMapper := &resource.Mapper{ ObjectTyper: typer, RESTMapper: mapper, ClientMapper: resource.ClientMapperFunc(f.ClientForMapping), Decoder: f.Decoder(true), } info, err := resourceMapper.InfoForObject(obj) if err != nil { return nil, "", nil, nil, err } if err := kubectl.CreateOrUpdateAnnotation(cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag), info, f.JSONEncoder()); err != nil { return nil, "", nil, nil, err } obj, err = resource.NewHelper(client, mapping).Create(namespace, false, info.Object) if err != nil { return nil, "", nil, nil, err } } return obj, groupVersionKind.Kind, mapper, mapping, err }
func (o *LogsOptions) Complete(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) error { containerName := cmdutil.GetFlagString(cmd, "container") switch len(args) { case 0: return cmdutil.UsageError(cmd, "POD is required for logs") case 1: o.ResourceArg = args[0] case 2: if cmd.Flag("container").Changed { return cmdutil.UsageError(cmd, "only one of -c, [CONTAINER] arg is allowed") } o.ResourceArg = args[0] containerName = args[1] default: return cmdutil.UsageError(cmd, "logs POD [-c CONTAINER]") } var err error o.Namespace, _, err = f.DefaultNamespace() if err != nil { return err } logOptions := &api.PodLogOptions{ Container: containerName, Follow: cmdutil.GetFlagBool(cmd, "follow"), Previous: cmdutil.GetFlagBool(cmd, "previous"), Timestamps: cmdutil.GetFlagBool(cmd, "timestamps"), } if sinceTime := cmdutil.GetFlagString(cmd, "since-time"); len(sinceTime) > 0 { t, err := api.ParseRFC3339(sinceTime, unversioned.Now) if err != nil { return err } logOptions.SinceTime = &t } if limit := cmdutil.GetFlagInt64(cmd, "limit-bytes"); limit != 0 { logOptions.LimitBytes = &limit } if tail := cmdutil.GetFlagInt64(cmd, "tail"); tail != -1 { logOptions.TailLines = &tail } if sinceSeconds := cmdutil.GetFlagDuration(cmd, "since"); sinceSeconds != 0 { // round up to the nearest second sec := int64(math.Ceil(float64(sinceSeconds) / float64(time.Second))) logOptions.SinceSeconds = &sec } o.Options = logOptions o.Mapper, o.Typer = f.Object() o.Decoder = f.Decoder(true) o.ClientMapper = resource.ClientMapperFunc(f.ClientForMapping) o.LogsForObject = f.LogsForObject o.Out = out return nil }
func createGeneratedObject(f *cmdutil.Factory, cmd *cobra.Command, generator kubectl.Generator, names []kubectl.GeneratorParam, params map[string]interface{}, overrides, namespace string) (runtime.Object, string, meta.RESTMapper, *meta.RESTMapping, error) { err := kubectl.ValidateParams(names, params) if err != nil { return nil, "", nil, nil, err } obj, err := generator.Generate(params) if err != nil { return nil, "", nil, nil, err } mapper, typer := f.Object() gvString, kind, err := typer.ObjectVersionAndKind(obj) if err != nil { return nil, "", nil, nil, err } gv, err := unversioned.ParseGroupVersion(gvString) if err != nil { return nil, "", nil, nil, err } gvk := gv.WithKind(kind) if len(overrides) > 0 { obj, err = cmdutil.Merge(obj, overrides, kind) if err != nil { return nil, "", nil, nil, err } } mapping, err := mapper.RESTMapping(gvk.GroupKind(), gvk.Version) if err != nil { return nil, "", nil, nil, err } client, err := f.RESTClient(mapping) if err != nil { return nil, "", nil, nil, err } // TODO: extract this flag to a central location, when such a location exists. if !cmdutil.GetFlagBool(cmd, "dry-run") { resourceMapper := &resource.Mapper{ObjectTyper: typer, RESTMapper: mapper, ClientMapper: f.ClientMapperForCommand()} info, err := resourceMapper.InfoForObject(obj) if err != nil { return nil, "", nil, nil, err } if err := kubectl.CreateOrUpdateAnnotation(cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag), info); err != nil { return nil, "", nil, nil, err } obj, err = resource.NewHelper(client, mapping).Create(namespace, false, info.Object) if err != nil { return nil, "", nil, nil, err } } return obj, kind, mapper, mapping, err }
// 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, err = cmdutil.OutputVersion(cmd, ®istered.EnabledVersionsForGroup(api.GroupName)[0]) if err != nil { return err } if !registered.IsEnabledVersion(o.outputVersion) { cmdutil.UsageError(cmd, "'%s' is not a registered version.", o.outputVersion) } // build the builder mapper, typer := f.Object() clientMapper := resource.ClientMapperFunc(f.ClientForMapping) if o.local { fmt.Fprintln(os.Stderr, "running in local mode...") o.builder = resource.NewBuilder(mapper, typer, resource.DisabledClientForMapping{ClientMapper: clientMapper}, f.Decoder(true)) } else { o.builder = resource.NewBuilder(mapper, typer, clientMapper, f.Decoder(true)) 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.FilenameOptions). 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.encoder = f.JSONEncoder() o.printer, _, err = kubectl.GetPrinter(outputFormat, templateFile, false, cmdutil.GetFlagBool(cmd, "allow-missing-template-keys")) if err != nil { return err } return nil }
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(cmdutil.GetIncludeThirdPartyAPIs(cmd)) r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). ContinueOnError(). NamespaceParam(cmdNamespace).DefaultNamespace(). FilenameParam(enforceNamespace, options.Recursive, 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 } } gracePeriod := cmdutil.GetFlagInt(cmd, "grace-period") if cmdutil.GetFlagBool(cmd, "now") { if gracePeriod != -1 { return fmt.Errorf("--now and --grace-period cannot be specified together") } gracePeriod = 0 } 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"), gracePeriod, shortOutput, mapper) } return DeleteResult(r, out, ignoreNotFound, shortOutput, mapper) }
func (o *CreateIdentityOptions) Complete(cmd *cobra.Command, f *clientcmd.Factory, args []string) error { switch len(args) { case 0: return fmt.Errorf("identity name in the format <PROVIDER_NAME>:<PROVIDER_USER_NAME> is required") case 1: parts := strings.Split(args[0], ":") if len(parts) != 2 { return fmt.Errorf("identity name in the format <PROVIDER_NAME>:<PROVIDER_USER_NAME> is required") } o.ProviderName = parts[0] o.ProviderUserName = parts[1] default: return fmt.Errorf("exactly one argument (username) is supported, not: %v", args) } o.DryRun = cmdutil.GetFlagBool(cmd, "dry-run") client, _, _, err := f.Clients() if err != nil { return err } o.IdentityClient = client.Identities() o.Mapper, _ = f.Object(false) o.OutputFormat = cmdutil.GetFlagString(cmd, "output") o.Printer = func(obj runtime.Object, out io.Writer) error { return f.PrintObject(cmd, o.Mapper, obj, out) } return nil }
func (o *CreateUserOptions) Complete(cmd *cobra.Command, f *clientcmd.Factory, args []string) error { switch len(args) { case 0: return fmt.Errorf("username is required") case 1: o.Name = args[0] default: return fmt.Errorf("exactly one argument (username) is supported, not: %v", args) } o.DryRun = cmdutil.GetFlagBool(cmd, "dry-run") client, _, err := f.Clients() if err != nil { return err } o.UserClient = client.Users() o.Mapper, _ = f.Object() o.OutputFormat = cmdutil.GetFlagString(cmd, "output") o.Printer = func(obj runtime.Object, out io.Writer) error { return f.PrintObject(cmd, o.Mapper, obj, out) } return nil }
func NewCmdApply(f cmdutil.Factory, out io.Writer) *cobra.Command { var options ApplyOptions cmd := &cobra.Command{ Use: "apply -f FILENAME", Short: "Apply a configuration to a resource by filename or stdin", Long: apply_long, Example: apply_example, Run: func(cmd *cobra.Command, args []string) { cmdutil.CheckErr(validateArgs(cmd, args)) cmdutil.CheckErr(cmdutil.ValidateOutputArgs(cmd)) cmdutil.CheckErr(validatePruneAll(options.Prune, cmdutil.GetFlagBool(cmd, "all"), options.Selector)) cmdutil.CheckErr(RunApply(f, cmd, out, &options)) }, } usage := "that contains the configuration to apply" cmdutil.AddFilenameOptionFlags(cmd, &options.FilenameOptions, usage) cmd.MarkFlagRequired("filename") cmd.Flags().Bool("overwrite", true, "Automatically resolve conflicts between the modified and live configuration by using values from the modified configuration") cmd.Flags().BoolVar(&options.Prune, "prune", false, "Automatically delete resource objects that do not appear in the configs") cmd.Flags().BoolVar(&options.Cascade, "cascade", true, "Only relevant during a prune. If true, cascade the deletion of the resources managed by pruned resources (e.g. Pods created by a ReplicationController).") cmd.Flags().IntVar(&options.GracePeriod, "grace-period", -1, "Period of time in seconds given to pruned resources to terminate gracefully. Ignored if negative.") cmdutil.AddValidateFlags(cmd) cmd.Flags().StringVarP(&options.Selector, "selector", "l", "", "Selector (label query) to filter on") cmd.Flags().Bool("all", false, "[-all] to select all the specified resources.") cmdutil.AddOutputFlagsForMutation(cmd) cmdutil.AddRecordFlag(cmd) cmdutil.AddInclude3rdPartyFlags(cmd) return cmd }
// RunExplain executes the appropriate steps to print a model's documentation func RunExplain(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) error { if len(args) != 1 { return cmdutil.UsageError(cmd, "We accept only this format: explain RESOURCE") } client, err := f.Client() if err != nil { return err } recursive := cmdutil.GetFlagBool(cmd, "recursive") apiV := cmdutil.GetFlagString(cmd, "api-version") swagSchema, err := kubectl.GetSwaggerSchema(apiV, client) if err != nil { return err } mapper, _ := f.Object() inModel, fieldsPath, err := kubectl.SplitAndParseResourceRequest(args[0], mapper) if err != nil { return err } return kubectl.PrintModelDescription(inModel, fieldsPath, out, swagSchema, recursive) }
func validateArguments(cmd *cobra.Command, filenames, args []string) error { deploymentKey := cmdutil.GetFlagString(cmd, "deployment-label-key") image := cmdutil.GetFlagString(cmd, "image") rollback := cmdutil.GetFlagBool(cmd, "rollback") if len(deploymentKey) == 0 { return cmdutil.UsageError(cmd, "--deployment-label-key can not be empty") } if len(filenames) > 1 { return cmdutil.UsageError(cmd, "May only specify a single filename for new controller") } if !rollback { if len(filenames) == 0 && len(image) == 0 { return cmdutil.UsageError(cmd, "Must specify --filename or --image for new controller") } if len(filenames) != 0 && len(image) != 0 { return cmdutil.UsageError(cmd, "--filename and --image can not both be specified") } } else { if len(filenames) != 0 || len(image) != 0 { return cmdutil.UsageError(cmd, "Don't specify --filename or --image on rollback") } } if len(args) < 1 { return cmdutil.UsageError(cmd, "Must specify the controller to update") } return nil }
// CreateSecretTLS is the implementation of the create secret tls command func CreateSecretTLS(f cmdutil.Factory, cmdOut io.Writer, cmd *cobra.Command, args []string) error { name, err := NameFromCommandArgs(cmd, args) if err != nil { return err } requiredFlags := []string{"cert", "key"} 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.SecretForTLSV1GeneratorName: generator = &kubectl.SecretForTLSGeneratorV1{ Name: name, Key: cmdutil.GetFlagString(cmd, "key"), Cert: cmdutil.GetFlagString(cmd, "cert"), } default: return cmdutil.UsageError(cmd, fmt.Sprintf("Generator: %s not supported.", generatorName)) } return RunCreateSubcommand(f, cmd, cmdOut, &CreateSubcommandOptions{ Name: name, StructuredGenerator: generator, DryRun: cmdutil.GetFlagBool(cmd, "dry-run"), OutputFormat: cmdutil.GetFlagString(cmd, "output"), }) }
// 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.GetFlagBool(cmd, "dry-run"), OutputFormat: cmdutil.GetFlagString(cmd, "output"), }) }
func NewCmdApply(f cmdutil.Factory, out io.Writer) *cobra.Command { var options ApplyOptions cmd := &cobra.Command{ Use: "apply -f FILENAME", Short: "Apply a configuration to a resource by filename or stdin", Long: apply_long, Example: apply_example, Run: func(cmd *cobra.Command, args []string) { cmdutil.CheckErr(validateArgs(cmd, args)) cmdutil.CheckErr(cmdutil.ValidateOutputArgs(cmd)) cmdutil.CheckErr(validatePruneAll(options.Prune, cmdutil.GetFlagBool(cmd, "all"), options.Selector)) cmdutil.CheckErr(RunApply(f, cmd, out, &options)) }, } usage := "that contains the configuration to apply" cmdutil.AddFilenameOptionFlags(cmd, &options.FilenameOptions, usage) cmd.MarkFlagRequired("filename") cmd.Flags().Bool("overwrite", true, "Automatically resolve conflicts between the modified and live configuration by using values from the modified configuration") cmd.Flags().BoolVar(&options.Prune, "prune", false, "Automatically delete resource objects that do not appear in the configs and are created by either apply or create --save-config. Should be used with either -l or --all.") cmd.Flags().BoolVar(&options.Cascade, "cascade", true, "Only relevant during a prune or a force apply. If true, cascade the deletion of the resources managed by pruned or deleted resources (e.g. Pods created by a ReplicationController).") cmd.Flags().IntVar(&options.GracePeriod, "grace-period", -1, "Only relevant during a prune or a force apply. Period of time in seconds given to pruned or deleted resources to terminate gracefully. Ignored if negative.") cmd.Flags().BoolVar(&options.Force, "force", false, fmt.Sprintf("Delete and re-create the specified resource, when PATCH encounters conflict and has retried for %d times.", maxPatchRetry)) cmd.Flags().DurationVar(&options.Timeout, "timeout", 0, "Only relevant during a force apply. The length of time to wait before giving up on a delete of the old resource, zero means determine a timeout from the size of the object. Any other values should contain a corresponding time unit (e.g. 1s, 2m, 3h).") cmdutil.AddValidateFlags(cmd) cmd.Flags().StringVarP(&options.Selector, "selector", "l", "", "Selector (label query) to filter on") cmd.Flags().Bool("all", false, "[-all] to select all the specified resources.") cmd.Flags().StringArray("prune-whitelist", []string{}, "Overwrite the default whitelist with <group/version/kind> for --prune") cmdutil.AddDryRunFlag(cmd) cmdutil.AddPrinterFlags(cmd) cmdutil.AddRecordFlag(cmd) cmdutil.AddInclude3rdPartyFlags(cmd) return cmd }
// validateFlags filters out flags that are not supposed to be used // when exposing a resource; depends on the provided generator func validateFlags(cmd *cobra.Command, generator string) error { invalidFlags := []string{} switch generator { case "service/v1", "service/v2": if len(cmdutil.GetFlagString(cmd, "hostname")) != 0 { invalidFlags = append(invalidFlags, "--hostname") } if len(cmdutil.GetFlagString(cmd, "path")) != 0 { invalidFlags = append(invalidFlags, "--path") } case "route/v1": if len(cmdutil.GetFlagString(cmd, "protocol")) != 0 { invalidFlags = append(invalidFlags, "--protocol") } if len(cmdutil.GetFlagString(cmd, "type")) != 0 { invalidFlags = append(invalidFlags, "--type") } if len(cmdutil.GetFlagString(cmd, "selector")) != 0 { invalidFlags = append(invalidFlags, "--selector") } if len(cmdutil.GetFlagString(cmd, "container-port")) != 0 { invalidFlags = append(invalidFlags, "--container-port") } if len(cmdutil.GetFlagString(cmd, "target-port")) != 0 { invalidFlags = append(invalidFlags, "--target-port") } if len(cmdutil.GetFlagString(cmd, "external-ip")) != 0 { invalidFlags = append(invalidFlags, "--external-ip") } if len(cmdutil.GetFlagString(cmd, "port")) != 0 { invalidFlags = append(invalidFlags, "--port") } if len(cmdutil.GetFlagString(cmd, "load-balancer-ip")) != 0 { invalidFlags = append(invalidFlags, "--load-balancer-ip") } if len(cmdutil.GetFlagString(cmd, "session-affinity")) != 0 { invalidFlags = append(invalidFlags, "--session-affinity") } if cmdutil.GetFlagBool(cmd, "create-external-load-balancer") { invalidFlags = append(invalidFlags, "--create-external-load-balancer") } } msg := "" switch len(invalidFlags) { case 0: return nil case 1: msg = invalidFlags[0] default: commaSeparated, last := invalidFlags[:len(invalidFlags)-1], invalidFlags[len(invalidFlags)-1] msg = fmt.Sprintf("%s or %s", strings.Join(commaSeparated, ", "), last) } return fmt.Errorf("cannot use %s when generating a %s", msg, strings.Split(generator, "/")[0]) }
func createGeneratedObject(f *cmdutil.Factory, cmd *cobra.Command, generator kubectl.Generator, names []kubectl.GeneratorParam, params map[string]interface{}, overrides, namespace string) (runtime.Object, string, meta.RESTMapper, *meta.RESTMapping, error) { err := kubectl.ValidateParams(names, params) if err != nil { return nil, "", nil, nil, err } obj, err := generator.Generate(params) if err != nil { return nil, "", nil, nil, err } mapper, typer := f.Object() version, kind, err := typer.ObjectVersionAndKind(obj) if err != nil { return nil, "", nil, nil, err } if len(overrides) > 0 { obj, err = cmdutil.Merge(obj, overrides, kind) if err != nil { return nil, "", nil, nil, err } } mapping, err := mapper.RESTMapping(kind, version) if err != nil { return nil, "", nil, nil, err } client, err := f.RESTClient(mapping) if err != nil { return nil, "", nil, nil, err } // TODO: extract this flag to a central location, when such a location exists. if !cmdutil.GetFlagBool(cmd, "dry-run") { resourceMapper := &resource.Mapper{ObjectTyper: typer, RESTMapper: mapper, ClientMapper: f.ClientMapperForCommand()} info, err := resourceMapper.InfoForObject(obj) if err != nil { return nil, "", nil, nil, err } // Serialize the configuration into an annotation. if err := kubectl.UpdateApplyAnnotation(info); err != nil { return nil, "", nil, nil, err } // Serialize the object with the annotation applied. data, err := mapping.Codec.Encode(info.Object) if err != nil { return nil, "", nil, nil, err } obj, err = resource.NewHelper(client, mapping).Create(namespace, false, data) if err != nil { return nil, "", nil, nil, err } } return obj, kind, mapper, mapping, err }
func (o *LoginOptions) Complete(f *osclientcmd.Factory, cmd *cobra.Command, args []string) error { kubeconfig, err := f.OpenShiftClientConfig.RawConfig() o.StartingKubeConfig = &kubeconfig if err != nil { if !os.IsNotExist(err) { return err } // build a valid object to use if we failed on a non-existent file o.StartingKubeConfig = kclientcmdapi.NewConfig() } addr := flagtypes.Addr{Value: "localhost:8443", DefaultScheme: "https", DefaultPort: 8443, AllowPrefix: true}.Default() if serverFlag := kcmdutil.GetFlagString(cmd, "server"); len(serverFlag) > 0 { if err := addr.Set(serverFlag); err != nil { return err } o.Server = addr.String() } else if len(args) == 1 { if err := addr.Set(args[0]); err != nil { return err } o.Server = addr.String() } else if len(o.Server) == 0 { if defaultContext, defaultContextExists := o.StartingKubeConfig.Contexts[o.StartingKubeConfig.CurrentContext]; defaultContextExists { if cluster, exists := o.StartingKubeConfig.Clusters[defaultContext.Cluster]; exists { o.Server = cluster.Server } } } o.CertFile = kcmdutil.GetFlagString(cmd, "client-certificate") o.KeyFile = kcmdutil.GetFlagString(cmd, "client-key") o.APIVersion = kcmdutil.GetFlagString(cmd, "api-version") // if the API version isn't explicitly passed, use the API version from the default context (same rules as the server above) if len(o.APIVersion) == 0 { if defaultContext, defaultContextExists := o.StartingKubeConfig.Contexts[o.StartingKubeConfig.CurrentContext]; defaultContextExists { if cluster, exists := o.StartingKubeConfig.Clusters[defaultContext.Cluster]; exists { o.APIVersion = cluster.APIVersion } } } o.CAFile = kcmdutil.GetFlagString(cmd, "certificate-authority") o.InsecureTLS = kcmdutil.GetFlagBool(cmd, "insecure-skip-tls-verify") o.Token = kcmdutil.GetFlagString(cmd, "token") o.DefaultNamespace, _, _ = f.OpenShiftClientConfig.Namespace() o.PathOptions = config.NewPathOptions(cmd) return nil }
// CreatePassthroughRoute implements the behavior to run the create passthrough route command. func CreatePassthroughRoute(f *clientcmd.Factory, out io.Writer, cmd *cobra.Command, args []string) error { oc, kc, err := f.Clients() if err != nil { return err } ns, _, err := f.DefaultNamespace() if err != nil { return err } serviceName, err := resolveServiceName(f, kcmdutil.GetFlagString(cmd, "service")) if err != nil { return err } routeName, err := resolveRouteName(args) if err != nil { return err } route, err := cmdutil.UnsecuredRoute(kc, ns, routeName, serviceName, kcmdutil.GetFlagString(cmd, "port")) if err != nil { return err } route.Spec.Host = kcmdutil.GetFlagString(cmd, "hostname") route.Spec.TLS = new(api.TLSConfig) route.Spec.TLS.Termination = api.TLSTerminationPassthrough dryRun := kcmdutil.GetFlagBool(cmd, "dry-run") actualRoute := route if !dryRun { actualRoute, err = oc.Routes(ns).Create(route) if err != nil { return err } } mapper, typer := f.Object(false) resourceMapper := &resource.Mapper{ ObjectTyper: typer, RESTMapper: mapper, ClientMapper: resource.ClientMapperFunc(f.ClientForMapping), } info, err := resourceMapper.InfoForObject(actualRoute, nil) if err != nil { return err } created := "created" if dryRun { created = "created (DRY RUN)" } shortOutput := kcmdutil.GetFlagString(cmd, "output") == "name" kcmdutil.PrintSuccess(mapper, shortOutput, out, info.Mapping.Resource, info.Name, created) return nil }
// 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 }
func RunReplace(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) error { if len(os.Args) > 1 && os.Args[1] == "update" { printDeprecationWarning("replace", "update") } schema, err := f.Validator() if err != nil { return err } cmdNamespace, enforceNamespace, err := f.DefaultNamespace() if err != nil { return err } force := cmdutil.GetFlagBool(cmd, "force") filenames := cmdutil.GetFlagStringSlice(cmd, "filename") if len(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, filenames, shortOutput) } mapper, typer := f.Object() r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()). Schema(schema). ContinueOnError(). NamespaceParam(cmdNamespace).DefaultNamespace(). FilenameParam(enforceNamespace, 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 } data, err := info.Mapping.Codec.Encode(info.Object) if err != nil { return cmdutil.AddSourceToErr("replacing", info.Source, err) } obj, err := resource.NewHelper(info.Client, info.Mapping).Replace(info.Namespace, info.Name, true, data) 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 }) }
// RunExplain executes the appropriate steps to print a model's documentation func RunExplain(f *cmdutil.Factory, out, cmdErr io.Writer, cmd *cobra.Command, args []string) error { if len(args) == 0 { fmt.Fprint(cmdErr, "You must specify the type of resource to explain. ", valid_resources) return cmdutil.UsageError(cmd, "Required resource not specified.") } if len(args) > 1 { return cmdutil.UsageError(cmd, "We accept only this format: explain RESOURCE") } recursive := cmdutil.GetFlagBool(cmd, "recursive") apiVersionString := cmdutil.GetFlagString(cmd, "api-version") apiVersion := unversioned.GroupVersion{} mapper, _ := f.Object(cmdutil.GetIncludeThirdPartyAPIs(cmd)) // TODO: After we figured out the new syntax to separate group and resource, allow // the users to use it in explain (kubectl explain <group><syntax><resource>). // Refer to issue #16039 for why we do this. Refer to PR #15808 that used "/" syntax. inModel, fieldsPath, err := kubectl.SplitAndParseResourceRequest(args[0], mapper) if err != nil { return err } // TODO: We should deduce the group for a resource by discovering the supported resources at server. fullySpecifiedGVR, groupResource := unversioned.ParseResourceArg(inModel) gvk := unversioned.GroupVersionKind{} if fullySpecifiedGVR != nil { gvk, _ = mapper.KindFor(*fullySpecifiedGVR) } if gvk.Empty() { gvk, err = mapper.KindFor(groupResource.WithVersion("")) if err != nil { return err } } if len(apiVersionString) == 0 { groupMeta, err := registered.Group(gvk.Group) if err != nil { return err } apiVersion = groupMeta.GroupVersion } else { apiVersion, err = unversioned.ParseGroupVersion(apiVersionString) if err != nil { return nil } } schema, err := f.SwaggerSchema(apiVersion.WithKind(gvk.Kind)) if err != nil { return err } return kubectl.PrintModelDescription(inModel, fieldsPath, out, schema, recursive) }
func Run(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) error { if len(os.Args) > 1 && os.Args[1] == "run-container" { printDeprecationWarning("run", "run-container") } if len(args) != 1 { return cmdutil.UsageError(cmd, "NAME is required for run") } namespace, _, err := f.DefaultNamespace() if err != nil { return err } client, err := f.Client() if err != nil { return err } generatorName := cmdutil.GetFlagString(cmd, "generator") generator, found := f.Generator(generatorName) if !found { return cmdutil.UsageError(cmd, fmt.Sprintf("Generator: %s not found.", generator)) } names := generator.ParamNames() params := kubectl.MakeParams(cmd, names) params["name"] = args[0] err = kubectl.ValidateParams(names, params) if err != nil { return err } controller, err := generator.Generate(params) if err != nil { return err } inline := cmdutil.GetFlagString(cmd, "overrides") if len(inline) > 0 { controller, err = cmdutil.Merge(controller, inline, "ReplicationController") if err != nil { return err } } // TODO: extract this flag to a central location, when such a location exists. if !cmdutil.GetFlagBool(cmd, "dry-run") { controller, err = client.ReplicationControllers(namespace).Create(controller.(*api.ReplicationController)) if err != nil { return err } } return f.PrintObject(cmd, controller, out) }