当前位置: 首页>>代码示例>>Golang>>正文


Golang unversioned.New函数代码示例

本文整理汇总了Golang中k8s/io/kubernetes/pkg/client/unversioned.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了New函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: 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 *unversioned.GroupVersion) (*client.Client, error) {
	if version != nil {
		if client, ok := c.clients[*version]; ok {
			return client, nil
		}
	}
	config, err := c.ClientConfigForVersion(version)
	if err != nil {
		return nil, err
	}

	kubeclient, err := client.New(config)
	if err != nil {
		return nil, err
	}
	c.clients[*config.GroupVersion] = kubeclient

	// `version` does not necessarily equal `config.Version`.  However, we know that if we call this method again with
	// `version`, we should get a client based on the same config we just found.  There's no guarantee that a client
	// is copiable, so create a new client and save it in the cache.
	if version != nil {
		configCopy := *config
		kubeclient, err := client.New(&configCopy)
		if err != nil {
			return nil, err
		}
		c.clients[*version] = kubeclient
	}

	return kubeclient, nil
}
开发者ID:nickschuch,项目名称:kube-haproxy,代码行数:33,代码来源:clientcache.go

示例2: 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())
	}
	if c.CurrentContext == "" || len(c.Clusters) == 0 {
		return "", nil, fmt.Errorf("invalid kubeConfig: %+v", *c)
	}
	config, err := kclientcmd.NewDefaultClientConfig(
		*c,
		&kclientcmd.ConfigOverrides{
			ClusterInfo: kclientcmdkapi.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
}
开发者ID:jcantrill,项目名称:heapster,代码行数:25,代码来源:framework.go

示例3: main

func main() {
	clientConfig := kubectl_util.DefaultClientConfig(flags)
	flags.Parse(os.Args)
	cfg := parseCfg(*config, *lbDefAlgorithm)

	var kubeClient *unversioned.Client
	var err error

	defErrorPage := newStaticPageHandler(*errorPage, defaultErrorPage)
	if defErrorPage == nil {
		glog.Fatalf("Failed to load the default error page")
	}

	go registerHandlers(defErrorPage)

	var tcpSvcs map[string]int
	if *tcpServices != "" {
		tcpSvcs = parseTCPServices(*tcpServices)
	} else {
		glog.Infof("No tcp/https services specified")
	}

	if *startSyslog {
		cfg.startSyslog = true
		_, err = newSyslogServer("/var/run/haproxy.log.socket")
		if err != nil {
			glog.Fatalf("Failed to start syslog server: %v", err)
		}
	}

	if *cluster {
		if kubeClient, err = unversioned.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 = unversioned.New(config)
	}
	namespace, specified, err := clientConfig.Namespace()
	if err != nil {
		glog.Fatalf("unexpected error: %v", err)
	}
	if !specified {
		namespace = api.NamespaceAll
	}

	// TODO: Handle multiple namespaces
	lbc := newLoadBalancerController(cfg, kubeClient, namespace, tcpSvcs)
	go lbc.epController.Run(util.NeverStop)
	go lbc.svcController.Run(util.NeverStop)
	if *dry {
		dryRun(lbc)
	} else {
		lbc.cfg.reload()
		util.Until(lbc.worker, time.Second, util.NeverStop)
	}
}
开发者ID:PDKK,项目名称:contrib,代码行数:60,代码来源:service_loadbalancer.go

示例4: Run

// Run runs the specified KubeletExecutorServer.
func (s *KubeletExecutorServer) Run(hks hyperkube.Interface, _ []string) error {
	// create shared channels
	kubeletFinished := make(chan struct{})
	execUpdates := make(chan kubetypes.PodUpdate, 1)
	nodeInfos := make(chan executor.NodeInfo, 1)

	// create static pods directory
	staticPodsConfigPath := filepath.Join(s.RootDirectory, "static-pods")
	err := os.Mkdir(staticPodsConfigPath, 0750)
	if err != nil {
		return err
	}

	// create apiserver client
	var apiclient *client.Client
	clientConfig, err := s.CreateAPIServerClientConfig()
	if err == nil {
		apiclient, err = client.New(clientConfig)
	}
	if err != nil {
		// required for k8sm since we need to send api.Binding information back to the apiserver
		return fmt.Errorf("cannot create API client: %v", err)
	}

	// start executor
	err = s.runExecutor(execUpdates, nodeInfos, kubeletFinished, staticPodsConfigPath, apiclient)
	if err != nil {
		return err
	}

	// start kubelet, blocking
	return s.runKubelet(execUpdates, nodeInfos, kubeletFinished, staticPodsConfigPath, apiclient)
}
开发者ID:pologood,项目名称:kubernetes,代码行数:34,代码来源:service.go

示例5: GetScopedClientForUser

func GetScopedClientForUser(adminClient *client.Client, clientConfig restclient.Config, username string, scopes []string) (*client.Client, *kclient.Client, *restclient.Config, error) {
	// make sure the user exists
	if _, _, _, err := GetClientForUser(clientConfig, username); err != nil {
		return nil, nil, nil, err
	}
	user, err := adminClient.Users().Get(username)
	if err != nil {
		return nil, nil, nil, err
	}

	token := &oauthapi.OAuthAccessToken{
		ObjectMeta:  kapi.ObjectMeta{Name: fmt.Sprintf("%s-token-plus-some-padding-here-to-make-the-limit-%d", username, rand.Int())},
		ClientName:  origin.OpenShiftCLIClientID,
		ExpiresIn:   86400,
		Scopes:      scopes,
		RedirectURI: "https://127.0.0.1:12000/oauth/token/implicit",
		UserName:    user.Name,
		UserUID:     string(user.UID),
	}
	if _, err := adminClient.OAuthAccessTokens().Create(token); err != nil {
		return nil, nil, nil, err
	}

	scopedConfig := clientcmd.AnonymousClientConfig(&clientConfig)
	scopedConfig.BearerToken = token.Name
	kubeClient, err := kclient.New(&scopedConfig)
	if err != nil {
		return nil, nil, nil, err
	}
	osClient, err := client.New(&scopedConfig)
	if err != nil {
		return nil, nil, nil, err
	}
	return osClient, kubeClient, &scopedConfig, nil
}
开发者ID:LalatenduMohanty,项目名称:origin,代码行数:35,代码来源:client.go

示例6: CreateApiserverClient

// Creates new Kubernetes Apiserver client. When apiserverHost param is empty string the function
// assumes that it is running inside a Kubernetes cluster and attempts to discover the Apiserver.
// Otherwise, it connects to the Apiserver specified.
//
// apiserverHost param is in the format of protocol://address:port/pathPrefix, e.g.,
// http://localhost:8001.
//
// Returns created client and its configuration.
func CreateApiserverClient(apiserverHost string) (*client.Client, clientcmd.ClientConfig, error) {

	overrides := &clientcmd.ConfigOverrides{}

	if apiserverHost != "" {
		overrides.ClusterInfo = clientcmdapi.Cluster{Server: apiserverHost}
	}

	clientConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
		&clientcmd.ClientConfigLoadingRules{}, overrides)

	cfg, err := clientConfig.ClientConfig()

	if err != nil {
		return nil, nil, err
	}

	log.Printf("Creating API server client for %s", cfg.Host)

	client, err := client.New(cfg)

	if err != nil {
		return nil, nil, err
	}

	return client, clientConfig, nil
}
开发者ID:lohmander,项目名称:dashboard,代码行数:35,代码来源:apiserverclient.go

