本文整理汇总了Golang中github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/cmd/util.GetFlagString函数的典型用法代码示例。如果您正苦于以下问题:Golang GetFlagString函数的具体用法?Golang GetFlagString怎么用?Golang GetFlagString使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了GetFlagString函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: RunProxy
func RunProxy(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command) error {
port := cmdutil.GetFlagInt(cmd, "port")
fmt.Fprintf(out, "Starting to serve on localhost:%d", 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 += "/"
}
server, err := kubectl.NewProxyServer(cmdutil.GetFlagString(cmd, "www"), apiProxyPrefix, staticPrefix, clientConfig)
if err != nil {
return err
}
glog.Fatal(server.Serve(port))
return nil
}
示例2: RunNewApplication
// RunNewApplication contains all the necessary functionality for the OpenShift cli new-app command
func RunNewApplication(fullName string, f *clientcmd.Factory, out io.Writer, c *cobra.Command, args []string, config *newcmd.AppConfig) error {
if err := setupAppConfig(f, c, args, config); err != nil {
return err
}
if config.Querying() {
result, err := config.RunQuery(out, c.Out())
if err != nil {
return handleRunError(c, err)
}
if len(cmdutil.GetFlagString(c, "output")) != 0 {
return f.Factory.PrintObject(c, result.List, out)
}
return printHumanReadableQueryResult(result, out, fullName)
}
if err := setAppConfigLabels(c, config); err != nil {
return err
}
result, err := config.RunAll(out, c.Out())
if err != nil {
return handleRunError(c, err)
}
if err := setLabels(config.Labels, result); err != nil {
return err
}
if len(cmdutil.GetFlagString(c, "output")) != 0 {
return f.Factory.PrintObject(c, result.List, out)
}
if err := createObjects(f, out, result); err != nil {
return err
}
hasMissingRepo := false
for _, item := range result.List.Items {
switch t := item.(type) {
case *kapi.Service:
portMappings := "."
if len(t.Spec.Ports) > 0 {
portMappings = fmt.Sprintf(" with port mappings %s.", describeServicePorts(t.Spec))
}
fmt.Fprintf(c.Out(), "Service %q created at %s%s\n", t.Name, t.Spec.ClusterIP, portMappings)
case *buildapi.BuildConfig:
fmt.Fprintf(c.Out(), "A build was created - you can run `%s start-build %s` to start it.\n", fullName, t.Name)
case *imageapi.ImageStream:
if len(t.Status.DockerImageRepository) == 0 {
if hasMissingRepo {
continue
}
hasMissingRepo = true
fmt.Fprintf(c.Out(), "WARNING: We created an image stream %q, but it does not look like a Docker registry has been integrated with the server. Automatic builds and deployments depend on that integration to detect new images and will not function properly.\n", t.Name)
}
}
}
fmt.Fprintf(c.Out(), "Run '%s status' to view your app.\n", fullName)
return nil
}
示例3: Run
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)
}
示例4: NewCmdCreateSecret
func NewCmdCreateSecret(name, fullName string, f *clientcmd.Factory, out io.Writer) *cobra.Command {
options := NewCreateSecretOptions()
options.Out = out
cmd := &cobra.Command{
Use: fmt.Sprintf("%s NAME [KEY=]SOURCE ...", name),
Short: "Create a new secret based on a key file or on files within a directory",
Long: newLong,
Example: fmt.Sprintf(newExamples, fullName),
Run: func(c *cobra.Command, args []string) {
cmdutil.CheckErr(options.Complete(args, f))
cmdutil.CheckErr(options.Validate())
if len(cmdutil.GetFlagString(c, "output")) != 0 {
secret, err := options.BundleSecret()
cmdutil.CheckErr(err)
cmdutil.CheckErr(f.Factory.PrintObject(c, secret, out))
return
}
_, err := options.CreateSecret()
cmdutil.CheckErr(err)
},
}
cmd.Flags().BoolVarP(&options.Quiet, "quiet", "q", options.Quiet, "Suppress warnings")
cmd.Flags().StringVar(&options.SecretTypeName, "type", "", "The type of secret")
cmdutil.AddPrinterFlags(cmd)
return cmd
}
示例5: NewCmdStop
func NewCmdStop(f *cmdutil.Factory, out io.Writer) *cobra.Command {
flags := &struct {
Filenames util.StringList
}{}
cmd := &cobra.Command{
Use: "stop (-f FILENAME | RESOURCE (NAME | -l label | --all))",
Short: "Gracefully shut down a resource by name or filename.",
Long: stop_long,
Example: stop_example,
Run: func(cmd *cobra.Command, args []string) {
cmdutil.CheckErr(cmdutil.ValidateOutputArgs(cmd))
shortOutput := cmdutil.GetFlagString(cmd, "output") == "name"
cmdutil.CheckErr(RunStop(f, cmd, args, flags.Filenames, out, shortOutput))
},
}
usage := "Filename, directory, or URL to file of resource(s) to be stopped."
kubectl.AddJsonFilenameFlag(cmd, &flags.Filenames, usage)
cmd.Flags().StringP("selector", "l", "", "Selector (label query) to filter on.")
cmd.Flags().Bool("all", false, "[-all] to select all the specified resources.")
cmd.Flags().Bool("ignore-not-found", false, "Treat \"resource not found\" as a successful stop.")
cmd.Flags().Int("grace-period", -1, "Period of time in seconds given to the resource to terminate gracefully. Ignored if negative.")
cmd.Flags().Duration("timeout", 0, "The length of time to wait before giving up on a delete, zero means determine a timeout from the size of the object")
cmdutil.AddOutputFlagsForMutation(cmd)
return cmd
}
示例6: NewCmdReplace
func NewCmdReplace(f *cmdutil.Factory, out io.Writer) *cobra.Command {
var filenames util.StringList
cmd := &cobra.Command{
Use: "replace -f FILENAME",
// update is deprecated.
Aliases: []string{"update"},
Short: "Replace a resource by filename or stdin.",
Long: replace_long,
Example: replace_example,
Run: func(cmd *cobra.Command, args []string) {
cmdutil.CheckErr(cmdutil.ValidateOutputArgs(cmd))
shortOutput := cmdutil.GetFlagString(cmd, "output") == "name"
err := RunReplace(f, out, cmd, args, filenames, shortOutput)
cmdutil.CheckCustomErr("Replace failed", err)
},
}
usage := "Filename, directory, or URL to file to use to replace the resource."
kubectl.AddJsonFilenameFlag(cmd, &filenames, usage)
cmd.MarkFlagRequired("filename")
cmd.Flags().Bool("force", false, "Delete and re-create the specified resource")
cmd.Flags().Bool("cascade", false, "Only relevant during a force replace. If true, cascade the deletion of the resources managed by this resource (e.g. Pods created by a ReplicationController). Default true.")
cmd.Flags().Int("grace-period", -1, "Only relevant during a force replace. Period of time in seconds given to the old resource to terminate gracefully. Ignored if negative.")
cmd.Flags().Duration("timeout", 0, "Only relevant during a force replace. 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")
cmdutil.AddOutputFlagsForMutation(cmd)
return cmd
}
示例7: RunDelete
func RunDelete(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, filenames util.StringList) 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().
FilenameParam(enforceNamespace, filenames...).
SelectorParam(cmdutil.GetFlagString(cmd, "selector")).
SelectAllParam(cmdutil.GetFlagBool(cmd, "all")).
ResourceTypeOrNameArgs(false, args...).RequireObject(false).
Flatten().
Do()
err = r.Err()
if err != nil {
return err
}
ignoreNotFound := cmdutil.GetFlagBool(cmd, "ignore-not-found")
// 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"))
}
return DeleteResult(r, out, ignoreNotFound)
}
示例8: NewCmdDelete
func NewCmdDelete(f *cmdutil.Factory, out io.Writer) *cobra.Command {
var filenames util.StringList
cmd := &cobra.Command{
Use: "delete ([-f FILENAME] | (RESOURCE [(NAME | -l label | --all)]",
Short: "Delete a resource by filename, stdin, resource and name, or by resources and label selector.",
Long: delete_long,
Example: delete_example,
Run: func(cmd *cobra.Command, args []string) {
cmdutil.CheckErr(cmdutil.ValidateOutputArgs(cmd))
shortOutput := cmdutil.GetFlagString(cmd, "output") == "name"
err := RunDelete(f, out, cmd, args, filenames, shortOutput)
cmdutil.CheckErr(err)
},
}
usage := "Filename, directory, or URL to a file containing the resource to delete."
kubectl.AddJsonFilenameFlag(cmd, &filenames, usage)
cmd.Flags().StringP("selector", "l", "", "Selector (label query) to filter on.")
cmd.Flags().Bool("all", false, "[-all] to select all the specified resources.")
cmd.Flags().Bool("ignore-not-found", false, "Treat \"resource not found\" as a successful delete. Defaults to \"true\" when --all is specified.")
cmd.Flags().Bool("cascade", true, "If true, cascade the deletion of the resources managed by this resource (e.g. Pods created by a ReplicationController). Default true.")
cmd.Flags().Int("grace-period", -1, "Period of time in seconds given to the resource to terminate gracefully. Ignored if negative.")
cmd.Flags().Duration("timeout", 0, "The length of time to wait before giving up on a delete, zero means determine a timeout from the size of the object")
cmdutil.AddOutputFlagsForMutation(cmd)
return cmd
}
示例9: RunUpdate
func RunUpdate(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, filenames util.StringList) error {
schema, err := f.Validator()
if err != nil {
return err
}
cmdNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
patch := cmdutil.GetFlagString(cmd, "patch")
if len(filenames) == 0 && len(patch) == 0 {
return cmdutil.UsageError(cmd, "Must specify --filename or --patch to update")
}
if len(filenames) != 0 && len(patch) != 0 {
return cmdutil.UsageError(cmd, "Can not specify both --filename and --patch")
}
// TODO: Make patching work with -f, updating with patched JSON input files
if len(filenames) == 0 {
name, err := updateWithPatch(cmd, args, f, patch)
if err != nil {
return err
}
fmt.Fprintf(out, "%s\n", name)
return nil
}
if len(filenames) == 0 {
return cmdutil.UsageError(cmd, "Must specify --filename to update")
}
mapper, typer := f.Object()
r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()).
Schema(schema).
ContinueOnError().
NamespaceParam(cmdNamespace).RequireNamespace().
FilenameParam(filenames...).
Flatten().
Do()
err = r.Err()
if err != nil {
return err
}
return r.Visit(func(info *resource.Info) error {
data, err := info.Mapping.Codec.Encode(info.Object)
if err != nil {
return err
}
obj, err := resource.NewHelper(info.Client, info.Mapping).Update(info.Namespace, info.Name, true, data)
if err != nil {
return err
}
info.Refresh(obj, true)
printObjectSpecificMessage(obj, out)
fmt.Fprintf(out, "%s/%s\n", info.Mapping.Resource, info.Name)
return nil
})
}
示例10: RunPortForward
func RunPortForward(f *Factory, cmd *cobra.Command, args []string) error {
podName := util.GetFlagString(cmd, "pod")
if len(podName) == 0 {
return util.UsageError(cmd, "POD is required for exec")
}
if len(args) < 1 {
return util.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.Get().
Prefix("proxy").
Resource("minions").
Name(pod.Status.Host).
Suffix("portForward", namespace, podName)
pf, err := portforward.New(req, config, args, stopCh)
if err != nil {
return err
}
return pf.ForwardPorts()
}
示例11: RunScale
// RunScale executes the scaling
func RunScale(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, shortOutput bool) 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 RESOURCE NAME")
}
cmdNamespace, _, 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...).
Flatten().
Do()
err = r.Err()
if err != nil {
return err
}
mapping, err := r.ResourceMapping()
if err != nil {
return err
}
infos, err := r.Infos()
if err != nil {
return err
}
if len(infos) > 1 {
return fmt.Errorf("multiple resources provided: %v", args)
}
info := infos[0]
scaler, err := f.Scaler(mapping)
if err != nil {
return err
}
resourceVersion := cmdutil.GetFlagString(cmd, "resource-version")
currentSize := cmdutil.GetFlagInt(cmd, "current-replicas")
precondition := &kubectl.ScalePrecondition{currentSize, resourceVersion}
retry := kubectl.NewRetryParams(kubectl.Interval, kubectl.Timeout)
waitForReplicas := kubectl.NewRetryParams(kubectl.Interval, kubectl.Timeout)
if err := scaler.Scale(info.Namespace, info.Name, uint(count), precondition, retry, waitForReplicas); err != nil {
return err
}
cmdutil.PrintSuccess(mapper, shortOutput, out, info.Mapping.Resource, info.Name, "scaled")
return nil
}
示例12: setAppConfigLabels
func setAppConfigLabels(c *cobra.Command, config *newcmd.AppConfig) error {
labelStr := cmdutil.GetFlagString(c, "labels")
if len(labelStr) != 0 {
var err error
config.Labels, err = ctl.ParseLabels(labelStr)
if err != nil {
return err
}
}
return nil
}
示例13: RunNewApplication
// RunNewApplication contains all the necessary functionality for the OpenShift cli new-app command
func RunNewApplication(fullName string, f *clientcmd.Factory, out io.Writer, c *cobra.Command, args []string, config *newcmd.AppConfig) error {
if err := setupAppConfig(f, c, args, config); err != nil {
return err
}
result, err := config.RunAll(out, c.Out())
if err != nil {
if errs, ok := err.(errors.Aggregate); ok {
if len(errs.Errors()) == 1 {
err = errs.Errors()[0]
}
}
if err == newcmd.ErrNoInputs {
// TODO: suggest things to the user
return cmdutil.UsageError(c, "You must specify one or more images, image streams, templates or source code locations to create an application.")
}
return err
}
if err := setLabels(c, result); err != nil {
return err
}
if len(cmdutil.GetFlagString(c, "output")) != 0 {
return f.Factory.PrintObject(c, result.List, out)
}
if err := createObjects(f, out, result); err != nil {
return err
}
hasMissingRepo := false
for _, item := range result.List.Items {
switch t := item.(type) {
case *kapi.Service:
portMappings := "."
if len(t.Spec.Ports) > 0 {
portMappings = fmt.Sprintf(" with port mappings %s.", describeServicePorts(t.Spec))
}
fmt.Fprintf(c.Out(), "Service %q created at %s%s\n", t.Name, t.Spec.ClusterIP, portMappings)
case *buildapi.BuildConfig:
fmt.Fprintf(c.Out(), "A build was created - you can run `%s start-build %s` to start it.\n", fullName, t.Name)
case *imageapi.ImageStream:
if len(t.Status.DockerImageRepository) == 0 {
if hasMissingRepo {
continue
}
hasMissingRepo = true
fmt.Fprintf(c.Out(), "WARNING: We created an ImageStream %q, but it does not look like a Docker registry has been integrated with the OpenShift server. Automatic builds and deployments depend on that integration to detect new images and will not function properly.\n", t.Name)
}
}
}
fmt.Fprintf(c.Out(), "Run '%s status' to view your app.\n", fullName)
return nil
}
示例14: validateArguments
func validateArguments(cmd *cobra.Command, args []string) (deploymentKey, filename, image, oldName string, err error) {
deploymentKey = cmdutil.GetFlagString(cmd, "deployment-label-key")
filename = cmdutil.GetFlagString(cmd, "filename")
image = cmdutil.GetFlagString(cmd, "image")
if len(deploymentKey) == 0 {
return "", "", "", "", cmdutil.UsageError(cmd, "--deployment-label-key can not be empty")
}
if len(filename) == 0 && len(image) == 0 {
return "", "", "", "", cmdutil.UsageError(cmd, "Must specify --filename or --image for new controller")
}
if len(filename) != 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
}
示例15: RunResize
func RunResize(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) error {
count := cmdutil.GetFlagInt(cmd, "replicas")
if len(args) != 2 || count < 0 {
return cmdutil.UsageError(cmd, "--replicas=COUNT RESOURCE ID")
}
cmdNamespace, 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...).
Flatten().
Do()
err = r.Err()
if err != nil {
return err
}
mapping, err := r.ResourceMapping()
if err != nil {
return err
}
infos, err := r.Infos()
if err != nil {
return err
}
info := infos[0]
resizer, err := f.Resizer(mapping)
if err != nil {
return err
}
resourceVersion := cmdutil.GetFlagString(cmd, "resource-version")
currentSize := cmdutil.GetFlagInt(cmd, "current-replicas")
precondition := &kubectl.ResizePrecondition{currentSize, resourceVersion}
cond := kubectl.ResizeCondition(resizer, precondition, info.Namespace, info.Name, uint(count))
msg := "resized"
if err = wait.Poll(retryFrequency, retryTimeout, cond); err != nil {
msg = fmt.Sprintf("Failed to resize controller in spite of retrying for %s", retryTimeout)
if err != nil {
return err
}
}
fmt.Fprintf(out, "%s\n", msg)
return nil
}