本文整理汇总了Golang中k8s/io/kubernetes/pkg/kubectl/cmd/util.PrinterForCommand函数的典型用法代码示例。如果您正苦于以下问题:Golang PrinterForCommand函数的具体用法?Golang PrinterForCommand怎么用?Golang PrinterForCommand使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了PrinterForCommand函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Complete
func (n *NodeOptions) Complete(f *clientcmd.Factory, c *cobra.Command, args []string, out io.Writer) error {
defaultNamespace, _, err := f.DefaultNamespace()
if err != nil {
return err
}
_, kc, err := f.Clients()
if err != nil {
return err
}
cmdPrinter, output, err := kcmdutil.PrinterForCommand(c)
if err != nil {
return err
}
mapper, typer := f.Object(false)
n.DefaultNamespace = defaultNamespace
n.Kclient = kc
n.Writer = out
n.Mapper = mapper
n.Typer = typer
n.RESTClientFactory = f.Factory.ClientForMapping
n.Printer = f.Printer
n.NodeNames = []string{}
n.CmdPrinter = cmdPrinter
n.CmdPrinterOutput = false
if output {
n.CmdPrinterOutput = true
}
if len(args) != 0 {
n.NodeNames = append(n.NodeNames, args...)
}
return nil
}
示例2: NewCmdConfigView
func NewCmdConfigView(out io.Writer, ConfigAccess clientcmd.ConfigAccess) *cobra.Command {
options := &ViewOptions{ConfigAccess: ConfigAccess}
// Default to yaml
defaultOutputFormat := "yaml"
cmd := &cobra.Command{
Use: "view",
Short: "Displays merged kubeconfig settings or a specified kubeconfig file.",
Long: view_long,
Example: view_example,
Run: func(cmd *cobra.Command, args []string) {
options.Complete()
outputFormat := cmdutil.GetFlagString(cmd, "output")
if outputFormat == "wide" {
fmt.Printf("--output wide is not available in kubectl config view; reset to default output format (%s)\n\n", defaultOutputFormat)
cmd.Flags().Set("output", defaultOutputFormat)
}
if outputFormat == "" {
fmt.Printf("reset to default output format (%s) as --output is empty", defaultOutputFormat)
cmd.Flags().Set("output", defaultOutputFormat)
}
printer, _, err := cmdutil.PrinterForCommand(cmd)
cmdutil.CheckErr(err)
version, err := cmdutil.OutputVersion(cmd, &latest.ExternalVersion)
cmdutil.CheckErr(err)
printer = kubectl.NewVersionedPrinter(printer, clientcmdapi.Scheme, version)
cmdutil.CheckErr(options.Run(out, printer))
},
}
cmdutil.AddPrinterFlags(cmd)
cmd.Flags().Set("output", defaultOutputFormat)
options.Merge.Default(true)
f := cmd.Flags().VarPF(&options.Merge, "merge", "", "merge together the full hierarchy of kubeconfig files")
f.NoOptDefVal = "true"
cmd.Flags().BoolVar(&options.RawByteData, "raw", false, "display raw byte data")
cmd.Flags().BoolVar(&options.Flatten, "flatten", false, "flatten the resulting kubeconfig file into self contained output (useful for creating portable kubeconfig files)")
cmd.Flags().BoolVar(&options.Minify, "minify", false, "remove all information not used by current-context from the output")
return cmd
}
示例3: previewConfiguration
// Preview the configuration if required - returns true|false and errors.
func previewConfiguration(c *ipfailover.Configurator, cmd *cobra.Command, out io.Writer) (bool, error) {
p, output, err := cmdutil.PrinterForCommand(cmd)
if err != nil {
return true, fmt.Errorf("Error configuring printer: %v", err)
}
// Check if we are outputting info.
if !output {
return false, nil
}
configList, err := c.Generate()
if err != nil {
return true, fmt.Errorf("Error generating config: %v", err)
}
if err := p.PrintObj(configList, out); err != nil {
return true, fmt.Errorf("Unable to print object: %v", err)
}
return true, nil
}
示例4: TestImageLocal
func TestImageLocal(t *testing.T) {
f, tf, _, ns := cmdtesting.NewAPIFactory()
tf.Client = &fake.RESTClient{
NegotiatedSerializer: ns,
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
t.Fatalf("unexpected request: %s %#v\n%#v", req.Method, req.URL, req)
return nil, nil
}),
}
tf.Namespace = "test"
tf.ClientConfig = &restclient.Config{ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}
buf := bytes.NewBuffer([]byte{})
cmd := NewCmdImage(f, buf, buf)
cmd.SetOutput(buf)
cmd.Flags().Set("output", "name")
tf.Printer, _, _ = cmdutil.PrinterForCommand(cmd)
opts := ImageOptions{FilenameOptions: resource.FilenameOptions{
Filenames: []string{"../../../../examples/storage/cassandra/cassandra-controller.yaml"}},
Out: buf,
Local: true}
err := opts.Complete(f, cmd, []string{"cassandra=thingy"})
if err == nil {
err = opts.Validate()
}
if err == nil {
err = opts.Run()
}
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !strings.Contains(buf.String(), "replicationcontroller/cassandra") {
t.Errorf("did not set image: %s", buf.String())
}
}
示例5: NewCmdConfigView
func NewCmdConfigView(out io.Writer, ConfigAccess ConfigAccess) *cobra.Command {
options := &ViewOptions{ConfigAccess: ConfigAccess}
cmd := &cobra.Command{
Use: "view",
Short: "displays Merged kubeconfig settings or a specified kubeconfig file.",
Long: view_long,
Example: view_example,
Run: func(cmd *cobra.Command, args []string) {
options.Complete()
printer, _, err := cmdutil.PrinterForCommand(cmd)
if err != nil {
glog.FatalDepth(1, err)
}
version := cmdutil.OutputVersion(cmd, latest.Version)
printer = kubectl.NewVersionedPrinter(printer, clientcmdapi.Scheme, version)
if err := options.Run(out, printer); err != nil {
glog.FatalDepth(1, err)
}
},
}
cmdutil.AddPrinterFlags(cmd)
// Default to yaml
cmd.Flags().Set("output", "yaml")
options.Merge.Default(true)
cmd.Flags().Var(&options.Merge, "merge", "merge together the full hierarchy of kubeconfig files")
cmd.Flags().BoolVar(&options.RawByteData, "raw", false, "display raw byte data")
cmd.Flags().BoolVar(&options.Flatten, "flatten", false, "flatten the resulting kubeconfig file into self contained output (useful for creating portable kubeconfig files)")
cmd.Flags().BoolVar(&options.Minify, "minify", false, "remove all information not used by current-context from the output")
return cmd
}
示例6: RunCmdRouter
// RunCmdRouter contains all the necessary functionality for the
// OpenShift CLI router command.
func RunCmdRouter(f *clientcmd.Factory, cmd *cobra.Command, out io.Writer, cfg *RouterConfig, args []string) error {
var name string
switch len(args) {
case 0:
name = "router"
case 1:
name = args[0]
default:
return cmdutil.UsageError(cmd, "You may pass zero or one arguments to provide a name for the router")
}
if len(cfg.StatsUsername) > 0 {
if strings.Contains(cfg.StatsUsername, ":") {
return cmdutil.UsageError(cmd, "username %s must not contain ':'", cfg.StatsUsername)
}
}
ports, err := app.ContainerPortsFromString(cfg.Ports)
if err != nil {
glog.Fatal(err)
}
// For the host networking case, ensure the ports match.
if cfg.HostNetwork {
for i := 0; i < len(ports); i++ {
if ports[i].ContainerPort != ports[i].HostPort {
return cmdutil.UsageError(cmd, "For host networking mode, please ensure that the container [%v] and host [%v] ports match", ports[i].ContainerPort, ports[i].HostPort)
}
}
}
if cfg.StatsPort > 0 {
ports = append(ports, kapi.ContainerPort{
Name: "stats",
HostPort: cfg.StatsPort,
ContainerPort: cfg.StatsPort,
Protocol: kapi.ProtocolTCP,
})
}
label := map[string]string{"router": name}
if cfg.Labels != defaultLabel {
valid, remove, err := app.LabelsFromSpec(strings.Split(cfg.Labels, ","))
if err != nil {
glog.Fatal(err)
}
if len(remove) > 0 {
return cmdutil.UsageError(cmd, "You may not pass negative labels in %q", cfg.Labels)
}
label = valid
}
nodeSelector := map[string]string{}
if len(cfg.Selector) > 0 {
valid, remove, err := app.LabelsFromSpec(strings.Split(cfg.Selector, ","))
if err != nil {
glog.Fatal(err)
}
if len(remove) > 0 {
return cmdutil.UsageError(cmd, "You may not pass negative labels in selector %q", cfg.Selector)
}
nodeSelector = valid
}
image := cfg.ImageTemplate.ExpandOrDie(cfg.Type)
namespace, _, err := f.OpenShiftClientConfig.Namespace()
if err != nil {
return fmt.Errorf("error getting client: %v", err)
}
_, kClient, err := f.Clients()
if err != nil {
return fmt.Errorf("error getting client: %v", err)
}
_, output, err := cmdutil.PrinterForCommand(cmd)
if err != nil {
return fmt.Errorf("unable to configure printer: %v", err)
}
generate := output
if !generate {
_, err = kClient.Services(namespace).Get(name)
if err != nil {
if !errors.IsNotFound(err) {
return fmt.Errorf("can't check for existing router %q: %v", name, err)
}
generate = true
}
}
if generate {
if cfg.DryRun && !output {
return fmt.Errorf("router %q does not exist (no service)", name)
}
if len(cfg.ServiceAccount) == 0 {
return fmt.Errorf("router could not be created; you must specify a service account with --service-account")
//.........这里部分代码省略.........
示例7: RunGet
// RunGet implements the generic Get command
// TODO: convert all direct flag accessors to a struct and pass that instead of cmd
func RunGet(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, options *GetOptions) error {
selector := cmdutil.GetFlagString(cmd, "selector")
allNamespaces := cmdutil.GetFlagBool(cmd, "all-namespaces")
mapper, typer := f.Object()
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 get. ", valid_resources)
return cmdutil.UsageError(cmd, "Required resource not specified.")
}
// always show resources when getting by name or filename
argsHasNames, err := resource.HasNames(args)
if err != nil {
return err
}
if len(options.Filenames) > 0 || argsHasNames {
cmd.Flag("show-all").Value.Set("true")
}
export := cmdutil.GetFlagBool(cmd, "export")
// handle watch separately since we cannot watch multiple resource types
isWatch, isWatchOnly := cmdutil.GetFlagBool(cmd, "watch"), cmdutil.GetFlagBool(cmd, "watch-only")
if isWatch || isWatchOnly {
r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)).
NamespaceParam(cmdNamespace).DefaultNamespace().AllNamespaces(allNamespaces).
FilenameParam(enforceNamespace, options.Filenames...).
SelectorParam(selector).
ExportParam(export).
ResourceTypeOrNameArgs(true, args...).
SingleResourceType().
Latest().
Do()
err := r.Err()
if err != nil {
return err
}
infos, err := r.Infos()
if err != nil {
return err
}
if len(infos) != 1 {
return fmt.Errorf("watch is only supported on individual resources and resource collections - %d resources were found", len(infos))
}
info := infos[0]
mapping := info.ResourceMapping()
printer, err := f.PrinterForMapping(cmd, mapping, allNamespaces)
if err != nil {
return err
}
obj, err := r.Object()
if err != nil {
return err
}
rv, err := mapping.MetadataAccessor.ResourceVersion(obj)
if err != nil {
return err
}
// print the current object
if !isWatchOnly {
if err := printer.PrintObj(obj, out); err != nil {
return fmt.Errorf("unable to output the provided object: %v", err)
}
}
// print watched changes
w, err := r.Watch(rv)
if err != nil {
return err
}
kubectl.WatchLoop(w, func(e watch.Event) error {
return printer.PrintObj(e.Object, out)
})
return nil
}
b := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)).
NamespaceParam(cmdNamespace).DefaultNamespace().AllNamespaces(allNamespaces).
FilenameParam(enforceNamespace, options.Filenames...).
SelectorParam(selector).
ExportParam(export).
ResourceTypeOrNameArgs(true, args...).
ContinueOnError().
Latest()
printer, generic, err := cmdutil.PrinterForCommand(cmd)
if err != nil {
return err
}
if generic {
clientConfig, err := f.ClientConfig()
//.........这里部分代码省略.........
示例8: NewFactory
//.........这里部分代码省略.........
builds, err := oc.Builds(t.Namespace).List(api.ListOptions{})
if err != nil {
return nil, err
}
builds.Items = buildapi.FilterBuilds(builds.Items, buildapi.ByBuildConfigPredicate(t.Name))
if len(builds.Items) == 0 {
return nil, fmt.Errorf("no builds found for %q", t.Name)
}
if bopts.Version != nil {
// If a version has been specified, try to get the logs from that build.
desired := buildutil.BuildNameForConfigVersion(t.Name, int(*bopts.Version))
return oc.BuildLogs(t.Namespace).Get(desired, *bopts), nil
}
sort.Sort(sort.Reverse(buildapi.BuildSliceByCreationTimestamp(builds.Items)))
return oc.BuildLogs(t.Namespace).Get(builds.Items[0].Name, *bopts), nil
default:
return kLogsForObjectFunc(object, options)
}
}
// Saves current resource name (or alias if any) in PrintOptions. Once saved, it will not be overwritten by the
// kubernetes resource alias look-up, as it will notice a non-empty value in `options.Kind`
w.Printer = func(mapping *meta.RESTMapping, options kubectl.PrintOptions) (kubectl.ResourcePrinter, error) {
if mapping != nil {
options.Kind = mapping.Resource
if alias, ok := resourceShortFormFor(mapping.Resource); ok {
options.Kind = alias
}
}
return describe.NewHumanReadablePrinter(options), nil
}
// PrintResourceInfos receives a list of resource infos and prints versioned objects if a generic output format was specified
// otherwise, it iterates through info objects, printing each resource with a unique printer for its mapping
w.PrintResourceInfos = func(cmd *cobra.Command, infos []*resource.Info, out io.Writer) error {
printer, generic, err := cmdutil.PrinterForCommand(cmd)
if err != nil {
return nil
}
if !generic {
for _, info := range infos {
mapping := info.ResourceMapping()
printer, err := w.PrinterForMapping(cmd, mapping, false)
if err != nil {
return err
}
if err := printer.PrintObj(info.Object, out); err != nil {
return nil
}
}
return nil
}
clientConfig, err := w.ClientConfig()
if err != nil {
return err
}
outputVersion, err := cmdutil.OutputVersion(cmd, clientConfig.GroupVersion)
if err != nil {
return err
}
object, err := resource.AsVersionedObject(infos, len(infos) != 1, outputVersion, api.Codecs.LegacyCodec(outputVersion))
if err != nil {
return err
}
return printer.PrintObj(object, out)
}
示例9: RunCmdRegistry
// RunCmdRegistry contains all the necessary functionality for the OpenShift cli registry command
func RunCmdRegistry(f *clientcmd.Factory, cmd *cobra.Command, out io.Writer, cfg *RegistryConfig, args []string) error {
var name string
switch len(args) {
case 0:
name = "docker-registry"
default:
return cmdutil.UsageError(cmd, "No arguments are allowed to this command")
}
ports, err := app.ContainerPortsFromString(cfg.Ports)
if err != nil {
return err
}
label := map[string]string{
"docker-registry": "default",
}
if cfg.Labels != defaultLabel {
valid, remove, err := app.LabelsFromSpec(strings.Split(cfg.Labels, ","))
if err != nil {
return err
}
if len(remove) > 0 {
return cmdutil.UsageError(cmd, "You may not pass negative labels in %q", cfg.Labels)
}
label = valid
}
nodeSelector := map[string]string{}
if len(cfg.Selector) > 0 {
valid, remove, err := app.LabelsFromSpec(strings.Split(cfg.Selector, ","))
if err != nil {
return err
}
if len(remove) > 0 {
return cmdutil.UsageError(cmd, "You may not pass negative labels in selector %q", cfg.Selector)
}
nodeSelector = valid
}
image := cfg.ImageTemplate.ExpandOrDie(cfg.Type)
namespace, _, err := f.OpenShiftClientConfig.Namespace()
if err != nil {
return fmt.Errorf("error getting client: %v", err)
}
_, kClient, err := f.Clients()
if err != nil {
return fmt.Errorf("error getting client: %v", err)
}
_, output, err := cmdutil.PrinterForCommand(cmd)
if err != nil {
return fmt.Errorf("unable to configure printer: %v", err)
}
generate := output
if !generate {
_, err = kClient.Services(namespace).Get(name)
if err != nil {
if !errors.IsNotFound(err) {
return fmt.Errorf("can't check for existing docker-registry %q: %v", name, err)
}
generate = true
}
}
if generate {
if cfg.DryRun && !output {
return fmt.Errorf("docker-registry %q does not exist (no service).", name)
}
// create new registry
if len(cfg.Credentials) == 0 {
return fmt.Errorf("registry does not exist; you must specify a .kubeconfig file path containing credentials for connecting the registry to the master with --credentials")
}
clientConfigLoadingRules := &kclientcmd.ClientConfigLoadingRules{ExplicitPath: cfg.Credentials}
credentials, err := clientConfigLoadingRules.Load()
if err != nil {
return fmt.Errorf("registry does not exist; the provided credentials %q could not be loaded: %v", cfg.Credentials, err)
}
config, err := kclientcmd.NewDefaultClientConfig(*credentials, &kclientcmd.ConfigOverrides{}).ClientConfig()
if err != nil {
return fmt.Errorf("registry does not exist; the provided credentials %q could not be used: %v", cfg.Credentials, err)
}
if err := kclient.LoadTLSFiles(config); err != nil {
return fmt.Errorf("registry does not exist; the provided credentials %q could not load certificate info: %v", cfg.Credentials, err)
}
insecure := "false"
if config.Insecure {
insecure = "true"
} else {
if len(config.KeyData) == 0 || len(config.CertData) == 0 {
return fmt.Errorf("registry does not exist; the provided credentials %q are missing the client certificate and/or key", cfg.Credentials)
}
}
env := app.Environment{
"OPENSHIFT_MASTER": config.Host,
//.........这里部分代码省略.........
示例10: RunCmdRegistry
// RunCmdRegistry contains all the necessary functionality for the OpenShift cli registry command
func RunCmdRegistry(f *clientcmd.Factory, cmd *cobra.Command, out io.Writer, cfg *RegistryConfig, args []string) error {
var name string
switch len(args) {
case 0:
name = "docker-registry"
default:
return cmdutil.UsageError(cmd, "No arguments are allowed to this command")
}
ports, err := app.ContainerPortsFromString(cfg.Ports)
if err != nil {
return err
}
label := map[string]string{
"docker-registry": "default",
}
if cfg.Labels != defaultLabel {
valid, remove, err := app.LabelsFromSpec(strings.Split(cfg.Labels, ","))
if err != nil {
return err
}
if len(remove) > 0 {
return cmdutil.UsageError(cmd, "You may not pass negative labels in %q", cfg.Labels)
}
label = valid
}
nodeSelector := map[string]string{}
if len(cfg.Selector) > 0 {
valid, remove, err := app.LabelsFromSpec(strings.Split(cfg.Selector, ","))
if err != nil {
return err
}
if len(remove) > 0 {
return cmdutil.UsageError(cmd, "You may not pass negative labels in selector %q", cfg.Selector)
}
nodeSelector = valid
}
image := cfg.ImageTemplate.ExpandOrDie(cfg.Type)
namespace, _, err := f.OpenShiftClientConfig.Namespace()
if err != nil {
return fmt.Errorf("error getting client: %v", err)
}
_, kClient, err := f.Clients()
if err != nil {
return fmt.Errorf("error getting client: %v", err)
}
_, output, err := cmdutil.PrinterForCommand(cmd)
if err != nil {
return fmt.Errorf("unable to configure printer: %v", err)
}
generate := output
if !generate {
_, err = kClient.Services(namespace).Get(name)
if err != nil {
if !errors.IsNotFound(err) {
return fmt.Errorf("can't check for existing docker-registry %q: %v", name, err)
}
generate = true
}
}
if generate {
if cfg.DryRun && !output {
return fmt.Errorf("docker-registry %q does not exist (no service).", name)
}
// create new registry
if len(cfg.Credentials) == 0 {
return fmt.Errorf("registry does not exist; you must specify a .kubeconfig file path containing credentials for connecting the registry to the master with --credentials")
}
clientConfigLoadingRules := &kclientcmd.ClientConfigLoadingRules{ExplicitPath: cfg.Credentials}
credentials, err := clientConfigLoadingRules.Load()
if err != nil {
return fmt.Errorf("registry does not exist; the provided credentials %q could not be loaded: %v", cfg.Credentials, err)
}
config, err := kclientcmd.NewDefaultClientConfig(*credentials, &kclientcmd.ConfigOverrides{}).ClientConfig()
if err != nil {
return fmt.Errorf("registry does not exist; the provided credentials %q could not be used: %v", cfg.Credentials, err)
}
if err := kclient.LoadTLSFiles(config); err != nil {
return fmt.Errorf("registry does not exist; the provided credentials %q could not load certificate info: %v", cfg.Credentials, err)
}
insecure := "false"
if config.Insecure {
insecure = "true"
} else {
if len(config.KeyData) == 0 || len(config.CertData) == 0 {
return fmt.Errorf("registry does not exist; the provided credentials %q are missing the client certificate and/or key", cfg.Credentials)
}
}
env := app.Environment{
"OPENSHIFT_MASTER": config.Host,
//.........这里部分代码省略.........
示例11: RunGet
// RunGet implements the generic Get command
// TODO: convert all direct flag accessors to a struct and pass that instead of cmd
func RunGet(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) error {
selector := cmdutil.GetFlagString(cmd, "selector")
allNamespaces := cmdutil.GetFlagBool(cmd, "all-namespaces")
mapper, typer := f.Object()
cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
filenames := cmdutil.GetFlagStringSlice(cmd, "filename")
if len(args) == 0 && len(filenames) == 0 {
fmt.Fprint(out, "You must specify the type of resource to get. ", valid_resources, ` * componentstatuses (aka 'cs')
* endpoints (aka 'ep')
`)
return cmdutil.UsageError(cmd, "Required resource not specified.")
}
// handle watch separately since we cannot watch multiple resource types
isWatch, isWatchOnly := cmdutil.GetFlagBool(cmd, "watch"), cmdutil.GetFlagBool(cmd, "watch-only")
if isWatch || isWatchOnly {
r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()).
NamespaceParam(cmdNamespace).DefaultNamespace().AllNamespaces(allNamespaces).
FilenameParam(enforceNamespace, filenames...).
SelectorParam(selector).
ResourceTypeOrNameArgs(true, args...).
SingleResourceType().
Latest().
Do()
if err != nil {
return err
}
infos, err := r.Infos()
if err != nil {
return err
}
if len(infos) != 1 {
return fmt.Errorf("watch is only supported on a single resource - %d resources were found", len(infos))
}
info := infos[0]
mapping := info.ResourceMapping()
printer, err := f.PrinterForMapping(cmd, mapping, allNamespaces)
if err != nil {
return err
}
obj, err := r.Object()
if err != nil {
return err
}
rv, err := mapping.MetadataAccessor.ResourceVersion(obj)
if err != nil {
return err
}
// print the current object
if !isWatchOnly {
if err := printer.PrintObj(obj, out); err != nil {
return fmt.Errorf("unable to output the provided object: %v", err)
}
}
// print watched changes
w, err := r.Watch(rv)
if err != nil {
return err
}
kubectl.WatchLoop(w, func(e watch.Event) error {
return printer.PrintObj(e.Object, out)
})
return nil
}
b := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()).
NamespaceParam(cmdNamespace).DefaultNamespace().AllNamespaces(allNamespaces).
FilenameParam(enforceNamespace, filenames...).
SelectorParam(selector).
ResourceTypeOrNameArgs(true, args...).
ContinueOnError().
Latest()
printer, generic, err := cmdutil.PrinterForCommand(cmd)
if err != nil {
return err
}
if generic {
clientConfig, err := f.ClientConfig()
if err != nil {
return err
}
defaultVersion := clientConfig.Version
singular := false
r := b.Flatten().Do()
infos, err := r.IntoSingular(&singular).Infos()
if err != nil {
//.........这里部分代码省略.........
示例12: RunGet
//.........这里部分代码省略.........
if !isList && first {
// drop the initial watch event in the single resource case
first = false
return false, nil
}
err := printer.PrintObj(e.Object, out)
if err != nil {
return false, err
}
filteredResourceCount++
cmdutil.PrintFilterCount(filteredResourceCount, mapping.Resource, filterOpts)
return false, nil
})
return err
})
return nil
}
r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.UnstructuredClientForMapping), runtime.UnstructuredJSONScheme).
NamespaceParam(cmdNamespace).DefaultNamespace().AllNamespaces(allNamespaces).
FilenameParam(enforceNamespace, &options.FilenameOptions).
SelectorParam(selector).
ExportParam(export).
ResourceTypeOrNameArgs(true, args...).
ContinueOnError().
Latest().
Flatten().
Do()
err = r.Err()
if err != nil {
return err
}
printer, generic, err := cmdutil.PrinterForCommand(cmd)
if err != nil {
return err
}
if generic {
// we flattened the data from the builder, so we have individual items, but now we'd like to either:
// 1. if there is more than one item, combine them all into a single list
// 2. if there is a single item and that item is a list, leave it as its specific list
// 3. if there is a single item and it is not a a list, leave it as a single item
var errs []error
singular := false
infos, err := r.IntoSingular(&singular).Infos()
if err != nil {
if singular {
return err
}
errs = append(errs, err)
}
if len(infos) == 0 && len(errs) == 0 {
outputEmptyListWarning(errOut)
}
res := ""
if len(infos) > 0 {
res = infos[0].ResourceMapping().Resource
}
var obj runtime.Object
if singular {
obj = infos[0].Object
} else {
// we have more than one item, so coerce all items into a list
示例13: RunGet
//.........这里部分代码省略.........
}
first := true
kubectl.WatchLoop(w, func(e watch.Event) error {
if !isList && first {
// drop the initial watch event in the single resource case
first = false
return nil
}
err := printer.PrintObj(e.Object, out)
if err == nil {
printer.AfterPrint(errOut, mapping.Resource)
}
return err
})
return nil
}
r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)).
NamespaceParam(cmdNamespace).DefaultNamespace().AllNamespaces(allNamespaces).
FilenameParam(enforceNamespace, &options.FilenameOptions).
SelectorParam(selector).
ExportParam(export).
ResourceTypeOrNameArgs(true, args...).
ContinueOnError().
Latest().
Flatten().
Do()
err = r.Err()
if err != nil {
return err
}
printer, generic, err := cmdutil.PrinterForCommand(cmd)
if err != nil {
return err
}
if generic {
clientConfig, err := f.ClientConfig()
if err != nil {
return err
}
allErrs := []error{}
singular := false
infos, err := r.IntoSingular(&singular).Infos()
if err != nil {
if singular {
return err
}
allErrs = append(allErrs, err)
}
// the outermost object will be converted to the output-version, but inner
// objects can use their mappings
version, err := cmdutil.OutputVersion(cmd, clientConfig.GroupVersion)
if err != nil {
return err
}
res := ""
if len(infos) > 0 {
res = infos[0].ResourceMapping().Resource
}
obj, err := resource.AsVersionedObject(infos, !singular, version, f.JSONEncoder())
示例14: RunProcess
//.........这里部分代码省略.........
} else {
infos, err = resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), kapi.Codecs.UniversalDecoder()).
NamespaceParam(namespace).RequireNamespace().
FilenameParam(explicit, false, filename).
Do().
Infos()
if err != nil {
return err
}
}
if len(infos) > 1 {
// in order to run validation on the input given to us by a user, we only support the processing
// of one template in a list. For instance, we want to be able to fail when a user does not give
// a parameter that the template wants or when they give a parameter the template doesn't need,
// as this may indicate that they have mis-used `oc process`. This is much less complicated when
// we process at most one template.
fmt.Fprintf(out, "%d input templates found, but only the first will be processed", len(infos))
}
obj, ok := infos[0].Object.(*templateapi.Template)
if !ok {
sourceName := filename
if len(templateName) > 0 {
sourceName = namespace + "/" + templateName
}
return fmt.Errorf("unable to parse %q, not a valid Template but %s\n", sourceName, reflect.TypeOf(infos[0].Object))
}
// If 'parameters' flag is set it does not do processing but only print
// the template parameters to console for inspection.
if kcmdutil.GetFlagBool(cmd, "parameters") {
return describe.PrintTemplateParameters(obj.Parameters, out)
}
if label := kcmdutil.GetFlagString(cmd, "labels"); len(label) > 0 {
lbl, err := kubectl.ParseLabels(label)
if err != nil {
return fmt.Errorf("error parsing labels: %v\n", err)
}
if obj.ObjectLabels == nil {
obj.ObjectLabels = make(map[string]string)
}
for key, value := range lbl {
obj.ObjectLabels[key] = value
}
}
// Raise parameter parsing errors here after we had chance to return UsageErrors first
if paramErr != nil {
return paramErr
}
if errs := injectUserVars(params, obj); errs != nil {
return kerrors.NewAggregate(errs)
}
resultObj, err := client.TemplateConfigs(namespace).Create(obj)
if err != nil {
return fmt.Errorf("error processing the template %q: %v\n", obj.Name, err)
}
outputFormat := kcmdutil.GetFlagString(cmd, "output")
if outputFormat == "describe" {
if s, err := (&describe.TemplateDescriber{
MetadataAccessor: meta.NewAccessor(),
ObjectTyper: kapi.Scheme,
ObjectDescriber: nil,
}).DescribeTemplate(resultObj); err != nil {
return fmt.Errorf("error describing %q: %v\n", obj.Name, err)
} else {
_, err := fmt.Fprintf(out, s)
return err
}
}
objects = append(objects, resultObj.Objects...)
p, _, err := kcmdutil.PrinterForCommand(cmd)
if err != nil {
return err
}
gv := mapping.GroupVersionKind.GroupVersion()
version, err := kcmdutil.OutputVersion(cmd, &gv)
if err != nil {
return err
}
p = kubectl.NewVersionedPrinter(p, kapi.Scheme, version)
// use generic output
if kcmdutil.GetFlagBool(cmd, "raw") {
for i := range objects {
p.PrintObj(objects[i], out)
}
return nil
}
return p.PrintObj(&kapi.List{
ListMeta: unversioned.ListMeta{},
Items: objects,
}, out)
}
示例15: RunCmdRouter
// RunCmdRouter contains all the necessary functionality for the
// OpenShift CLI router command.
func RunCmdRouter(f *clientcmd.Factory, cmd *cobra.Command, out io.Writer, cfg *RouterConfig, args []string) error {
switch len(args) {
case 0:
// uses default value
case 1:
cfg.Name = args[0]
default:
return kcmdutil.UsageError(cmd, "You may pass zero or one arguments to provide a name for the router")
}
name := cfg.Name
if len(cfg.StatsUsername) > 0 {
if strings.Contains(cfg.StatsUsername, ":") {
return kcmdutil.UsageError(cmd, "username %s must not contain ':'", cfg.StatsUsername)
}
}
ports, err := app.ContainerPortsFromString(cfg.Ports)
if err != nil {
return fmt.Errorf("unable to parse --ports: %v", err)
}
// For the host networking case, ensure the ports match. Otherwise, remove host ports
for i := 0; i < len(ports); i++ {
if cfg.HostNetwork && ports[i].HostPort != 0 && ports[i].ContainerPort != ports[i].HostPort {
return fmt.Errorf("when using host networking mode, container port %d and host port %d must be equal", ports[i].ContainerPort, ports[i].HostPort)
}
}
if cfg.StatsPort > 0 {
port := kapi.ContainerPort{
Name: "stats",
ContainerPort: cfg.StatsPort,
Protocol: kapi.ProtocolTCP,
}
ports = append(ports, port)
}
label := map[string]string{"router": name}
if cfg.Labels != defaultLabel {
valid, remove, err := app.LabelsFromSpec(strings.Split(cfg.Labels, ","))
if err != nil {
glog.Fatal(err)
}
if len(remove) > 0 {
return kcmdutil.UsageError(cmd, "You may not pass negative labels in %q", cfg.Labels)
}
label = valid
}
nodeSelector := map[string]string{}
if len(cfg.Selector) > 0 {
valid, remove, err := app.LabelsFromSpec(strings.Split(cfg.Selector, ","))
if err != nil {
glog.Fatal(err)
}
if len(remove) > 0 {
return kcmdutil.UsageError(cmd, "You may not pass negative labels in selector %q", cfg.Selector)
}
nodeSelector = valid
}
image := cfg.ImageTemplate.ExpandOrDie(cfg.Type)
namespace, _, err := f.OpenShiftClientConfig.Namespace()
if err != nil {
return fmt.Errorf("error getting client: %v", err)
}
_, kClient, err := f.Clients()
if err != nil {
return fmt.Errorf("error getting client: %v", err)
}
_, output, err := kcmdutil.PrinterForCommand(cmd)
if err != nil {
return fmt.Errorf("unable to configure printer: %v", err)
}
generate := output
if !generate {
_, err = kClient.Services(namespace).Get(name)
if err != nil {
if !errors.IsNotFound(err) {
return fmt.Errorf("can't check for existing router %q: %v", name, err)
}
generate = true
}
}
if !generate {
fmt.Fprintf(out, "Router %q service exists\n", name)
return nil
}
if cfg.DryRun && !output {
return fmt.Errorf("router %q does not exist (no service)", name)
}
if len(cfg.ServiceAccount) == 0 {
//.........这里部分代码省略.........