本文整理匯總了Golang中k8s/io/kubernetes/pkg/kubectl/cmd/util.Factory.ClientConfig方法的典型用法代碼示例。如果您正苦於以下問題:Golang Factory.ClientConfig方法的具體用法?Golang Factory.ClientConfig怎麽用?Golang Factory.ClientConfig使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類k8s/io/kubernetes/pkg/kubectl/cmd/util.Factory
的用法示例。
在下文中一共展示了Factory.ClientConfig方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: RunClusterInfo
func RunClusterInfo(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command) error {
if len(os.Args) > 1 && os.Args[1] == "clusterinfo" {
printDeprecationWarning("cluster-info", "clusterinfo")
}
client, err := f.ClientConfig()
if err != nil {
return err
}
printService(out, "Kubernetes master", client.Host)
mapper, typer := f.Object(cmdutil.GetIncludeThirdPartyAPIs(cmd))
cmdNamespace := cmdutil.GetFlagString(cmd, "namespace")
if cmdNamespace == "" {
cmdNamespace = api.NamespaceSystem
}
// TODO use generalized labels once they are implemented (#341)
b := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)).
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(int(port.Port)) + " "
}
} else {
if len(client.GroupVersion.Group) == 0 {
link = client.Host + "/api/" + client.GroupVersion.Version + "/proxy/namespaces/" + service.ObjectMeta.Namespace + "/services/" + service.ObjectMeta.Name
} else {
link = client.Host + "/api/" + client.GroupVersion.Group + "/" + client.GroupVersion.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
})
out.Write([]byte("\nTo further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.\n"))
return nil
// TODO consider printing more information about cluster
}
示例2: Complete
// Complete verifies command line arguments and loads data from the command environment
func (p *AttachOptions) Complete(f *cmdutil.Factory, cmd *cobra.Command, argsIn []string) error {
if len(argsIn) == 0 {
return cmdutil.UsageError(cmd, "POD is required for attach")
}
if len(argsIn) > 1 {
return cmdutil.UsageError(cmd, fmt.Sprintf("expected a single argument: POD, saw %d: %s", len(argsIn), argsIn))
}
p.PodName = argsIn[0]
namespace, _, err := f.DefaultNamespace()
if err != nil {
return err
}
p.Namespace = namespace
config, err := f.ClientConfig()
if err != nil {
return err
}
p.Config = config
client, err := f.Client()
if err != nil {
return err
}
p.Client = client
return nil
}
示例3: execute
func execute(f cmdutil.Factory, cmd *cobra.Command, options *ExecOptions) error {
if len(options.Namespace) == 0 {
namespace, _, err := f.DefaultNamespace()
if err != nil {
return err
}
options.Namespace = namespace
}
container := cmdutil.GetFlagString(cmd, "container")
if len(container) > 0 {
options.ContainerName = container
}
config, err := f.ClientConfig()
if err != nil {
return err
}
options.Config = config
clientset, err := f.ClientSet()
if err != nil {
return err
}
options.PodClient = clientset.Core()
if err := options.Validate(); err != nil {
return err
}
if err := options.Run(); err != nil {
return err
}
return nil
}
示例4: Complete
// Complete completes all the required options for port-forward cmd.
func (o *PortForwardOptions) Complete(f *cmdutil.Factory, cmd *cobra.Command, args []string, cmdOut io.Writer, cmdErr io.Writer) error {
var err error
o.PodName = cmdutil.GetFlagString(cmd, "pod")
if len(o.PodName) == 0 && len(args) == 0 {
return cmdutil.UsageError(cmd, "POD is required for port-forward")
}
if len(o.PodName) != 0 {
printDeprecationWarning("port-forward POD", "-p POD")
o.Ports = args
} else {
o.PodName = args[0]
o.Ports = args[1:]
}
o.Namespace, _, err = f.DefaultNamespace()
if err != nil {
return err
}
o.Client, err = f.Client()
if err != nil {
return err
}
o.Config, err = f.ClientConfig()
if err != nil {
return err
}
o.StopChannel = make(chan struct{}, 1)
o.ReadyChannel = make(chan struct{})
return nil
}
示例5: 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)
}
示例6: getClient
func getClient(f *cmdutil.Factory) (*k8client.Client, *restclient.Config, error) {
var err error
cfg, err := f.ClientConfig()
if err != nil {
return nil, cfg, err
}
c, err := k8client.New(cfg)
if err != nil {
return nil, cfg, err
}
return c, cfg, nil
}
示例7: 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
}
示例8: NewClient
func NewClient(f *cmdutil.Factory) (*client.Client, *restclient.Config) {
var err error
cfg, err := f.ClientConfig()
if err != nil {
util.Error("Could not initialise a client - is your server setting correct?\n\n")
util.Fatalf("%v", err)
}
c, err := client.New(cfg)
if err != nil {
util.Fatalf("Could not initialise a client: %v", err)
}
return c, cfg
}
示例9: Complete
// Complete verifies command line arguments and loads data from the command environment
func (p *ExecOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, argsIn []string, argsLenAtDash int) error {
// Let kubectl exec follow rules for `--`, see #13004 issue
if len(p.PodName) == 0 && (len(argsIn) == 0 || argsLenAtDash == 0) {
return cmdutil.UsageError(cmd, execUsageStr)
}
if len(p.PodName) != 0 {
printDeprecationWarning("exec POD_NAME", "-p POD_NAME")
if len(argsIn) < 1 {
return cmdutil.UsageError(cmd, execUsageStr)
}
p.Command = argsIn
} else {
p.PodName = argsIn[0]
p.Command = argsIn[1:]
if len(p.Command) < 1 {
return cmdutil.UsageError(cmd, execUsageStr)
}
}
cmdParent := cmd.Parent()
if cmdParent != nil {
p.FullCmdName = cmdParent.CommandPath()
}
if len(p.FullCmdName) > 0 && cmdutil.IsSiblingCommandExists(cmd, "describe") {
p.SuggestedCmdUsage = fmt.Sprintf("Use '%s describe pod/%s' to see all of the containers in this pod.", p.FullCmdName, p.PodName)
}
namespace, _, err := f.DefaultNamespace()
if err != nil {
return err
}
p.Namespace = namespace
config, err := f.ClientConfig()
if err != nil {
return err
}
p.Config = config
clientset, err := f.ClientSet()
if err != nil {
return err
}
p.PodClient = clientset.Core()
return nil
}
示例10: Complete
// Complete verifies command line arguments and loads data from the command environment
func (p *ExecOptions) Complete(f *cmdutil.Factory, cmd *cobra.Command, argsIn []string, argsLenAtDash int) error {
if len(p.FullCmdName) == 0 {
p.FullCmdName = "kubectl"
}
// Let kubectl exec follow rules for `--`, see #13004 issue
if len(p.PodName) == 0 && (len(argsIn) == 0 || argsLenAtDash == 0) {
return cmdutil.UsageError(cmd, "POD is required for exec")
}
if len(p.PodName) != 0 {
printDeprecationWarning("exec POD", "-p POD")
if len(argsIn) < 1 {
return cmdutil.UsageError(cmd, "COMMAND is required for exec")
}
p.Command = argsIn
} else {
p.PodName = argsIn[0]
p.Command = argsIn[1:]
if len(p.Command) < 1 {
return cmdutil.UsageError(cmd, "COMMAND is required for exec")
}
}
namespace, _, err := f.DefaultNamespace()
if err != nil {
return err
}
p.Namespace = namespace
config, err := f.ClientConfig()
if err != nil {
return err
}
p.Config = config
client, err := f.Client()
if err != nil {
return err
}
p.Client = client
return nil
}
示例11: RunProxy
func RunProxy(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command) error {
port := cmdutil.GetFlagInt(cmd, "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") {
glog.Warning("Request filter disabled, your proxy is vulnerable to XSRF attacks, please be cautious")
filter = nil
}
server, err := kubectl.NewProxyServer(port, cmdutil.GetFlagString(cmd, "www"), apiProxyPrefix, staticPrefix, filter, clientConfig)
if err != nil {
return err
}
// Separate listening from serving so we can report the bound port
// when it is chosen by os (port == 0)
l, err := server.Listen()
if err != nil {
glog.Fatal(err)
}
fmt.Fprintf(out, "Starting to serve on %s", l.Addr().String())
glog.Fatal(server.ServeOnListener(l))
return nil
}
示例12: Complete
// Complete verifies command line arguments and loads data from the command environment
func (p *ExecOptions) Complete(f *cmdutil.Factory, cmd *cobra.Command, argsIn []string) error {
if len(p.PodName) == 0 && len(argsIn) == 0 {
return cmdutil.UsageError(cmd, "POD is required for exec")
}
if len(p.PodName) != 0 {
printDeprecationWarning("exec POD", "-p POD")
if len(argsIn) < 1 {
return cmdutil.UsageError(cmd, "COMMAND is required for exec")
}
p.Command = argsIn
} else {
p.PodName = argsIn[0]
p.Command = argsIn[1:]
if len(p.Command) < 1 {
return cmdutil.UsageError(cmd, "COMMAND is required for exec")
}
}
namespace, _, err := f.DefaultNamespace()
if err != nil {
return err
}
p.Namespace = namespace
config, err := f.ClientConfig()
if err != nil {
return err
}
p.Config = config
client, err := f.Client()
if err != nil {
return err
}
p.Client = client
return nil
}
示例13: Run
func Run(f *cmdutil.Factory, cmdIn io.Reader, cmdOut, cmdErr io.Writer, cmd *cobra.Command, args []string, argsLenAtDash int) error {
if len(os.Args) > 1 && os.Args[1] == "run-container" {
printDeprecationWarning("run", "run-container")
}
// Let kubectl run follow rules for `--`, see #13004 issue
if len(args) == 0 || argsLenAtDash == 0 {
return cmdutil.UsageError(cmd, "NAME is required for run")
}
interactive := cmdutil.GetFlagBool(cmd, "stdin")
tty := cmdutil.GetFlagBool(cmd, "tty")
if tty && !interactive {
return cmdutil.UsageError(cmd, "-i/--stdin is required for containers with --tty=true")
}
replicas := cmdutil.GetFlagInt(cmd, "replicas")
if interactive && replicas != 1 {
return cmdutil.UsageError(cmd, fmt.Sprintf("-i/--stdin requires that replicas is 1, found %d", replicas))
}
namespace, _, err := f.DefaultNamespace()
if err != nil {
return err
}
restartPolicy, err := getRestartPolicy(cmd, interactive)
if err != nil {
return err
}
if restartPolicy != api.RestartPolicyAlways && replicas != 1 {
return cmdutil.UsageError(cmd, fmt.Sprintf("--restart=%s requires that --replicas=1, found %d", restartPolicy, replicas))
}
generatorName := cmdutil.GetFlagString(cmd, "generator")
if len(generatorName) == 0 {
// TODO: Change the default to "deployment/v1beta1" when deployment reaches beta (#15313)
if restartPolicy == api.RestartPolicyAlways {
generatorName = "run/v1"
} else {
generatorName = "job/v1beta1"
}
}
generator, found := f.Generator(generatorName)
if !found {
return cmdutil.UsageError(cmd, fmt.Sprintf("Generator: %s not found.", generatorName))
}
names := generator.ParamNames()
params := kubectl.MakeParams(cmd, names)
params["name"] = args[0]
if len(args) > 1 {
params["args"] = args[1:]
}
params["env"] = cmdutil.GetFlagStringSlice(cmd, "env")
if cmdutil.GetFlagBool(cmd, "expose") {
serviceGenerator := cmdutil.GetFlagString(cmd, "service-generator")
if len(serviceGenerator) == 0 {
return cmdutil.UsageError(cmd, fmt.Sprintf("No service generator specified"))
}
if err := generateService(f, cmd, args, serviceGenerator, params, namespace, cmdOut); err != nil {
return err
}
}
obj, _, mapper, mapping, err := createGeneratedObject(f, cmd, generator, names, params, cmdutil.GetFlagString(cmd, "overrides"), namespace)
if err != nil {
return err
}
attachFlag := cmd.Flags().Lookup("attach")
attach := cmdutil.GetFlagBool(cmd, "attach")
if !attachFlag.Changed && interactive {
attach = true
}
if attach {
opts := &AttachOptions{
In: cmdIn,
Out: cmdOut,
Err: cmdErr,
Stdin: interactive,
TTY: tty,
Attach: &DefaultRemoteAttach{},
}
config, err := f.ClientConfig()
if err != nil {
return err
}
opts.Config = config
client, err := f.Client()
if err != nil {
return err
}
opts.Client = client
attachablePod, err := f.AttachablePodForObject(obj)
if err != nil {
//.........這裏部分代碼省略.........
示例14: RunEdit
func RunEdit(f *cmdutil.Factory, out, errOut io.Writer, cmd *cobra.Command, args []string, options *EditOptions) error {
var printer kubectl.ResourcePrinter
var ext string
switch format := cmdutil.GetFlagString(cmd, "output"); format {
case "json":
printer = &kubectl.JSONPrinter{}
ext = ".json"
case "yaml":
printer = &kubectl.YAMLPrinter{}
ext = ".yaml"
default:
return cmdutil.UsageError(cmd, "The flag 'output' must be one of yaml|json")
}
cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
mapper, typer := f.Object(cmdutil.GetIncludeThirdPartyAPIs(cmd))
resourceMapper := &resource.Mapper{
ObjectTyper: typer,
RESTMapper: mapper,
ClientMapper: resource.ClientMapperFunc(f.ClientForMapping),
// NB: we use `f.Decoder(false)` to get a plain deserializer for
// the resourceMapper, since it's used to read in edits and
// we don't want to convert into the internal version when
// reading in edits (this would cause us to potentially try to
// compare two different GroupVersions).
Decoder: f.Decoder(false),
}
r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)).
NamespaceParam(cmdNamespace).DefaultNamespace().
FilenameParam(enforceNamespace, options.Recursive, options.Filenames...).
ResourceTypeOrNameArgs(true, args...).
Flatten().
Latest().
Do()
err = r.Err()
if err != nil {
return err
}
infos, err := r.Infos()
if err != nil {
return err
}
clientConfig, err := f.ClientConfig()
if err != nil {
return err
}
encoder := f.JSONEncoder()
defaultVersion, err := cmdutil.OutputVersion(cmd, clientConfig.GroupVersion)
if err != nil {
return err
}
originalObj, err := resource.AsVersionedObject(infos, false, defaultVersion, encoder)
if err != nil {
return err
}
var (
windowsLineEndings = cmdutil.GetFlagBool(cmd, "windows-line-endings")
edit = editor.NewDefaultEditor(f.EditorEnvs())
results = editResults{}
original = []byte{}
edited = []byte{}
file string
)
containsError := false
for {
// infos mutates over time to be the list of things we've tried and failed to edit
// this means that our overall list changes over time.
objToEdit, err := resource.AsVersionedObject(infos, false, defaultVersion, encoder)
if err != nil {
return err
}
// generate the file to edit
buf := &bytes.Buffer{}
var w io.Writer = buf
if windowsLineEndings {
w = crlf.NewCRLFWriter(w)
}
if err := results.header.writeTo(w); err != nil {
return preservedFile(err, results.file, errOut)
}
if !containsError {
if err := printer.PrintObj(objToEdit, w); err != nil {
return preservedFile(err, results.file, errOut)
}
original = buf.Bytes()
} else {
// In case of an error, preserve the edited file.
//.........這裏部分代碼省略.........
示例15: 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 {
//.........這裏部分代碼省略.........