Exemple #1
0
// 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
}
Exemple #2
0
func validateToken(token string, clientConfig *kclient.Config) {
	if len(token) == 0 {
		fmt.Println("You must provide a token to validate")
		return
	}
	fmt.Printf("Using token: %v\n", token)

	clientConfig.BearerToken = token

	osClient, err := osclient.New(clientConfig)
	if err != nil {
		fmt.Printf("Error building osClient: %v\n", err)
		return
	}

	jsonResponse, _, err := getTokenInfo(token, osClient)
	if err != nil {
		fmt.Printf("%v\n", err)
		fmt.Println("Try visiting " + getRequestTokenURL(clientConfig) + " for a new token.")
		return
	}
	fmt.Printf("%v\n", string(jsonResponse))

	whoami, err := osClient.Users().Get("~")
	if err != nil {
		fmt.Printf("Error making whoami request: %v\n", err)
		return
	}
	whoamiJSON, err := json.Marshal(whoami)
	if err != nil {
		fmt.Printf("Error interpretting whoami response: %v\n", err)
		return
	}
	fmt.Printf("%v\n", string(whoamiJSON))
}
Exemple #3
0
// AnonymousClientConfig returns a copy of the given config with all user credentials (cert/key, bearer token, and username/password) removed
func AnonymousClientConfig(config kclient.Config) kclient.Config {
	config.BearerToken = ""
	config.CertData = nil
	config.CertFile = ""
	config.KeyData = nil
	config.KeyFile = ""
	config.Username = ""
	config.Password = ""
	return config
}
// MergeWithConfig returns a copy of a client.Config with values from the Info.
// The fields of client.Config with a corresponding field in the Info are set
// with the value from the Info.
func (info Info) MergeWithConfig(c client.Config) (client.Config, error) {
	var config client.Config = c
	config.Username = info.User
	config.Password = info.Password
	config.CAFile = info.CAFile
	config.CertFile = info.CertFile
	config.KeyFile = info.KeyFile
	config.BearerToken = info.BearerToken
	if info.Insecure != nil {
		config.Insecure = *info.Insecure
	}
	return config, nil
}
Exemple #5
0
// newAPIClient creates a new client to speak to the kubernetes api service
func (r *kubeAPIImpl) newAPIClient() (*unversioned.Client, error) {
	// step: create the configuration
	cfg := unversioned.Config{
		Host:     getURL(),
		Insecure: config.HTTPInsecure,
		Version:  config.APIVersion,
	}

	// check: ensure the token file exists
	if config.TokenFile != "" {
		if _, err := os.Stat(config.TokenFile); os.IsNotExist(err) {
			return nil, fmt.Errorf("the token file: %s does not exist", config.TokenFile)
		}

		content, err := ioutil.ReadFile(config.TokenFile)
		if err != nil {
			return nil, fmt.Errorf("unable to read the token file: %s, error: %s", config.TokenFile, err)
		}
		config.Token = string(content)
	}

	// check: are we using a user token to authenticate?
	if config.Token != "" {
		cfg.BearerToken = config.Token
	}

	// check: are we using a cert to authenticate
	if config.CaCertFile != "" {
		cfg.Insecure = false
		cfg.TLSClientConfig = unversioned.TLSClientConfig{
			CAFile: config.CaCertFile,
		}
	}

	// step: initialize the client
	kube, err := unversioned.New(&cfg)
	if err != nil {
		return nil, fmt.Errorf("unable to create a kubernetes api client, reason: %s", err)
	}

	return kube, nil
}
Exemple #6
0
func CreateKubeSources(uri *url.URL, c cache.Cache) ([]api.Source, error) {
	var (
		kubeConfig *kube_client.Config
		err        error
	)

	opts := uri.Query()
	configOverrides, err := getConfigOverrides(uri)
	if err != nil {
		return nil, err
	}

	inClusterConfig := defaultInClusterConfig
	if len(opts["inClusterConfig"]) > 0 {
		inClusterConfig, err = strconv.ParseBool(opts["inClusterConfig"][0])
		if err != nil {
			return nil, err
		}
	}

	if inClusterConfig {
		kubeConfig, err = kube_client.InClusterConfig()
		if err != nil {
			return nil, err
		}

		if configOverrides.ClusterInfo.Server != "" {
			kubeConfig.Host = configOverrides.ClusterInfo.Server
		}
		kubeConfig.Version = configOverrides.ClusterInfo.APIVersion
	} else {
		authFile := ""
		if len(opts["auth"]) > 0 {
			authFile = opts["auth"][0]
		}

		if authFile != "" {
			if kubeConfig, err = kubeClientCmd.NewNonInteractiveDeferredLoadingClientConfig(
				&kubeClientCmd.ClientConfigLoadingRules{ExplicitPath: authFile},
				configOverrides).ClientConfig(); err != nil {
				return nil, err
			}
		} else {
			kubeConfig = &kube_client.Config{
				Host:     configOverrides.ClusterInfo.Server,
				Version:  configOverrides.ClusterInfo.APIVersion,
				Insecure: configOverrides.ClusterInfo.InsecureSkipTLSVerify,
			}
		}
	}
	if len(kubeConfig.Host) == 0 {
		return nil, fmt.Errorf("invalid kubernetes master url specified")
	}
	if len(kubeConfig.Version) == 0 {
		return nil, fmt.Errorf("invalid kubernetes API version specified")
	}

	useServiceAccount := defaultUseServiceAccount
	if len(opts["useServiceAccount"]) >= 1 {
		useServiceAccount, err = strconv.ParseBool(opts["useServiceAccount"][0])
		if err != nil {
			return nil, err
		}
	}

	if useServiceAccount {
		// If a readable service account token exists, then use it
		if contents, err := ioutil.ReadFile(defaultServiceAccountFile); err == nil {
			kubeConfig.BearerToken = string(contents)
		}
	}

	kubeClient := kube_client.NewOrDie(kubeConfig)

	nodesApi, err := nodes.NewKubeNodes(kubeClient)
	if err != nil {
		return nil, err
	}
	kubeletPort := defaultKubeletPort
	if len(opts["kubeletPort"]) >= 1 {
		kubeletPort, err = strconv.Atoi(opts["kubeletPort"][0])
		if err != nil {
			return nil, err
		}
	}

	kubeletHttps := defaultKubeletHttps
	if len(opts["kubeletHttps"]) >= 1 {
		kubeletHttps, err = strconv.ParseBool(opts["kubeletHttps"][0])
		if err != nil {
			return nil, err
		}
	}
	glog.Infof("Using Kubernetes client with master %q and version %q\n", kubeConfig.Host, kubeConfig.Version)
	glog.Infof("Using kubelet port %d", kubeletPort)

	kubeletConfig := &kube_client.KubeletConfig{
		Port:            uint(kubeletPort),
		EnableHttps:     kubeletHttps,
		TLSClientConfig: kubeConfig.TLSClientConfig,
	}

	kubeletApi, err := datasource.NewKubelet(kubeletConfig)
	if err != nil {
		return nil, err
	}

	kubePodsSource := NewKubePodMetrics(kubeletPort, kubeletApi, nodesApi, newPodsApi(kubeClient))
	kubeNodeSource := NewKubeNodeMetrics(kubeletPort, kubeletApi, nodesApi)
	kubeEventsSource := NewKubeEvents(kubeClient, c)

	return []api.Source{kubePodsSource, kubeNodeSource, kubeEventsSource}, nil
}