本文整理汇总了Golang中vulcan/kubernetes/pkg/kubectl/cmd/util.GetFlagString函数的典型用法代码示例。如果您正苦于以下问题:Golang GetFlagString函数的具体用法?Golang GetFlagString怎么用?Golang GetFlagString使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了GetFlagString函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: validateArguments
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
}
示例2: validateArguments
func validateArguments(cmd *cobra.Command, filenames, args []string) (deploymentKey, filename, image, oldName string, err error) {
deploymentKey = cmdutil.GetFlagString(cmd, "deployment-label-key")
image = cmdutil.GetFlagString(cmd, "image")
filename = ""
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 specificy a single filename for new controller")
}
if len(filenames) > 0 {
filename = filenames[0]
}
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")
}
if len(args) < 1 {
return "", "", "", "", cmdutil.UsageError(cmd, "Must specify the controller to update")
}
return deploymentKey, filename, image, args[0], nil
}
示例3: 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
})
}
示例4: 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
}
示例5: NewCmdScale
// NewCmdScale returns a cobra command with the appropriate configuration and flags to run scale
func NewCmdScale(f *cmdutil.Factory, out io.Writer) *cobra.Command {
options := &ScaleOptions{}
cmd := &cobra.Command{
Use: "scale [--resource-version=version] [--current-replicas=count] --replicas=COUNT (-f FILENAME | TYPE NAME)",
// resize is deprecated
Aliases: []string{"resize"},
Short: "Set a new size for a Replication Controller.",
Long: scale_long,
Example: scale_example,
Run: func(cmd *cobra.Command, args []string) {
cmdutil.CheckErr(cmdutil.ValidateOutputArgs(cmd))
shortOutput := cmdutil.GetFlagString(cmd, "output") == "name"
err := RunScale(f, out, cmd, args, shortOutput, options)
cmdutil.CheckErr(err)
},
}
cmd.Flags().String("resource-version", "", "Precondition for resource version. Requires that the current resource version match this value in order to scale.")
cmd.Flags().Int("current-replicas", -1, "Precondition for current size. Requires that the current size of the replication controller match this value in order to scale.")
cmd.Flags().Int("replicas", -1, "The new desired number of replicas. Required.")
cmd.MarkFlagRequired("replicas")
cmd.Flags().Duration("timeout", 0, "The length of time to wait before giving up on a scale operation, zero means don't wait.")
cmdutil.AddOutputFlagsForMutation(cmd)
usage := "Filename, directory, or URL to a file identifying the replication controller to set a new size"
kubectl.AddJsonFilenameFlag(cmd, &options.Filenames, usage)
return cmd
}
示例6: RunPortForward
func RunPortForward(f *cmdutil.Factory, cmd *cobra.Command, args []string, fw portForwarder) error {
podName := cmdutil.GetFlagString(cmd, "pod")
if len(podName) == 0 && len(args) == 0 {
return cmdutil.UsageError(cmd, "POD is required for port-forward")
}
if len(podName) != 0 {
printDeprecationWarning("port-forward POD", "-p POD")
} else {
podName = args[0]
args = args[1:]
}
if len(args) < 1 {
return cmdutil.UsageError(cmd, "at least 1 PORT is required for port-forward")
}
namespace, _, err := f.DefaultNamespace()
if err != nil {
return err
}
client, err := f.Client()
if err != nil {
return err
}
pod, err := client.Pods(namespace).Get(podName)
if err != nil {
return err
}
if pod.Status.Phase != api.PodRunning {
glog.Fatalf("Unable to execute command because pod is not running. Current status=%v", pod.Status.Phase)
}
config, err := f.ClientConfig()
if err != nil {
return err
}
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt)
defer signal.Stop(signals)
stopCh := make(chan struct{}, 1)
go func() {
<-signals
close(stopCh)
}()
req := client.RESTClient.Post().
Resource("pods").
Namespace(namespace).
Name(pod.Name).
SubResource("portforward")
return fw.ForwardPorts("POST", req.URL(), config, args, stopCh)
}
示例7: 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
}
示例8: RunProxy
func RunProxy(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command) error {
path := cmdutil.GetFlagString(cmd, "unix-socket")
port := cmdutil.GetFlagInt(cmd, "port")
address := cmdutil.GetFlagString(cmd, "address")
if port != default_port && path != "" {
return errors.New("Don't specify both --unix-socket and --port")
}
clientConfig, err := f.ClientConfig()
if err != nil {
return err
}
staticPrefix := cmdutil.GetFlagString(cmd, "www-prefix")
if !strings.HasSuffix(staticPrefix, "/") {
staticPrefix += "/"
}
apiProxyPrefix := cmdutil.GetFlagString(cmd, "api-prefix")
if !strings.HasSuffix(apiProxyPrefix, "/") {
apiProxyPrefix += "/"
}
filter := &kubectl.FilterServer{
AcceptPaths: kubectl.MakeRegexpArrayOrDie(cmdutil.GetFlagString(cmd, "accept-paths")),
RejectPaths: kubectl.MakeRegexpArrayOrDie(cmdutil.GetFlagString(cmd, "reject-paths")),
AcceptHosts: kubectl.MakeRegexpArrayOrDie(cmdutil.GetFlagString(cmd, "accept-hosts")),
}
if cmdutil.GetFlagBool(cmd, "disable-filter") {
if path == "" {
glog.Warning("Request filter disabled, your proxy is vulnerable to XSRF attacks, please be cautious")
}
filter = nil
}
server, err := kubectl.NewProxyServer(cmdutil.GetFlagString(cmd, "www"), apiProxyPrefix, staticPrefix, filter, clientConfig)
// Separate listening from serving so we can report the bound port
// when it is chosen by os (eg: port == 0)
var l net.Listener
if path == "" {
l, err = server.Listen(address, port)
} else {
l, err = server.ListenUnix(path)
}
if err != nil {
glog.Fatal(err)
}
fmt.Fprintf(out, "Starting to serve on %s", l.Addr().String())
glog.Fatal(server.ServeOnListener(l))
return nil
}
示例9: 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
}
示例10: 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)
}
示例11: 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)
}
示例12: 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
}
示例13: 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)
}
示例14: generateService
func generateService(f *cmdutil.Factory, cmd *cobra.Command, args []string, serviceGenerator string, paramsIn map[string]interface{}, namespace string, out io.Writer) error {
generator, found := f.Generator(serviceGenerator)
if !found {
return fmt.Errorf("missing service generator: %s", serviceGenerator)
}
names := generator.ParamNames()
port := cmdutil.GetFlagInt(cmd, "port")
if port < 1 {
return fmt.Errorf("--port must be a positive integer when exposing a service")
}
params := map[string]interface{}{}
for key, value := range paramsIn {
_, isString := value.(string)
if isString {
params[key] = value
}
}
name, found := params["name"]
if !found || len(name.(string)) == 0 {
return fmt.Errorf("name is a required parameter")
}
selector, found := params["labels"]
if !found || len(selector.(string)) == 0 {
selector = fmt.Sprintf("run=%s", name.(string))
}
params["selector"] = selector
if defaultName, found := params["default-name"]; !found || len(defaultName.(string)) == 0 {
params["default-name"] = name
}
obj, _, mapper, mapping, err := createGeneratedObject(f, cmd, generator, names, params, cmdutil.GetFlagString(cmd, "service-overrides"), namespace)
if err != nil {
return err
}
if cmdutil.GetFlagString(cmd, "output") != "" {
return f.PrintObject(cmd, obj, out)
}
cmdutil.PrintSuccess(mapper, false, out, mapping.Resource, args[0], "created")
return nil
}
示例15: RunExplain
// 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")
mapper, _ := f.Object()
// 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.
group, err := mapper.GroupForResource(inModel)
if err != nil {
return err
}
if len(apiV) == 0 {
groupMeta, err := latest.Group(group)
if err != nil {
return err
}
apiV = groupMeta.GroupVersion
}
swagSchema, err := kubectl.GetSwaggerSchema(apiV, client)
if err != nil {
return err
}
return kubectl.PrintModelDescription(inModel, fieldsPath, out, swagSchema, recursive)
}