node.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. /*
  2. Copyright 2015 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 node
  14. import (
  15. "encoding/json"
  16. "fmt"
  17. "net"
  18. "os"
  19. "strings"
  20. "time"
  21. "k8s.io/klog"
  22. "k8s.io/api/core/v1"
  23. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  24. "k8s.io/apimachinery/pkg/types"
  25. "k8s.io/apimachinery/pkg/util/strategicpatch"
  26. clientset "k8s.io/client-go/kubernetes"
  27. v1core "k8s.io/client-go/kubernetes/typed/core/v1"
  28. )
  29. const (
  30. // NodeUnreachablePodReason is the reason on a pod when its state cannot be confirmed as kubelet is unresponsive
  31. // on the node it is (was) running.
  32. NodeUnreachablePodReason = "NodeLost"
  33. // NodeUnreachablePodMessage is the message on a pod when its state cannot be confirmed as kubelet is unresponsive
  34. // on the node it is (was) running.
  35. NodeUnreachablePodMessage = "Node %v which was running pod %v is unresponsive"
  36. )
  37. // GetHostname returns OS's hostname if 'hostnameOverride' is empty; otherwise, return 'hostnameOverride'.
  38. func GetHostname(hostnameOverride string) (string, error) {
  39. hostName := hostnameOverride
  40. if len(hostName) == 0 {
  41. nodeName, err := os.Hostname()
  42. if err != nil {
  43. return "", fmt.Errorf("couldn't determine hostname: %v", err)
  44. }
  45. hostName = nodeName
  46. }
  47. // Trim whitespaces first to avoid getting an empty hostname
  48. // For linux, the hostname is read from file /proc/sys/kernel/hostname directly
  49. hostName = strings.TrimSpace(hostName)
  50. if len(hostName) == 0 {
  51. return "", fmt.Errorf("empty hostname is invalid")
  52. }
  53. return strings.ToLower(hostName), nil
  54. }
  55. // NoMatchError is a typed implementation of the error interface. It indicates a failure to get a matching Node.
  56. type NoMatchError struct {
  57. addresses []v1.NodeAddress
  58. }
  59. // Error is the implementation of the conventional interface for
  60. // representing an error condition, with the nil value representing no error.
  61. func (e *NoMatchError) Error() string {
  62. return fmt.Sprintf("no preferred addresses found; known addresses: %v", e.addresses)
  63. }
  64. // GetPreferredNodeAddress returns the address of the provided node, using the provided preference order.
  65. // If none of the preferred address types are found, an error is returned.
  66. func GetPreferredNodeAddress(node *v1.Node, preferredAddressTypes []v1.NodeAddressType) (string, error) {
  67. for _, addressType := range preferredAddressTypes {
  68. for _, address := range node.Status.Addresses {
  69. if address.Type == addressType {
  70. return address.Address, nil
  71. }
  72. }
  73. }
  74. return "", &NoMatchError{addresses: node.Status.Addresses}
  75. }
  76. // GetNodeHostIP returns the provided node's IP, based on the priority:
  77. // 1. NodeInternalIP
  78. // 2. NodeExternalIP
  79. func GetNodeHostIP(node *v1.Node) (net.IP, error) {
  80. addresses := node.Status.Addresses
  81. addressMap := make(map[v1.NodeAddressType][]v1.NodeAddress)
  82. for i := range addresses {
  83. addressMap[addresses[i].Type] = append(addressMap[addresses[i].Type], addresses[i])
  84. }
  85. if addresses, ok := addressMap[v1.NodeInternalIP]; ok {
  86. return net.ParseIP(addresses[0].Address), nil
  87. }
  88. if addresses, ok := addressMap[v1.NodeExternalIP]; ok {
  89. return net.ParseIP(addresses[0].Address), nil
  90. }
  91. return nil, fmt.Errorf("host IP unknown; known addresses: %v", addresses)
  92. }
  93. // GetNodeIP returns the ip of node with the provided hostname
  94. func GetNodeIP(client clientset.Interface, hostname string) net.IP {
  95. var nodeIP net.IP
  96. node, err := client.CoreV1().Nodes().Get(hostname, metav1.GetOptions{})
  97. if err != nil {
  98. klog.Warningf("Failed to retrieve node info: %v", err)
  99. return nil
  100. }
  101. nodeIP, err = GetNodeHostIP(node)
  102. if err != nil {
  103. klog.Warningf("Failed to retrieve node IP: %v", err)
  104. return nil
  105. }
  106. return nodeIP
  107. }
  108. // GetZoneKey is a helper function that builds a string identifier that is unique per failure-zone;
  109. // it returns empty-string for no zone.
  110. func GetZoneKey(node *v1.Node) string {
  111. labels := node.Labels
  112. if labels == nil {
  113. return ""
  114. }
  115. region, _ := labels[v1.LabelZoneRegion]
  116. failureDomain, _ := labels[v1.LabelZoneFailureDomain]
  117. if region == "" && failureDomain == "" {
  118. return ""
  119. }
  120. // We include the null character just in case region or failureDomain has a colon
  121. // (We do assume there's no null characters in a region or failureDomain)
  122. // As a nice side-benefit, the null character is not printed by fmt.Print or glog
  123. return region + ":\x00:" + failureDomain
  124. }
  125. // SetNodeCondition updates specific node condition with patch operation.
  126. func SetNodeCondition(c clientset.Interface, node types.NodeName, condition v1.NodeCondition) error {
  127. generatePatch := func(condition v1.NodeCondition) ([]byte, error) {
  128. raw, err := json.Marshal(&[]v1.NodeCondition{condition})
  129. if err != nil {
  130. return nil, err
  131. }
  132. return []byte(fmt.Sprintf(`{"status":{"conditions":%s}}`, raw)), nil
  133. }
  134. condition.LastHeartbeatTime = metav1.NewTime(time.Now())
  135. patch, err := generatePatch(condition)
  136. if err != nil {
  137. return nil
  138. }
  139. _, err = c.CoreV1().Nodes().PatchStatus(string(node), patch)
  140. return err
  141. }
  142. // PatchNodeCIDR patches the specified node's CIDR to the given value.
  143. func PatchNodeCIDR(c clientset.Interface, node types.NodeName, cidr string) error {
  144. raw, err := json.Marshal(cidr)
  145. if err != nil {
  146. return fmt.Errorf("failed to json.Marshal CIDR: %v", err)
  147. }
  148. patchBytes := []byte(fmt.Sprintf(`{"spec":{"podCIDR":%s}}`, raw))
  149. if _, err := c.CoreV1().Nodes().Patch(string(node), types.StrategicMergePatchType, patchBytes); err != nil {
  150. return fmt.Errorf("failed to patch node CIDR: %v", err)
  151. }
  152. return nil
  153. }
  154. // PatchNodeStatus patches node status.
  155. func PatchNodeStatus(c v1core.CoreV1Interface, nodeName types.NodeName, oldNode *v1.Node, newNode *v1.Node) (*v1.Node, []byte, error) {
  156. patchBytes, err := preparePatchBytesforNodeStatus(nodeName, oldNode, newNode)
  157. if err != nil {
  158. return nil, nil, err
  159. }
  160. updatedNode, err := c.Nodes().Patch(string(nodeName), types.StrategicMergePatchType, patchBytes, "status")
  161. if err != nil {
  162. return nil, nil, fmt.Errorf("failed to patch status %q for node %q: %v", patchBytes, nodeName, err)
  163. }
  164. return updatedNode, patchBytes, nil
  165. }
  166. func preparePatchBytesforNodeStatus(nodeName types.NodeName, oldNode *v1.Node, newNode *v1.Node) ([]byte, error) {
  167. oldData, err := json.Marshal(oldNode)
  168. if err != nil {
  169. return nil, fmt.Errorf("failed to Marshal oldData for node %q: %v", nodeName, err)
  170. }
  171. // Reset spec to make sure only patch for Status or ObjectMeta is generated.
  172. // Note that we don't reset ObjectMeta here, because:
  173. // 1. This aligns with Nodes().UpdateStatus().
  174. // 2. Some component does use this to update node annotations.
  175. newNode.Spec = oldNode.Spec
  176. newData, err := json.Marshal(newNode)
  177. if err != nil {
  178. return nil, fmt.Errorf("failed to Marshal newData for node %q: %v", nodeName, err)
  179. }
  180. patchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, v1.Node{})
  181. if err != nil {
  182. return nil, fmt.Errorf("failed to CreateTwoWayMergePatch for node %q: %v", nodeName, err)
  183. }
  184. return patchBytes, nil
  185. }