本文整理汇总了Golang中k8s/io/kubernetes/pkg/client/restclient.InClusterConfig函数的典型用法代码示例。如果您正苦于以下问题:Golang InClusterConfig函数的具体用法?Golang InClusterConfig怎么用?Golang InClusterConfig使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了InClusterConfig函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: main
func main() {
cc, err := restclient.InClusterConfig()
if err != nil {
log.Fatalf("Failed to create client: %v", err)
}
kubeClient, err := clientset.NewForConfig(cc)
if err != nil {
log.Fatalf("Failed to create client: %v", err)
}
listAll := api.ListOptions{LabelSelector: labels.Everything(), FieldSelector: fields.Everything()}
nodes, err := kubeClient.Core().Nodes().List(listAll)
if err != nil {
log.Fatalf("Failed to list nodes: %v", err)
}
log.Printf("Nodes:")
for _, node := range nodes.Items {
log.Printf("\t%v", node.Name)
}
services, err := kubeClient.Core().Services(api.NamespaceDefault).List(listAll)
if err != nil {
log.Fatalf("Failed to list services: %v", err)
}
log.Printf("Services:")
for _, svc := range services.Items {
log.Printf("\t%v", svc.Name)
}
log.Printf("Success")
http.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Ok")
})
log.Fatal(http.ListenAndServe(":8080", nil))
}
示例2: newTokenAccessReview
func (s *DelegatingAuthenticationOptions) newTokenAccessReview() (authenticationclient.TokenReviewInterface, error) {
var clientConfig *restclient.Config
var err error
if len(s.RemoteKubeConfigFile) > 0 {
loadingRules := &clientcmd.ClientConfigLoadingRules{ExplicitPath: s.RemoteKubeConfigFile}
loader := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, &clientcmd.ConfigOverrides{})
clientConfig, err = loader.ClientConfig()
} else {
// without the remote kubeconfig file, try to use the in-cluster config. Most addon API servers will
// use this path
clientConfig, err = restclient.InClusterConfig()
}
if err != nil {
return nil, err
}
// set high qps/burst limits since this will effectively limit API server responsiveness
clientConfig.QPS = 200
clientConfig.Burst = 400
client, err := authenticationclient.NewForConfig(clientConfig)
if err != nil {
return nil, err
}
return client.TokenReviews(), nil
}
示例3: NewInCluster
// NewInCluster is a shortcut for calling InClusterConfig() and then New().
func NewInCluster() (*Client, error) {
cc, err := restclient.InClusterConfig()
if err != nil {
return nil, err
}
return New(cc)
}
示例4: getClient
func getClient() (client.Interface, error) {
clientConfig, err := restclient.InClusterConfig()
if err != nil {
return nil, fmt.Errorf("failed to get client config: %v", err)
}
osClient, err := client.New(clientConfig)
if err != nil {
return nil, fmt.Errorf("error obtaining OpenShift client: %v", err)
}
return osClient, nil
}
示例5: TestFromEnv
func TestFromEnv(t *testing.T) {
if _, err := restclient.InClusterConfig(); err != nil {
t.Skip("This can only be run inside Kubernetes. Skipping.")
}
me, err := FromEnv()
if err != nil {
t.Errorf("Could not get an environment: %s", err)
}
if len(me.Name) == 0 {
t.Error("Could not get a pod name.")
}
}
示例6: BuildConfigFromFlags
// BuildConfigFromFlags is a helper function that builds configs from a master
// url or a kubeconfig filepath. These are passed in as command line flags for cluster
// components. Warnings should reflect this usage. If neither masterUrl or kubeconfigPath
// are passed in we fallback to inClusterConfig. If inClusterConfig fails, we fallback
// to the default config.
func BuildConfigFromFlags(masterUrl, kubeconfigPath string) (*restclient.Config, error) {
if kubeconfigPath == "" && masterUrl == "" {
glog.Warningf("Neither --kubeconfig nor --master was specified. Using the inClusterConfig. This might not work.")
kubeconfig, err := restclient.InClusterConfig()
if err == nil {
return kubeconfig, nil
}
glog.Warning("error creating inClusterConfig, falling back to default config: ", err)
}
return NewNonInteractiveDeferredLoadingClientConfig(
&ClientConfigLoadingRules{ExplicitPath: kubeconfigPath},
&ConfigOverrides{ClusterInfo: clientcmdapi.Cluster{Server: masterUrl}}).ClientConfig()
}
示例7: contactOthers
// Find all sibling pods in the service and post to their /write handler.
func contactOthers(state *State) {
sleepTime := 5 * time.Second
// In large cluster getting all endpoints is pretty expensive.
// Thus, we will limit ourselves to send on average at most 10 such
// requests per second
if sleepTime < time.Duration(*peerCount/10)*time.Second {
sleepTime = time.Duration(*peerCount/10) * time.Second
}
timeout := 5 * time.Minute
// Similarly we need to bump timeout so that it is reasonable in large
// clusters.
if timeout < time.Duration(*peerCount)*time.Second {
timeout = time.Duration(*peerCount) * time.Second
}
defer state.doneContactingPeers()
config, err := restclient.InClusterConfig()
if err != nil {
log.Fatalf("Unable to create config; error: %v\n", err)
}
config.ContentType = "application/vnd.kubernetes.protobuf"
client, err := client.New(config)
if err != nil {
log.Fatalf("Unable to create client; error: %v\n", err)
}
// Double check that that worked by getting the server version.
if v, err := client.Discovery().ServerVersion(); err != nil {
log.Fatalf("Unable to get server version: %v\n", err)
} else {
log.Printf("Server version: %#v\n", v)
}
for start := time.Now(); time.Since(start) < timeout; time.Sleep(sleepTime) {
eps := getWebserverEndpoints(client)
if eps.Len() >= *peerCount {
break
}
state.Logf("%v/%v has %v endpoints (%v), which is less than %v as expected. Waiting for all endpoints to come up.", *namespace, *service, len(eps), eps.List(), *peerCount)
}
// Do this repeatedly, in case there's some propagation delay with getting
// newly started pods into the endpoints list.
for i := 0; i < 15; i++ {
eps := getWebserverEndpoints(client)
for ep := range eps {
state.Logf("Attempting to contact %s", ep)
contactSingle(ep, state)
}
time.Sleep(sleepTime)
}
}
示例8: newBuilderConfigFromEnvironment
func newBuilderConfigFromEnvironment(out io.Writer) (*builderConfig, error) {
cfg := &builderConfig{}
var err error
cfg.out = out
// build (BUILD)
buildStr := os.Getenv("BUILD")
glog.V(4).Infof("$BUILD env var is %s \n", buildStr)
cfg.build = &api.Build{}
if err := runtime.DecodeInto(kapi.Codecs.UniversalDecoder(), []byte(buildStr), cfg.build); err != nil {
return nil, fmt.Errorf("unable to parse build: %v", err)
}
if errs := validation.ValidateBuild(cfg.build); len(errs) > 0 {
return nil, errors.NewInvalid(unversioned.GroupKind{Kind: "Build"}, cfg.build.Name, errs)
}
glog.V(4).Infof("Build: %#v", cfg.build)
masterVersion := os.Getenv(api.OriginVersion)
thisVersion := version.Get().String()
if len(masterVersion) != 0 && masterVersion != thisVersion {
fmt.Fprintf(cfg.out, "warning: OpenShift server version %q differs from this image %q\n", masterVersion, thisVersion)
} else {
glog.V(4).Infof("Master version %q, Builder version %q", masterVersion, thisVersion)
}
// sourceSecretsDir (SOURCE_SECRET_PATH)
cfg.sourceSecretDir = os.Getenv("SOURCE_SECRET_PATH")
// dockerClient and dockerEndpoint (DOCKER_HOST)
// usually not set, defaults to docker socket
cfg.dockerClient, cfg.dockerEndpoint, err = dockerutil.NewHelper().GetClient()
if err != nil {
return nil, fmt.Errorf("no Docker configuration defined: %v", err)
}
// buildsClient (KUBERNETES_SERVICE_HOST, KUBERNETES_SERVICE_PORT)
clientConfig, err := restclient.InClusterConfig()
if err != nil {
return nil, fmt.Errorf("cannot connect to the server: %v", err)
}
osClient, err := client.New(clientConfig)
if err != nil {
return nil, fmt.Errorf("failed to get client: %v", err)
}
cfg.buildsClient = osClient.Builds(cfg.build.Namespace)
return cfg, nil
}
示例9: NewClient
// NewClient returns a usable Client. Don't forget to Stop it.
func NewClient(addr string, resyncPeriod time.Duration) (Client, error) {
var config *restclient.Config
if addr != "" {
config = &restclient.Config{Host: addr}
} else {
// If no API server address was provided, assume we are running
// inside a pod. Try to connect to the API server through its
// Service environment variables, using the default Service
// Account Token.
var err error
if config, err = restclient.InClusterConfig(); err != nil {
return nil, err
}
}
c, err := unversioned.New(config)
if err != nil {
return nil, err
}
ec, err := unversioned.NewExtensions(config)
if err != nil {
return nil, err
}
result := &client{
quit: make(chan struct{}),
resyncPeriod: resyncPeriod,
client: c,
extensionsClient: ec,
}
result.podStore = &cache.StoreToPodLister{Store: result.setupStore(c, "pods", &api.Pod{})}
result.serviceStore = &cache.StoreToServiceLister{Store: result.setupStore(c, "services", &api.Service{})}
result.replicationControllerStore = &cache.StoreToReplicationControllerLister{Store: result.setupStore(c, "replicationcontrollers", &api.ReplicationController{})}
result.nodeStore = &cache.StoreToNodeLister{Store: result.setupStore(c, "nodes", &api.Node{})}
// We list deployments here to check if this version of kubernetes is >= 1.2.
// We would use NegotiateVersion, but Kubernetes 1.1 "supports"
// extensions/v1beta1, but not deployments or replicasets.
if _, err := ec.Deployments(api.NamespaceAll).List(api.ListOptions{}); err != nil {
log.Infof("Deployments and ReplicaSets are not supported by this Kubernetes version")
} else {
result.deploymentStore = &cache.StoreToDeploymentLister{Store: result.setupStore(ec, "deployments", &extensions.Deployment{})}
result.replicaSetStore = &cache.StoreToReplicaSetLister{Store: result.setupStore(ec, "replicasets", &extensions.ReplicaSet{})}
}
return result, nil
}
示例10: createKubeClient
func createKubeClient(flags *flag.FlagSet, inCluster bool) (*kube_client.Client, error) {
var config *kube_restclient.Config
var err error
if inCluster {
config, err = kube_restclient.InClusterConfig()
} else {
clientConfig := kubectl_util.DefaultClientConfig(flags)
config, err = clientConfig.ClientConfig()
}
if err != nil {
fmt.Errorf("error connecting to the client: %v", err)
}
config.ContentType = *contentType
return kube_client.NewOrDie(config), nil
}
示例11: makeClient
func makeClient() (*client.Client, error) {
var cfg *restclient.Config
var err error
if *inCluster {
if cfg, err = restclient.InClusterConfig(); err != nil {
return nil, err
}
} else {
clientConfig := kubectl_util.DefaultClientConfig(flags)
if cfg, err = clientConfig.ClientConfig(); err != nil {
return nil, err
}
}
return client.New(cfg)
}
示例12: TestPodClient
func TestPodClient(t *testing.T) {
// A pod can't really be mocked efficiently without major filesystem
// manipulation. So we're testing fully only when this is running inside of
// a k8s pod.
if _, err := restclient.InClusterConfig(); err != nil {
t.Skip("This can only be run inside Kubernetes. Skipping.")
}
c, err := PodClient()
if err != nil {
t.Errorf("Error constructing client: %s", err)
}
if _, err := c.ServerVersion(); err != nil {
t.Errorf("Failed to connect to given server: %s", err)
}
}
示例13: NewCommandDeployer
// NewCommandDeployer provides a CLI handler for deploy.
func NewCommandDeployer(name string) *cobra.Command {
cfg := &config{}
cmd := &cobra.Command{
Use: fmt.Sprintf("%s%s", name, clientcmd.ConfigSyntax),
Short: "Run the deployer",
Long: deployerLong,
Run: func(c *cobra.Command, args []string) {
if len(cfg.DeploymentName) == 0 {
glog.Fatal("deployment is required")
}
if len(cfg.Namespace) == 0 {
glog.Fatal("namespace is required")
}
kcfg, err := restclient.InClusterConfig()
if err != nil {
glog.Fatal(err)
}
kc, err := kclient.New(kcfg)
if err != nil {
glog.Fatal(err)
}
oc, err := client.New(kcfg)
if err != nil {
glog.Fatal(err)
}
deployer := NewDeployer(kc, oc)
if err = deployer.Deploy(cfg.Namespace, cfg.DeploymentName); err != nil {
glog.Fatal(err)
}
},
}
cmd.AddCommand(version.NewVersionCommand(name, false))
flag := cmd.Flags()
flag.StringVar(&cfg.DeploymentName, "deployment", util.Env("OPENSHIFT_DEPLOYMENT_NAME", ""), "The deployment name to start")
flag.StringVar(&cfg.Namespace, "namespace", util.Env("OPENSHIFT_DEPLOYMENT_NAMESPACE", ""), "The deployment namespace")
return cmd
}
示例14: newBuilderConfigFromEnvironment
func newBuilderConfigFromEnvironment() (*builderConfig, error) {
cfg := &builderConfig{}
var err error
// build (BUILD)
buildStr := os.Getenv("BUILD")
glog.V(4).Infof("$BUILD env var is %s \n", buildStr)
cfg.build = &api.Build{}
if err = runtime.DecodeInto(kapi.Codecs.UniversalDecoder(), []byte(buildStr), cfg.build); err != nil {
return nil, fmt.Errorf("unable to parse build: %v", err)
}
masterVersion := os.Getenv(api.OriginVersion)
thisVersion := version.Get().String()
if len(masterVersion) != 0 && masterVersion != thisVersion {
glog.Warningf("Master version %q does not match Builder image version %q", masterVersion, thisVersion)
} else {
glog.V(2).Infof("Master version %q, Builder version %q", masterVersion, thisVersion)
}
// sourceSecretsDir (SOURCE_SECRET_PATH)
cfg.sourceSecretDir = os.Getenv("SOURCE_SECRET_PATH")
// dockerClient and dockerEndpoint (DOCKER_HOST)
// usually not set, defaults to docker socket
cfg.dockerClient, cfg.dockerEndpoint, err = dockerutil.NewHelper().GetClient()
if err != nil {
return nil, fmt.Errorf("error obtaining docker client: %v", err)
}
// buildsClient (KUBERNETES_SERVICE_HOST, KUBERNETES_SERVICE_PORT)
clientConfig, err := restclient.InClusterConfig()
if err != nil {
return nil, fmt.Errorf("failed to get client config: %v", err)
}
osClient, err := client.New(clientConfig)
if err != nil {
return nil, fmt.Errorf("error obtaining OpenShift client: %v", err)
}
cfg.buildsClient = osClient.Builds(cfg.build.Namespace)
return cfg, nil
}
示例15: NewSubnetManager
func NewSubnetManager() (subnet.Manager, error) {
cfg, err := restclient.InClusterConfig()
if err != nil {
return nil, fmt.Errorf("unable to initialize inclusterconfig: %v", err)
}
c, err := clientset.NewForConfig(cfg)
if err != nil {
return nil, fmt.Errorf("unable to initialize client: %v", err)
}
podName := os.Getenv("POD_NAME")
podNamespace := os.Getenv("POD_NAMESPACE")
if podName == "" || podNamespace == "" {
return nil, fmt.Errorf("env variables POD_NAME and POD_NAMESPACE must be set")
}
pod, err := c.Pods(podNamespace).Get(podName)
if err != nil {
return nil, fmt.Errorf("error retrieving pod spec for '%s/%s': %v", podNamespace, podName, err)
}
nodeName := pod.Spec.NodeName
if nodeName == "" {
return nil, fmt.Errorf("node name not present in pod spec '%s/%s'", podNamespace, podName)
}
netConf, err := ioutil.ReadFile(netConfPath)
if err != nil {
return nil, fmt.Errorf("failed to read net conf: %v", err)
}
sc, err := subnet.ParseConfig(string(netConf))
if err != nil {
return nil, fmt.Errorf("error parsing subnet config: %s", err)
}
sm, err := newKubeSubnetManager(c, sc, nodeName)
if err != nil {
return nil, fmt.Errorf("error creating network manager: %s", err)
}
go sm.Run(context.Background())
return sm, err
}