示例7: newKubeClient

func newKubeClient() (*kclient.Client, error) {
	var (
		config    *restclient.Config
		err       error
		masterURL string
	)

	*argKubecfgFile = os.Getenv("KUBE_CFG_FILE")

	logrus.Print("kubeconfig: ", argKubecfgFile)

	if *argKubeMasterURL != "" {
		masterURL, err = expandKubeMasterURL()

		if err != nil {
			return nil, err
		}
	}

	if masterURL != "" && *argKubecfgFile == "" {
		config = &restclient.Config{
			Host: masterURL,
		}
	} else {
		overrides := &kclientcmd.ConfigOverrides{}
		overrides.ClusterInfo.Server = masterURL
		rules := &kclientcmd.ClientConfigLoadingRules{ExplicitPath: *argKubecfgFile}
		if config, err = kclientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, overrides).ClientConfig(); err != nil {
			return nil, err
		}
	}

	logrus.Print("Using ", config.Host, " for kubernetes master")
	return kclient.New(config)
}
开发者ID:stevesloka,项目名称:kubecraft,代码行数:35,代码来源:main.go

示例8: NewCluster

// NewCluster returns a usable cluster. Host should be of the form
// "http://hostname:8080".
func NewCluster(config *restclient.Config, kubectl string, logger log.Logger) (*Cluster, error) {
	client, err := k8sclient.New(config)
	if err != nil {
		return nil, err
	}
	extclient, err := k8sclient.NewExtensions(config)
	if err != nil {
		return nil, err
	}

	if kubectl == "" {
		kubectl, err = exec.LookPath("kubectl")
		if err != nil {
			return nil, err
		}
	} else {
		if _, err := os.Stat(kubectl); err != nil {
			return nil, err
		}
	}
	logger.Log("kubectl", kubectl)

	c := &Cluster{
		config:  config,
		client:  extendedClient{client, extclient},
		kubectl: kubectl,
		status:  newStatusMap(),
		actionc: make(chan func()),
		logger:  logger,
	}
	go c.loop()
	return c, nil
}
开发者ID:weaveworks,项目名称:flux,代码行数:35,代码来源:kubernetes.go

