本文整理汇总了Golang中k8s/io/kubernetes/pkg/client.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了New函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Clients
// Clients returns an OpenShift and Kubernetes client with the credentials of the named service account
// TODO: change return types to client.Interface/kclient.Interface to allow auto-reloading credentials
func Clients(config kclient.Config, tokenRetriever TokenRetriever, namespace, name string) (*client.Client, *kclient.Client, error) {
// Clear existing auth info
config.Username = ""
config.Password = ""
config.CertFile = ""
config.CertData = []byte{}
config.KeyFile = ""
config.KeyData = []byte{}
// For now, just initialize the token once
// TODO: refetch the token if the client encounters 401 errors
token, err := tokenRetriever.GetToken(namespace, name)
if err != nil {
return nil, nil, err
}
config.BearerToken = token
c, err := client.New(&config)
if err != nil {
return nil, nil, err
}
kc, err := kclient.New(&config)
if err != nil {
return nil, nil, err
}
return c, kc, nil
}
示例2: Init
// Run runs the specified SimulatorBuilder. This should never exit.
func (s *SimulatorBuilder) Init(_ []string) *SimulatorBuilder {
glog.V(3).Info("Try to get kubernetes client.")
if s.Kubeconfig == "" && s.Master == "" {
glog.Warningf("Neither --kubeconfig nor --master was specified. Using default API client. This might not work.")
}
if (s.EtcdConfigFile != "" && len(s.EtcdServerList) != 0) || (s.EtcdConfigFile == "" && len(s.EtcdServerList) == 0) {
glog.Fatalf("specify either --etcd-servers or --etcd-config")
}
// This creates a client, first loading any specified kubeconfig
// file, and then overriding the Master flag, if non-empty.
kubeconfig, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
&clientcmd.ClientConfigLoadingRules{ExplicitPath: s.Kubeconfig},
&clientcmd.ConfigOverrides{ClusterInfo: clientcmdapi.Cluster{Server: s.Master}}).ClientConfig()
if err != nil {
return nil
}
kubeconfig.QPS = 20.0
kubeconfig.Burst = 30
kubeClient, err := client.New(kubeconfig)
if err != nil {
glog.Fatalf("Invalid API configuration: %v", err)
}
s.KubeClient = kubeClient
s.EtcdPathPrefix = master.DefaultEtcdPathPrefix
return s
}
示例3: GetClientForUser
func GetClientForUser(clientConfig kclient.Config, username string) (*client.Client, *kclient.Client, *kclient.Config, error) {
token, err := tokencmd.RequestToken(&clientConfig, nil, username, "password")
if err != nil {
return nil, nil, nil, err
}
userClientConfig := clientConfig
userClientConfig.BearerToken = token
userClientConfig.Username = ""
userClientConfig.Password = ""
userClientConfig.TLSClientConfig.CertFile = ""
userClientConfig.TLSClientConfig.KeyFile = ""
userClientConfig.TLSClientConfig.CertData = nil
userClientConfig.TLSClientConfig.KeyData = nil
kubeClient, err := kclient.New(&userClientConfig)
if err != nil {
return nil, nil, nil, err
}
osClient, err := client.New(&userClientConfig)
if err != nil {
return nil, nil, nil, err
}
return osClient, kubeClient, &userClientConfig, nil
}
示例4: createAPIServerClient
// TODO(jdef): hacked from kubelet/server/server.go
// TODO(k8s): replace this with clientcmd
func (s *SchedulerServer) createAPIServerClient() (*client.Client, error) {
authInfo, err := clientauth.LoadFromFile(s.AuthPath)
if err != nil {
log.Warningf("Could not load kubernetes auth path: %v. Continuing with defaults.", err)
}
if authInfo == nil {
// authInfo didn't load correctly - continue with defaults.
authInfo = &clientauth.Info{}
}
clientConfig, err := authInfo.MergeWithConfig(client.Config{})
if err != nil {
return nil, err
}
if len(s.APIServerList) < 1 {
return nil, fmt.Errorf("no api servers specified")
}
// TODO: adapt Kube client to support LB over several servers
if len(s.APIServerList) > 1 {
log.Infof("Multiple api servers specified. Picking first one")
}
clientConfig.Host = s.APIServerList[0]
c, err := client.New(&clientConfig)
if err != nil {
return nil, err
}
return c, nil
}
示例5: Kubeclient
func Kubeclient() (*kubeclient.Client, error) {
config := &kubeclient.Config{
//Host: "http://10.65.224.102:8080",
Host: "http://172.20.2.3:8080",
Username: "jabooth",
}
return kubeclient.New(config)
}
示例6: update
func (k *Krud) update(h *Webhook) error {
h.UpdateAttempt = true
h.UpdateStart = time.Now()
defer func() {
h.UpdateEnd = time.Now()
}()
conf := &client.Config{
Host: k.Endpoint,
}
client, err := client.New(conf)
if err != nil {
return err
}
rcs := client.ReplicationControllers(k.Namespace)
oldRc, err := rcs.Get(k.ControllerName)
if err != nil {
return err
}
newRc, err := rcs.Get(k.ControllerName)
if err != nil {
return err
}
hash, err := api.HashObject(oldRc, client.Codec)
if err != nil {
return err
}
h.UpdateID = hash
newRc.Name = fmt.Sprintf("%s-%s", k.ControllerName, hash)
newRc.ResourceVersion = ""
apply := func(key, value string, ms ...map[string]string) {
for _, m := range ms {
m[key] = value
}
}
apply(k.DeploymentKey, hash, newRc.Spec.Selector, newRc.Spec.Template.Labels)
apply("run", k.ControllerName, newRc.Spec.Selector, newRc.Spec.Template.Labels)
ruconf := kubectl.RollingUpdaterConfig{
Out: &lockBuffer{
k: k,
h: h,
},
OldRc: oldRc,
NewRc: newRc,
UpdatePeriod: time.Second * 3, // todo: change to time.Minute
Timeout: time.Minute * 5,
Interval: time.Second * 3,
UpdateAcceptor: kubectl.DefaultUpdateAcceptor,
CleanupPolicy: kubectl.RenameRollingUpdateCleanupPolicy,
}
ruc := kubectl.NewRollingUpdaterClient(client)
println("doing rolling update")
err = kubectl.NewRollingUpdater(k.Namespace, ruc).Update(&ruconf)
println("done")
k.Lock()
h.UpdateSuccess = err == nil
k.Unlock()
return err
}
示例7: Run
// Run runs the specified SchedulerServer. This should never exit.
func (s *SchedulerServer) Run(_ []string) error {
if s.Kubeconfig == "" && s.Master == "" {
glog.Warningf("Neither --kubeconfig nor --master was specified. Using default API client. This might not work.")
}
// This creates a client, first loading any specified kubeconfig
// file, and then overriding the Master flag, if non-empty.
kubeconfig, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
&clientcmd.ClientConfigLoadingRules{ExplicitPath: s.Kubeconfig},
&clientcmd.ConfigOverrides{ClusterInfo: clientcmdapi.Cluster{Server: s.Master}}).ClientConfig()
if err != nil {
return err
}
kubeconfig.QPS = 20.0
kubeconfig.Burst = 30
kubeClient, err := client.New(kubeconfig)
if err != nil {
glog.Fatalf("Invalid API configuration: %v", err)
}
go func() {
mux := http.NewServeMux()
healthz.InstallHandler(mux)
if s.EnableProfiling {
mux.HandleFunc("/debug/pprof/", pprof.Index)
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
}
mux.Handle("/metrics", prometheus.Handler())
server := &http.Server{
Addr: net.JoinHostPort(s.Address.String(), strconv.Itoa(s.Port)),
Handler: mux,
}
glog.Fatal(server.ListenAndServe())
}()
configFactory := factory.NewConfigFactory(kubeClient)
config, err := s.createConfig(configFactory)
if err != nil {
glog.Fatalf("Failed to create scheduler configuration: %v", err)
}
eventBroadcaster := record.NewBroadcaster()
config.Recorder = eventBroadcaster.NewRecorder(api.EventSource{Component: "scheduler"})
eventBroadcaster.StartLogging(glog.Infof)
eventBroadcaster.StartRecordingToSink(kubeClient.Events(""))
sched := scheduler.New(config)
sched.Run()
select {}
}
示例8: main
func main() {
flag.Usage = usage
flag.Parse()
var (
cfg *kclient.Config
err error
)
if *local {
cfg = &kclient.Config{Host: fmt.Sprintf("http://localhost:%d", *localPort)}
} else {
cfg, err = kclient.InClusterConfig()
if err != nil {
glog.Errorf("failed to load config: %v", err)
flag.Usage()
os.Exit(1)
}
}
client, err = kclient.New(cfg)
selector, err := labels.Parse(*userLabels)
if err != nil {
glog.Fatal(err)
}
tc, err := parseTimeCounts(*times, *counts)
if err != nil {
glog.Fatal(err)
}
if namespace == "" {
glog.Fatal("POD_NAMESPACE is not set. Set to the namespace of the replication controller if running locally.")
}
scaler := Scaler{timeCounts: tc, selector: selector}
if err != nil {
glog.Fatal(err)
}
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan,
syscall.SIGHUP,
syscall.SIGINT,
syscall.SIGQUIT,
syscall.SIGTERM)
glog.Info("starting scaling")
if err := scaler.Start(); err != nil {
glog.Fatal(err)
}
<-sigChan
glog.Info("stopping scaling")
if err := scaler.Stop(); err != nil {
glog.Fatal(err)
}
}
示例9: NewClient
func NewClient(f *cmdutil.Factory) (*client.Client, *client.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
}
示例10: Clients
// Clients returns an OpenShift and a Kubernetes client from a given configuration
func (cfg *Config) Clients() (osclient.Interface, kclient.Interface, error) {
cfg.bindEnv()
kubeClient, err := kclient.New(cfg.KubeConfig())
if err != nil {
return nil, nil, fmt.Errorf("Unable to configure Kubernetes client: %v", err)
}
osClient, err := osclient.New(cfg.OpenShiftConfig())
if err != nil {
return nil, nil, fmt.Errorf("Unable to configure Origin client: %v", err)
}
return osClient, kubeClient, nil
}
示例11: ClientForVersion
// ClientForVersion initializes or reuses a client for the specified version, or returns an
// error if that is not possible
func (c *ClientCache) ClientForVersion(version string) (*client.Client, error) {
if client, ok := c.clients[version]; ok {
return client, nil
}
config, err := c.ClientConfigForVersion(version)
if err != nil {
return nil, err
}
client, err := client.New(config)
if err != nil {
return nil, err
}
c.clients[config.Version] = client
return client, nil
}
示例12: NewRegistrar
// NewRegistrar returns a ptr to a new Registrar from a Config
func NewRegistrar(c *Config) (*Registrar, error) {
cf := c.kc()
kc, err := client.New(&cf)
if err != nil {
return nil, err
}
ec, err := NewEtcdClient(c.ps(), formatEtcdNamespace(c.VulcanEtcdNamespace), c.EtcdTimeout)
if err != nil {
return nil, err
}
return &Registrar{
e: ec,
k: kc,
v: c.APIVersion,
s: c.Selector.fixNamespace(),
vk: formatEtcdNamespace(c.VulcanEtcdNamespace),
}, nil
}
示例13: main
func main() {
flags.Parse(os.Args)
cfg := parseCfg(*config)
if len(*tcpServices) == 0 {
glog.Infof("All tcp/https services will be ignored.")
}
go healthzServer()
var kubeClient *client.Client
var err error
clientConfig := kubectl_util.DefaultClientConfig(flags)
if *cluster {
if kubeClient, err = client.NewInCluster(); err != nil {
glog.Fatalf("Failed to create client: %v", err)
}
} else {
config, err := clientConfig.ClientConfig()
if err != nil {
glog.Fatalf("error connecting to the client: %v", err)
}
kubeClient, err = client.New(config)
}
namespace, specified, err := clientConfig.Namespace()
if err != nil {
glog.Fatalf("unexpected error: %v", err)
}
if !specified {
namespace = "default"
}
namespace = ""
// TODO: Handle multiple namespaces
lbc := newLoadBalancerController(cfg, kubeClient, namespace)
go lbc.epController.Run(util.NeverStop)
go lbc.svcController.Run(util.NeverStop)
if *dry {
dryRun(lbc)
} else {
util.Until(lbc.worker, time.Second, util.NeverStop)
}
}
示例14: getKubeClient
func getKubeClient() (string, *kclient.Client, error) {
c, err := kclientcmd.LoadFromFile(*kubeConfig)
if err != nil {
return "", nil, fmt.Errorf("error loading kubeConfig: %v", err.Error())
}
config, err := kclientcmd.NewDefaultClientConfig(
*c,
&kclientcmd.ConfigOverrides{
ClusterInfo: kclientcmdapi.Cluster{
APIVersion: "v1",
},
}).ClientConfig()
if err != nil {
return "", nil, fmt.Errorf("error parsing kubeConfig: %v", err.Error())
}
kubeClient, err := kclient.New(config)
if err != nil {
return "", nil, fmt.Errorf("error creating client - %q", err)
}
return c.Clusters[c.CurrentContext].Server, kubeClient, nil
}
示例15: newKubeClient
// TODO: evaluate using pkg/client/clientcmd
func newKubeClient() (*kclient.Client, error) {
var (
config *kclient.Config
err error
masterURL string
)
// If the user specified --kube_master_url, expand env vars and verify it.
if *argKubeMasterURL != "" {
masterURL, err = expandKubeMasterURL()
if err != nil {
return nil, err
}
}
if masterURL != "" && *argKubecfgFile == "" {
// Only --kube_master_url was provided.
config = &kclient.Config{
Host: masterURL,
Version: "v1",
}
} else {
// We either have:
// 1) --kube_master_url and --kubecfg_file
// 2) just --kubecfg_file
// 3) neither flag
// In any case, the logic is the same. If (3), this will automatically
// fall back on the service account token.
overrides := &kclientcmd.ConfigOverrides{}
overrides.ClusterInfo.Server = masterURL // might be "", but that is OK
rules := &kclientcmd.ClientConfigLoadingRules{ExplicitPath: *argKubecfgFile} // might be "", but that is OK
if config, err = kclientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, overrides).ClientConfig(); err != nil {
return nil, err
}
}
glog.Infof("Using %s for kubernetes master", config.Host)
glog.Infof("Using kubernetes API %s", config.Version)
return kclient.New(config)
}