kubelet_client.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package client
  14. import (
  15. "context"
  16. "fmt"
  17. "net/http"
  18. "strconv"
  19. "time"
  20. v1 "k8s.io/api/core/v1"
  21. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  22. "k8s.io/apimachinery/pkg/types"
  23. utilnet "k8s.io/apimachinery/pkg/util/net"
  24. "k8s.io/apiserver/pkg/server/egressselector"
  25. restclient "k8s.io/client-go/rest"
  26. "k8s.io/client-go/transport"
  27. nodeutil "k8s.io/kubernetes/pkg/util/node"
  28. )
  29. // KubeletClientConfig defines config parameters for the kubelet client
  30. type KubeletClientConfig struct {
  31. // Port specifies the default port - used if no information about Kubelet port can be found in Node.NodeStatus.DaemonEndpoints.
  32. Port uint
  33. // ReadOnlyPort specifies the Port for ReadOnly communications.
  34. ReadOnlyPort uint
  35. // EnableHTTPs specifies if traffic should be encrypted.
  36. EnableHTTPS bool
  37. // PreferredAddressTypes - used to select an address from Node.NodeStatus.Addresses
  38. PreferredAddressTypes []string
  39. // TLSClientConfig contains settings to enable transport layer security
  40. restclient.TLSClientConfig
  41. // Server requires Bearer authentication
  42. BearerToken string
  43. // HTTPTimeout is used by the client to timeout http requests to Kubelet.
  44. HTTPTimeout time.Duration
  45. // Dial is a custom dialer used for the client
  46. Dial utilnet.DialFunc
  47. // Lookup will give us a dialer if the egress selector is configured for it
  48. Lookup egressselector.Lookup
  49. }
  50. // ConnectionInfo provides the information needed to connect to a kubelet
  51. type ConnectionInfo struct {
  52. Scheme string
  53. Hostname string
  54. Port string
  55. Transport http.RoundTripper
  56. InsecureSkipTLSVerifyTransport http.RoundTripper
  57. }
  58. // ConnectionInfoGetter provides ConnectionInfo for the kubelet running on a named node
  59. type ConnectionInfoGetter interface {
  60. GetConnectionInfo(ctx context.Context, nodeName types.NodeName) (*ConnectionInfo, error)
  61. }
  62. // MakeTransport creates a secure RoundTripper for HTTP Transport.
  63. func MakeTransport(config *KubeletClientConfig) (http.RoundTripper, error) {
  64. return makeTransport(config, false)
  65. }
  66. // MakeInsecureTransport creates an insecure RoundTripper for HTTP Transport.
  67. func MakeInsecureTransport(config *KubeletClientConfig) (http.RoundTripper, error) {
  68. return makeTransport(config, true)
  69. }
  70. // makeTransport creates a RoundTripper for HTTP Transport.
  71. func makeTransport(config *KubeletClientConfig, insecureSkipTLSVerify bool) (http.RoundTripper, error) {
  72. // do the insecureSkipTLSVerify on the pre-transport *before* we go get a potentially cached connection.
  73. // transportConfig always produces a new struct pointer.
  74. preTLSConfig := config.transportConfig()
  75. if insecureSkipTLSVerify && preTLSConfig != nil {
  76. preTLSConfig.TLS.Insecure = true
  77. preTLSConfig.TLS.CAData = nil
  78. preTLSConfig.TLS.CAFile = ""
  79. }
  80. tlsConfig, err := transport.TLSConfigFor(preTLSConfig)
  81. if err != nil {
  82. return nil, err
  83. }
  84. rt := http.DefaultTransport
  85. dialer := config.Dial
  86. if dialer == nil && config.Lookup != nil {
  87. // Assuming EgressSelector if SSHTunnel is not turned on.
  88. // We will not get a dialer if egress selector is disabled.
  89. networkContext := egressselector.Cluster.AsNetworkContext()
  90. dialer, err = config.Lookup(networkContext)
  91. if err != nil {
  92. return nil, fmt.Errorf("failed to get context dialer for 'cluster': got %v", err)
  93. }
  94. }
  95. if dialer != nil || tlsConfig != nil {
  96. // If SSH Tunnel is turned on
  97. rt = utilnet.SetOldTransportDefaults(&http.Transport{
  98. DialContext: dialer,
  99. TLSClientConfig: tlsConfig,
  100. })
  101. }
  102. return transport.HTTPWrappersForConfig(config.transportConfig(), rt)
  103. }
  104. // transportConfig converts a client config to an appropriate transport config.
  105. func (c *KubeletClientConfig) transportConfig() *transport.Config {
  106. cfg := &transport.Config{
  107. TLS: transport.TLSConfig{
  108. CAFile: c.CAFile,
  109. CAData: c.CAData,
  110. CertFile: c.CertFile,
  111. CertData: c.CertData,
  112. KeyFile: c.KeyFile,
  113. KeyData: c.KeyData,
  114. NextProtos: c.NextProtos,
  115. },
  116. BearerToken: c.BearerToken,
  117. }
  118. if c.EnableHTTPS && !cfg.HasCA() {
  119. cfg.TLS.Insecure = true
  120. }
  121. return cfg
  122. }
  123. // NodeGetter defines an interface for looking up a node by name
  124. type NodeGetter interface {
  125. Get(ctx context.Context, name string, options metav1.GetOptions) (*v1.Node, error)
  126. }
  127. // NodeGetterFunc allows implementing NodeGetter with a function
  128. type NodeGetterFunc func(ctx context.Context, name string, options metav1.GetOptions) (*v1.Node, error)
  129. // Get fetches information via NodeGetterFunc.
  130. func (f NodeGetterFunc) Get(ctx context.Context, name string, options metav1.GetOptions) (*v1.Node, error) {
  131. return f(ctx, name, options)
  132. }
  133. // NodeConnectionInfoGetter obtains connection info from the status of a Node API object
  134. type NodeConnectionInfoGetter struct {
  135. // nodes is used to look up Node objects
  136. nodes NodeGetter
  137. // scheme is the scheme to use to connect to all kubelets
  138. scheme string
  139. // defaultPort is the port to use if no Kubelet endpoint port is recorded in the node status
  140. defaultPort int
  141. // transport is the transport to use to send a request to all kubelets
  142. transport http.RoundTripper
  143. // insecureSkipTLSVerifyTransport is the transport to use if the kube-apiserver wants to skip verifying the TLS certificate of the kubelet
  144. insecureSkipTLSVerifyTransport http.RoundTripper
  145. // preferredAddressTypes specifies the preferred order to use to find a node address
  146. preferredAddressTypes []v1.NodeAddressType
  147. }
  148. // NewNodeConnectionInfoGetter creates a new NodeConnectionInfoGetter.
  149. func NewNodeConnectionInfoGetter(nodes NodeGetter, config KubeletClientConfig) (ConnectionInfoGetter, error) {
  150. scheme := "http"
  151. if config.EnableHTTPS {
  152. scheme = "https"
  153. }
  154. transport, err := MakeTransport(&config)
  155. if err != nil {
  156. return nil, err
  157. }
  158. insecureSkipTLSVerifyTransport, err := MakeInsecureTransport(&config)
  159. if err != nil {
  160. return nil, err
  161. }
  162. types := []v1.NodeAddressType{}
  163. for _, t := range config.PreferredAddressTypes {
  164. types = append(types, v1.NodeAddressType(t))
  165. }
  166. return &NodeConnectionInfoGetter{
  167. nodes: nodes,
  168. scheme: scheme,
  169. defaultPort: int(config.Port),
  170. transport: transport,
  171. insecureSkipTLSVerifyTransport: insecureSkipTLSVerifyTransport,
  172. preferredAddressTypes: types,
  173. }, nil
  174. }
  175. // GetConnectionInfo retrieves connection info from the status of a Node API object.
  176. func (k *NodeConnectionInfoGetter) GetConnectionInfo(ctx context.Context, nodeName types.NodeName) (*ConnectionInfo, error) {
  177. node, err := k.nodes.Get(ctx, string(nodeName), metav1.GetOptions{})
  178. if err != nil {
  179. return nil, err
  180. }
  181. // Find a kubelet-reported address, using preferred address type
  182. host, err := nodeutil.GetPreferredNodeAddress(node, k.preferredAddressTypes)
  183. if err != nil {
  184. return nil, err
  185. }
  186. // Use the kubelet-reported port, if present
  187. port := int(node.Status.DaemonEndpoints.KubeletEndpoint.Port)
  188. if port <= 0 {
  189. port = k.defaultPort
  190. }
  191. return &ConnectionInfo{
  192. Scheme: k.scheme,
  193. Hostname: host,
  194. Port: strconv.Itoa(port),
  195. Transport: k.transport,
  196. InsecureSkipTLSVerifyTransport: k.insecureSkipTLSVerifyTransport,
  197. }, nil
  198. }