示例9: init

func (m *NetworkManager) init(args []string) {
	configFile := m.parseConfig()
	defer func() {
		if configFile != nil {
			configFile.Close()
		}
	}()

	loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
	if m.config.KubeConfig != "" {
		loadingRules.ExplicitPath = m.config.KubeConfig
	}
	configOverrides := &clientcmd.ConfigOverrides{}
	if m.config.KubeUrl != "" {
		configOverrides.ClusterInfo.Server = m.config.KubeUrl
	}
	kubeConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, configOverrides)
	config, err := kubeConfig.ClientConfig()
	if err != nil {
		glog.Fatal(err)
	}
	m.Client, err = client.New(config)
	if err != nil {
		glog.Fatalf("Invalid API configuratin: %v", err)
	}

	m.Controller = network.NewNetworkFactory().Create(m.Client, args)
	m.Controller.Init(&m.config, configFile)
}
开发者ID:michaelkuty,项目名称:contrail-kubernetes,代码行数:29,代码来源:server.go

示例10: AddNode

func (p *kubernetesProvisioner) AddNode(opts provision.AddNodeOptions) error {
	coll, err := nodeAddrCollection()
	if err != nil {
		return err
	}
	defer coll.Close()
	token, err := config.GetString("kubernetes:token")
	if err != nil {
		return err
	}
	_, err = client.New(&restclient.Config{
		Host:        opts.Address,
		Insecure:    true,
		BearerToken: token,
	})
	if err != nil {
		return err
	}
	addrs := []string{opts.Address}
	_, err = coll.UpsertId(uniqueDocumentID, bson.M{"$set": bson.M{"addresses": addrs}})
	if err != nil {
		return errors.WithStack(err)
	}
	return nil
}
开发者ID:tsuru,项目名称:tsuru,代码行数:25,代码来源:provisioner.go

示例11: newKubeClient

/**
Initialize a kubernetes API client
*/
func newKubeClient(apiserverURLString string) (*kubeClient.Client, error) {
	var u *url.URL
	var err error
	if u, err = url.Parse(os.ExpandEnv(apiserverURLString)); err != nil {
		return nil, fmt.Errorf("Could not parse Kubernetes apiserver URL: %v. Error: %v", apiserverURLString, err)
	}
	if u.Scheme == "" || u.Host == "" || u.Host == ":" || u.Path != "" {
		return nil, fmt.Errorf("Invalid URL provided for Kubernetes API server: %v.", u)
	}

	loadingRules := kubeClientCmd.NewDefaultClientConfigLoadingRules()
	configOverrides := &kubeClientCmd.ConfigOverrides{}
	kubeConfig := kubeClientCmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, configOverrides)

	config, err := kubeConfig.ClientConfig()
	if err != nil {
		return nil, err
	}
	config.Host = apiserverURLString
	config.Version = "v1"

	log.WithFields(log.Fields{"host": config.Host, "apiVersion": config.Version}).Debug("Creating kubernetes API client")

	return kubeClient.New(config)
}
开发者ID:3ko,项目名称:kubernetes-vulcand-router,代码行数:28,代码来源:kubernetes.go

示例12: UnversionedClient

