strategy.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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. // Nodes allow *all* fields, including status, to be set on create.
  59. if !utilfeature.DefaultFeatureGate.Enabled(features.DynamicKubeletConfig) {
  60. node.Spec.ConfigSource = nil
  61. node.Status.Config = nil
  62. }
  63. }
  64. // PrepareForUpdate clears fields that are not allowed to be set by end users on update.
  65. func (nodeStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {
  66. newNode := obj.(*api.Node)
  67. oldNode := old.(*api.Node)
  68. newNode.Status = oldNode.Status
  69. if !utilfeature.DefaultFeatureGate.Enabled(features.DynamicKubeletConfig) && !nodeConfigSourceInUse(oldNode) {
  70. newNode.Spec.ConfigSource = nil
  71. }
  72. }
  73. // nodeConfigSourceInUse returns true if node's Spec ConfigSource is set(used)
  74. func nodeConfigSourceInUse(node *api.Node) bool {
  75. if node == nil {
  76. return false
  77. }
  78. if node.Spec.ConfigSource != nil {
  79. return true
  80. }
  81. return false
  82. }
  83. // Validate validates a new node.
  84. func (nodeStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {
  85. node := obj.(*api.Node)
  86. return validation.ValidateNode(node)
  87. }
  88. // Canonicalize normalizes the object after validation.
  89. func (nodeStrategy) Canonicalize(obj runtime.Object) {
  90. }
  91. // ValidateUpdate is the default update validation for an end user.
  92. func (nodeStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {
  93. errorList := validation.ValidateNode(obj.(*api.Node))
  94. return append(errorList, validation.ValidateNodeUpdate(obj.(*api.Node), old.(*api.Node))...)
  95. }
  96. func (nodeStrategy) AllowUnconditionalUpdate() bool {
  97. return true
  98. }
  99. func (ns nodeStrategy) Export(ctx context.Context, obj runtime.Object, exact bool) error {
  100. n, ok := obj.(*api.Node)
  101. if !ok {
  102. // unexpected programmer error
  103. return fmt.Errorf("unexpected object: %v", obj)
  104. }
  105. ns.PrepareForCreate(ctx, obj)
  106. if exact {
  107. return nil
  108. }
  109. // Nodes are the only resources that allow direct status edits, therefore
  110. // we clear that without exact so that the node value can be reused.
  111. n.Status = api.NodeStatus{}
  112. return nil
  113. }
  114. type nodeStatusStrategy struct {
  115. nodeStrategy
  116. }
  117. var StatusStrategy = nodeStatusStrategy{Strategy}
  118. func (nodeStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {
  119. newNode := obj.(*api.Node)
  120. oldNode := old.(*api.Node)
  121. newNode.Spec = oldNode.Spec
  122. if !utilfeature.DefaultFeatureGate.Enabled(features.DynamicKubeletConfig) && !nodeStatusConfigInUse(oldNode) {
  123. newNode.Status.Config = nil
  124. }
  125. }
  126. // nodeStatusConfigInUse returns true if node's Status Config is set(used)
  127. func nodeStatusConfigInUse(node *api.Node) bool {
  128. if node == nil {
  129. return false
  130. }
  131. if node.Status.Config != nil {
  132. return true
  133. }
  134. return false
  135. }
  136. func (nodeStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {
  137. return validation.ValidateNodeUpdate(obj.(*api.Node), old.(*api.Node))
  138. }
  139. // Canonicalize normalizes the object after validation.
  140. func (nodeStatusStrategy) Canonicalize(obj runtime.Object) {
  141. }
  142. // ResourceGetter is an interface for retrieving resources by ResourceLocation.
  143. type ResourceGetter interface {
  144. Get(context.Context, string, *metav1.GetOptions) (runtime.Object, error)
  145. }
  146. // NodeToSelectableFields returns a field set that represents the object.
  147. func NodeToSelectableFields(node *api.Node) fields.Set {
  148. objectMetaFieldsSet := generic.ObjectMetaFieldsSet(&node.ObjectMeta, false)
  149. specificFieldsSet := fields.Set{
  150. "spec.unschedulable": fmt.Sprint(node.Spec.Unschedulable),
  151. }
  152. return generic.MergeFieldsSets(objectMetaFieldsSet, specificFieldsSet)
  153. }
  154. // GetAttrs returns labels and fields of a given object for filtering purposes.
  155. func GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error) {
  156. nodeObj, ok := obj.(*api.Node)
  157. if !ok {
  158. return nil, nil, fmt.Errorf("not a node")
  159. }
  160. return labels.Set(nodeObj.ObjectMeta.Labels), NodeToSelectableFields(nodeObj), nil
  161. }
  162. // MatchNode returns a generic matcher for a given label and field selector.
  163. func MatchNode(label labels.Selector, field fields.Selector) pkgstorage.SelectionPredicate {
  164. return pkgstorage.SelectionPredicate{
  165. Label: label,
  166. Field: field,
  167. GetAttrs: GetAttrs,
  168. IndexFields: []string{"metadata.name"},
  169. }
  170. }
  171. func NodeNameTriggerFunc(obj runtime.Object) []pkgstorage.MatchValue {
  172. node := obj.(*api.Node)
  173. result := pkgstorage.MatchValue{IndexName: "metadata.name", Value: node.ObjectMeta.Name}
  174. return []pkgstorage.MatchValue{result}
  175. }
  176. // ResourceLocation returns a URL and transport which one can use to send traffic for the specified node.
  177. func ResourceLocation(getter ResourceGetter, connection client.ConnectionInfoGetter, proxyTransport http.RoundTripper, ctx context.Context, id string) (*url.URL, http.RoundTripper, error) {
  178. schemeReq, name, portReq, valid := utilnet.SplitSchemeNamePort(id)
  179. if !valid {
  180. return nil, nil, errors.NewBadRequest(fmt.Sprintf("invalid node request %q", id))
  181. }
  182. info, err := connection.GetConnectionInfo(ctx, types.NodeName(name))
  183. if err != nil {
  184. return nil, nil, err
  185. }
  186. // We check if we want to get a default Kubelet's transport. It happens if either:
  187. // - no port is specified in request (Kubelet's port is default)
  188. // - the requested port matches the kubelet port for this node
  189. if portReq == "" || portReq == info.Port {
  190. return &url.URL{
  191. Scheme: info.Scheme,
  192. Host: net.JoinHostPort(info.Hostname, info.Port),
  193. },
  194. info.Transport,
  195. nil
  196. }
  197. if err := proxyutil.IsProxyableHostname(ctx, &net.Resolver{}, info.Hostname); err != nil {
  198. return nil, nil, errors.NewBadRequest(err.Error())
  199. }
  200. // Otherwise, return the requested scheme and port, and the proxy transport
  201. return &url.URL{Scheme: schemeReq, Host: net.JoinHostPort(info.Hostname, portReq)}, proxyTransport, nil
  202. }