strategy.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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 node
  14. import (
  15. "context"
  16. "fmt"
  17. "net"
  18. "net/http"
  19. "net/url"
  20. "k8s.io/apimachinery/pkg/api/errors"
  21. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  22. "k8s.io/apimachinery/pkg/fields"
  23. "k8s.io/apimachinery/pkg/labels"
  24. "k8s.io/apimachinery/pkg/runtime"
  25. "k8s.io/apimachinery/pkg/types"
  26. utilnet "k8s.io/apimachinery/pkg/util/net"
  27. "k8s.io/apimachinery/pkg/util/validation/field"
  28. "k8s.io/apiserver/pkg/registry/generic"
  29. pkgstorage "k8s.io/apiserver/pkg/storage"
  30. "k8s.io/apiserver/pkg/storage/names"
  31. utilfeature "k8s.io/apiserver/pkg/util/feature"
  32. "k8s.io/kubernetes/pkg/api/legacyscheme"
  33. api "k8s.io/kubernetes/pkg/apis/core"
  34. "k8s.io/kubernetes/pkg/apis/core/validation"
  35. "k8s.io/kubernetes/pkg/features"
  36. "k8s.io/kubernetes/pkg/kubelet/client"
  37. proxyutil "k8s.io/kubernetes/pkg/proxy/util"
  38. )
  39. // nodeStrategy implements behavior for nodes
  40. type nodeStrategy struct {
  41. runtime.ObjectTyper
  42. names.NameGenerator
  43. }
  44. // Nodes is the default logic that applies when creating and updating Node
  45. // objects.
  46. var Strategy = nodeStrategy{legacyscheme.Scheme, names.SimpleNameGenerator}
  47. // NamespaceScoped is false for nodes.
  48. func (nodeStrategy) NamespaceScoped() bool {
  49. return false
  50. }
  51. // AllowCreateOnUpdate is false for nodes.
  52. func (nodeStrategy) AllowCreateOnUpdate() bool {
  53. return false
  54. }
  55. // PrepareForCreate clears fields that are not allowed to be set by end users on creation.
  56. func (nodeStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {
  57. node := obj.(*api.Node)
  58. dropDisabledFields(node, nil)
  59. }
  60. // PrepareForUpdate clears fields that are not allowed to be set by end users on update.
  61. func (nodeStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {
  62. newNode := obj.(*api.Node)
  63. oldNode := old.(*api.Node)
  64. newNode.Status = oldNode.Status
  65. dropDisabledFields(newNode, oldNode)
  66. }
  67. func dropDisabledFields(node *api.Node, oldNode *api.Node) {
  68. // Nodes allow *all* fields, including status, to be set on create.
  69. // for create
  70. if !utilfeature.DefaultFeatureGate.Enabled(features.DynamicKubeletConfig) && oldNode == nil {
  71. node.Spec.ConfigSource = nil
  72. node.Status.Config = nil
  73. }
  74. // for update
  75. if !utilfeature.DefaultFeatureGate.Enabled(features.DynamicKubeletConfig) && !nodeConfigSourceInUse(oldNode) && oldNode != nil {
  76. node.Spec.ConfigSource = nil
  77. }
  78. if !utilfeature.DefaultFeatureGate.Enabled(features.IPv6DualStack) && !multiNodeCIDRsInUse(oldNode) {
  79. if len(node.Spec.PodCIDRs) > 1 {
  80. node.Spec.PodCIDRs = node.Spec.PodCIDRs[0:1]
  81. }
  82. }
  83. }
  84. // multiNodeCIDRsInUse returns true if Node.Spec.PodCIDRs is greater than one
  85. func multiNodeCIDRsInUse(node *api.Node) bool {
  86. if node == nil {
  87. return false
  88. }
  89. if len(node.Spec.PodCIDRs) > 1 {
  90. return true
  91. }
  92. return false
  93. }
  94. // nodeConfigSourceInUse returns true if node's Spec ConfigSource is set(used)
  95. func nodeConfigSourceInUse(node *api.Node) bool {
  96. if node == nil {
  97. return false
  98. }
  99. if node.Spec.ConfigSource != nil {
  100. return true
  101. }
  102. return false
  103. }
  104. // Validate validates a new node.
  105. func (nodeStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {
  106. node := obj.(*api.Node)
  107. opts := validation.NodeValidationOptions{
  108. // This ensures new nodes have no more than one hugepages resource
  109. // TODO: set to false in 1.19; 1.18 servers tolerate multiple hugepages resources on update
  110. ValidateSingleHugePageResource: true,
  111. }
  112. return validation.ValidateNode(node, opts)
  113. }
  114. // Canonicalize normalizes the object after validation.
  115. func (nodeStrategy) Canonicalize(obj runtime.Object) {
  116. }
  117. // ValidateUpdate is the default update validation for an end user.
  118. func (nodeStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {
  119. oldPassesSingleHugepagesValidation := len(validation.ValidateNodeSingleHugePageResources(old.(*api.Node))) == 0
  120. opts := validation.NodeValidationOptions{
  121. // This ensures the new node has no more than one hugepages resource, if the old node did as well.
  122. // TODO: set to false in 1.19; 1.18 servers tolerate relaxed validation on update
  123. ValidateSingleHugePageResource: oldPassesSingleHugepagesValidation,
  124. }
  125. errorList := validation.ValidateNode(obj.(*api.Node), opts)
  126. return append(errorList, validation.ValidateNodeUpdate(obj.(*api.Node), old.(*api.Node), opts)...)
  127. }
  128. func (nodeStrategy) AllowUnconditionalUpdate() bool {
  129. return true
  130. }
  131. func (ns nodeStrategy) Export(ctx context.Context, obj runtime.Object, exact bool) error {
  132. n, ok := obj.(*api.Node)
  133. if !ok {
  134. // unexpected programmer error
  135. return fmt.Errorf("unexpected object: %v", obj)
  136. }
  137. ns.PrepareForCreate(ctx, obj)
  138. if exact {
  139. return nil
  140. }
  141. // Nodes are the only resources that allow direct status edits, therefore
  142. // we clear that without exact so that the node value can be reused.
  143. n.Status = api.NodeStatus{}
  144. return nil
  145. }
  146. type nodeStatusStrategy struct {
  147. nodeStrategy
  148. }
  149. var StatusStrategy = nodeStatusStrategy{Strategy}
  150. func (nodeStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {
  151. newNode := obj.(*api.Node)
  152. oldNode := old.(*api.Node)
  153. newNode.Spec = oldNode.Spec
  154. if !utilfeature.DefaultFeatureGate.Enabled(features.DynamicKubeletConfig) && !nodeStatusConfigInUse(oldNode) {
  155. newNode.Status.Config = nil
  156. }
  157. }
  158. // nodeStatusConfigInUse returns true if node's Status Config is set(used)
  159. func nodeStatusConfigInUse(node *api.Node) bool {
  160. if node == nil {
  161. return false
  162. }
  163. if node.Status.Config != nil {
  164. return true
  165. }
  166. return false
  167. }
  168. func (nodeStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {
  169. oldPassesSingleHugepagesValidation := len(validation.ValidateNodeSingleHugePageResources(old.(*api.Node))) == 0
  170. opts := validation.NodeValidationOptions{
  171. // This ensures the new node has no more than one hugepages resource, if the old node did as well.
  172. // TODO: set to false in 1.19; 1.18 servers tolerate relaxed validation on update
  173. ValidateSingleHugePageResource: oldPassesSingleHugepagesValidation,
  174. }
  175. return validation.ValidateNodeUpdate(obj.(*api.Node), old.(*api.Node), opts)
  176. }
  177. // Canonicalize normalizes the object after validation.
  178. func (nodeStatusStrategy) Canonicalize(obj runtime.Object) {
  179. }
  180. // ResourceGetter is an interface for retrieving resources by ResourceLocation.
  181. type ResourceGetter interface {
  182. Get(context.Context, string, *metav1.GetOptions) (runtime.Object, error)
  183. }
  184. // NodeToSelectableFields returns a field set that represents the object.
  185. func NodeToSelectableFields(node *api.Node) fields.Set {
  186. objectMetaFieldsSet := generic.ObjectMetaFieldsSet(&node.ObjectMeta, false)
  187. specificFieldsSet := fields.Set{
  188. "spec.unschedulable": fmt.Sprint(node.Spec.Unschedulable),
  189. }
  190. return generic.MergeFieldsSets(objectMetaFieldsSet, specificFieldsSet)
  191. }
  192. // GetAttrs returns labels and fields of a given object for filtering purposes.
  193. func GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error) {
  194. nodeObj, ok := obj.(*api.Node)
  195. if !ok {
  196. return nil, nil, fmt.Errorf("not a node")
  197. }
  198. return labels.Set(nodeObj.ObjectMeta.Labels), NodeToSelectableFields(nodeObj), nil
  199. }
  200. // MatchNode returns a generic matcher for a given label and field selector.
  201. func MatchNode(label labels.Selector, field fields.Selector) pkgstorage.SelectionPredicate {
  202. return pkgstorage.SelectionPredicate{
  203. Label: label,
  204. Field: field,
  205. GetAttrs: GetAttrs,
  206. IndexFields: []string{"metadata.name"},
  207. }
  208. }
  209. // NameTriggerFunc returns value metadata.namespace of given object.
  210. func NameTriggerFunc(obj runtime.Object) string {
  211. return obj.(*api.Node).ObjectMeta.Name
  212. }
  213. // ResourceLocation returns a URL and transport which one can use to send traffic for the specified node.
  214. func ResourceLocation(getter ResourceGetter, connection client.ConnectionInfoGetter, proxyTransport http.RoundTripper, ctx context.Context, id string) (*url.URL, http.RoundTripper, error) {
  215. schemeReq, name, portReq, valid := utilnet.SplitSchemeNamePort(id)
  216. if !valid {
  217. return nil, nil, errors.NewBadRequest(fmt.Sprintf("invalid node request %q", id))
  218. }
  219. info, err := connection.GetConnectionInfo(ctx, types.NodeName(name))
  220. if err != nil {
  221. return nil, nil, err
  222. }
  223. // We check if we want to get a default Kubelet's transport. It happens if either:
  224. // - no port is specified in request (Kubelet's port is default)
  225. // - the requested port matches the kubelet port for this node
  226. if portReq == "" || portReq == info.Port {
  227. return &url.URL{
  228. Scheme: info.Scheme,
  229. Host: net.JoinHostPort(info.Hostname, info.Port),
  230. },
  231. info.Transport,
  232. nil
  233. }
  234. if err := proxyutil.IsProxyableHostname(ctx, &net.Resolver{}, info.Hostname); err != nil {
  235. return nil, nil, errors.NewBadRequest(err.Error())
  236. }
  237. // Otherwise, return the requested scheme and port, and the proxy transport
  238. return &url.URL{Scheme: schemeReq, Host: net.JoinHostPort(info.Hostname, portReq)}, proxyTransport, nil
  239. }