func (k8scc *K8sClientConfig) UnversionedClient() *unversioned.Client {
	config := clientcmdapi.NewConfig()
	config.Clusters[k8scc.ClusterID] = &clientcmdapi.Cluster{
		InsecureSkipTLSVerify:    k8scc.InsecureSkipTLSVerify,
		Server:                   k8scc.Server,
		CertificateAuthority:     k8scc.CertificateAuthority,
		CertificateAuthorityData: k8scc.CertificateAuthorityData,
	}
	config.AuthInfos[k8scc.ClusterID] = &clientcmdapi.AuthInfo{
		ClientCertificate:     k8scc.ClientCertificate,
		ClientKey:             k8scc.ClientKey,
		ClientCertificateData: k8scc.ClientCertificateData,
		ClientKeyData:         k8scc.ClientKeyData,
	}
	config.Contexts[k8scc.ClusterID] = &clientcmdapi.Context{
		Cluster:  k8scc.ClusterID,
		AuthInfo: k8scc.ClusterID,
	}
	config.CurrentContext = k8scc.ClusterID

	clientBuilder := clientcmd.NewNonInteractiveClientConfig(*config, k8scc.ClusterID, &clientcmd.ConfigOverrides{})

	clientConfig, err := clientBuilder.ClientConfig()
	if err != nil {
		log.Fatalf("Unexpected error: %v", err)
	}
	client, err := unversioned.New(clientConfig)
	if err != nil {
		log.Fatalf("Unexpected error: %v", err)
	}

	return client
}
开发者ID:tangfeixiong,项目名称:go-to-kubernetes,代码行数:33,代码来源:client.go

示例13: 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 restclient.Config, tokenRetriever TokenRetriever, namespace, name string) (*restclient.Config, *client.Client, *kclient.Client, error) {
	// Clear existing auth info
	config.Username = ""
	config.Password = ""
	config.CertFile = ""
	config.CertData = []byte{}
	config.KeyFile = ""
	config.KeyData = []byte{}
	config.BearerToken = ""

	if len(config.UserAgent) > 0 {
		config.UserAgent += " "
	}
	config.UserAgent += fmt.Sprintf("system:serviceaccount:%s:%s", namespace, name)

	// 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, nil, err
	}
	config.BearerToken = token

	c, err := client.New(&config)
	if err != nil {
		return nil, nil, nil, err
	}

	kc, err := kclient.New(&config)
	if err != nil {
		return nil, nil, nil, err
	}

	return &config, c, kc, nil
}
开发者ID:poomsujarit,项目名称:origin,代码行数:37,代码来源:client.go

示例14: main

func main() {
	config := HollowNodeConfig{}
	config.addFlags(pflag.CommandLine)
	flag.InitFlags()

	if !knownMorphs.Has(config.Morph) {
		glog.Fatalf("Unknown morph: %v. Allowed values: %v", config.Morph, knownMorphs.List())
	}

	// create a client to communicate with API server.
	clientConfig, err := config.createClientConfigFromFile()
	if err != nil {
		glog.Fatalf("Failed to create a ClientConfig: %v. Exiting.", err)
	}
	cl, err := client.New(clientConfig)
	if err != nil {
		glog.Fatalf("Failed to create a Client: %v. Exiting.", err)
	}
	clientset, err := internalclientset.NewForConfig(clientConfig)
	if err != nil {
		glog.Fatalf("Failed to create a ClientSet: %v. Exiting.", err)
	}

	if config.Morph == "kubelet" {
		cadvisorInterface := new(cadvisortest.Fake)
		containerManager := cm.NewStubContainerManager()

		fakeDockerClient := dockertools.NewFakeDockerClient()
		fakeDockerClient.EnableSleep = true

		hollowKubelet := kubemark.NewHollowKubelet(
			config.NodeName,
			clientset,
			cadvisorInterface,
			fakeDockerClient,
			config.KubeletPort,
			config.KubeletReadOnlyPort,
			containerManager,
			maxPods,
			podsPerCore,
		)
		hollowKubelet.Run()
	}

	if config.Morph == "proxy" {
		eventBroadcaster := record.NewBroadcaster()
		recorder := eventBroadcaster.NewRecorder(api.EventSource{Component: "kube-proxy", Host: config.NodeName})

		iptInterface := fakeiptables.NewFake()

		serviceConfig := proxyconfig.NewServiceConfig()
		serviceConfig.RegisterHandler(&kubemark.FakeProxyHandler{})

		endpointsConfig := proxyconfig.NewEndpointsConfig()
		endpointsConfig.RegisterHandler(&kubemark.FakeProxyHandler{})

		hollowProxy := kubemark.NewHollowProxyOrDie(config.NodeName, cl, endpointsConfig, serviceConfig, iptInterface, eventBroadcaster, recorder)
		hollowProxy.Run()
	}
}
开发者ID:ncdc,项目名称:kubernetes,代码行数:60,代码来源:hollow-node.go

示例15: 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
}
开发者ID:rusenask,项目名称:origin,代码行数:27,代码来源:client.go


注:本文中的k8s/io/kubernetes/pkg/client/unversioned.New函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。